blob: 44a1b69b0772c0ace3d6bf1c52c5cd65adbf591e [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() {
fayang2205d952020-05-12 13:45:56 -0700906 if (GetQuicReloadableFlag(quic_use_idle_network_detector)) {
fayangb9c88442020-03-26 07:03:57 -0700907 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
908 QuicConnectionPeer::GetIdleNetworkDetectorAlarm(this));
909 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500910 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
911 QuicConnectionPeer::GetTimeoutAlarm(this));
912 }
913
914 TestAlarmFactory::TestAlarm* GetMtuDiscoveryAlarm() {
915 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
916 QuicConnectionPeer::GetMtuDiscoveryAlarm(this));
917 }
918
QUICHE teama6ef0a62019-03-07 20:34:33 -0500919 TestAlarmFactory::TestAlarm* GetProcessUndecryptablePacketsAlarm() {
920 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
921 QuicConnectionPeer::GetProcessUndecryptablePacketsAlarm(this));
922 }
923
fayangb59c6f12020-03-23 15:06:14 -0700924 TestAlarmFactory::TestAlarm* GetBlackholeDetectorAlarm() {
fayangb59c6f12020-03-23 15:06:14 -0700925 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
926 QuicConnectionPeer::GetBlackholeDetectorAlarm(this));
927 }
928
929 void PathDegradingTimeout() {
930 DCHECK(PathDegradingDetectionInProgress());
fayang2205d952020-05-12 13:45:56 -0700931 GetBlackholeDetectorAlarm()->Fire();
fayangb59c6f12020-03-23 15:06:14 -0700932 }
933
934 bool PathDegradingDetectionInProgress() {
fayang2205d952020-05-12 13:45:56 -0700935 return QuicConnectionPeer::GetPathDegradingDeadline(this).IsInitialized();
fayangb59c6f12020-03-23 15:06:14 -0700936 }
937
938 bool BlackholeDetectionInProgress() {
fayangb59c6f12020-03-23 15:06:14 -0700939 return QuicConnectionPeer::GetBlackholeDetectionDeadline(this)
940 .IsInitialized();
941 }
942
QUICHE teama6ef0a62019-03-07 20:34:33 -0500943 void SetMaxTailLossProbes(size_t max_tail_loss_probes) {
944 QuicSentPacketManagerPeer::SetMaxTailLossProbes(
945 QuicConnectionPeer::GetSentPacketManager(this), max_tail_loss_probes);
946 }
947
948 QuicByteCount GetBytesInFlight() {
ianswett9f459cb2019-04-21 06:39:59 -0700949 return QuicConnectionPeer::GetSentPacketManager(this)->GetBytesInFlight();
QUICHE teama6ef0a62019-03-07 20:34:33 -0500950 }
951
952 void set_notifier(SimpleSessionNotifier* notifier) { notifier_ = notifier; }
953
954 void ReturnEffectivePeerAddressForNextPacket(const QuicSocketAddress& addr) {
vasilvv0fc587f2019-09-06 13:33:08 -0700955 next_effective_peer_addr_ = std::make_unique<QuicSocketAddress>(addr);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500956 }
957
fayang5f135052019-08-22 17:59:40 -0700958 bool PtoEnabled() {
959 if (QuicConnectionPeer::GetSentPacketManager(this)->pto_enabled()) {
960 // PTO mode is default enabled for T099. And TLP/RTO related tests are
961 // stale.
fayang5d011982020-05-13 14:14:38 -0700962 DCHECK(PROTOCOL_TLS1_3 == version().handshake_protocol ||
963 GetQuicReloadableFlag(quic_default_on_pto));
fayang5f135052019-08-22 17:59:40 -0700964 return true;
965 }
966 return false;
967 }
968
nharper46833c32019-05-15 21:33:05 -0700969 SimpleDataProducer* producer() { return &producer_; }
970
QUICHE teama6ef0a62019-03-07 20:34:33 -0500971 using QuicConnection::active_effective_peer_migration_type;
972 using QuicConnection::IsCurrentPacketConnectivityProbing;
973 using QuicConnection::SelectMutualVersion;
974 using QuicConnection::SendProbingRetransmissions;
975 using QuicConnection::set_defer_send_in_response_to_packets;
976
977 protected:
978 QuicSocketAddress GetEffectivePeerAddressFromCurrentPacket() const override {
979 if (next_effective_peer_addr_) {
980 return *std::move(next_effective_peer_addr_);
981 }
982 return QuicConnection::GetEffectivePeerAddressFromCurrentPacket();
983 }
984
985 private:
986 TestPacketWriter* writer() {
987 return static_cast<TestPacketWriter*>(QuicConnection::writer());
988 }
989
990 SimpleDataProducer producer_;
991
992 SimpleSessionNotifier* notifier_;
993
994 std::unique_ptr<QuicSocketAddress> next_effective_peer_addr_;
995};
996
997enum class AckResponse { kDefer, kImmediate };
998
999// Run tests with combinations of {ParsedQuicVersion, AckResponse}.
1000struct TestParams {
1001 TestParams(ParsedQuicVersion version,
1002 AckResponse ack_response,
1003 bool no_stop_waiting)
1004 : version(version),
1005 ack_response(ack_response),
1006 no_stop_waiting(no_stop_waiting) {}
1007
QUICHE teama6ef0a62019-03-07 20:34:33 -05001008 ParsedQuicVersion version;
1009 AckResponse ack_response;
1010 bool no_stop_waiting;
1011};
1012
dschinazi142051a2019-09-18 18:17:29 -07001013// Used by ::testing::PrintToStringParamName().
1014std::string PrintToString(const TestParams& p) {
dmcardlecf0bfcf2019-12-13 08:08:21 -08001015 return quiche::QuicheStrCat(
dschinazi142051a2019-09-18 18:17:29 -07001016 ParsedQuicVersionToString(p.version), "_",
1017 (p.ack_response == AckResponse::kDefer ? "defer" : "immediate"), "_",
1018 (p.no_stop_waiting ? "No" : ""), "StopWaiting");
1019}
1020
QUICHE teama6ef0a62019-03-07 20:34:33 -05001021// Constructs various test permutations.
1022std::vector<TestParams> GetTestParams() {
1023 QuicFlagSaver flags;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001024 std::vector<TestParams> params;
1025 ParsedQuicVersionVector all_supported_versions = AllSupportedVersions();
1026 for (size_t i = 0; i < all_supported_versions.size(); ++i) {
1027 for (AckResponse ack_response :
1028 {AckResponse::kDefer, AckResponse::kImmediate}) {
dschinazi142051a2019-09-18 18:17:29 -07001029 params.push_back(
1030 TestParams(all_supported_versions[i], ack_response, true));
1031 if (!VersionHasIetfInvariantHeader(
1032 all_supported_versions[i].transport_version)) {
fayangd4291e42019-05-30 10:31:21 -07001033 params.push_back(
dschinazi142051a2019-09-18 18:17:29 -07001034 TestParams(all_supported_versions[i], ack_response, false));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001035 }
1036 }
1037 }
1038 return params;
1039}
1040
1041class QuicConnectionTest : public QuicTestWithParam<TestParams> {
fkastenholz5d880a92019-06-21 09:01:56 -07001042 public:
1043 // For tests that do silent connection closes, no such packet is generated. In
1044 // order to verify the contents of the OnConnectionClosed upcall, EXPECTs
1045 // should invoke this method, saving the frame, and then the test can verify
1046 // the contents.
1047 void SaveConnectionCloseFrame(const QuicConnectionCloseFrame& frame,
1048 ConnectionCloseSource /*source*/) {
1049 saved_connection_close_frame_ = frame;
1050 connection_close_frame_count_++;
1051 }
1052
QUICHE teama6ef0a62019-03-07 20:34:33 -05001053 protected:
1054 QuicConnectionTest()
1055 : connection_id_(TestConnectionId()),
1056 framer_(SupportedVersions(version()),
1057 QuicTime::Zero(),
1058 Perspective::IS_CLIENT,
1059 connection_id_.length()),
1060 send_algorithm_(new StrictMock<MockSendAlgorithm>),
1061 loss_algorithm_(new MockLossAlgorithm()),
1062 helper_(new TestConnectionHelper(&clock_, &random_generator_)),
1063 alarm_factory_(new TestAlarmFactory()),
1064 peer_framer_(SupportedVersions(version()),
1065 QuicTime::Zero(),
1066 Perspective::IS_SERVER,
1067 connection_id_.length()),
1068 peer_creator_(connection_id_,
1069 &peer_framer_,
1070 /*delegate=*/nullptr),
1071 writer_(new TestPacketWriter(version(), &clock_)),
1072 connection_(connection_id_,
1073 kPeerAddress,
1074 helper_.get(),
1075 alarm_factory_.get(),
1076 writer_.get(),
1077 Perspective::IS_CLIENT,
1078 version()),
1079 creator_(QuicConnectionPeer::GetPacketCreator(&connection_)),
QUICHE teama6ef0a62019-03-07 20:34:33 -05001080 manager_(QuicConnectionPeer::GetSentPacketManager(&connection_)),
dmcardlecf0bfcf2019-12-13 08:08:21 -08001081 frame1_(0, false, 0, quiche::QuicheStringPiece(data1)),
1082 frame2_(0, false, 3, quiche::QuicheStringPiece(data2)),
1083 crypto_frame_(ENCRYPTION_INITIAL, 0, quiche::QuicheStringPiece(data1)),
QUICHE teama6ef0a62019-03-07 20:34:33 -05001084 packet_number_length_(PACKET_4BYTE_PACKET_NUMBER),
1085 connection_id_included_(CONNECTION_ID_PRESENT),
fkastenholz5d880a92019-06-21 09:01:56 -07001086 notifier_(&connection_),
1087 connection_close_frame_count_(0) {
dschinazi142051a2019-09-18 18:17:29 -07001088 QUIC_DVLOG(2) << "QuicConnectionTest(" << PrintToString(GetParam()) << ")";
QUICHE teama6ef0a62019-03-07 20:34:33 -05001089 connection_.set_defer_send_in_response_to_packets(GetParam().ack_response ==
1090 AckResponse::kDefer);
nharperc6b99512019-09-19 11:13:48 -07001091 framer_.SetInitialObfuscators(TestConnectionId());
1092 connection_.InstallInitialCrypters(TestConnectionId());
1093 CrypterPair crypters;
1094 CryptoUtils::CreateInitialObfuscators(Perspective::IS_SERVER, version(),
1095 TestConnectionId(), &crypters);
1096 peer_creator_.SetEncrypter(ENCRYPTION_INITIAL,
1097 std::move(crypters.encrypter));
1098 if (version().KnowsWhichDecrypterToUse()) {
1099 peer_framer_.InstallDecrypter(ENCRYPTION_INITIAL,
1100 std::move(crypters.decrypter));
1101 } else {
1102 peer_framer_.SetDecrypter(ENCRYPTION_INITIAL,
1103 std::move(crypters.decrypter));
1104 }
nharper2c9f02a2019-05-08 10:25:50 -07001105 for (EncryptionLevel level :
1106 {ENCRYPTION_ZERO_RTT, ENCRYPTION_FORWARD_SECURE}) {
1107 peer_creator_.SetEncrypter(
vasilvv0fc587f2019-09-06 13:33:08 -07001108 level, std::make_unique<NullEncrypter>(peer_framer_.perspective()));
nharper2c9f02a2019-05-08 10:25:50 -07001109 }
dschinazi7b9278c2019-05-20 07:36:21 -07001110 QuicFramerPeer::SetLastSerializedServerConnectionId(
QUICHE teama6ef0a62019-03-07 20:34:33 -05001111 QuicConnectionPeer::GetFramer(&connection_), connection_id_);
nharperc6b99512019-09-19 11:13:48 -07001112 QuicFramerPeer::SetLastWrittenPacketNumberLength(
1113 QuicConnectionPeer::GetFramer(&connection_), packet_number_length_);
fayangd4291e42019-05-30 10:31:21 -07001114 if (VersionHasIetfInvariantHeader(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001115 EXPECT_TRUE(QuicConnectionPeer::GetNoStopWaitingFrames(&connection_));
1116 } else {
1117 QuicConnectionPeer::SetNoStopWaitingFrames(&connection_,
1118 GetParam().no_stop_waiting);
1119 }
nharper46833c32019-05-15 21:33:05 -07001120 QuicStreamId stream_id;
1121 if (QuicVersionUsesCryptoFrames(version().transport_version)) {
1122 stream_id = QuicUtils::GetFirstBidirectionalStreamId(
1123 version().transport_version, Perspective::IS_CLIENT);
1124 } else {
1125 stream_id = QuicUtils::GetCryptoStreamId(version().transport_version);
1126 }
1127 frame1_.stream_id = stream_id;
1128 frame2_.stream_id = stream_id;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001129 connection_.set_visitor(&visitor_);
fayangcff885a2019-10-22 07:39:04 -07001130 connection_.SetSessionNotifier(&notifier_);
1131 connection_.set_notifier(&notifier_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001132 connection_.SetSendAlgorithm(send_algorithm_);
1133 connection_.SetLossAlgorithm(loss_algorithm_.get());
1134 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
1135 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1136 .Times(AnyNumber());
wubf4ab9652020-02-20 14:45:43 -08001137 EXPECT_CALL(*send_algorithm_, OnPacketNeutered(_)).Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -05001138 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
1139 .WillRepeatedly(Return(kDefaultTCPMSS));
1140 EXPECT_CALL(*send_algorithm_, PacingRate(_))
1141 .WillRepeatedly(Return(QuicBandwidth::Zero()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001142 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
1143 .Times(AnyNumber())
1144 .WillRepeatedly(Return(QuicBandwidth::Zero()));
wub5cd49592019-11-25 15:17:13 -08001145 EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_))
1146 .Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -05001147 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
1148 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
1149 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
1150 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).Times(AnyNumber());
fayangd58736d2019-11-27 13:35:31 -08001151 EXPECT_CALL(visitor_, OnPacketDecrypted(_)).Times(AnyNumber());
fayangcff885a2019-10-22 07:39:04 -07001152 EXPECT_CALL(visitor_, OnCanWrite())
1153 .WillRepeatedly(Invoke(&notifier_, &SimpleSessionNotifier::OnCanWrite));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001154 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
1155 .WillRepeatedly(Return(false));
1156 EXPECT_CALL(visitor_, OnCongestionWindowChange(_)).Times(AnyNumber());
zhongyi83161e42019-08-19 09:06:25 -07001157 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(AnyNumber());
wub256b2d62019-11-25 08:46:55 -08001158 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
fayang2f2915d2020-01-24 06:47:15 -08001159 EXPECT_CALL(visitor_, OnOneRttPacketAcknowledged())
1160 .Times(testing::AtMost(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001161 EXPECT_CALL(*loss_algorithm_, GetLossTimeout())
1162 .WillRepeatedly(Return(QuicTime::Zero()));
1163 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
1164 .Times(AnyNumber());
fayang5014e922020-01-22 12:28:11 -08001165 EXPECT_CALL(visitor_, GetHandshakeState())
1166 .WillRepeatedly(Return(HANDSHAKE_START));
zhongyi546cc452019-04-12 15:27:49 -07001167 if (connection_.version().KnowsWhichDecrypterToUse()) {
1168 connection_.InstallDecrypter(
1169 ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07001170 std::make_unique<NullDecrypter>(Perspective::IS_CLIENT));
zhongyi546cc452019-04-12 15:27:49 -07001171 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001172 }
1173
1174 QuicConnectionTest(const QuicConnectionTest&) = delete;
1175 QuicConnectionTest& operator=(const QuicConnectionTest&) = delete;
1176
1177 ParsedQuicVersion version() { return GetParam().version; }
1178
QUICHE teama6ef0a62019-03-07 20:34:33 -05001179 QuicStopWaitingFrame* stop_waiting() {
1180 QuicConnectionPeer::PopulateStopWaitingFrame(&connection_, &stop_waiting_);
1181 return &stop_waiting_;
1182 }
1183
1184 QuicPacketNumber least_unacked() {
1185 if (writer_->stop_waiting_frames().empty()) {
1186 return QuicPacketNumber();
1187 }
1188 return writer_->stop_waiting_frames()[0].least_unacked;
1189 }
1190
1191 void use_tagging_decrypter() { writer_->use_tagging_decrypter(); }
1192
zhongyi546cc452019-04-12 15:27:49 -07001193 void SetDecrypter(EncryptionLevel level,
1194 std::unique_ptr<QuicDecrypter> decrypter) {
1195 if (connection_.version().KnowsWhichDecrypterToUse()) {
1196 connection_.InstallDecrypter(level, std::move(decrypter));
1197 connection_.RemoveDecrypter(ENCRYPTION_INITIAL);
1198 } else {
1199 connection_.SetDecrypter(level, std::move(decrypter));
1200 }
1201 }
1202
QUICHE teama6ef0a62019-03-07 20:34:33 -05001203 void ProcessPacket(uint64_t number) {
1204 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
1205 ProcessDataPacket(number);
1206 if (connection_.GetSendAlarm()->IsSet()) {
1207 connection_.GetSendAlarm()->Fire();
1208 }
1209 }
1210
1211 void ProcessReceivedPacket(const QuicSocketAddress& self_address,
1212 const QuicSocketAddress& peer_address,
1213 const QuicReceivedPacket& packet) {
1214 connection_.ProcessUdpPacket(self_address, peer_address, packet);
1215 if (connection_.GetSendAlarm()->IsSet()) {
1216 connection_.GetSendAlarm()->Fire();
1217 }
1218 }
1219
wub8a5dafa2020-05-13 12:30:17 -07001220 QuicFrame MakeCryptoFrame() const {
1221 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1222 return QuicFrame(new QuicCryptoFrame(crypto_frame_));
1223 }
1224 return QuicFrame(QuicStreamFrame(
1225 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
1226 0u, quiche::QuicheStringPiece()));
1227 }
1228
QUICHE teama6ef0a62019-03-07 20:34:33 -05001229 void ProcessFramePacket(QuicFrame frame) {
1230 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
1231 }
1232
1233 void ProcessFramePacketWithAddresses(QuicFrame frame,
1234 QuicSocketAddress self_address,
1235 QuicSocketAddress peer_address) {
1236 QuicFrames frames;
1237 frames.push_back(QuicFrame(frame));
zhongyif06ca342020-02-24 14:11:13 -08001238 return ProcessFramesPacketWithAddresses(frames, self_address, peer_address);
1239 }
1240
1241 void ProcessFramesPacketWithAddresses(QuicFrames frames,
1242 QuicSocketAddress self_address,
1243 QuicSocketAddress peer_address) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001244 QuicPacketCreatorPeer::SetSendVersionInPacket(
wub031d47c2019-11-21 08:04:07 -08001245 &peer_creator_,
1246 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_) <
1247 ENCRYPTION_FORWARD_SECURE &&
1248 connection_.perspective() == Perspective::IS_SERVER);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001249
dschinazi66dea072019-04-09 11:41:06 -07001250 char buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05001251 SerializedPacket serialized_packet =
dschinazi66dea072019-04-09 11:41:06 -07001252 QuicPacketCreatorPeer::SerializeAllFrames(
1253 &peer_creator_, frames, buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001254 connection_.ProcessUdpPacket(
1255 self_address, peer_address,
1256 QuicReceivedPacket(serialized_packet.encrypted_buffer,
1257 serialized_packet.encrypted_length, clock_.Now()));
1258 if (connection_.GetSendAlarm()->IsSet()) {
1259 connection_.GetSendAlarm()->Fire();
1260 }
1261 }
1262
1263 // Bypassing the packet creator is unrealistic, but allows us to process
1264 // packets the QuicPacketCreator won't allow us to create.
1265 void ForceProcessFramePacket(QuicFrame frame) {
1266 QuicFrames frames;
1267 frames.push_back(QuicFrame(frame));
zhongyi546cc452019-04-12 15:27:49 -07001268 bool send_version = connection_.perspective() == Perspective::IS_SERVER;
1269 if (connection_.version().KnowsWhichDecrypterToUse()) {
1270 send_version = true;
1271 }
1272 QuicPacketCreatorPeer::SetSendVersionInPacket(&peer_creator_, send_version);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001273 QuicPacketHeader header;
1274 QuicPacketCreatorPeer::FillPacketHeader(&peer_creator_, &header);
dschinazi66dea072019-04-09 11:41:06 -07001275 char encrypted_buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05001276 size_t length = peer_framer_.BuildDataPacket(
dschinazi66dea072019-04-09 11:41:06 -07001277 header, frames, encrypted_buffer, kMaxOutgoingPacketSize,
1278 ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001279 DCHECK_GT(length, 0u);
1280
1281 const size_t encrypted_length = peer_framer_.EncryptInPlace(
QUICHE team6987b4a2019-03-15 16:23:04 -07001282 ENCRYPTION_INITIAL, header.packet_number,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001283 GetStartOfEncryptedData(peer_framer_.version().transport_version,
1284 header),
dschinazi66dea072019-04-09 11:41:06 -07001285 length, kMaxOutgoingPacketSize, encrypted_buffer);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001286 DCHECK_GT(encrypted_length, 0u);
1287
1288 connection_.ProcessUdpPacket(
1289 kSelfAddress, kPeerAddress,
1290 QuicReceivedPacket(encrypted_buffer, encrypted_length, clock_.Now()));
1291 }
1292
1293 size_t ProcessFramePacketAtLevel(uint64_t number,
1294 QuicFrame frame,
1295 EncryptionLevel level) {
fayang01062942020-01-22 07:23:23 -08001296 QuicFrames frames;
1297 frames.push_back(frame);
1298 return ProcessFramesPacketAtLevel(number, frames, level);
1299 }
1300
1301 size_t ProcessFramesPacketAtLevel(uint64_t number,
1302 const QuicFrames& frames,
1303 EncryptionLevel level) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001304 QuicPacketHeader header;
1305 header.destination_connection_id = connection_id_;
1306 header.packet_number_length = packet_number_length_;
1307 header.destination_connection_id_included = connection_id_included_;
dschinazi5e1a7b22019-07-31 12:23:21 -07001308 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001309 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1310 }
zhongyi546cc452019-04-12 15:27:49 -07001311 if (level == ENCRYPTION_INITIAL &&
1312 peer_framer_.version().KnowsWhichDecrypterToUse()) {
1313 header.version_flag = true;
nharperd43f1d62019-07-01 15:18:20 -07001314 if (QuicVersionHasLongHeaderLengths(peer_framer_.transport_version())) {
1315 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
1316 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
1317 }
QUICHE team2252b702019-05-14 23:55:14 -04001318 }
dschinazi5e1a7b22019-07-31 12:23:21 -07001319 if (header.version_flag &&
QUICHE team2252b702019-05-14 23:55:14 -04001320 peer_framer_.perspective() == Perspective::IS_SERVER) {
1321 header.source_connection_id = connection_id_;
1322 header.source_connection_id_included = CONNECTION_ID_PRESENT;
zhongyi546cc452019-04-12 15:27:49 -07001323 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001324 header.packet_number = QuicPacketNumber(number);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001325 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
QUICHE teamcd098022019-03-22 18:49:55 -07001326 // Set the correct encryption level and encrypter on peer_creator and
1327 // peer_framer, respectively.
1328 peer_creator_.set_encryption_level(level);
1329 if (QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_) >
1330 ENCRYPTION_INITIAL) {
1331 peer_framer_.SetEncrypter(
1332 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
vasilvv0fc587f2019-09-06 13:33:08 -07001333 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teamcd098022019-03-22 18:49:55 -07001334 // Set the corresponding decrypter.
zhongyi546cc452019-04-12 15:27:49 -07001335 if (connection_.version().KnowsWhichDecrypterToUse()) {
1336 connection_.InstallDecrypter(
1337 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
vasilvv0fc587f2019-09-06 13:33:08 -07001338 std::make_unique<StrictTaggingDecrypter>(0x01));
zhongyi546cc452019-04-12 15:27:49 -07001339 connection_.RemoveDecrypter(ENCRYPTION_INITIAL);
1340 } else {
1341 connection_.SetDecrypter(
1342 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
vasilvv0fc587f2019-09-06 13:33:08 -07001343 std::make_unique<StrictTaggingDecrypter>(0x01));
zhongyi546cc452019-04-12 15:27:49 -07001344 }
QUICHE teamcd098022019-03-22 18:49:55 -07001345 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001346
dschinazi66dea072019-04-09 11:41:06 -07001347 char buffer[kMaxOutgoingPacketSize];
1348 size_t encrypted_length =
1349 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
1350 buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001351 connection_.ProcessUdpPacket(
1352 kSelfAddress, kPeerAddress,
QUICHE teamcd098022019-03-22 18:49:55 -07001353 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1354 if (connection_.GetSendAlarm()->IsSet()) {
1355 connection_.GetSendAlarm()->Fire();
1356 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001357 return encrypted_length;
1358 }
1359
1360 size_t ProcessDataPacket(uint64_t number) {
nharper2c9f02a2019-05-08 10:25:50 -07001361 return ProcessDataPacketAtLevel(number, false, ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001362 }
1363
1364 size_t ProcessDataPacket(QuicPacketNumber packet_number) {
nharper2c9f02a2019-05-08 10:25:50 -07001365 return ProcessDataPacketAtLevel(packet_number, false,
1366 ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001367 }
1368
1369 size_t ProcessDataPacketAtLevel(QuicPacketNumber packet_number,
1370 bool has_stop_waiting,
1371 EncryptionLevel level) {
1372 return ProcessDataPacketAtLevel(packet_number.ToUint64(), has_stop_waiting,
1373 level);
1374 }
1375
dschinazi17d42422019-06-18 16:35:07 -07001376 size_t ProcessCryptoPacketAtLevel(uint64_t number,
1377 EncryptionLevel /*level*/) {
fayangc31c9952019-06-05 13:54:48 -07001378 QuicPacketHeader header = ConstructPacketHeader(number, ENCRYPTION_INITIAL);
nharper46833c32019-05-15 21:33:05 -07001379 QuicFrames frames;
1380 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1381 frames.push_back(QuicFrame(&crypto_frame_));
1382 } else {
1383 frames.push_back(QuicFrame(frame1_));
1384 }
fayang5f135052019-08-22 17:59:40 -07001385 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
nharper46833c32019-05-15 21:33:05 -07001386 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
1387 char buffer[kMaxOutgoingPacketSize];
1388 peer_creator_.set_encryption_level(ENCRYPTION_INITIAL);
fayangc31c9952019-06-05 13:54:48 -07001389 size_t encrypted_length = peer_framer_.EncryptPayload(
1390 ENCRYPTION_INITIAL, QuicPacketNumber(number), *packet, buffer,
1391 kMaxOutgoingPacketSize);
nharper46833c32019-05-15 21:33:05 -07001392 connection_.ProcessUdpPacket(
1393 kSelfAddress, kPeerAddress,
1394 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1395 if (connection_.GetSendAlarm()->IsSet()) {
1396 connection_.GetSendAlarm()->Fire();
1397 }
1398 return encrypted_length;
1399 }
1400
QUICHE teama6ef0a62019-03-07 20:34:33 -05001401 size_t ProcessDataPacketAtLevel(uint64_t number,
1402 bool has_stop_waiting,
1403 EncryptionLevel level) {
1404 std::unique_ptr<QuicPacket> packet(
QUICHE team8c1daa22019-03-13 08:33:41 -07001405 ConstructDataPacket(number, has_stop_waiting, level));
dschinazi66dea072019-04-09 11:41:06 -07001406 char buffer[kMaxOutgoingPacketSize];
QUICHE teamcd098022019-03-22 18:49:55 -07001407 peer_creator_.set_encryption_level(level);
dschinazi66dea072019-04-09 11:41:06 -07001408 size_t encrypted_length =
1409 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
1410 buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001411 connection_.ProcessUdpPacket(
1412 kSelfAddress, kPeerAddress,
1413 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1414 if (connection_.GetSendAlarm()->IsSet()) {
1415 connection_.GetSendAlarm()->Fire();
1416 }
1417 return encrypted_length;
1418 }
1419
1420 void ProcessClosePacket(uint64_t number) {
1421 std::unique_ptr<QuicPacket> packet(ConstructClosePacket(number));
dschinazi66dea072019-04-09 11:41:06 -07001422 char buffer[kMaxOutgoingPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07001423 size_t encrypted_length = peer_framer_.EncryptPayload(
nharperc6b99512019-09-19 11:13:48 -07001424 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(number), *packet, buffer,
dschinazi66dea072019-04-09 11:41:06 -07001425 kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001426 connection_.ProcessUdpPacket(
1427 kSelfAddress, kPeerAddress,
1428 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
1429 }
1430
1431 QuicByteCount SendStreamDataToPeer(QuicStreamId id,
dmcardlecf0bfcf2019-12-13 08:08:21 -08001432 quiche::QuicheStringPiece data,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001433 QuicStreamOffset offset,
1434 StreamSendingState state,
1435 QuicPacketNumber* last_packet) {
1436 QuicByteCount packet_size;
fayang0fcbf352019-08-30 11:15:58 -07001437 // Save the last packet's size.
QUICHE teama6ef0a62019-03-07 20:34:33 -05001438 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
fayang0fcbf352019-08-30 11:15:58 -07001439 .Times(AnyNumber())
1440 .WillRepeatedly(SaveArg<3>(&packet_size));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001441 connection_.SendStreamDataWithString(id, data, offset, state);
1442 if (last_packet != nullptr) {
1443 *last_packet = creator_->packet_number();
1444 }
1445 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1446 .Times(AnyNumber());
1447 return packet_size;
1448 }
1449
1450 void SendAckPacketToPeer() {
1451 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1452 {
fayanga4b37b22019-06-18 13:37:47 -07001453 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001454 connection_.SendAck();
1455 }
1456 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1457 .Times(AnyNumber());
1458 }
1459
1460 void SendRstStream(QuicStreamId id,
1461 QuicRstStreamErrorCode error,
1462 QuicStreamOffset bytes_written) {
fayangcff885a2019-10-22 07:39:04 -07001463 notifier_.WriteOrBufferRstStream(id, error, bytes_written);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001464 connection_.OnStreamReset(id, error);
1465 }
1466
fayangcff885a2019-10-22 07:39:04 -07001467 void SendPing() { notifier_.WriteOrBufferPing(); }
zhongyifbb25772019-04-10 16:54:08 -07001468
fayang61453cb2020-03-11 11:32:26 -07001469 MessageStatus SendMessage(quiche::QuicheStringPiece message) {
1470 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1471 QuicMemSliceStorage storage(nullptr, 0, nullptr, 0);
1472 return connection_.SendMessage(
1473 1,
1474 MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(), message,
1475 &storage),
1476 false);
1477 }
1478
QUICHE teama6ef0a62019-03-07 20:34:33 -05001479 void ProcessAckPacket(uint64_t packet_number, QuicAckFrame* frame) {
1480 if (packet_number > 1) {
1481 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, packet_number - 1);
1482 } else {
1483 QuicPacketCreatorPeer::ClearPacketNumber(&peer_creator_);
1484 }
1485 ProcessFramePacket(QuicFrame(frame));
1486 }
1487
1488 void ProcessAckPacket(QuicAckFrame* frame) {
1489 ProcessFramePacket(QuicFrame(frame));
1490 }
1491
1492 void ProcessStopWaitingPacket(QuicStopWaitingFrame frame) {
1493 ProcessFramePacket(QuicFrame(frame));
1494 }
1495
1496 size_t ProcessStopWaitingPacketAtLevel(uint64_t number,
1497 QuicStopWaitingFrame frame,
dschinazi17d42422019-06-18 16:35:07 -07001498 EncryptionLevel /*level*/) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001499 return ProcessFramePacketAtLevel(number, QuicFrame(frame),
1500 ENCRYPTION_ZERO_RTT);
1501 }
1502
1503 void ProcessGoAwayPacket(QuicGoAwayFrame* frame) {
1504 ProcessFramePacket(QuicFrame(frame));
1505 }
1506
1507 bool IsMissing(uint64_t number) {
fayangc31c9952019-06-05 13:54:48 -07001508 return IsAwaitingPacket(connection_.ack_frame(), QuicPacketNumber(number),
QUICHE teama6ef0a62019-03-07 20:34:33 -05001509 QuicPacketNumber());
1510 }
1511
1512 std::unique_ptr<QuicPacket> ConstructPacket(const QuicPacketHeader& header,
1513 const QuicFrames& frames) {
1514 auto packet = BuildUnsizedDataPacket(&peer_framer_, header, frames);
1515 EXPECT_NE(nullptr, packet.get());
1516 return packet;
1517 }
1518
nharper46833c32019-05-15 21:33:05 -07001519 QuicPacketHeader ConstructPacketHeader(uint64_t number,
1520 EncryptionLevel level) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001521 QuicPacketHeader header;
fayangd4291e42019-05-30 10:31:21 -07001522 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version()) &&
QUICHE team8c1daa22019-03-13 08:33:41 -07001523 level < ENCRYPTION_FORWARD_SECURE) {
1524 // Set long header type accordingly.
1525 header.version_flag = true;
nharperc6b99512019-09-19 11:13:48 -07001526 header.form = IETF_QUIC_LONG_HEADER_PACKET;
QUICHE team8c1daa22019-03-13 08:33:41 -07001527 header.long_packet_type = EncryptionlevelToLongHeaderType(level);
1528 if (QuicVersionHasLongHeaderLengths(
1529 peer_framer_.version().transport_version)) {
1530 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
1531 if (header.long_packet_type == INITIAL) {
1532 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
1533 }
1534 }
1535 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001536 // Set connection_id to peer's in memory representation as this data packet
1537 // is created by peer_framer.
dschinazi5e1a7b22019-07-31 12:23:21 -07001538 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
QUICHE team2252b702019-05-14 23:55:14 -04001539 header.source_connection_id = connection_id_;
1540 header.source_connection_id_included = connection_id_included_;
1541 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1542 } else {
1543 header.destination_connection_id = connection_id_;
1544 header.destination_connection_id_included = connection_id_included_;
1545 }
fayangd4291e42019-05-30 10:31:21 -07001546 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version()) &&
QUICHE teama6ef0a62019-03-07 20:34:33 -05001547 peer_framer_.perspective() == Perspective::IS_SERVER) {
1548 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
QUICHE team8c1daa22019-03-13 08:33:41 -07001549 if (header.version_flag) {
1550 header.source_connection_id = connection_id_;
1551 header.source_connection_id_included = CONNECTION_ID_PRESENT;
1552 if (GetParam().version.handshake_protocol == PROTOCOL_QUIC_CRYPTO &&
1553 header.long_packet_type == ZERO_RTT_PROTECTED) {
QUICHE team548d51b2019-03-14 10:06:54 -07001554 header.nonce = &kTestDiversificationNonce;
QUICHE team8c1daa22019-03-13 08:33:41 -07001555 }
1556 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001557 }
QUICHE team2252b702019-05-14 23:55:14 -04001558 header.packet_number_length = packet_number_length_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001559 header.packet_number = QuicPacketNumber(number);
nharper46833c32019-05-15 21:33:05 -07001560 return header;
1561 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001562
nharper46833c32019-05-15 21:33:05 -07001563 std::unique_ptr<QuicPacket> ConstructDataPacket(uint64_t number,
1564 bool has_stop_waiting,
1565 EncryptionLevel level) {
1566 QuicPacketHeader header = ConstructPacketHeader(number, level);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001567 QuicFrames frames;
1568 frames.push_back(QuicFrame(frame1_));
1569 if (has_stop_waiting) {
1570 frames.push_back(QuicFrame(stop_waiting_));
1571 }
1572 return ConstructPacket(header, frames);
1573 }
1574
wub8a5dafa2020-05-13 12:30:17 -07001575 std::unique_ptr<SerializedPacket> ConstructProbingPacket() {
fkastenholz305e1732019-06-18 05:01:22 -07001576 if (VersionHasIetfQuicFrames(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001577 QuicPathFrameBuffer payload = {
1578 {0xde, 0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xfe}};
1579 return QuicPacketCreatorPeer::
1580 SerializePathChallengeConnectivityProbingPacket(&peer_creator_,
1581 &payload);
1582 }
1583 return QuicPacketCreatorPeer::SerializeConnectivityProbingPacket(
1584 &peer_creator_);
1585 }
1586
1587 std::unique_ptr<QuicPacket> ConstructClosePacket(uint64_t number) {
1588 QuicPacketHeader header;
1589 // Set connection_id to peer's in memory representation as this connection
1590 // close packet is created by peer_framer.
dschinazi5e1a7b22019-07-31 12:23:21 -07001591 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
QUICHE team2252b702019-05-14 23:55:14 -04001592 header.source_connection_id = connection_id_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001593 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
fayangd4291e42019-05-30 10:31:21 -07001594 if (!VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04001595 header.source_connection_id_included = CONNECTION_ID_PRESENT;
1596 }
1597 } else {
1598 header.destination_connection_id = connection_id_;
fayangd4291e42019-05-30 10:31:21 -07001599 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04001600 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1601 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001602 }
1603
QUICHE team2252b702019-05-14 23:55:14 -04001604 header.packet_number = QuicPacketNumber(number);
1605
fkastenholz0d6554a2019-08-05 12:20:35 -07001606 QuicErrorCode kQuicErrorCode = QUIC_PEER_GOING_AWAY;
fkastenholz591814c2019-09-06 12:11:46 -07001607 QuicConnectionCloseFrame qccf(peer_framer_.transport_version(),
1608 kQuicErrorCode, "",
1609 /*transport_close_frame_type=*/0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001610 QuicFrames frames;
1611 frames.push_back(QuicFrame(&qccf));
1612 return ConstructPacket(header, frames);
1613 }
1614
1615 QuicTime::Delta DefaultRetransmissionTime() {
1616 return QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
1617 }
1618
1619 QuicTime::Delta DefaultDelayedAckTime() {
1620 return QuicTime::Delta::FromMilliseconds(kDefaultDelayedAckTimeMs);
1621 }
1622
1623 const QuicStopWaitingFrame InitStopWaitingFrame(uint64_t least_unacked) {
1624 QuicStopWaitingFrame frame;
1625 frame.least_unacked = QuicPacketNumber(least_unacked);
1626 return frame;
1627 }
1628
1629 // Construct a ack_frame that acks all packet numbers between 1 and
1630 // |largest_acked|, except |missing|.
1631 // REQUIRES: 1 <= |missing| < |largest_acked|
1632 QuicAckFrame ConstructAckFrame(uint64_t largest_acked, uint64_t missing) {
1633 return ConstructAckFrame(QuicPacketNumber(largest_acked),
1634 QuicPacketNumber(missing));
1635 }
1636
1637 QuicAckFrame ConstructAckFrame(QuicPacketNumber largest_acked,
1638 QuicPacketNumber missing) {
1639 if (missing == QuicPacketNumber(1)) {
1640 return InitAckFrame({{missing + 1, largest_acked + 1}});
1641 }
1642 return InitAckFrame(
1643 {{QuicPacketNumber(1), missing}, {missing + 1, largest_acked + 1}});
1644 }
1645
1646 // Undo nacking a packet within the frame.
1647 void AckPacket(QuicPacketNumber arrived, QuicAckFrame* frame) {
1648 EXPECT_FALSE(frame->packets.Contains(arrived));
1649 frame->packets.Add(arrived);
1650 }
1651
1652 void TriggerConnectionClose() {
1653 // Send an erroneous packet to close the connection.
fkastenholz5d880a92019-06-21 09:01:56 -07001654 EXPECT_CALL(visitor_,
1655 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
1656 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
1657
QUICHE teamcd098022019-03-22 18:49:55 -07001658 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1659 // Triggers a connection by receiving ACK of unsent packet.
1660 QuicAckFrame frame = InitAckFrame(10000);
1661 ProcessAckPacket(1, &frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001662 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1663 nullptr);
fkastenholz5d880a92019-06-21 09:01:56 -07001664 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08001665 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
1666 IsError(QUIC_INVALID_ACK_DATA));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001667 }
1668
1669 void BlockOnNextWrite() {
1670 writer_->BlockOnNextWrite();
1671 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
1672 }
1673
1674 void SimulateNextPacketTooLarge() { writer_->SimulateNextPacketTooLarge(); }
1675
1676 void AlwaysGetPacketTooLarge() { writer_->AlwaysGetPacketTooLarge(); }
1677
1678 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
1679 writer_->SetWritePauseTimeDelta(delta);
1680 }
1681
1682 void CongestionBlockWrites() {
1683 EXPECT_CALL(*send_algorithm_, CanSend(_))
1684 .WillRepeatedly(testing::Return(false));
1685 }
1686
1687 void CongestionUnblockWrites() {
1688 EXPECT_CALL(*send_algorithm_, CanSend(_))
1689 .WillRepeatedly(testing::Return(true));
1690 }
1691
1692 void set_perspective(Perspective perspective) {
1693 connection_.set_perspective(perspective);
1694 if (perspective == Perspective::IS_SERVER) {
1695 connection_.set_can_truncate_connection_ids(true);
wub256b2d62019-11-25 08:46:55 -08001696 QuicConnectionPeer::SetNegotiatedVersion(&connection_);
wubbea386e2020-01-27 09:04:51 -08001697 connection_.OnSuccessfulVersionNegotiation();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001698 }
1699 QuicFramerPeer::SetPerspective(&peer_framer_,
nharper4eba09b2019-06-26 20:17:25 -07001700 QuicUtils::InvertPerspective(perspective));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001701 }
1702
1703 void set_packets_between_probes_base(
1704 const QuicPacketCount packets_between_probes_base) {
wub173916e2019-11-27 14:36:24 -08001705 QuicConnectionPeer::ReInitializeMtuDiscoverer(
1706 &connection_, packets_between_probes_base,
1707 QuicPacketNumber(packets_between_probes_base));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001708 }
1709
1710 bool IsDefaultTestConfiguration() {
1711 TestParams p = GetParam();
1712 return p.ack_response == AckResponse::kImmediate &&
1713 p.version == AllSupportedVersions()[0] && p.no_stop_waiting;
1714 }
1715
fkastenholz5d880a92019-06-21 09:01:56 -07001716 void TestConnectionCloseQuicErrorCode(QuicErrorCode expected_code) {
1717 // Not strictly needed for this test, but is commonly done.
1718 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1719 nullptr);
1720 const std::vector<QuicConnectionCloseFrame>& connection_close_frames =
1721 writer_->connection_close_frames();
1722 ASSERT_EQ(1u, connection_close_frames.size());
bnc77e77b82020-04-05 10:36:49 -07001723
dschinazi39e5e552020-05-06 13:55:24 -07001724 EXPECT_THAT(connection_close_frames[0].quic_error_code,
1725 IsError(expected_code));
bnc77e77b82020-04-05 10:36:49 -07001726
fkastenholz0d6554a2019-08-05 12:20:35 -07001727 if (!VersionHasIetfQuicFrames(version().transport_version)) {
dschinazi39e5e552020-05-06 13:55:24 -07001728 EXPECT_THAT(connection_close_frames[0].wire_error_code,
1729 IsError(expected_code));
fkastenholz0d6554a2019-08-05 12:20:35 -07001730 EXPECT_EQ(GOOGLE_QUIC_CONNECTION_CLOSE,
1731 connection_close_frames[0].close_type);
1732 return;
1733 }
1734
1735 QuicErrorCodeToIetfMapping mapping =
1736 QuicErrorCodeToTransportErrorCode(expected_code);
1737
bnc0054cc62020-04-09 18:22:57 -07001738 if (mapping.is_transport_close) {
fkastenholz0d6554a2019-08-05 12:20:35 -07001739 // This Google QUIC Error Code maps to a transport close,
1740 EXPECT_EQ(IETF_QUIC_TRANSPORT_CONNECTION_CLOSE,
1741 connection_close_frames[0].close_type);
fkastenholz0d6554a2019-08-05 12:20:35 -07001742 } else {
1743 // This maps to an application close.
fkastenholz0d6554a2019-08-05 12:20:35 -07001744 EXPECT_EQ(IETF_QUIC_APPLICATION_CONNECTION_CLOSE,
1745 connection_close_frames[0].close_type);
fkastenholz0d6554a2019-08-05 12:20:35 -07001746 }
bnc0054cc62020-04-09 18:22:57 -07001747 EXPECT_EQ(mapping.error_code, connection_close_frames[0].wire_error_code);
fkastenholz5d880a92019-06-21 09:01:56 -07001748 }
1749
wub031d47c2019-11-21 08:04:07 -08001750 void MtuDiscoveryTestInit() {
1751 set_perspective(Perspective::IS_SERVER);
wub031d47c2019-11-21 08:04:07 -08001752 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
fayang6a258412020-05-28 08:57:12 -07001753 if (version().SupportsAntiAmplificationLimit()) {
1754 QuicConnectionPeer::SetAddressValidated(&connection_);
1755 }
wub031d47c2019-11-21 08:04:07 -08001756 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1757 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
1758 // QuicFramer::GetMaxPlaintextSize uses the smallest max plaintext size
1759 // across all encrypters. The initial encrypter used with IETF QUIC has a
1760 // 16-byte overhead, while the NullEncrypter used throughout this test has a
1761 // 12-byte overhead. This test tests behavior that relies on computing the
1762 // packet size correctly, so by unsetting the initial encrypter, we avoid
1763 // having a mismatch between the overheads for the encrypters used. In
1764 // non-test scenarios all encrypters used for a given connection have the
1765 // same overhead, either 12 bytes for ones using Google QUIC crypto, or 16
1766 // bytes for ones using TLS.
1767 connection_.SetEncrypter(ENCRYPTION_INITIAL, nullptr);
wubecb643f2020-03-19 08:58:46 -07001768 // Prevent packets from being coalesced.
1769 EXPECT_CALL(visitor_, GetHandshakeState())
1770 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
wub031d47c2019-11-21 08:04:07 -08001771 EXPECT_TRUE(connection_.connected());
1772 }
1773
dschinazi1c6e5922020-06-19 10:35:03 -07001774 void PathProbeTestInit(Perspective perspective) {
1775 set_perspective(perspective);
1776 EXPECT_EQ(connection_.perspective(), perspective);
1777 if (perspective == Perspective::IS_SERVER) {
1778 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1779 }
1780 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1781 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
1782 }
1783
dschinazi39e5e552020-05-06 13:55:24 -07001784 void TestClientRetryHandling(bool invalid_retry_tag,
dschinazie7c38a52020-05-29 15:25:45 -07001785 bool missing_original_id_in_config,
1786 bool wrong_original_id_in_config,
1787 bool missing_retry_id_in_config,
1788 bool wrong_retry_id_in_config);
dschinazi39e5e552020-05-06 13:55:24 -07001789
QUICHE teama6ef0a62019-03-07 20:34:33 -05001790 QuicConnectionId connection_id_;
1791 QuicFramer framer_;
1792
1793 MockSendAlgorithm* send_algorithm_;
1794 std::unique_ptr<MockLossAlgorithm> loss_algorithm_;
1795 MockClock clock_;
1796 MockRandom random_generator_;
1797 SimpleBufferAllocator buffer_allocator_;
1798 std::unique_ptr<TestConnectionHelper> helper_;
1799 std::unique_ptr<TestAlarmFactory> alarm_factory_;
1800 QuicFramer peer_framer_;
1801 QuicPacketCreator peer_creator_;
1802 std::unique_ptr<TestPacketWriter> writer_;
1803 TestConnection connection_;
1804 QuicPacketCreator* creator_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001805 QuicSentPacketManager* manager_;
1806 StrictMock<MockQuicConnectionVisitor> visitor_;
1807
1808 QuicStreamFrame frame1_;
1809 QuicStreamFrame frame2_;
nharper46833c32019-05-15 21:33:05 -07001810 QuicCryptoFrame crypto_frame_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001811 QuicAckFrame ack_;
1812 QuicStopWaitingFrame stop_waiting_;
1813 QuicPacketNumberLength packet_number_length_;
1814 QuicConnectionIdIncluded connection_id_included_;
1815
1816 SimpleSessionNotifier notifier_;
fkastenholz5d880a92019-06-21 09:01:56 -07001817
1818 QuicConnectionCloseFrame saved_connection_close_frame_;
1819 int connection_close_frame_count_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001820};
1821
1822// Run all end to end tests with all supported versions.
dschinazi39e5e552020-05-06 13:55:24 -07001823INSTANTIATE_TEST_SUITE_P(QuicConnectionTests,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001824 QuicConnectionTest,
dschinazi142051a2019-09-18 18:17:29 -07001825 ::testing::ValuesIn(GetTestParams()),
1826 ::testing::PrintToStringParamName());
QUICHE teama6ef0a62019-03-07 20:34:33 -05001827
fkastenholz0d6554a2019-08-05 12:20:35 -07001828// These two tests ensure that the QuicErrorCode mapping works correctly.
1829// Both tests expect to see a Google QUIC close if not running IETF QUIC.
1830// If running IETF QUIC, the first will generate a transport connection
1831// close, the second an application connection close.
1832// The connection close codes for the two tests are manually chosen;
1833// they are expected to always map to transport- and application-
dschinazi39e5e552020-05-06 13:55:24 -07001834// closes, respectively. If that changes, new codes should be chosen.
fkastenholz0d6554a2019-08-05 12:20:35 -07001835TEST_P(QuicConnectionTest, CloseErrorCodeTestTransport) {
1836 EXPECT_TRUE(connection_.connected());
1837 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
1838 connection_.CloseConnection(
1839 IETF_QUIC_PROTOCOL_VIOLATION, "Should be transport close",
1840 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1841 EXPECT_FALSE(connection_.connected());
1842 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
1843}
1844
1845// Test that the IETF QUIC Error code mapping function works
1846// properly for application connection close codes.
1847TEST_P(QuicConnectionTest, CloseErrorCodeTestApplication) {
1848 EXPECT_TRUE(connection_.connected());
1849 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
1850 connection_.CloseConnection(
1851 QUIC_HEADERS_STREAM_DATA_DECOMPRESS_FAILURE,
1852 "Should be application close",
1853 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1854 EXPECT_FALSE(connection_.connected());
1855 TestConnectionCloseQuicErrorCode(QUIC_HEADERS_STREAM_DATA_DECOMPRESS_FAILURE);
1856}
1857
QUICHE teama6ef0a62019-03-07 20:34:33 -05001858TEST_P(QuicConnectionTest, SelfAddressChangeAtClient) {
1859 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1860
1861 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
1862 EXPECT_TRUE(connection_.connected());
1863
nharper46833c32019-05-15 21:33:05 -07001864 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07001865 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1866 } else {
nharper46833c32019-05-15 21:33:05 -07001867 EXPECT_CALL(visitor_, OnStreamFrame(_));
1868 }
wub8a5dafa2020-05-13 12:30:17 -07001869 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
1870 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001871 // Cause change in self_address.
1872 QuicIpAddress host;
1873 host.FromString("1.1.1.1");
1874 QuicSocketAddress self_address(host, 123);
nharper46833c32019-05-15 21:33:05 -07001875 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1876 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1877 } else {
1878 EXPECT_CALL(visitor_, OnStreamFrame(_));
1879 }
wub8a5dafa2020-05-13 12:30:17 -07001880 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address,
1881 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001882 EXPECT_TRUE(connection_.connected());
1883}
1884
1885TEST_P(QuicConnectionTest, SelfAddressChangeAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001886 set_perspective(Perspective::IS_SERVER);
1887 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1888
1889 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1890 EXPECT_TRUE(connection_.connected());
1891
nharper46833c32019-05-15 21:33:05 -07001892 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07001893 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1894 } else {
nharper46833c32019-05-15 21:33:05 -07001895 EXPECT_CALL(visitor_, OnStreamFrame(_));
1896 }
wub8a5dafa2020-05-13 12:30:17 -07001897 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
1898 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001899 // Cause change in self_address.
1900 QuicIpAddress host;
1901 host.FromString("1.1.1.1");
1902 QuicSocketAddress self_address(host, 123);
1903 EXPECT_CALL(visitor_, AllowSelfAddressChange()).WillOnce(Return(false));
fkastenholz5d880a92019-06-21 09:01:56 -07001904 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
wub8a5dafa2020-05-13 12:30:17 -07001905 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address,
1906 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001907 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07001908 TestConnectionCloseQuicErrorCode(QUIC_ERROR_MIGRATING_ADDRESS);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001909}
1910
1911TEST_P(QuicConnectionTest, AllowSelfAddressChangeToMappedIpv4AddressAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001912 set_perspective(Perspective::IS_SERVER);
1913 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1914
1915 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1916 EXPECT_TRUE(connection_.connected());
1917
nharper46833c32019-05-15 21:33:05 -07001918 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07001919 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(3);
1920 } else {
nharper46833c32019-05-15 21:33:05 -07001921 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(3);
1922 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001923 QuicIpAddress host;
1924 host.FromString("1.1.1.1");
1925 QuicSocketAddress self_address1(host, 443);
wub8a5dafa2020-05-13 12:30:17 -07001926 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address1,
1927 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001928 // Cause self_address change to mapped Ipv4 address.
1929 QuicIpAddress host2;
dmcardlecf0bfcf2019-12-13 08:08:21 -08001930 host2.FromString(quiche::QuicheStrCat(
1931 "::ffff:", connection_.self_address().host().ToString()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001932 QuicSocketAddress self_address2(host2, connection_.self_address().port());
wub8a5dafa2020-05-13 12:30:17 -07001933 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address2,
1934 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001935 EXPECT_TRUE(connection_.connected());
1936 // self_address change back to Ipv4 address.
wub8a5dafa2020-05-13 12:30:17 -07001937 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address1,
1938 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001939 EXPECT_TRUE(connection_.connected());
1940}
1941
1942TEST_P(QuicConnectionTest, ClientAddressChangeAndPacketReordered) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001943 set_perspective(Perspective::IS_SERVER);
1944 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1945
1946 // Clear direct_peer_address.
1947 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1948 // Clear effective_peer_address, it is the same as direct_peer_address for
1949 // this test.
1950 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1951 QuicSocketAddress());
1952
nharper46833c32019-05-15 21:33:05 -07001953 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07001954 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1955 } else {
nharper46833c32019-05-15 21:33:05 -07001956 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1957 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001958 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001959 const QuicSocketAddress kNewPeerAddress =
1960 QuicSocketAddress(QuicIpAddress::Loopback6(),
1961 /*port=*/23456);
wub8a5dafa2020-05-13 12:30:17 -07001962 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
1963 kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001964 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1965 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1966
1967 // Decrease packet number to simulate out-of-order packets.
1968 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 4);
1969 // This is an old packet, do not migrate.
1970 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
wub8a5dafa2020-05-13 12:30:17 -07001971 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
1972 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001973 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1974 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1975}
1976
1977TEST_P(QuicConnectionTest, PeerAddressChangeAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001978 set_perspective(Perspective::IS_SERVER);
1979 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1980 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1981
1982 // Clear direct_peer_address.
1983 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1984 // Clear effective_peer_address, it is the same as direct_peer_address for
1985 // this test.
1986 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1987 QuicSocketAddress());
1988 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1989
nharper46833c32019-05-15 21:33:05 -07001990 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07001991 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1992 } else {
nharper46833c32019-05-15 21:33:05 -07001993 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1994 }
wub8a5dafa2020-05-13 12:30:17 -07001995 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
1996 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001997 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1998 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1999
2000 // Process another packet with a different peer address on server side will
2001 // start connection migration.
2002 const QuicSocketAddress kNewPeerAddress =
2003 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2004 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
wub8a5dafa2020-05-13 12:30:17 -07002005 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2006 kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002007 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2008 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2009}
2010
2011TEST_P(QuicConnectionTest, EffectivePeerAddressChangeAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002012 set_perspective(Perspective::IS_SERVER);
2013 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2014 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
fayang6a258412020-05-28 08:57:12 -07002015 if (version().SupportsAntiAmplificationLimit()) {
2016 QuicConnectionPeer::SetAddressValidated(&connection_);
2017 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002018
2019 // Clear direct_peer_address.
2020 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2021 // Clear effective_peer_address, it is different from direct_peer_address for
2022 // this test.
2023 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2024 QuicSocketAddress());
2025 const QuicSocketAddress kEffectivePeerAddress =
2026 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/43210);
2027 connection_.ReturnEffectivePeerAddressForNextPacket(kEffectivePeerAddress);
2028
nharper46833c32019-05-15 21:33:05 -07002029 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07002030 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2031 } else {
nharper46833c32019-05-15 21:33:05 -07002032 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2033 }
wub8a5dafa2020-05-13 12:30:17 -07002034 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2035 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002036 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2037 EXPECT_EQ(kEffectivePeerAddress, connection_.effective_peer_address());
2038
2039 // Process another packet with the same direct peer address and different
2040 // effective peer address on server side will start connection migration.
2041 const QuicSocketAddress kNewEffectivePeerAddress =
2042 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/54321);
2043 connection_.ReturnEffectivePeerAddressForNextPacket(kNewEffectivePeerAddress);
2044 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
wub8a5dafa2020-05-13 12:30:17 -07002045 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2046 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002047 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2048 EXPECT_EQ(kNewEffectivePeerAddress, connection_.effective_peer_address());
2049
2050 // Process another packet with a different direct peer address and the same
2051 // effective peer address on server side will not start connection migration.
2052 const QuicSocketAddress kNewPeerAddress =
2053 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2054 connection_.ReturnEffectivePeerAddressForNextPacket(kNewEffectivePeerAddress);
2055 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2056 // ack_frame is used to complete the migration started by the last packet, we
2057 // need to make sure a new migration does not start after the previous one is
2058 // completed.
2059 QuicAckFrame ack_frame = InitAckFrame(1);
2060 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
2061 ProcessFramePacketWithAddresses(QuicFrame(&ack_frame), kSelfAddress,
2062 kNewPeerAddress);
2063 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2064 EXPECT_EQ(kNewEffectivePeerAddress, connection_.effective_peer_address());
2065
2066 // Process another packet with different direct peer address and different
2067 // effective peer address on server side will start connection migration.
2068 const QuicSocketAddress kNewerEffectivePeerAddress =
2069 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/65432);
2070 const QuicSocketAddress kFinalPeerAddress =
2071 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/34567);
2072 connection_.ReturnEffectivePeerAddressForNextPacket(
2073 kNewerEffectivePeerAddress);
2074 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
wub8a5dafa2020-05-13 12:30:17 -07002075 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2076 kFinalPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002077 EXPECT_EQ(kFinalPeerAddress, connection_.peer_address());
2078 EXPECT_EQ(kNewerEffectivePeerAddress, connection_.effective_peer_address());
2079 EXPECT_EQ(PORT_CHANGE, connection_.active_effective_peer_migration_type());
2080
2081 // While the previous migration is ongoing, process another packet with the
2082 // same direct peer address and different effective peer address on server
2083 // side will start a new connection migration.
2084 const QuicSocketAddress kNewestEffectivePeerAddress =
2085 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/65430);
2086 connection_.ReturnEffectivePeerAddressForNextPacket(
2087 kNewestEffectivePeerAddress);
2088 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
2089 EXPECT_CALL(*send_algorithm_, OnConnectionMigration()).Times(1);
wub8a5dafa2020-05-13 12:30:17 -07002090 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2091 kFinalPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002092 EXPECT_EQ(kFinalPeerAddress, connection_.peer_address());
2093 EXPECT_EQ(kNewestEffectivePeerAddress, connection_.effective_peer_address());
2094 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
2095 connection_.active_effective_peer_migration_type());
2096}
2097
zhongyif06ca342020-02-24 14:11:13 -08002098TEST_P(QuicConnectionTest, ReceivePathProbeWithNoAddressChangeAtServer) {
dschinazi1c6e5922020-06-19 10:35:03 -07002099 PathProbeTestInit(Perspective::IS_SERVER);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002100
2101 // Clear direct_peer_address.
2102 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2103 // Clear effective_peer_address, it is the same as direct_peer_address for
2104 // this test.
2105 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2106 QuicSocketAddress());
2107 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2108
nharper46833c32019-05-15 21:33:05 -07002109 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07002110 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2111 } else {
nharper46833c32019-05-15 21:33:05 -07002112 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2113 }
wub8a5dafa2020-05-13 12:30:17 -07002114 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2115 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002116 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2117 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2118
2119 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyi83161e42019-08-19 09:06:25 -07002120 EXPECT_CALL(visitor_, OnPacketReceived(_, _, false)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002121
2122 // Process a padded PING or PATH CHALLENGE packet with no peer address change
2123 // on server side will be ignored.
wub8a5dafa2020-05-13 12:30:17 -07002124 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
zhongyif06ca342020-02-24 14:11:13 -08002125
QUICHE teama6ef0a62019-03-07 20:34:33 -05002126 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2127 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2128 probing_packet->encrypted_length),
2129 clock_.Now()));
2130
2131 uint64_t num_probing_received =
2132 connection_.GetStats().num_connectivity_probing_received;
2133 ProcessReceivedPacket(kSelfAddress, kPeerAddress, *received);
2134
2135 EXPECT_EQ(num_probing_received,
2136 connection_.GetStats().num_connectivity_probing_received);
2137 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2138 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2139}
2140
wub54bd5bf2020-05-13 13:02:16 -07002141// Regression test for b/150161358.
2142TEST_P(QuicConnectionTest, BufferedMtuPacketTooBig) {
wub54bd5bf2020-05-13 13:02:16 -07002143 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
2144 writer_->SetWriteBlocked();
2145
2146 // Send a MTU packet while blocked. It should be buffered.
2147 connection_.SendMtuDiscoveryPacket(kMaxOutgoingPacketSize);
2148 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2149 EXPECT_TRUE(writer_->IsWriteBlocked());
2150
2151 writer_->AlwaysGetPacketTooLarge();
2152 writer_->SetWritable();
2153 connection_.OnCanWrite();
2154}
2155
QUICHE teama6ef0a62019-03-07 20:34:33 -05002156TEST_P(QuicConnectionTest, WriteOutOfOrderQueuedPackets) {
2157 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
fayangc31c9952019-06-05 13:54:48 -07002158 if (!IsDefaultTestConfiguration()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002159 return;
2160 }
2161
2162 set_perspective(Perspective::IS_CLIENT);
2163
2164 BlockOnNextWrite();
2165
2166 QuicStreamId stream_id = 2;
2167 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
2168
2169 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2170
2171 writer_->SetWritable();
2172 connection_.SendConnectivityProbingPacket(writer_.get(),
2173 connection_.peer_address());
fayange62e63c2019-12-04 07:16:25 -08002174 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
2175 connection_.OnCanWrite();
QUICHE teama6ef0a62019-03-07 20:34:33 -05002176}
2177
2178TEST_P(QuicConnectionTest, DiscardQueuedPacketsAfterConnectionClose) {
2179 // Regression test for b/74073386.
2180 {
2181 InSequence seq;
rch39c88ab2019-10-16 19:24:40 -07002182 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2183 .Times(AtLeast(1));
2184 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002185 }
2186
2187 set_perspective(Perspective::IS_CLIENT);
2188
2189 writer_->SimulateNextPacketTooLarge();
2190
2191 // This packet write should fail, which should cause the connection to close
2192 // after sending a connection close packet, then the failed packet should be
2193 // queued.
2194 connection_.SendStreamDataWithString(/*id=*/2, "foo", 0, NO_FIN);
2195
2196 EXPECT_FALSE(connection_.connected());
fayange62e63c2019-12-04 07:16:25 -08002197 // No need to buffer packets.
2198 EXPECT_EQ(0u, connection_.NumQueuedPackets());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002199
2200 EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
2201 connection_.OnCanWrite();
fayang0f0c4e62019-07-16 08:55:54 -07002202 EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002203}
2204
zhongyif06ca342020-02-24 14:11:13 -08002205// Receive a path probe request at the server side, i.e.,
2206// in non-IETF version: receive a padded PING packet with a peer addess change;
2207// in IETF version: receive a packet contains PATH CHALLENGE with peer address
2208// change.
2209TEST_P(QuicConnectionTest, ReceivePathProbingAtServer) {
dschinazi1c6e5922020-06-19 10:35:03 -07002210 PathProbeTestInit(Perspective::IS_SERVER);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002211
2212 // Clear direct_peer_address.
2213 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2214 // Clear effective_peer_address, it is the same as direct_peer_address for
2215 // this test.
2216 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2217 QuicSocketAddress());
2218 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2219
nharper46833c32019-05-15 21:33:05 -07002220 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07002221 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2222 } else {
nharper46833c32019-05-15 21:33:05 -07002223 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2224 }
wub8a5dafa2020-05-13 12:30:17 -07002225 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2226 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002227 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2228 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2229
2230 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyif06ca342020-02-24 14:11:13 -08002231 if (!GetParam().version.HasIetfQuicFrames()) {
2232 EXPECT_CALL(visitor_,
2233 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2234 .Times(1);
2235 } else {
2236 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2237 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002238 // Process a padded PING packet from a new peer address on server side
2239 // is effectively receiving a connectivity probing.
2240 const QuicSocketAddress kNewPeerAddress =
2241 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2242
wub8a5dafa2020-05-13 12:30:17 -07002243 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
QUICHE teama6ef0a62019-03-07 20:34:33 -05002244 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2245 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2246 probing_packet->encrypted_length),
2247 clock_.Now()));
2248
2249 uint64_t num_probing_received =
2250 connection_.GetStats().num_connectivity_probing_received;
2251 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2252
2253 EXPECT_EQ(num_probing_received + 1,
2254 connection_.GetStats().num_connectivity_probing_received);
2255 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2256 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2257
2258 // Process another packet with the old peer address on server side will not
2259 // start peer migration.
2260 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
wub8a5dafa2020-05-13 12:30:17 -07002261 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2262 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002263 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2264 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2265}
2266
zhongyif06ca342020-02-24 14:11:13 -08002267// Receive a padded PING packet with a port change on server side.
2268TEST_P(QuicConnectionTest, ReceivePaddedPingWithPortChangeAtServer) {
2269 set_perspective(Perspective::IS_SERVER);
2270 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2271 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2272
2273 // Clear direct_peer_address.
2274 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2275 // Clear effective_peer_address, it is the same as direct_peer_address for
2276 // this test.
2277 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2278 QuicSocketAddress());
2279 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2280
zhongyif06ca342020-02-24 14:11:13 -08002281 if (GetParam().version.UsesCryptoFrames()) {
zhongyif06ca342020-02-24 14:11:13 -08002282 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2283 } else {
zhongyif06ca342020-02-24 14:11:13 -08002284 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2285 }
wub8a5dafa2020-05-13 12:30:17 -07002286 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2287 kPeerAddress);
zhongyif06ca342020-02-24 14:11:13 -08002288 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2289 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2290
2291 if (GetParam().version.HasIetfQuicFrames()) {
2292 // In IETF version, a padded PING packet with port change is not taken as
2293 // connectivity probe.
2294 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2295 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2296 } else {
2297 // In non-IETF version, process a padded PING packet from a new peer
2298 // address on server side is effectively receiving a connectivity probing.
2299 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2300 EXPECT_CALL(visitor_,
2301 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2302 .Times(1);
2303 }
2304 const QuicSocketAddress kNewPeerAddress =
2305 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2306
2307 QuicFrames frames;
2308 // Write a PING frame, which has no data payload.
2309 QuicPingFrame ping_frame;
2310 frames.push_back(QuicFrame(ping_frame));
2311
2312 // Add padding to the rest of the packet.
2313 QuicPaddingFrame padding_frame;
2314 frames.push_back(QuicFrame(padding_frame));
2315
2316 uint64_t num_probing_received =
2317 connection_.GetStats().num_connectivity_probing_received;
2318
2319 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress);
2320
2321 if (GetParam().version.HasIetfQuicFrames()) {
2322 // Padded PING with port changen is not considered as connectivity probe but
2323 // a PORT CHANGE.
2324 EXPECT_EQ(num_probing_received,
2325 connection_.GetStats().num_connectivity_probing_received);
2326 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2327 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2328 } else {
2329 EXPECT_EQ(num_probing_received + 1,
2330 connection_.GetStats().num_connectivity_probing_received);
2331 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2332 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2333 }
2334
2335 // Process another packet with the old peer address on server side.
2336 if (GetParam().version.HasIetfQuicFrames()) {
2337 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2338 } else {
2339 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2340 }
wub8a5dafa2020-05-13 12:30:17 -07002341 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2342 kPeerAddress);
zhongyif06ca342020-02-24 14:11:13 -08002343 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2344 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2345}
2346
2347TEST_P(QuicConnectionTest, ReceiveReorderedPathProbingAtServer) {
dschinazi1c6e5922020-06-19 10:35:03 -07002348 PathProbeTestInit(Perspective::IS_SERVER);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002349
2350 // Clear direct_peer_address.
2351 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2352 // Clear effective_peer_address, it is the same as direct_peer_address for
2353 // this test.
2354 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2355 QuicSocketAddress());
2356 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2357
nharper46833c32019-05-15 21:33:05 -07002358 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07002359 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2360 } else {
nharper46833c32019-05-15 21:33:05 -07002361 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2362 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002363 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
wub8a5dafa2020-05-13 12:30:17 -07002364 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2365 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002366 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2367 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2368
2369 // Decrease packet number to simulate out-of-order packets.
2370 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 4);
2371
2372 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyif06ca342020-02-24 14:11:13 -08002373 if (!GetParam().version.HasIetfQuicFrames()) {
2374 EXPECT_CALL(visitor_,
2375 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2376 .Times(1);
2377 } else {
2378 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2379 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002380
2381 // Process a padded PING packet from a new peer address on server side
2382 // is effectively receiving a connectivity probing, even if a newer packet has
2383 // been received before this one.
2384 const QuicSocketAddress kNewPeerAddress =
2385 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2386
wub8a5dafa2020-05-13 12:30:17 -07002387 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
QUICHE teama6ef0a62019-03-07 20:34:33 -05002388 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2389 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2390 probing_packet->encrypted_length),
2391 clock_.Now()));
2392
2393 uint64_t num_probing_received =
2394 connection_.GetStats().num_connectivity_probing_received;
2395 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2396
2397 EXPECT_EQ(num_probing_received + 1,
2398 connection_.GetStats().num_connectivity_probing_received);
2399 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2400 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2401}
2402
2403TEST_P(QuicConnectionTest, MigrateAfterProbingAtServer) {
dschinazi1c6e5922020-06-19 10:35:03 -07002404 PathProbeTestInit(Perspective::IS_SERVER);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002405
2406 // Clear direct_peer_address.
2407 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2408 // Clear effective_peer_address, it is the same as direct_peer_address for
2409 // this test.
2410 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2411 QuicSocketAddress());
2412 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2413
nharper46833c32019-05-15 21:33:05 -07002414 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07002415 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2416 } else {
nharper46833c32019-05-15 21:33:05 -07002417 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2418 }
wub8a5dafa2020-05-13 12:30:17 -07002419 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2420 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002421 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2422 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2423
2424 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyif06ca342020-02-24 14:11:13 -08002425 if (!GetParam().version.HasIetfQuicFrames()) {
2426 EXPECT_CALL(visitor_,
2427 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2428 .Times(1);
2429 } else {
2430 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2431 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002432
2433 // Process a padded PING packet from a new peer address on server side
2434 // is effectively receiving a connectivity probing.
2435 const QuicSocketAddress kNewPeerAddress =
2436 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2437
wub8a5dafa2020-05-13 12:30:17 -07002438 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
QUICHE teama6ef0a62019-03-07 20:34:33 -05002439 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2440 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2441 probing_packet->encrypted_length),
2442 clock_.Now()));
2443 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2444 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2445 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2446
2447 // Process another non-probing packet with the new peer address on server
2448 // side will start peer migration.
2449 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2450
wub8a5dafa2020-05-13 12:30:17 -07002451 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2452 kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002453 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2454 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2455}
2456
2457TEST_P(QuicConnectionTest, ReceivePaddedPingAtClient) {
2458 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
dschinazi1c6e5922020-06-19 10:35:03 -07002459 PathProbeTestInit(Perspective::IS_CLIENT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002460
2461 // Clear direct_peer_address.
2462 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2463 // Clear effective_peer_address, it is the same as direct_peer_address for
2464 // this test.
2465 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2466 QuicSocketAddress());
2467 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2468
nharper46833c32019-05-15 21:33:05 -07002469 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07002470 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2471 } else {
nharper46833c32019-05-15 21:33:05 -07002472 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2473 }
wub8a5dafa2020-05-13 12:30:17 -07002474 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2475 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002476 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2477 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2478
2479 // Client takes all padded PING packet as speculative connectivity
2480 // probing packet, and reports to visitor.
2481 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyi83161e42019-08-19 09:06:25 -07002482 EXPECT_CALL(visitor_, OnPacketReceived(_, _, false)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002483
wub8a5dafa2020-05-13 12:30:17 -07002484 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
QUICHE teama6ef0a62019-03-07 20:34:33 -05002485 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2486 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2487 probing_packet->encrypted_length),
2488 clock_.Now()));
2489 uint64_t num_probing_received =
2490 connection_.GetStats().num_connectivity_probing_received;
2491 ProcessReceivedPacket(kSelfAddress, kPeerAddress, *received);
2492
2493 EXPECT_EQ(num_probing_received,
2494 connection_.GetStats().num_connectivity_probing_received);
2495 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2496 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2497}
2498
zhongyif06ca342020-02-24 14:11:13 -08002499TEST_P(QuicConnectionTest, ReceiveConnectivityProbingResponseAtClient) {
2500 // TODO(b/150095484): add test coverage for IETF to verify that client takes
2501 // PATH RESPONSE with peer address change as correct validation on the new
2502 // path.
2503 if (GetParam().version.HasIetfQuicFrames()) {
2504 return;
2505 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002506 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
dschinazi1c6e5922020-06-19 10:35:03 -07002507 PathProbeTestInit(Perspective::IS_CLIENT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002508
2509 // Clear direct_peer_address.
2510 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2511 // Clear effective_peer_address, it is the same as direct_peer_address for
2512 // this test.
2513 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2514 QuicSocketAddress());
2515 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2516
nharper46833c32019-05-15 21:33:05 -07002517 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07002518 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2519 } else {
nharper46833c32019-05-15 21:33:05 -07002520 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2521 }
wub8a5dafa2020-05-13 12:30:17 -07002522 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2523 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002524 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2525 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2526
2527 // Process a padded PING packet with a different self address on client side
2528 // is effectively receiving a connectivity probing.
2529 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyif06ca342020-02-24 14:11:13 -08002530 if (!GetParam().version.HasIetfQuicFrames()) {
2531 EXPECT_CALL(visitor_,
2532 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2533 .Times(1);
2534 } else {
2535 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2536 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002537
2538 const QuicSocketAddress kNewSelfAddress =
2539 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2540
wub8a5dafa2020-05-13 12:30:17 -07002541 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
QUICHE teama6ef0a62019-03-07 20:34:33 -05002542 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2543 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2544 probing_packet->encrypted_length),
2545 clock_.Now()));
2546 uint64_t num_probing_received =
2547 connection_.GetStats().num_connectivity_probing_received;
2548 ProcessReceivedPacket(kNewSelfAddress, kPeerAddress, *received);
2549
2550 EXPECT_EQ(num_probing_received + 1,
2551 connection_.GetStats().num_connectivity_probing_received);
2552 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2553 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2554}
2555
2556TEST_P(QuicConnectionTest, PeerAddressChangeAtClient) {
2557 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2558 set_perspective(Perspective::IS_CLIENT);
2559 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2560
2561 // Clear direct_peer_address.
2562 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2563 // Clear effective_peer_address, it is the same as direct_peer_address for
2564 // this test.
2565 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2566 QuicSocketAddress());
2567 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2568
nharper46833c32019-05-15 21:33:05 -07002569 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07002570 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2571 } else {
nharper46833c32019-05-15 21:33:05 -07002572 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2573 }
wub8a5dafa2020-05-13 12:30:17 -07002574 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2575 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002576 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2577 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2578
2579 // Process another packet with a different peer address on client side will
2580 // only update peer address.
2581 const QuicSocketAddress kNewPeerAddress =
2582 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2583 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
wub8a5dafa2020-05-13 12:30:17 -07002584 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2585 kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002586 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2587 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2588}
2589
2590TEST_P(QuicConnectionTest, MaxPacketSize) {
2591 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2592 EXPECT_EQ(1350u, connection_.max_packet_length());
2593}
2594
dschinazi4ad1f462020-01-16 11:56:52 -08002595TEST_P(QuicConnectionTest, PeerLowersMaxPacketSize) {
2596 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2597
2598 // SetFromConfig is always called after construction from InitializeSession.
2599 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
2600 constexpr uint32_t kTestMaxPacketSize = 1233u;
2601 QuicConfig config;
2602 QuicConfigPeer::SetReceivedMaxPacketSize(&config, kTestMaxPacketSize);
2603 connection_.SetFromConfig(config);
2604
2605 EXPECT_EQ(kTestMaxPacketSize, connection_.max_packet_length());
2606}
2607
vasilvvebc5d0c2020-01-16 15:19:21 -08002608TEST_P(QuicConnectionTest, PeerCannotRaiseMaxPacketSize) {
2609 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2610
2611 // SetFromConfig is always called after construction from InitializeSession.
2612 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
2613 constexpr uint32_t kTestMaxPacketSize = 1450u;
2614 QuicConfig config;
2615 QuicConfigPeer::SetReceivedMaxPacketSize(&config, kTestMaxPacketSize);
2616 connection_.SetFromConfig(config);
2617
2618 EXPECT_EQ(kDefaultMaxPacketSize, connection_.max_packet_length());
2619}
2620
QUICHE teama6ef0a62019-03-07 20:34:33 -05002621TEST_P(QuicConnectionTest, SmallerServerMaxPacketSize) {
2622 TestConnection connection(TestConnectionId(), kPeerAddress, helper_.get(),
2623 alarm_factory_.get(), writer_.get(),
2624 Perspective::IS_SERVER, version());
2625 EXPECT_EQ(Perspective::IS_SERVER, connection.perspective());
2626 EXPECT_EQ(1000u, connection.max_packet_length());
2627}
2628
2629TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSize) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002630 set_perspective(Perspective::IS_SERVER);
2631 connection_.SetMaxPacketLength(1000);
2632
2633 QuicPacketHeader header;
2634 header.destination_connection_id = connection_id_;
2635 header.version_flag = true;
nharper21af28e2019-06-17 15:54:34 -07002636 header.packet_number = QuicPacketNumber(12);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002637
2638 if (QuicVersionHasLongHeaderLengths(
2639 peer_framer_.version().transport_version)) {
2640 header.long_packet_type = INITIAL;
2641 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
2642 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
2643 }
2644
2645 QuicFrames frames;
2646 QuicPaddingFrame padding;
nharper46833c32019-05-15 21:33:05 -07002647 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2648 frames.push_back(QuicFrame(&crypto_frame_));
2649 } else {
2650 frames.push_back(QuicFrame(frame1_));
2651 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002652 frames.push_back(QuicFrame(padding));
2653 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
dschinazi66dea072019-04-09 11:41:06 -07002654 char buffer[kMaxOutgoingPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07002655 size_t encrypted_length =
2656 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12),
dschinazi66dea072019-04-09 11:41:06 -07002657 *packet, buffer, kMaxOutgoingPacketSize);
2658 EXPECT_EQ(kMaxOutgoingPacketSize, encrypted_length);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002659
2660 framer_.set_version(version());
nharper46833c32019-05-15 21:33:05 -07002661 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2662 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
2663 } else {
2664 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2665 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002666 connection_.ProcessUdpPacket(
2667 kSelfAddress, kPeerAddress,
2668 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
2669
dschinazi66dea072019-04-09 11:41:06 -07002670 EXPECT_EQ(kMaxOutgoingPacketSize, connection_.max_packet_length());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002671}
2672
2673TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSizeWhileWriterLimited) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002674 const QuicByteCount lower_max_packet_size = 1240;
2675 writer_->set_max_packet_size(lower_max_packet_size);
2676 set_perspective(Perspective::IS_SERVER);
2677 connection_.SetMaxPacketLength(1000);
2678 EXPECT_EQ(1000u, connection_.max_packet_length());
2679
2680 QuicPacketHeader header;
2681 header.destination_connection_id = connection_id_;
2682 header.version_flag = true;
nharper21af28e2019-06-17 15:54:34 -07002683 header.packet_number = QuicPacketNumber(12);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002684
2685 if (QuicVersionHasLongHeaderLengths(
2686 peer_framer_.version().transport_version)) {
2687 header.long_packet_type = INITIAL;
2688 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
2689 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
2690 }
2691
2692 QuicFrames frames;
2693 QuicPaddingFrame padding;
nharper46833c32019-05-15 21:33:05 -07002694 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2695 frames.push_back(QuicFrame(&crypto_frame_));
2696 } else {
2697 frames.push_back(QuicFrame(frame1_));
2698 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002699 frames.push_back(QuicFrame(padding));
2700 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
dschinazi66dea072019-04-09 11:41:06 -07002701 char buffer[kMaxOutgoingPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07002702 size_t encrypted_length =
2703 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12),
dschinazi66dea072019-04-09 11:41:06 -07002704 *packet, buffer, kMaxOutgoingPacketSize);
2705 EXPECT_EQ(kMaxOutgoingPacketSize, encrypted_length);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002706
2707 framer_.set_version(version());
nharper46833c32019-05-15 21:33:05 -07002708 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2709 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
2710 } else {
2711 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2712 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002713 connection_.ProcessUdpPacket(
2714 kSelfAddress, kPeerAddress,
2715 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
2716
2717 // Here, the limit imposed by the writer is lower than the size of the packet
2718 // received, so the writer max packet size is used.
2719 EXPECT_EQ(lower_max_packet_size, connection_.max_packet_length());
2720}
2721
2722TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriter) {
2723 const QuicByteCount lower_max_packet_size = 1240;
2724 writer_->set_max_packet_size(lower_max_packet_size);
2725
2726 static_assert(lower_max_packet_size < kDefaultMaxPacketSize,
2727 "Default maximum packet size is too low");
2728 connection_.SetMaxPacketLength(kDefaultMaxPacketSize);
2729
2730 EXPECT_EQ(lower_max_packet_size, connection_.max_packet_length());
2731}
2732
2733TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriterForNewConnection) {
2734 const QuicConnectionId connection_id = TestConnectionId(17);
2735 const QuicByteCount lower_max_packet_size = 1240;
2736 writer_->set_max_packet_size(lower_max_packet_size);
2737 TestConnection connection(connection_id, kPeerAddress, helper_.get(),
2738 alarm_factory_.get(), writer_.get(),
2739 Perspective::IS_CLIENT, version());
2740 EXPECT_EQ(Perspective::IS_CLIENT, connection.perspective());
2741 EXPECT_EQ(lower_max_packet_size, connection.max_packet_length());
2742}
2743
2744TEST_P(QuicConnectionTest, PacketsInOrder) {
2745 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2746
2747 ProcessPacket(1);
fayangc31c9952019-06-05 13:54:48 -07002748 EXPECT_EQ(QuicPacketNumber(1u), LargestAcked(connection_.ack_frame()));
2749 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002750
2751 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07002752 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(connection_.ack_frame()));
2753 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002754
2755 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002756 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
2757 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002758}
2759
2760TEST_P(QuicConnectionTest, PacketsOutOfOrder) {
2761 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2762
2763 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002764 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002765 EXPECT_TRUE(IsMissing(2));
2766 EXPECT_TRUE(IsMissing(1));
2767
2768 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07002769 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002770 EXPECT_FALSE(IsMissing(2));
2771 EXPECT_TRUE(IsMissing(1));
2772
2773 ProcessPacket(1);
fayangc31c9952019-06-05 13:54:48 -07002774 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002775 EXPECT_FALSE(IsMissing(2));
2776 EXPECT_FALSE(IsMissing(1));
2777}
2778
2779TEST_P(QuicConnectionTest, DuplicatePacket) {
2780 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2781
2782 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002783 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002784 EXPECT_TRUE(IsMissing(2));
2785 EXPECT_TRUE(IsMissing(1));
2786
2787 // Send packet 3 again, but do not set the expectation that
2788 // the visitor OnStreamFrame() will be called.
2789 ProcessDataPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002790 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002791 EXPECT_TRUE(IsMissing(2));
2792 EXPECT_TRUE(IsMissing(1));
2793}
2794
2795TEST_P(QuicConnectionTest, PacketsOutOfOrderWithAdditionsAndLeastAwaiting) {
QUICHE teamcd098022019-03-22 18:49:55 -07002796 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2797 return;
2798 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002799 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2800
2801 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002802 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002803 EXPECT_TRUE(IsMissing(2));
2804 EXPECT_TRUE(IsMissing(1));
2805
2806 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07002807 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002808 EXPECT_TRUE(IsMissing(1));
2809
2810 ProcessPacket(5);
fayangc31c9952019-06-05 13:54:48 -07002811 EXPECT_EQ(QuicPacketNumber(5u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002812 EXPECT_TRUE(IsMissing(1));
2813 EXPECT_TRUE(IsMissing(4));
2814
2815 // Pretend at this point the client has gotten acks for 2 and 3 and 1 is a
2816 // packet the peer will not retransmit. It indicates this by sending 'least
2817 // awaiting' is 4. The connection should then realize 1 will not be
2818 // retransmitted, and will remove it from the missing list.
2819 QuicAckFrame frame = InitAckFrame(1);
2820 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
2821 ProcessAckPacket(6, &frame);
2822
2823 // Force an ack to be sent.
2824 SendAckPacketToPeer();
2825 EXPECT_TRUE(IsMissing(4));
2826}
2827
QUICHE teama6ef0a62019-03-07 20:34:33 -05002828TEST_P(QuicConnectionTest, RejectUnencryptedStreamData) {
2829 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
2830 if (!IsDefaultTestConfiguration()) {
2831 return;
2832 }
2833
2834 // Process an unencrypted packet from the non-crypto stream.
2835 frame1_.stream_id = 3;
2836 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fkastenholz5d880a92019-06-21 09:01:56 -07002837 EXPECT_CALL(visitor_,
2838 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
nharper2c9f02a2019-05-08 10:25:50 -07002839 EXPECT_QUIC_PEER_BUG(ProcessDataPacketAtLevel(1, false, ENCRYPTION_INITIAL),
2840 "");
fkastenholz5d880a92019-06-21 09:01:56 -07002841 TestConnectionCloseQuicErrorCode(QUIC_UNENCRYPTED_STREAM_DATA);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002842}
2843
2844TEST_P(QuicConnectionTest, OutOfOrderReceiptCausesAckSend) {
2845 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2846
2847 ProcessPacket(3);
fayang6dba4902019-06-17 10:04:23 -07002848 // Should not cause an ack.
2849 EXPECT_EQ(0u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002850
2851 ProcessPacket(2);
fayang6dba4902019-06-17 10:04:23 -07002852 // Should ack immediately, since this fills the last hole.
2853 EXPECT_EQ(1u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002854
2855 ProcessPacket(1);
2856 // Should ack immediately, since this fills the last hole.
fayang6dba4902019-06-17 10:04:23 -07002857 EXPECT_EQ(2u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002858
2859 ProcessPacket(4);
2860 // Should not cause an ack.
fayang6dba4902019-06-17 10:04:23 -07002861 EXPECT_EQ(2u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002862}
2863
2864TEST_P(QuicConnectionTest, OutOfOrderAckReceiptCausesNoAck) {
2865 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2866
2867 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
2868 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
2869 EXPECT_EQ(2u, writer_->packets_write_attempts());
2870
2871 QuicAckFrame ack1 = InitAckFrame(1);
2872 QuicAckFrame ack2 = InitAckFrame(2);
2873 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
fayang2f2915d2020-01-24 06:47:15 -08002874 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2875 EXPECT_CALL(visitor_, OnOneRttPacketAcknowledged()).Times(1);
2876 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002877 ProcessAckPacket(2, &ack2);
2878 // Should ack immediately since we have missing packets.
2879 EXPECT_EQ(2u, writer_->packets_write_attempts());
2880
fayang2f2915d2020-01-24 06:47:15 -08002881 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2882 EXPECT_CALL(visitor_, OnOneRttPacketAcknowledged()).Times(0);
2883 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002884 ProcessAckPacket(1, &ack1);
2885 // Should not ack an ack filling a missing packet.
2886 EXPECT_EQ(2u, writer_->packets_write_attempts());
2887}
2888
2889TEST_P(QuicConnectionTest, AckReceiptCausesAckSend) {
2890 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2891 QuicPacketNumber original, second;
2892
2893 QuicByteCount packet_size =
2894 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &original); // 1st packet.
2895 SendStreamDataToPeer(3, "bar", 3, NO_FIN, &second); // 2nd packet.
2896
2897 QuicAckFrame frame = InitAckFrame({{second, second + 1}});
2898 // First nack triggers early retransmit.
2899 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07002900 lost_packets.push_back(LostPacket(original, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002901 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07002902 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
2903 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002904 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2905 QuicPacketNumber retransmission;
2906 // Packet 1 is short header for IETF QUIC because the encryption level
2907 // switched to ENCRYPTION_FORWARD_SECURE in SendStreamDataToPeer.
fayangd4291e42019-05-30 10:31:21 -07002908 EXPECT_CALL(*send_algorithm_,
2909 OnPacketSent(_, _, _,
2910 VersionHasIetfInvariantHeader(
2911 GetParam().version.transport_version)
2912 ? packet_size
2913 : packet_size - kQuicVersionSize,
2914 _))
QUICHE teama6ef0a62019-03-07 20:34:33 -05002915 .WillOnce(SaveArg<2>(&retransmission));
2916
2917 ProcessAckPacket(&frame);
2918
2919 QuicAckFrame frame2 = ConstructAckFrame(retransmission, original);
2920 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2921 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
2922 ProcessAckPacket(&frame2);
2923
2924 // Now if the peer sends an ack which still reports the retransmitted packet
2925 // as missing, that will bundle an ack with data after two acks in a row
2926 // indicate the high water mark needs to be raised.
2927 EXPECT_CALL(*send_algorithm_,
2928 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA));
2929 connection_.SendStreamDataWithString(3, "foo", 6, NO_FIN);
2930 // No ack sent.
nharper55fa6132019-05-07 19:37:21 -07002931 size_t padding_frame_count = writer_->padding_frames().size();
2932 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002933 EXPECT_EQ(1u, writer_->stream_frames().size());
2934
2935 // No more packet loss for the rest of the test.
2936 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
2937 .Times(AnyNumber());
2938 ProcessAckPacket(&frame2);
2939 EXPECT_CALL(*send_algorithm_,
2940 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA));
fayang03916692019-05-22 17:57:18 -07002941 connection_.SendStreamDataWithString(3, "foofoofoo", 9, NO_FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002942 // Ack bundled.
2943 if (GetParam().no_stop_waiting) {
fayang8a27b0f2019-11-04 11:27:40 -08002944 // Do not ACK acks.
2945 EXPECT_EQ(1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002946 } else {
2947 EXPECT_EQ(3u, writer_->frame_count());
2948 }
2949 EXPECT_EQ(1u, writer_->stream_frames().size());
fayang8a27b0f2019-11-04 11:27:40 -08002950 if (GetParam().no_stop_waiting) {
fayang03916692019-05-22 17:57:18 -07002951 EXPECT_TRUE(writer_->ack_frames().empty());
2952 } else {
2953 EXPECT_FALSE(writer_->ack_frames().empty());
2954 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002955
2956 // But an ack with no missing packets will not send an ack.
2957 AckPacket(original, &frame2);
2958 ProcessAckPacket(&frame2);
2959 ProcessAckPacket(&frame2);
2960}
2961
2962TEST_P(QuicConnectionTest, AckSentEveryNthPacket) {
2963 connection_.set_ack_frequency_before_ack_decimation(3);
2964
2965 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2966 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(39);
2967
2968 // Expect 13 acks, every 3rd packet.
2969 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(13);
2970 // Receives packets 1 - 39.
2971 for (size_t i = 1; i <= 39; ++i) {
2972 ProcessDataPacket(i);
2973 }
2974}
2975
2976TEST_P(QuicConnectionTest, AckDecimationReducesAcks) {
2977 const size_t kMinRttMs = 40;
2978 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
2979 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
2980 QuicTime::Delta::Zero(), QuicTime::Zero());
2981 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
2982
2983 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
2984
2985 // Start ack decimation from 10th packet.
2986 connection_.set_min_received_before_ack_decimation(10);
2987
2988 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2989 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(30);
2990
2991 // Expect 6 acks: 5 acks between packets 1-10, and ack at 20.
2992 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(6);
2993 // Receives packets 1 - 29.
2994 for (size_t i = 1; i <= 29; ++i) {
2995 ProcessDataPacket(i);
2996 }
2997
2998 // We now receive the 30th packet, and so we send an ack.
2999 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3000 ProcessDataPacket(30);
3001}
3002
3003TEST_P(QuicConnectionTest, AckNeedsRetransmittableFrames) {
ianswett68cf0042019-05-09 08:37:58 -07003004 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003005 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3006 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(99);
3007
3008 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(19);
3009 // Receives packets 1 - 39.
3010 for (size_t i = 1; i <= 39; ++i) {
3011 ProcessDataPacket(i);
3012 }
3013 // Receiving Packet 40 causes 20th ack to send. Session is informed and adds
3014 // WINDOW_UPDATE.
3015 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
3016 .WillOnce(Invoke([this]() {
3017 connection_.SendControlFrame(
3018 QuicFrame(new QuicWindowUpdateFrame(1, 0, 0)));
3019 }));
3020 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3021 EXPECT_EQ(0u, writer_->window_update_frames().size());
3022 ProcessDataPacket(40);
3023 EXPECT_EQ(1u, writer_->window_update_frames().size());
3024
3025 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(9);
3026 // Receives packets 41 - 59.
3027 for (size_t i = 41; i <= 59; ++i) {
3028 ProcessDataPacket(i);
3029 }
3030 // Send a packet containing stream frame.
QUICHE team8c1daa22019-03-13 08:33:41 -07003031 SendStreamDataToPeer(
nharper46833c32019-05-15 21:33:05 -07003032 QuicUtils::GetFirstBidirectionalStreamId(
3033 connection_.version().transport_version, Perspective::IS_CLIENT),
QUICHE team8c1daa22019-03-13 08:33:41 -07003034 "bar", 0, NO_FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003035
3036 // Session will not be informed until receiving another 20 packets.
3037 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(19);
3038 for (size_t i = 60; i <= 98; ++i) {
3039 ProcessDataPacket(i);
3040 EXPECT_EQ(0u, writer_->window_update_frames().size());
3041 }
3042 // Session does not add a retransmittable frame.
3043 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
3044 .WillOnce(Invoke([this]() {
3045 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
3046 }));
3047 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3048 EXPECT_EQ(0u, writer_->ping_frames().size());
3049 ProcessDataPacket(99);
3050 EXPECT_EQ(0u, writer_->window_update_frames().size());
3051 // A ping frame will be added.
3052 EXPECT_EQ(1u, writer_->ping_frames().size());
3053}
3054
ianswett6083a102020-02-09 12:04:04 -08003055TEST_P(QuicConnectionTest, AckNeedsRetransmittableFramesAfterPto) {
ianswett6083a102020-02-09 12:04:04 -08003056 // Disable TLP so the RTO fires immediately.
3057 connection_.SetMaxTailLossProbes(0);
3058 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3059 QuicConfig config;
3060 QuicTagVector connection_options;
3061 connection_options.push_back(kEACK);
3062 config.SetConnectionOptionsToSend(connection_options);
3063 connection_.SetFromConfig(config);
3064
3065 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3066 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3067 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(10);
3068
3069 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(4);
3070 // Receive packets 1 - 9.
3071 for (size_t i = 1; i <= 9; ++i) {
3072 ProcessDataPacket(i);
3073 }
3074
3075 // Send a ping and fire the retransmission alarm.
3076 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3077 SendPing();
3078 QuicTime retransmission_time =
3079 connection_.GetRetransmissionAlarm()->deadline();
3080 clock_.AdvanceTime(retransmission_time - clock_.Now());
3081 connection_.GetRetransmissionAlarm()->Fire();
3082 ASSERT_TRUE(manager_->GetConsecutiveRtoCount() > 0 ||
3083 manager_->GetConsecutivePtoCount() > 0);
3084
3085 // Process a packet, which requests a retransmittable frame be bundled
3086 // with the ACK.
3087 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
3088 .WillOnce(Invoke([this]() {
3089 connection_.SendControlFrame(
3090 QuicFrame(new QuicWindowUpdateFrame(1, 0, 0)));
3091 }));
3092 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3093 ProcessDataPacket(11);
3094 EXPECT_EQ(1u, writer_->window_update_frames().size());
3095}
3096
QUICHE teama6ef0a62019-03-07 20:34:33 -05003097TEST_P(QuicConnectionTest, LeastUnackedLower) {
fayangc31c9952019-06-05 13:54:48 -07003098 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003099 return;
3100 }
3101 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3102
3103 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
3104 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
3105 SendStreamDataToPeer(1, "eep", 6, NO_FIN, nullptr);
3106
3107 // Start out saying the least unacked is 2.
3108 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
3109 ProcessStopWaitingPacket(InitStopWaitingFrame(2));
3110
3111 // Change it to 1, but lower the packet number to fake out-of-order packets.
3112 // This should be fine.
3113 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 1);
3114 // The scheduler will not process out of order acks, but all packet processing
3115 // causes the connection to try to write.
3116 if (!GetParam().no_stop_waiting) {
3117 EXPECT_CALL(visitor_, OnCanWrite());
3118 }
3119 ProcessStopWaitingPacket(InitStopWaitingFrame(1));
3120
3121 // Now claim it's one, but set the ordering so it was sent "after" the first
3122 // one. This should cause a connection error.
3123 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 7);
3124 if (!GetParam().no_stop_waiting) {
rch39c88ab2019-10-16 19:24:40 -07003125 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3126 .Times(AtLeast(1));
fkastenholz5d880a92019-06-21 09:01:56 -07003127 EXPECT_CALL(visitor_,
rch39c88ab2019-10-16 19:24:40 -07003128 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
3129 .Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003130 }
3131 ProcessStopWaitingPacket(InitStopWaitingFrame(1));
fkastenholz5d880a92019-06-21 09:01:56 -07003132 if (!GetParam().no_stop_waiting) {
3133 TestConnectionCloseQuicErrorCode(QUIC_INVALID_STOP_WAITING_DATA);
3134 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003135}
3136
3137TEST_P(QuicConnectionTest, TooManySentPackets) {
3138 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3139
3140 QuicPacketCount max_tracked_packets = 50;
3141 QuicConnectionPeer::SetMaxTrackedPackets(&connection_, max_tracked_packets);
3142
3143 const int num_packets = max_tracked_packets + 5;
3144
3145 for (int i = 0; i < num_packets; ++i) {
3146 SendStreamDataToPeer(1, "foo", 3 * i, NO_FIN, nullptr);
3147 }
3148
3149 // Ack packet 1, which leaves more than the limit outstanding.
3150 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3151 EXPECT_CALL(visitor_,
fkastenholz5d880a92019-06-21 09:01:56 -07003152 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003153
3154 // Nack the first packet and ack the rest, leaving a huge gap.
3155 QuicAckFrame frame1 = ConstructAckFrame(num_packets, 1);
3156 ProcessAckPacket(&frame1);
fkastenholz5d880a92019-06-21 09:01:56 -07003157 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003158}
3159
3160TEST_P(QuicConnectionTest, LargestObservedLower) {
3161 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3162
3163 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
3164 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
3165 SendStreamDataToPeer(1, "eep", 6, NO_FIN, nullptr);
3166 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3167
3168 // Start out saying the largest observed is 2.
3169 QuicAckFrame frame1 = InitAckFrame(1);
3170 QuicAckFrame frame2 = InitAckFrame(2);
3171 ProcessAckPacket(&frame2);
3172
fayang745c93a2019-06-21 13:43:04 -07003173 EXPECT_CALL(visitor_, OnCanWrite());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003174 ProcessAckPacket(&frame1);
3175}
3176
3177TEST_P(QuicConnectionTest, AckUnsentData) {
3178 // Ack a packet which has not been sent.
fkastenholz5d880a92019-06-21 09:01:56 -07003179 EXPECT_CALL(visitor_,
3180 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003181 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
rch39c88ab2019-10-16 19:24:40 -07003182 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003183 QuicAckFrame frame = InitAckFrame(1);
3184 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
3185 ProcessAckPacket(&frame);
fkastenholz5d880a92019-06-21 09:01:56 -07003186 TestConnectionCloseQuicErrorCode(QUIC_INVALID_ACK_DATA);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003187}
3188
3189TEST_P(QuicConnectionTest, BasicSending) {
QUICHE teamcd098022019-03-22 18:49:55 -07003190 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3191 return;
3192 }
fayang643c7dd2020-05-18 07:11:27 -07003193 const QuicConnectionStats& stats = connection_.GetStats();
3194 EXPECT_FALSE(stats.first_decrypted_packet.IsInitialized());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003195 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3196 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3197 ProcessDataPacket(1);
fayang643c7dd2020-05-18 07:11:27 -07003198 EXPECT_EQ(QuicPacketNumber(1), stats.first_decrypted_packet);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003199 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
3200 QuicPacketNumber last_packet;
3201 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
3202 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
3203 SendAckPacketToPeer(); // Packet 2
3204
3205 if (GetParam().no_stop_waiting) {
3206 // Expect no stop waiting frame is sent.
3207 EXPECT_FALSE(least_unacked().IsInitialized());
3208 } else {
3209 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
3210 }
3211
3212 SendAckPacketToPeer(); // Packet 3
3213 if (GetParam().no_stop_waiting) {
3214 // Expect no stop waiting frame is sent.
3215 EXPECT_FALSE(least_unacked().IsInitialized());
3216 } else {
3217 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
3218 }
3219
3220 SendStreamDataToPeer(1, "bar", 3, NO_FIN, &last_packet); // Packet 4
3221 EXPECT_EQ(QuicPacketNumber(4u), last_packet);
3222 SendAckPacketToPeer(); // Packet 5
3223 if (GetParam().no_stop_waiting) {
3224 // Expect no stop waiting frame is sent.
3225 EXPECT_FALSE(least_unacked().IsInitialized());
3226 } else {
3227 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
3228 }
3229
3230 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3231
3232 // Peer acks up to packet 3.
3233 QuicAckFrame frame = InitAckFrame(3);
3234 ProcessAckPacket(&frame);
3235 SendAckPacketToPeer(); // Packet 6
3236
3237 // As soon as we've acked one, we skip ack packets 2 and 3 and note lack of
3238 // ack for 4.
3239 if (GetParam().no_stop_waiting) {
3240 // Expect no stop waiting frame is sent.
3241 EXPECT_FALSE(least_unacked().IsInitialized());
3242 } else {
3243 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
3244 }
3245
3246 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3247
3248 // Peer acks up to packet 4, the last packet.
3249 QuicAckFrame frame2 = InitAckFrame(6);
3250 ProcessAckPacket(&frame2); // Acks don't instigate acks.
3251
3252 // Verify that we did not send an ack.
3253 EXPECT_EQ(QuicPacketNumber(6u), writer_->header().packet_number);
3254
3255 // So the last ack has not changed.
3256 if (GetParam().no_stop_waiting) {
3257 // Expect no stop waiting frame is sent.
3258 EXPECT_FALSE(least_unacked().IsInitialized());
3259 } else {
3260 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
3261 }
3262
3263 // If we force an ack, we shouldn't change our retransmit state.
3264 SendAckPacketToPeer(); // Packet 7
3265 if (GetParam().no_stop_waiting) {
3266 // Expect no stop waiting frame is sent.
3267 EXPECT_FALSE(least_unacked().IsInitialized());
3268 } else {
3269 EXPECT_EQ(QuicPacketNumber(7u), least_unacked());
3270 }
3271
3272 // But if we send more data it should.
3273 SendStreamDataToPeer(1, "eep", 6, NO_FIN, &last_packet); // Packet 8
3274 EXPECT_EQ(QuicPacketNumber(8u), last_packet);
3275 SendAckPacketToPeer(); // Packet 9
3276 if (GetParam().no_stop_waiting) {
3277 // Expect no stop waiting frame is sent.
3278 EXPECT_FALSE(least_unacked().IsInitialized());
3279 } else {
3280 EXPECT_EQ(QuicPacketNumber(7u), least_unacked());
3281 }
fayang643c7dd2020-05-18 07:11:27 -07003282 EXPECT_EQ(QuicPacketNumber(1), stats.first_decrypted_packet);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003283}
3284
3285// QuicConnection should record the packet sent-time prior to sending the
3286// packet.
3287TEST_P(QuicConnectionTest, RecordSentTimeBeforePacketSent) {
3288 // We're using a MockClock for the tests, so we have complete control over the
3289 // time.
3290 // Our recorded timestamp for the last packet sent time will be passed in to
3291 // the send_algorithm. Make sure that it is set to the correct value.
3292 QuicTime actual_recorded_send_time = QuicTime::Zero();
3293 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3294 .WillOnce(SaveArg<0>(&actual_recorded_send_time));
3295
3296 // First send without any pause and check the result.
3297 QuicTime expected_recorded_send_time = clock_.Now();
3298 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3299 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
3300 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
3301 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
3302
3303 // Now pause during the write, and check the results.
3304 actual_recorded_send_time = QuicTime::Zero();
3305 const QuicTime::Delta write_pause_time_delta =
3306 QuicTime::Delta::FromMilliseconds(5000);
3307 SetWritePauseTimeDelta(write_pause_time_delta);
3308 expected_recorded_send_time = clock_.Now();
3309
3310 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3311 .WillOnce(SaveArg<0>(&actual_recorded_send_time));
3312 connection_.SendStreamDataWithString(2, "baz", 0, NO_FIN);
3313 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
3314 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
3315 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
3316}
3317
3318TEST_P(QuicConnectionTest, FramePacking) {
3319 // Send two stream frames in 1 packet by queueing them.
3320 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3321 {
fayanga4b37b22019-06-18 13:37:47 -07003322 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003323 connection_.SendStreamData3();
3324 connection_.SendStreamData5();
3325 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3326 }
3327 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3328 EXPECT_FALSE(connection_.HasQueuedData());
3329
3330 // Parse the last packet and ensure it's an ack and two stream frames from
3331 // two different streams.
3332 if (GetParam().no_stop_waiting) {
3333 EXPECT_EQ(2u, writer_->frame_count());
3334 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
3335 } else {
3336 EXPECT_EQ(2u, writer_->frame_count());
3337 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
3338 }
3339
3340 EXPECT_TRUE(writer_->ack_frames().empty());
3341
3342 ASSERT_EQ(2u, writer_->stream_frames().size());
3343 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3344 writer_->stream_frames()[0]->stream_id);
3345 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3346 writer_->stream_frames()[1]->stream_id);
3347}
3348
3349TEST_P(QuicConnectionTest, FramePackingNonCryptoThenCrypto) {
3350 // Send two stream frames (one non-crypto, then one crypto) in 2 packets by
3351 // queueing them.
3352 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3353 {
3354 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
fayanga4b37b22019-06-18 13:37:47 -07003355 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003356 connection_.SendStreamData3();
fayang58f71072019-11-05 08:47:02 -08003357 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003358 connection_.SendCryptoStreamData();
fayang58f71072019-11-05 08:47:02 -08003359 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003360 }
3361 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3362 EXPECT_FALSE(connection_.HasQueuedData());
3363
3364 // Parse the last packet and ensure it's the crypto stream frame.
3365 EXPECT_EQ(2u, writer_->frame_count());
3366 ASSERT_EQ(1u, writer_->padding_frames().size());
QUICHE teamea740082019-03-11 17:58:43 -07003367 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003368 ASSERT_EQ(1u, writer_->stream_frames().size());
3369 EXPECT_EQ(QuicUtils::GetCryptoStreamId(connection_.transport_version()),
3370 writer_->stream_frames()[0]->stream_id);
3371 } else {
3372 EXPECT_EQ(1u, writer_->crypto_frames().size());
3373 }
3374}
3375
3376TEST_P(QuicConnectionTest, FramePackingCryptoThenNonCrypto) {
3377 // Send two stream frames (one crypto, then one non-crypto) in 2 packets by
3378 // queueing them.
3379 {
3380 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3381 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
fayanga4b37b22019-06-18 13:37:47 -07003382 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003383 connection_.SendCryptoStreamData();
3384 connection_.SendStreamData3();
3385 }
3386 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3387 EXPECT_FALSE(connection_.HasQueuedData());
3388
3389 // Parse the last packet and ensure it's the stream frame from stream 3.
nharper55fa6132019-05-07 19:37:21 -07003390 size_t padding_frame_count = writer_->padding_frames().size();
3391 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003392 ASSERT_EQ(1u, writer_->stream_frames().size());
3393 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3394 writer_->stream_frames()[0]->stream_id);
3395}
3396
3397TEST_P(QuicConnectionTest, FramePackingAckResponse) {
3398 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3399 // Process a data packet to queue up a pending ack.
fayang3451f6e2019-06-11 08:18:12 -07003400 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3401 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
3402 } else {
3403 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3404 }
3405 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
3406
QUICHE teama6ef0a62019-03-07 20:34:33 -05003407 QuicPacketNumber last_packet;
nharper46833c32019-05-15 21:33:05 -07003408 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3409 connection_.SendCryptoDataWithString("foo", 0);
3410 } else {
3411 SendStreamDataToPeer(
3412 QuicUtils::GetCryptoStreamId(connection_.transport_version()), "foo", 0,
3413 NO_FIN, &last_packet);
3414 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003415 // Verify ack is bundled with outging packet.
3416 EXPECT_FALSE(writer_->ack_frames().empty());
3417
3418 EXPECT_CALL(visitor_, OnCanWrite())
3419 .WillOnce(DoAll(IgnoreResult(InvokeWithoutArgs(
3420 &connection_, &TestConnection::SendStreamData3)),
3421 IgnoreResult(InvokeWithoutArgs(
3422 &connection_, &TestConnection::SendStreamData5))));
3423
3424 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3425
3426 // Process a data packet to cause the visitor's OnCanWrite to be invoked.
3427 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
QUICHE team8c1daa22019-03-13 08:33:41 -07003428 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07003429 std::make_unique<TaggingEncrypter>(0x01));
zhongyi546cc452019-04-12 15:27:49 -07003430 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07003431 std::make_unique<StrictTaggingDecrypter>(0x01));
nharper2c9f02a2019-05-08 10:25:50 -07003432 ProcessDataPacket(2);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003433
3434 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3435 EXPECT_FALSE(connection_.HasQueuedData());
3436
3437 // Parse the last packet and ensure it's an ack and two stream frames from
3438 // two different streams.
3439 if (GetParam().no_stop_waiting) {
3440 EXPECT_EQ(3u, writer_->frame_count());
3441 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
3442 } else {
3443 EXPECT_EQ(4u, writer_->frame_count());
3444 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3445 }
3446 EXPECT_FALSE(writer_->ack_frames().empty());
3447 ASSERT_EQ(2u, writer_->stream_frames().size());
3448 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3449 writer_->stream_frames()[0]->stream_id);
3450 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3451 writer_->stream_frames()[1]->stream_id);
3452}
3453
3454TEST_P(QuicConnectionTest, FramePackingSendv) {
nharper46833c32019-05-15 21:33:05 -07003455 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003456 // Send data in 1 packet by writing multiple blocks in a single iovector
3457 // using writev.
3458 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3459
3460 char data[] = "ABCDEF";
3461 struct iovec iov[2];
3462 iov[0].iov_base = data;
3463 iov[0].iov_len = 4;
3464 iov[1].iov_base = data + 4;
3465 iov[1].iov_len = 2;
nharper46833c32019-05-15 21:33:05 -07003466 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
3467 connection_.transport_version(), Perspective::IS_CLIENT);
3468 connection_.SaveAndSendStreamData(stream_id, iov, 2, 6, 0, NO_FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003469
3470 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3471 EXPECT_FALSE(connection_.HasQueuedData());
3472
3473 // Parse the last packet and ensure multiple iovector blocks have
3474 // been packed into a single stream frame from one stream.
nharper46833c32019-05-15 21:33:05 -07003475 EXPECT_EQ(1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003476 EXPECT_EQ(1u, writer_->stream_frames().size());
nharper46833c32019-05-15 21:33:05 -07003477 EXPECT_EQ(0u, writer_->padding_frames().size());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003478 QuicStreamFrame* frame = writer_->stream_frames()[0].get();
nharper46833c32019-05-15 21:33:05 -07003479 EXPECT_EQ(stream_id, frame->stream_id);
dmcardlecf0bfcf2019-12-13 08:08:21 -08003480 EXPECT_EQ("ABCDEF",
3481 quiche::QuicheStringPiece(frame->data_buffer, frame->data_length));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003482}
3483
3484TEST_P(QuicConnectionTest, FramePackingSendvQueued) {
nharper46833c32019-05-15 21:33:05 -07003485 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003486 // Try to send two stream frames in 1 packet by using writev.
3487 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3488
3489 BlockOnNextWrite();
3490 char data[] = "ABCDEF";
3491 struct iovec iov[2];
3492 iov[0].iov_base = data;
3493 iov[0].iov_len = 4;
3494 iov[1].iov_base = data + 4;
3495 iov[1].iov_len = 2;
nharper46833c32019-05-15 21:33:05 -07003496 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
3497 connection_.transport_version(), Perspective::IS_CLIENT);
3498 connection_.SaveAndSendStreamData(stream_id, iov, 2, 6, 0, NO_FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003499
3500 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3501 EXPECT_TRUE(connection_.HasQueuedData());
3502
3503 // Unblock the writes and actually send.
3504 writer_->SetWritable();
3505 connection_.OnCanWrite();
3506 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3507
3508 // Parse the last packet and ensure it's one stream frame from one stream.
nharper46833c32019-05-15 21:33:05 -07003509 EXPECT_EQ(1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003510 EXPECT_EQ(1u, writer_->stream_frames().size());
nharper46833c32019-05-15 21:33:05 -07003511 EXPECT_EQ(0u, writer_->padding_frames().size());
3512 EXPECT_EQ(stream_id, writer_->stream_frames()[0]->stream_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003513}
3514
3515TEST_P(QuicConnectionTest, SendingZeroBytes) {
3516 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3517 // Send a zero byte write with a fin using writev.
3518 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
nharper46833c32019-05-15 21:33:05 -07003519 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
3520 connection_.transport_version(), Perspective::IS_CLIENT);
3521 connection_.SaveAndSendStreamData(stream_id, nullptr, 0, 0, 0, FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003522
3523 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3524 EXPECT_FALSE(connection_.HasQueuedData());
3525
nharper55fa6132019-05-07 19:37:21 -07003526 // Padding frames are added by v99 to ensure a minimum packet size.
3527 size_t extra_padding_frames = 0;
3528 if (GetParam().version.HasHeaderProtection()) {
3529 extra_padding_frames = 1;
3530 }
3531
QUICHE teama6ef0a62019-03-07 20:34:33 -05003532 // Parse the last packet and ensure it's one stream frame from one stream.
nharper55fa6132019-05-07 19:37:21 -07003533 EXPECT_EQ(1u + extra_padding_frames, writer_->frame_count());
3534 EXPECT_EQ(extra_padding_frames, writer_->padding_frames().size());
3535 ASSERT_EQ(1u, writer_->stream_frames().size());
nharper46833c32019-05-15 21:33:05 -07003536 EXPECT_EQ(stream_id, writer_->stream_frames()[0]->stream_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003537 EXPECT_TRUE(writer_->stream_frames()[0]->fin);
3538}
3539
3540TEST_P(QuicConnectionTest, LargeSendWithPendingAck) {
3541 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3542 // Set the ack alarm by processing a ping frame.
3543 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3544
3545 // Processs a PING frame.
3546 ProcessFramePacket(QuicFrame(QuicPingFrame()));
3547 // Ensure that this has caused the ACK alarm to be set.
fayang9adfb532020-06-04 06:58:45 -07003548 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003549
3550 // Send data and ensure the ack is bundled.
3551 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(8);
3552 size_t len = 10000;
3553 std::unique_ptr<char[]> data_array(new char[len]);
3554 memset(data_array.get(), '?', len);
3555 struct iovec iov;
3556 iov.iov_base = data_array.get();
3557 iov.iov_len = len;
3558 QuicConsumedData consumed = connection_.SaveAndSendStreamData(
dschinazi552accc2019-06-17 17:07:34 -07003559 GetNthClientInitiatedStreamId(0, connection_.transport_version()), &iov,
3560 1, len, 0, FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003561 EXPECT_EQ(len, consumed.bytes_consumed);
3562 EXPECT_TRUE(consumed.fin_consumed);
3563 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3564 EXPECT_FALSE(connection_.HasQueuedData());
3565
3566 // Parse the last packet and ensure it's one stream frame with a fin.
3567 EXPECT_EQ(1u, writer_->frame_count());
nharper55fa6132019-05-07 19:37:21 -07003568 ASSERT_EQ(1u, writer_->stream_frames().size());
dschinazi552accc2019-06-17 17:07:34 -07003569 EXPECT_EQ(GetNthClientInitiatedStreamId(0, connection_.transport_version()),
QUICHE teama6ef0a62019-03-07 20:34:33 -05003570 writer_->stream_frames()[0]->stream_id);
3571 EXPECT_TRUE(writer_->stream_frames()[0]->fin);
3572 // Ensure the ack alarm was cancelled when the ack was sent.
fayang9adfb532020-06-04 06:58:45 -07003573 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003574}
3575
3576TEST_P(QuicConnectionTest, OnCanWrite) {
3577 // Visitor's OnCanWrite will send data, but will have more pending writes.
3578 EXPECT_CALL(visitor_, OnCanWrite())
3579 .WillOnce(DoAll(IgnoreResult(InvokeWithoutArgs(
3580 &connection_, &TestConnection::SendStreamData3)),
3581 IgnoreResult(InvokeWithoutArgs(
3582 &connection_, &TestConnection::SendStreamData5))));
3583 {
3584 InSequence seq;
3585 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillOnce(Return(true));
3586 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
3587 .WillRepeatedly(Return(false));
3588 }
3589
3590 EXPECT_CALL(*send_algorithm_, CanSend(_))
3591 .WillRepeatedly(testing::Return(true));
3592
3593 connection_.OnCanWrite();
3594
3595 // Parse the last packet and ensure it's the two stream frames from
3596 // two different streams.
3597 EXPECT_EQ(2u, writer_->frame_count());
3598 EXPECT_EQ(2u, writer_->stream_frames().size());
3599 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3600 writer_->stream_frames()[0]->stream_id);
3601 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3602 writer_->stream_frames()[1]->stream_id);
3603}
3604
3605TEST_P(QuicConnectionTest, RetransmitOnNack) {
3606 QuicPacketNumber last_packet;
3607 QuicByteCount second_packet_size;
3608 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet); // Packet 1
3609 second_packet_size =
3610 SendStreamDataToPeer(3, "foos", 3, NO_FIN, &last_packet); // Packet 2
3611 SendStreamDataToPeer(3, "fooos", 7, NO_FIN, &last_packet); // Packet 3
3612
3613 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3614
3615 // Don't lose a packet on an ack, and nothing is retransmitted.
3616 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3617 QuicAckFrame ack_one = InitAckFrame(1);
3618 ProcessAckPacket(&ack_one);
3619
3620 // Lose a packet and ensure it triggers retransmission.
3621 QuicAckFrame nack_two = ConstructAckFrame(3, 2);
3622 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003623 lost_packets.push_back(
3624 LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003625 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07003626 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
3627 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003628 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3629 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3630 EXPECT_FALSE(QuicPacketCreatorPeer::SendVersionInPacket(creator_));
3631 ProcessAckPacket(&nack_two);
3632}
3633
3634TEST_P(QuicConnectionTest, DoNotSendQueuedPacketForResetStream) {
3635 // Block the connection to queue the packet.
3636 BlockOnNextWrite();
3637
3638 QuicStreamId stream_id = 2;
3639 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
3640
3641 // Now that there is a queued packet, reset the stream.
3642 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
3643
3644 // Unblock the connection and verify that only the RST_STREAM is sent.
3645 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3646 writer_->SetWritable();
3647 connection_.OnCanWrite();
nharper55fa6132019-05-07 19:37:21 -07003648 size_t padding_frame_count = writer_->padding_frames().size();
3649 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003650 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3651}
3652
3653TEST_P(QuicConnectionTest, SendQueuedPacketForQuicRstStreamNoError) {
3654 // Block the connection to queue the packet.
3655 BlockOnNextWrite();
3656
3657 QuicStreamId stream_id = 2;
fayange62e63c2019-12-04 07:16:25 -08003658 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003659 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
3660
3661 // Now that there is a queued packet, reset the stream.
3662 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 3);
3663
3664 // Unblock the connection and verify that the RST_STREAM is sent and the data
3665 // packet is sent.
fayange62e63c2019-12-04 07:16:25 -08003666 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003667 writer_->SetWritable();
3668 connection_.OnCanWrite();
nharper55fa6132019-05-07 19:37:21 -07003669 size_t padding_frame_count = writer_->padding_frames().size();
3670 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003671 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3672}
3673
3674TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnNack) {
3675 QuicStreamId stream_id = 2;
3676 QuicPacketNumber last_packet;
3677 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3678 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3679 SendStreamDataToPeer(stream_id, "fooos", 7, NO_FIN, &last_packet);
3680
3681 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3682 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 12);
3683
3684 // Lose a packet and ensure it does not trigger retransmission.
3685 QuicAckFrame nack_two = ConstructAckFrame(last_packet, last_packet - 1);
3686 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3687 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3688 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3689 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3690 ProcessAckPacket(&nack_two);
3691}
3692
3693TEST_P(QuicConnectionTest, RetransmitForQuicRstStreamNoErrorOnNack) {
3694 QuicStreamId stream_id = 2;
3695 QuicPacketNumber last_packet;
3696 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3697 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3698 SendStreamDataToPeer(stream_id, "fooos", 7, NO_FIN, &last_packet);
3699
3700 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3701 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 12);
3702
3703 // Lose a packet, ensure it triggers retransmission.
3704 QuicAckFrame nack_two = ConstructAckFrame(last_packet, last_packet - 1);
3705 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3706 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003707 lost_packets.push_back(LostPacket(last_packet - 1, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003708 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07003709 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
3710 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003711 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3712 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
3713 ProcessAckPacket(&nack_two);
3714}
3715
3716TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnRTO) {
3717 QuicStreamId stream_id = 2;
3718 QuicPacketNumber last_packet;
3719 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3720
3721 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3722 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
3723
3724 // Fire the RTO and verify that the RST_STREAM is resent, not stream data.
3725 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3726 clock_.AdvanceTime(DefaultRetransmissionTime());
3727 connection_.GetRetransmissionAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07003728 size_t padding_frame_count = writer_->padding_frames().size();
3729 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003730 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3731 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
3732}
3733
3734// Ensure that if the only data in flight is non-retransmittable, the
3735// retransmission alarm is not set.
3736TEST_P(QuicConnectionTest, CancelRetransmissionAlarmAfterResetStream) {
3737 QuicStreamId stream_id = 2;
3738 QuicPacketNumber last_data_packet;
3739 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
3740
3741 // Cancel the stream.
3742 const QuicPacketNumber rst_packet = last_data_packet + 1;
3743 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, rst_packet, _, _)).Times(1);
3744 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
3745
3746 // Ack the RST_STREAM frame (since it's retransmittable), but not the data
3747 // packet, which is no longer retransmittable since the stream was cancelled.
3748 QuicAckFrame nack_stream_data =
3749 ConstructAckFrame(rst_packet, last_data_packet);
3750 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3751 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3752 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3753 ProcessAckPacket(&nack_stream_data);
3754
3755 // Ensure that the data is still in flight, but the retransmission alarm is no
3756 // longer set.
ianswett9f459cb2019-04-21 06:39:59 -07003757 EXPECT_GT(manager_->GetBytesInFlight(), 0u);
fayangcff885a2019-10-22 07:39:04 -07003758 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003759}
3760
3761TEST_P(QuicConnectionTest, RetransmitForQuicRstStreamNoErrorOnRTO) {
3762 connection_.SetMaxTailLossProbes(0);
3763
3764 QuicStreamId stream_id = 2;
3765 QuicPacketNumber last_packet;
3766 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3767
3768 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3769 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 3);
3770
3771 // Fire the RTO and verify that the RST_STREAM is resent, the stream data
3772 // is sent.
fayang1c2d1ab2020-03-11 12:08:41 -07003773 const size_t num_retransmissions =
3774 connection_.SupportsMultiplePacketNumberSpaces() ? 1 : 2;
3775 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3776 .Times(AtLeast(num_retransmissions));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003777 clock_.AdvanceTime(DefaultRetransmissionTime());
3778 connection_.GetRetransmissionAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07003779 size_t padding_frame_count = writer_->padding_frames().size();
3780 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
fayang1c2d1ab2020-03-11 12:08:41 -07003781 if (num_retransmissions == 2) {
3782 ASSERT_EQ(1u, writer_->rst_stream_frames().size());
3783 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
3784 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003785}
3786
3787TEST_P(QuicConnectionTest, DoNotSendPendingRetransmissionForResetStream) {
3788 QuicStreamId stream_id = 2;
3789 QuicPacketNumber last_packet;
3790 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3791 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3792 BlockOnNextWrite();
3793 connection_.SendStreamDataWithString(stream_id, "fooos", 7, NO_FIN);
3794
3795 // Lose a packet which will trigger a pending retransmission.
3796 QuicAckFrame ack = ConstructAckFrame(last_packet, last_packet - 1);
3797 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3798 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3799 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3800 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3801 ProcessAckPacket(&ack);
3802
3803 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 12);
3804
3805 // Unblock the connection and verify that the RST_STREAM is sent but not the
3806 // second data packet nor a retransmit.
3807 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3808 writer_->SetWritable();
3809 connection_.OnCanWrite();
nharper55fa6132019-05-07 19:37:21 -07003810 size_t padding_frame_count = writer_->padding_frames().size();
3811 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
zhongyi546cc452019-04-12 15:27:49 -07003812 ASSERT_EQ(1u, writer_->rst_stream_frames().size());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003813 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
3814}
3815
3816TEST_P(QuicConnectionTest, SendPendingRetransmissionForQuicRstStreamNoError) {
3817 QuicStreamId stream_id = 2;
3818 QuicPacketNumber last_packet;
3819 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3820 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3821 BlockOnNextWrite();
3822 connection_.SendStreamDataWithString(stream_id, "fooos", 7, NO_FIN);
3823
3824 // Lose a packet which will trigger a pending retransmission.
3825 QuicAckFrame ack = ConstructAckFrame(last_packet, last_packet - 1);
3826 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3827 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003828 lost_packets.push_back(LostPacket(last_packet - 1, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003829 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07003830 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
3831 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003832 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3833 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3834 ProcessAckPacket(&ack);
3835
3836 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 12);
3837
3838 // Unblock the connection and verify that the RST_STREAM is sent and the
3839 // second data packet or a retransmit is sent.
3840 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(2));
3841 writer_->SetWritable();
3842 connection_.OnCanWrite();
3843 // The RST_STREAM_FRAME is sent after queued packets and pending
3844 // retransmission.
3845 connection_.SendControlFrame(QuicFrame(
3846 new QuicRstStreamFrame(1, stream_id, QUIC_STREAM_NO_ERROR, 14)));
nharper55fa6132019-05-07 19:37:21 -07003847 size_t padding_frame_count = writer_->padding_frames().size();
3848 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003849 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3850}
3851
3852TEST_P(QuicConnectionTest, RetransmitAckedPacket) {
3853 QuicPacketNumber last_packet;
3854 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
3855 SendStreamDataToPeer(1, "foos", 3, NO_FIN, &last_packet); // Packet 2
3856 SendStreamDataToPeer(1, "fooos", 7, NO_FIN, &last_packet); // Packet 3
3857
3858 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3859
3860 // Instigate a loss with an ack.
3861 QuicAckFrame nack_two = ConstructAckFrame(3, 2);
3862 // The first nack should trigger a fast retransmission, but we'll be
3863 // write blocked, so the packet will be queued.
3864 BlockOnNextWrite();
3865
3866 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003867 lost_packets.push_back(
3868 LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003869 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07003870 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
3871 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003872 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
fayange62e63c2019-12-04 07:16:25 -08003873 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _))
3874 .Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003875 ProcessAckPacket(&nack_two);
3876 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3877
3878 // Now, ack the previous transmission.
3879 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3880 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(false, _, _, _, _));
3881 QuicAckFrame ack_all = InitAckFrame(3);
3882 ProcessAckPacket(&ack_all);
3883
fayange62e63c2019-12-04 07:16:25 -08003884 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _))
3885 .Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003886
3887 writer_->SetWritable();
3888 connection_.OnCanWrite();
3889
3890 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3891 // We do not store retransmittable frames of this retransmission.
3892 EXPECT_FALSE(QuicConnectionPeer::HasRetransmittableFrames(&connection_, 4));
3893}
3894
3895TEST_P(QuicConnectionTest, RetransmitNackedLargestObserved) {
3896 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3897 QuicPacketNumber original, second;
3898
3899 QuicByteCount packet_size =
3900 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &original); // 1st packet.
3901 SendStreamDataToPeer(3, "bar", 3, NO_FIN, &second); // 2nd packet.
3902
3903 QuicAckFrame frame = InitAckFrame({{second, second + 1}});
3904 // The first nack should retransmit the largest observed packet.
3905 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003906 lost_packets.push_back(LostPacket(original, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003907 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07003908 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
3909 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003910 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3911 // Packet 1 is short header for IETF QUIC because the encryption level
3912 // switched to ENCRYPTION_FORWARD_SECURE in SendStreamDataToPeer.
fayangd4291e42019-05-30 10:31:21 -07003913 EXPECT_CALL(*send_algorithm_,
3914 OnPacketSent(_, _, _,
3915 VersionHasIetfInvariantHeader(
3916 GetParam().version.transport_version)
3917 ? packet_size
3918 : packet_size - kQuicVersionSize,
3919 _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003920 ProcessAckPacket(&frame);
3921}
3922
3923TEST_P(QuicConnectionTest, QueueAfterTwoRTOs) {
fayangcff885a2019-10-22 07:39:04 -07003924 if (connection_.PtoEnabled()) {
fayang5f135052019-08-22 17:59:40 -07003925 return;
3926 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003927 connection_.SetMaxTailLossProbes(0);
3928
3929 for (int i = 0; i < 10; ++i) {
3930 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3931 connection_.SendStreamDataWithString(3, "foo", i * 3, NO_FIN);
3932 }
3933
3934 // Block the writer and ensure they're queued.
3935 BlockOnNextWrite();
3936 clock_.AdvanceTime(DefaultRetransmissionTime());
fayange62e63c2019-12-04 07:16:25 -08003937 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003938 connection_.GetRetransmissionAlarm()->Fire();
3939 EXPECT_TRUE(connection_.HasQueuedData());
3940
3941 // Unblock the writer.
3942 writer_->SetWritable();
3943 clock_.AdvanceTime(QuicTime::Delta::FromMicroseconds(
3944 2 * DefaultRetransmissionTime().ToMicroseconds()));
fayange62e63c2019-12-04 07:16:25 -08003945 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003946 connection_.GetRetransmissionAlarm()->Fire();
3947 connection_.OnCanWrite();
3948}
3949
3950TEST_P(QuicConnectionTest, WriteBlockedBufferedThenSent) {
3951 BlockOnNextWrite();
3952 writer_->set_is_write_blocked_data_buffered(true);
3953 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3954 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3955 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3956
3957 writer_->SetWritable();
3958 connection_.OnCanWrite();
3959 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3960}
3961
3962TEST_P(QuicConnectionTest, WriteBlockedThenSent) {
3963 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3964 BlockOnNextWrite();
fayange62e63c2019-12-04 07:16:25 -08003965 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003966 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
fayange62e63c2019-12-04 07:16:25 -08003967 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003968 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3969
3970 // The second packet should also be queued, in order to ensure packets are
3971 // never sent out of order.
3972 writer_->SetWritable();
fayange62e63c2019-12-04 07:16:25 -08003973 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003974 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3975 EXPECT_EQ(2u, connection_.NumQueuedPackets());
3976
3977 // Now both are sent in order when we unblock.
fayange62e63c2019-12-04 07:16:25 -08003978 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003979 connection_.OnCanWrite();
3980 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
fayang2ce66082019-10-02 06:29:04 -07003981 EXPECT_EQ(0u, connection_.NumQueuedPackets());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003982}
3983
3984TEST_P(QuicConnectionTest, RetransmitWriteBlockedAckedOriginalThenSent) {
3985 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3986 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
3987 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3988
3989 BlockOnNextWrite();
3990 writer_->set_is_write_blocked_data_buffered(true);
3991 // Simulate the retransmission alarm firing.
3992 clock_.AdvanceTime(DefaultRetransmissionTime());
3993 connection_.GetRetransmissionAlarm()->Fire();
3994
3995 // Ack the sent packet before the callback returns, which happens in
3996 // rare circumstances with write blocked sockets.
3997 QuicAckFrame ack = InitAckFrame(1);
3998 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3999 ProcessAckPacket(&ack);
4000
4001 writer_->SetWritable();
4002 connection_.OnCanWrite();
fayangcff885a2019-10-22 07:39:04 -07004003 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
fayang5d011982020-05-13 14:14:38 -07004004 uint64_t retransmission = connection_.SupportsMultiplePacketNumberSpaces() &&
4005 !GetQuicReloadableFlag(quic_default_on_pto)
4006 ? 3
4007 : 2;
fayang1c2d1ab2020-03-11 12:08:41 -07004008 EXPECT_FALSE(QuicConnectionPeer::HasRetransmittableFrames(&connection_,
4009 retransmission));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004010}
4011
4012TEST_P(QuicConnectionTest, AlarmsWhenWriteBlocked) {
4013 // Block the connection.
4014 BlockOnNextWrite();
4015 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
4016 EXPECT_EQ(1u, writer_->packets_write_attempts());
4017 EXPECT_TRUE(writer_->IsWriteBlocked());
4018
4019 // Set the send alarm. Fire the alarm and ensure it doesn't attempt to write.
4020 connection_.GetSendAlarm()->Set(clock_.ApproximateNow());
4021 connection_.GetSendAlarm()->Fire();
4022 EXPECT_TRUE(writer_->IsWriteBlocked());
4023 EXPECT_EQ(1u, writer_->packets_write_attempts());
4024}
4025
4026TEST_P(QuicConnectionTest, NoSendAlarmAfterProcessPacketWhenWriteBlocked) {
4027 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4028
4029 // Block the connection.
4030 BlockOnNextWrite();
4031 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
4032 EXPECT_TRUE(writer_->IsWriteBlocked());
4033 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4034 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4035
4036 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4037 // Process packet number 1. Can not call ProcessPacket or ProcessDataPacket
4038 // here, because they will fire the alarm after QuicConnection::ProcessPacket
4039 // is returned.
4040 const uint64_t received_packet_num = 1;
4041 const bool has_stop_waiting = false;
nharperc6b99512019-09-19 11:13:48 -07004042 const EncryptionLevel level = ENCRYPTION_FORWARD_SECURE;
4043 std::unique_ptr<QuicPacket> packet(
4044 ConstructDataPacket(received_packet_num, has_stop_waiting, level));
dschinazi66dea072019-04-09 11:41:06 -07004045 char buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05004046 size_t encrypted_length =
4047 peer_framer_.EncryptPayload(level, QuicPacketNumber(received_packet_num),
dschinazi66dea072019-04-09 11:41:06 -07004048 *packet, buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004049 connection_.ProcessUdpPacket(
4050 kSelfAddress, kPeerAddress,
4051 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
4052
4053 EXPECT_TRUE(writer_->IsWriteBlocked());
4054 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4055}
4056
4057TEST_P(QuicConnectionTest, AddToWriteBlockedListIfWriterBlockedWhenProcessing) {
4058 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4059 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
4060
4061 // Simulate the case where a shared writer gets blocked by another connection.
4062 writer_->SetWriteBlocked();
4063
4064 // Process an ACK, make sure the connection calls visitor_->OnWriteBlocked().
4065 QuicAckFrame ack1 = InitAckFrame(1);
4066 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
4067 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
4068 ProcessAckPacket(1, &ack1);
4069}
4070
4071TEST_P(QuicConnectionTest, DoNotAddToWriteBlockedListAfterDisconnect) {
4072 writer_->SetBatchMode(true);
4073 EXPECT_TRUE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07004074 // Have to explicitly grab the OnConnectionClosed frame and check
4075 // its parameters because this is a silent connection close and the
4076 // frame is not also transmitted to the peer.
4077 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
4078 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004079
4080 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
4081
4082 {
fayanga4b37b22019-06-18 13:37:47 -07004083 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004084 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
4085 ConnectionCloseBehavior::SILENT_CLOSE);
4086
4087 EXPECT_FALSE(connection_.connected());
4088 writer_->SetWriteBlocked();
4089 }
fkastenholz5d880a92019-06-21 09:01:56 -07004090 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08004091 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
4092 IsError(QUIC_PEER_GOING_AWAY));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004093}
4094
4095TEST_P(QuicConnectionTest, AddToWriteBlockedListIfBlockedOnFlushPackets) {
4096 writer_->SetBatchMode(true);
4097 writer_->BlockOnNextFlush();
4098
4099 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
4100 {
fayanga4b37b22019-06-18 13:37:47 -07004101 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004102 // flusher's destructor will call connection_.FlushPackets, which should add
4103 // the connection to the write blocked list.
4104 }
4105}
4106
4107TEST_P(QuicConnectionTest, NoLimitPacketsPerNack) {
4108 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4109 int offset = 0;
4110 // Send packets 1 to 15.
4111 for (int i = 0; i < 15; ++i) {
4112 SendStreamDataToPeer(1, "foo", offset, NO_FIN, nullptr);
4113 offset += 3;
4114 }
4115
4116 // Ack 15, nack 1-14.
4117
4118 QuicAckFrame nack =
4119 InitAckFrame({{QuicPacketNumber(15), QuicPacketNumber(16)}});
4120
4121 // 14 packets have been NACK'd and lost.
4122 LostPacketVector lost_packets;
4123 for (int i = 1; i < 15; ++i) {
dschinazi66dea072019-04-09 11:41:06 -07004124 lost_packets.push_back(
4125 LostPacket(QuicPacketNumber(i), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004126 }
4127 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07004128 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
4129 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004130 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
fayangcff885a2019-10-22 07:39:04 -07004131 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004132 ProcessAckPacket(&nack);
4133}
4134
4135// Test sending multiple acks from the connection to the session.
4136TEST_P(QuicConnectionTest, MultipleAcks) {
QUICHE teamcd098022019-03-22 18:49:55 -07004137 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4138 return;
4139 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004140 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4141 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4142 ProcessDataPacket(1);
4143 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
4144 QuicPacketNumber last_packet;
4145 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
4146 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4147 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet); // Packet 2
4148 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
4149 SendAckPacketToPeer(); // Packet 3
4150 SendStreamDataToPeer(5, "foo", 0, NO_FIN, &last_packet); // Packet 4
4151 EXPECT_EQ(QuicPacketNumber(4u), last_packet);
4152 SendStreamDataToPeer(1, "foo", 3, NO_FIN, &last_packet); // Packet 5
4153 EXPECT_EQ(QuicPacketNumber(5u), last_packet);
4154 SendStreamDataToPeer(3, "foo", 3, NO_FIN, &last_packet); // Packet 6
4155 EXPECT_EQ(QuicPacketNumber(6u), last_packet);
4156
4157 // Client will ack packets 1, 2, [!3], 4, 5.
4158 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4159 QuicAckFrame frame1 = ConstructAckFrame(5, 3);
4160 ProcessAckPacket(&frame1);
4161
4162 // Now the client implicitly acks 3, and explicitly acks 6.
4163 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4164 QuicAckFrame frame2 = InitAckFrame(6);
4165 ProcessAckPacket(&frame2);
4166}
4167
4168TEST_P(QuicConnectionTest, DontLatchUnackedPacket) {
QUICHE teamcd098022019-03-22 18:49:55 -07004169 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4170 return;
4171 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004172 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4173 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4174 ProcessDataPacket(1);
4175 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
4176 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr); // Packet 1;
4177 // From now on, we send acks, so the send algorithm won't mark them pending.
4178 SendAckPacketToPeer(); // Packet 2
4179
4180 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4181 QuicAckFrame frame = InitAckFrame(1);
4182 ProcessAckPacket(&frame);
4183
4184 // Verify that our internal state has least-unacked as 2, because we're still
4185 // waiting for a potential ack for 2.
4186
4187 EXPECT_EQ(QuicPacketNumber(2u), stop_waiting()->least_unacked);
4188
4189 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4190 frame = InitAckFrame(2);
4191 ProcessAckPacket(&frame);
4192 EXPECT_EQ(QuicPacketNumber(3u), stop_waiting()->least_unacked);
4193
4194 // When we send an ack, we make sure our least-unacked makes sense. In this
4195 // case since we're not waiting on an ack for 2 and all packets are acked, we
4196 // set it to 3.
4197 SendAckPacketToPeer(); // Packet 3
4198 // Least_unacked remains at 3 until another ack is received.
4199 EXPECT_EQ(QuicPacketNumber(3u), stop_waiting()->least_unacked);
4200 if (GetParam().no_stop_waiting) {
4201 // Expect no stop waiting frame is sent.
4202 EXPECT_FALSE(least_unacked().IsInitialized());
4203 } else {
4204 // Check that the outgoing ack had its packet number as least_unacked.
4205 EXPECT_EQ(QuicPacketNumber(3u), least_unacked());
4206 }
4207
4208 // Ack the ack, which updates the rtt and raises the least unacked.
4209 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4210 frame = InitAckFrame(3);
4211 ProcessAckPacket(&frame);
4212
4213 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr); // Packet 4
4214 EXPECT_EQ(QuicPacketNumber(4u), stop_waiting()->least_unacked);
4215 SendAckPacketToPeer(); // Packet 5
4216 if (GetParam().no_stop_waiting) {
4217 // Expect no stop waiting frame is sent.
4218 EXPECT_FALSE(least_unacked().IsInitialized());
4219 } else {
4220 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
4221 }
4222
4223 // Send two data packets at the end, and ensure if the last one is acked,
4224 // the least unacked is raised above the ack packets.
4225 SendStreamDataToPeer(1, "bar", 6, NO_FIN, nullptr); // Packet 6
4226 SendStreamDataToPeer(1, "bar", 9, NO_FIN, nullptr); // Packet 7
4227
4228 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4229 frame = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(5)},
4230 {QuicPacketNumber(7), QuicPacketNumber(8)}});
4231 ProcessAckPacket(&frame);
4232
4233 EXPECT_EQ(QuicPacketNumber(6u), stop_waiting()->least_unacked);
4234}
4235
4236TEST_P(QuicConnectionTest, TLP) {
fayang5d011982020-05-13 14:14:38 -07004237 if (connection_.PtoEnabled()) {
4238 return;
4239 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004240 connection_.SetMaxTailLossProbes(1);
4241
4242 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
4243 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4244 QuicTime retransmission_time =
4245 connection_.GetRetransmissionAlarm()->deadline();
4246 EXPECT_NE(QuicTime::Zero(), retransmission_time);
4247
4248 EXPECT_EQ(QuicPacketNumber(1u), writer_->header().packet_number);
4249 // Simulate the retransmission alarm firing and sending a tlp,
4250 // so send algorithm's OnRetransmissionTimeout is not called.
4251 clock_.AdvanceTime(retransmission_time - clock_.Now());
fayang1c2d1ab2020-03-11 12:08:41 -07004252 const QuicPacketNumber retransmission(
4253 connection_.SupportsMultiplePacketNumberSpaces() ? 3 : 2);
4254 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, retransmission, _, _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004255 connection_.GetRetransmissionAlarm()->Fire();
fayang1c2d1ab2020-03-11 12:08:41 -07004256 EXPECT_EQ(retransmission, writer_->header().packet_number);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004257 // We do not raise the high water mark yet.
4258 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4259}
4260
zhongyifbb25772019-04-10 16:54:08 -07004261TEST_P(QuicConnectionTest, TailLossProbeDelayForStreamDataInTLPR) {
fayangcff885a2019-10-22 07:39:04 -07004262 if (connection_.PtoEnabled()) {
zhongyi1b2f7832019-06-14 13:31:34 -07004263 return;
4264 }
4265
zhongyifbb25772019-04-10 16:54:08 -07004266 // Set TLPR from QuicConfig.
4267 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4268 QuicConfig config;
4269 QuicTagVector options;
4270 options.push_back(kTLPR);
4271 config.SetConnectionOptionsToSend(options);
4272 connection_.SetFromConfig(config);
4273 connection_.SetMaxTailLossProbes(1);
4274
4275 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
4276 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4277
4278 QuicTime retransmission_time =
4279 connection_.GetRetransmissionAlarm()->deadline();
4280 EXPECT_NE(QuicTime::Zero(), retransmission_time);
4281 QuicTime::Delta expected_tlp_delay =
4282 0.5 * manager_->GetRttStats()->SmoothedOrInitialRtt();
4283 EXPECT_EQ(expected_tlp_delay, retransmission_time - clock_.Now());
4284
4285 EXPECT_EQ(QuicPacketNumber(1u), writer_->header().packet_number);
4286 // Simulate firing of the retransmission alarm and retransmit the packet.
4287 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
4288 clock_.AdvanceTime(retransmission_time - clock_.Now());
4289 connection_.GetRetransmissionAlarm()->Fire();
4290 EXPECT_EQ(QuicPacketNumber(2u), writer_->header().packet_number);
4291
4292 // We do not raise the high water mark yet.
4293 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4294}
4295
4296TEST_P(QuicConnectionTest, TailLossProbeDelayForNonStreamDataInTLPR) {
fayangcff885a2019-10-22 07:39:04 -07004297 if (connection_.PtoEnabled()) {
zhongyi1b2f7832019-06-14 13:31:34 -07004298 return;
4299 }
4300
zhongyifbb25772019-04-10 16:54:08 -07004301 // Set TLPR from QuicConfig.
4302 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4303 QuicConfig config;
4304 QuicTagVector options;
4305 options.push_back(kTLPR);
4306 config.SetConnectionOptionsToSend(options);
dschinazif7c6a912020-05-05 11:39:53 -07004307 QuicConfigPeer::SetNegotiated(&config, true);
dschinazie7c38a52020-05-29 15:25:45 -07004308 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
4309 QuicConfigPeer::SetReceivedOriginalConnectionId(
4310 &config, connection_.connection_id());
4311 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
4312 &config, connection_.connection_id());
4313 }
zhongyifbb25772019-04-10 16:54:08 -07004314 connection_.SetFromConfig(config);
4315 connection_.SetMaxTailLossProbes(1);
4316
4317 // Sets retransmittable on wire.
4318 const QuicTime::Delta retransmittable_on_wire_timeout =
4319 QuicTime::Delta::FromMilliseconds(50);
zhongyi79ace162019-10-21 15:57:09 -07004320 connection_.set_initial_retransmittable_on_wire_timeout(
zhongyifbb25772019-04-10 16:54:08 -07004321 retransmittable_on_wire_timeout);
4322
4323 EXPECT_TRUE(connection_.connected());
4324 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4325 .WillRepeatedly(Return(true));
fayangb59c6f12020-03-23 15:06:14 -07004326 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
zhongyifbb25772019-04-10 16:54:08 -07004327 EXPECT_FALSE(connection_.IsPathDegrading());
4328 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4329
4330 const char data[] = "data";
4331 size_t data_size = strlen(data);
4332 QuicStreamOffset offset = 0;
4333
4334 // Send a data packet.
4335 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
4336 offset += data_size;
4337
4338 // Path degrading alarm should be set when there is a retransmittable packet
4339 // on the wire.
fayangb59c6f12020-03-23 15:06:14 -07004340 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
zhongyifbb25772019-04-10 16:54:08 -07004341
4342 // Verify the path degrading delay.
4343 // First TLP with stream data.
4344 QuicTime::Delta srtt = manager_->GetRttStats()->SmoothedOrInitialRtt();
4345 QuicTime::Delta expected_delay = 0.5 * srtt;
4346 // Add 1st RTO.
4347 QuicTime::Delta retransmission_delay =
4348 QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
4349 expected_delay = expected_delay + retransmission_delay;
4350 // Add 2nd RTO.
4351 expected_delay = expected_delay + retransmission_delay * 2;
4352 EXPECT_EQ(expected_delay,
4353 QuicConnectionPeer::GetSentPacketManager(&connection_)
4354 ->GetPathDegradingDelay());
4355 ASSERT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
4356
4357 // The ping alarm is set for the ping timeout, not the shorter
4358 // retransmittable_on_wire_timeout.
4359 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004360 EXPECT_EQ(connection_.ping_timeout(),
zhongyifbb25772019-04-10 16:54:08 -07004361 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
4362
4363 // Receive an ACK for the data packet.
4364 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4365 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4366 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4367 QuicAckFrame frame =
4368 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
4369 ProcessAckPacket(&frame);
4370
4371 // Path degrading alarm should be cancelled as there is no more
4372 // reretransmittable packets on the wire.
fayangb59c6f12020-03-23 15:06:14 -07004373 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
zhongyifbb25772019-04-10 16:54:08 -07004374 // The ping alarm should be set to the retransmittable_on_wire_timeout.
4375 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4376 EXPECT_EQ(retransmittable_on_wire_timeout,
4377 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
4378
4379 // Simulate firing of the retransmittable on wire and send a PING.
4380 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
4381 clock_.AdvanceTime(retransmittable_on_wire_timeout);
4382 connection_.GetPingAlarm()->Fire();
4383
4384 // The retransmission alarm and the path degrading alarm should be set as
4385 // there is a retransmittable packet (PING) on the wire,
4386 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
fayangb59c6f12020-03-23 15:06:14 -07004387 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
zhongyifbb25772019-04-10 16:54:08 -07004388
4389 // Verify the retransmission delay.
4390 QuicTime::Delta min_rto_timeout =
4391 QuicTime::Delta::FromMilliseconds(kMinRetransmissionTimeMs);
4392 srtt = manager_->GetRttStats()->SmoothedOrInitialRtt();
zhongyi9fa2be32019-09-10 12:39:01 -07004393
4394 // First TLP without unacked stream data will no longer use TLPR.
4395 expected_delay = std::max(2 * srtt, 1.5 * srtt + 0.5 * min_rto_timeout);
zhongyifbb25772019-04-10 16:54:08 -07004396 EXPECT_EQ(expected_delay,
4397 connection_.GetRetransmissionAlarm()->deadline() - clock_.Now());
4398
zhongyi1b2f7832019-06-14 13:31:34 -07004399 // Verify the path degrading delay = TLP delay + 1st RTO + 2nd RTO.
zhongyifbb25772019-04-10 16:54:08 -07004400 // Add 1st RTO.
4401 retransmission_delay =
4402 std::max(manager_->GetRttStats()->smoothed_rtt() +
4403 4 * manager_->GetRttStats()->mean_deviation(),
4404 min_rto_timeout);
4405 expected_delay = expected_delay + retransmission_delay;
4406 // Add 2nd RTO.
4407 expected_delay = expected_delay + retransmission_delay * 2;
4408 EXPECT_EQ(expected_delay,
4409 QuicConnectionPeer::GetSentPacketManager(&connection_)
4410 ->GetPathDegradingDelay());
4411
4412 // The ping alarm is set for the ping timeout, not the shorter
4413 // retransmittable_on_wire_timeout.
4414 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004415 EXPECT_EQ(connection_.ping_timeout(),
zhongyifbb25772019-04-10 16:54:08 -07004416 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
zhongyi1b2f7832019-06-14 13:31:34 -07004417
4418 // Advance a small period of time: 5ms. And receive a retransmitted ACK.
4419 // This will update the retransmission alarm, verify the retransmission delay
4420 // is correct.
4421 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4422 QuicAckFrame ack = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
4423 ProcessAckPacket(&ack);
4424
4425 // Verify the retransmission delay.
zhongyi9fa2be32019-09-10 12:39:01 -07004426 // First TLP without unacked stream data will no longer use TLPR.
4427 expected_delay = std::max(2 * srtt, 1.5 * srtt + 0.5 * min_rto_timeout);
zhongyi1b2f7832019-06-14 13:31:34 -07004428 expected_delay = expected_delay - QuicTime::Delta::FromMilliseconds(5);
4429 EXPECT_EQ(expected_delay,
4430 connection_.GetRetransmissionAlarm()->deadline() - clock_.Now());
zhongyifbb25772019-04-10 16:54:08 -07004431}
4432
QUICHE teama6ef0a62019-03-07 20:34:33 -05004433TEST_P(QuicConnectionTest, RTO) {
fayang5f135052019-08-22 17:59:40 -07004434 if (connection_.PtoEnabled()) {
4435 return;
4436 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004437 connection_.SetMaxTailLossProbes(0);
4438
4439 QuicTime default_retransmission_time =
4440 clock_.ApproximateNow() + DefaultRetransmissionTime();
4441 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
4442 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4443
4444 EXPECT_EQ(QuicPacketNumber(1u), writer_->header().packet_number);
4445 EXPECT_EQ(default_retransmission_time,
4446 connection_.GetRetransmissionAlarm()->deadline());
4447 // Simulate the retransmission alarm firing.
4448 clock_.AdvanceTime(DefaultRetransmissionTime());
4449 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
4450 connection_.GetRetransmissionAlarm()->Fire();
4451 EXPECT_EQ(QuicPacketNumber(2u), writer_->header().packet_number);
4452 // We do not raise the high water mark yet.
4453 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4454}
4455
fayanga29eb242019-07-16 12:25:38 -07004456// Regression test of b/133771183.
4457TEST_P(QuicConnectionTest, RtoWithNoDataToRetransmit) {
fayangcff885a2019-10-22 07:39:04 -07004458 if (connection_.PtoEnabled()) {
fayanga29eb242019-07-16 12:25:38 -07004459 return;
4460 }
4461 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4462 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4463 connection_.SetMaxTailLossProbes(0);
4464
4465 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
4466 // Connection is cwnd limited.
4467 CongestionBlockWrites();
4468 // Stream gets reset.
4469 SendRstStream(3, QUIC_ERROR_PROCESSING_STREAM, 3);
4470 // Simulate the retransmission alarm firing.
4471 clock_.AdvanceTime(DefaultRetransmissionTime());
4472 // RTO fires, but there is no packet to be RTOed.
fayange861aee2019-10-16 13:40:39 -07004473 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
fayanga29eb242019-07-16 12:25:38 -07004474 connection_.GetRetransmissionAlarm()->Fire();
fayange861aee2019-10-16 13:40:39 -07004475 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
fayanga29eb242019-07-16 12:25:38 -07004476
4477 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(40);
4478 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(20);
fayange861aee2019-10-16 13:40:39 -07004479 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(false));
4480 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(1);
fayanga29eb242019-07-16 12:25:38 -07004481 // Receives packets 1 - 40.
4482 for (size_t i = 1; i <= 40; ++i) {
4483 ProcessDataPacket(i);
4484 }
4485}
4486
QUICHE teama6ef0a62019-03-07 20:34:33 -05004487TEST_P(QuicConnectionTest, SendHandshakeMessages) {
4488 use_tagging_decrypter();
4489 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
4490 // the end of the packet. We can test this to check which encrypter was used.
QUICHE team6987b4a2019-03-15 16:23:04 -07004491 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07004492 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004493
4494 // Attempt to send a handshake message and have the socket block.
4495 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
4496 BlockOnNextWrite();
nharper46833c32019-05-15 21:33:05 -07004497 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004498 // The packet should be serialized, but not queued.
4499 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4500
4501 // Switch to the new encrypter.
4502 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004503 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004504 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4505
4506 // Now become writeable and flush the packets.
4507 writer_->SetWritable();
4508 EXPECT_CALL(visitor_, OnCanWrite());
4509 connection_.OnCanWrite();
4510 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4511
4512 // Verify that the handshake packet went out at the null encryption.
4513 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
4514}
4515
4516TEST_P(QuicConnectionTest,
4517 DropRetransmitsForNullEncryptedPacketAfterForwardSecure) {
4518 use_tagging_decrypter();
QUICHE team6987b4a2019-03-15 16:23:04 -07004519 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07004520 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004521 connection_.SendCryptoStreamData();
4522
4523 // Simulate the retransmission alarm firing and the socket blocking.
4524 BlockOnNextWrite();
4525 clock_.AdvanceTime(DefaultRetransmissionTime());
fayange62e63c2019-12-04 07:16:25 -08004526 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004527 connection_.GetRetransmissionAlarm()->Fire();
fayang2ce66082019-10-02 06:29:04 -07004528 EXPECT_EQ(1u, connection_.NumQueuedPackets());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004529
4530 // Go forward secure.
4531 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07004532 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004533 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4534 notifier_.NeuterUnencryptedData();
4535 connection_.NeuterUnencryptedPackets();
fayang2ce66082019-10-02 06:29:04 -07004536 connection_.OnHandshakeComplete();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004537
4538 EXPECT_EQ(QuicTime::Zero(), connection_.GetRetransmissionAlarm()->deadline());
4539 // Unblock the socket and ensure that no packets are sent.
4540 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4541 writer_->SetWritable();
4542 connection_.OnCanWrite();
4543}
4544
4545TEST_P(QuicConnectionTest, RetransmitPacketsWithInitialEncryption) {
renjietang37d4ae12020-06-18 11:18:31 -07004546 SetQuicReloadableFlag(quic_do_not_retransmit_immediately_on_zero_rtt_reject,
4547 true);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004548 use_tagging_decrypter();
QUICHE team6987b4a2019-03-15 16:23:04 -07004549 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07004550 std::make_unique<TaggingEncrypter>(0x01));
QUICHE team6987b4a2019-03-15 16:23:04 -07004551 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004552
nharper46833c32019-05-15 21:33:05 -07004553 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004554
4555 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004556 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004557 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4558
4559 SendStreamDataToPeer(2, "bar", 0, NO_FIN, nullptr);
renjietang37d4ae12020-06-18 11:18:31 -07004560 EXPECT_FALSE(notifier_.HasLostStreamData());
renjietangc0080082020-05-26 18:35:19 -07004561 connection_.RetransmitZeroRttPackets();
renjietang37d4ae12020-06-18 11:18:31 -07004562 EXPECT_TRUE(notifier_.HasLostStreamData());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004563}
4564
4565TEST_P(QuicConnectionTest, BufferNonDecryptablePackets) {
QUICHE teamcd098022019-03-22 18:49:55 -07004566 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4567 return;
4568 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004569 // SetFromConfig is always called after construction from InitializeSession.
4570 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4571 QuicConfig config;
4572 connection_.SetFromConfig(config);
4573 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4574 use_tagging_decrypter();
4575
4576 const uint8_t tag = 0x07;
4577 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004578 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004579
4580 // Process an encrypted packet which can not yet be decrypted which should
4581 // result in the packet being buffered.
4582 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4583
4584 // Transition to the new encryption state and process another encrypted packet
4585 // which should result in the original packet being processed.
zhongyi546cc452019-04-12 15:27:49 -07004586 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004587 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004588 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4589 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004590 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004591 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(2);
4592 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4593
4594 // Finally, process a third packet and note that we do not reprocess the
4595 // buffered packet.
4596 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4597 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4598}
4599
4600TEST_P(QuicConnectionTest, TestRetransmitOrder) {
fayang5f135052019-08-22 17:59:40 -07004601 if (connection_.PtoEnabled()) {
4602 return;
4603 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004604 connection_.SetMaxTailLossProbes(0);
4605
4606 QuicByteCount first_packet_size;
4607 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4608 .WillOnce(SaveArg<3>(&first_packet_size));
4609
4610 connection_.SendStreamDataWithString(3, "first_packet", 0, NO_FIN);
4611 QuicByteCount second_packet_size;
4612 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4613 .WillOnce(SaveArg<3>(&second_packet_size));
4614 connection_.SendStreamDataWithString(3, "second_packet", 12, NO_FIN);
4615 EXPECT_NE(first_packet_size, second_packet_size);
4616 // Advance the clock by huge time to make sure packets will be retransmitted.
4617 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
4618 {
4619 InSequence s;
4620 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, first_packet_size, _));
4621 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, second_packet_size, _));
4622 }
4623 connection_.GetRetransmissionAlarm()->Fire();
4624
4625 // Advance again and expect the packets to be sent again in the same order.
4626 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(20));
4627 {
4628 InSequence s;
4629 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, first_packet_size, _));
4630 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, second_packet_size, _));
4631 }
4632 connection_.GetRetransmissionAlarm()->Fire();
4633}
4634
4635TEST_P(QuicConnectionTest, Buffer100NonDecryptablePacketsThenKeyChange) {
QUICHE teamcd098022019-03-22 18:49:55 -07004636 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4637 return;
4638 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004639 // SetFromConfig is always called after construction from InitializeSession.
4640 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4641 QuicConfig config;
4642 config.set_max_undecryptable_packets(100);
4643 connection_.SetFromConfig(config);
4644 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4645 use_tagging_decrypter();
4646
4647 const uint8_t tag = 0x07;
4648 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004649 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004650
4651 // Process an encrypted packet which can not yet be decrypted which should
4652 // result in the packet being buffered.
4653 for (uint64_t i = 1; i <= 100; ++i) {
4654 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4655 }
4656
4657 // Transition to the new encryption state and process another encrypted packet
4658 // which should result in the original packets being processed.
4659 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
zhongyi546cc452019-04-12 15:27:49 -07004660 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004661 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004662 EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
4663 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4664 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004665 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004666
4667 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(100);
4668 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
4669
4670 // Finally, process a third packet and note that we do not reprocess the
4671 // buffered packet.
4672 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4673 ProcessDataPacketAtLevel(102, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4674}
4675
4676TEST_P(QuicConnectionTest, SetRTOAfterWritingToSocket) {
4677 BlockOnNextWrite();
fayange62e63c2019-12-04 07:16:25 -08004678 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004679 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
fayange62e63c2019-12-04 07:16:25 -08004680 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004681
4682 // Test that RTO is started once we write to the socket.
4683 writer_->SetWritable();
fayange62e63c2019-12-04 07:16:25 -08004684 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004685 connection_.OnCanWrite();
4686 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4687}
4688
4689TEST_P(QuicConnectionTest, DelayRTOWithAckReceipt) {
fayang5f135052019-08-22 17:59:40 -07004690 if (connection_.PtoEnabled()) {
4691 return;
4692 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004693 connection_.SetMaxTailLossProbes(0);
4694
4695 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4696 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
4697 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
4698 connection_.SendStreamDataWithString(3, "bar", 0, NO_FIN);
4699 QuicAlarm* retransmission_alarm = connection_.GetRetransmissionAlarm();
4700 EXPECT_TRUE(retransmission_alarm->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004701 EXPECT_EQ(DefaultRetransmissionTime(),
4702 retransmission_alarm->deadline() - clock_.Now());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004703
4704 // Advance the time right before the RTO, then receive an ack for the first
4705 // packet to delay the RTO.
4706 clock_.AdvanceTime(DefaultRetransmissionTime());
4707 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4708 QuicAckFrame ack = InitAckFrame(1);
4709 ProcessAckPacket(&ack);
4710 // Now we have an RTT sample of DefaultRetransmissionTime(500ms),
4711 // so the RTO has increased to 2 * SRTT.
4712 EXPECT_TRUE(retransmission_alarm->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004713 EXPECT_EQ(retransmission_alarm->deadline() - clock_.Now(),
4714 2 * DefaultRetransmissionTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004715
4716 // Move forward past the original RTO and ensure the RTO is still pending.
4717 clock_.AdvanceTime(2 * DefaultRetransmissionTime());
4718
4719 // Ensure the second packet gets retransmitted when it finally fires.
4720 EXPECT_TRUE(retransmission_alarm->IsSet());
4721 EXPECT_EQ(retransmission_alarm->deadline(), clock_.ApproximateNow());
4722 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4723 // Manually cancel the alarm to simulate a real test.
4724 connection_.GetRetransmissionAlarm()->Fire();
4725
4726 // The new retransmitted packet number should set the RTO to a larger value
4727 // than previously.
4728 EXPECT_TRUE(retransmission_alarm->IsSet());
4729 QuicTime next_rto_time = retransmission_alarm->deadline();
4730 QuicTime expected_rto_time =
4731 connection_.sent_packet_manager().GetRetransmissionTime();
4732 EXPECT_EQ(next_rto_time, expected_rto_time);
4733}
4734
4735TEST_P(QuicConnectionTest, TestQueued) {
4736 connection_.SetMaxTailLossProbes(0);
4737
4738 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4739 BlockOnNextWrite();
4740 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4741 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4742
4743 // Unblock the writes and actually send.
4744 writer_->SetWritable();
4745 connection_.OnCanWrite();
4746 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4747}
4748
4749TEST_P(QuicConnectionTest, InitialTimeout) {
4750 EXPECT_TRUE(connection_.connected());
4751 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4752 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4753
4754 // SetFromConfig sets the initial timeouts before negotiation.
4755 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4756 QuicConfig config;
4757 connection_.SetFromConfig(config);
4758 // Subtract a second from the idle timeout on the client side.
4759 QuicTime default_timeout =
4760 clock_.ApproximateNow() +
4761 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4762 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
4763
fkastenholz5d880a92019-06-21 09:01:56 -07004764 EXPECT_CALL(visitor_,
4765 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004766 // Simulate the timeout alarm firing.
4767 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1));
4768 connection_.GetTimeoutAlarm()->Fire();
4769
4770 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4771 EXPECT_FALSE(connection_.connected());
4772
fayang9adfb532020-06-04 06:58:45 -07004773 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004774 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4775 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4776 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4777 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
renjietang11e4a3d2019-05-03 11:27:26 -07004778 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07004779 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004780}
4781
4782TEST_P(QuicConnectionTest, IdleTimeoutAfterFirstSentPacket) {
4783 EXPECT_TRUE(connection_.connected());
4784 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4785 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4786
4787 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4788 QuicConfig config;
4789 connection_.SetFromConfig(config);
4790 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4791 QuicTime initial_ddl =
4792 clock_.ApproximateNow() +
4793 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4794 EXPECT_EQ(initial_ddl, connection_.GetTimeoutAlarm()->deadline());
4795 EXPECT_TRUE(connection_.connected());
4796
4797 // Advance the time and send the first packet to the peer.
fayangb9c88442020-03-26 07:03:57 -07004798 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004799 QuicPacketNumber last_packet;
4800 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4801 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4802 // This will be the updated deadline for the connection to idle time out.
4803 QuicTime new_ddl = clock_.ApproximateNow() +
4804 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4805
4806 // Simulate the timeout alarm firing, the connection should not be closed as
4807 // a new packet has been sent.
fkastenholz5d880a92019-06-21 09:01:56 -07004808 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004809 QuicTime::Delta delay = initial_ddl - clock_.ApproximateNow();
4810 clock_.AdvanceTime(delay);
fayang2205d952020-05-12 13:45:56 -07004811 if (!GetQuicReloadableFlag(quic_use_idle_network_detector)) {
fayangb9c88442020-03-26 07:03:57 -07004812 connection_.GetTimeoutAlarm()->Fire();
4813 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004814 // Verify the timeout alarm deadline is updated.
4815 EXPECT_TRUE(connection_.connected());
4816 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4817 EXPECT_EQ(new_ddl, connection_.GetTimeoutAlarm()->deadline());
4818
4819 // Simulate the timeout alarm firing again, the connection now should be
4820 // closed.
fkastenholz5d880a92019-06-21 09:01:56 -07004821 EXPECT_CALL(visitor_,
4822 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004823 clock_.AdvanceTime(new_ddl - clock_.ApproximateNow());
4824 connection_.GetTimeoutAlarm()->Fire();
4825 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4826 EXPECT_FALSE(connection_.connected());
4827
fayang9adfb532020-06-04 06:58:45 -07004828 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004829 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4830 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4831 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4832 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07004833 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004834}
4835
4836TEST_P(QuicConnectionTest, IdleTimeoutAfterSendTwoPackets) {
4837 EXPECT_TRUE(connection_.connected());
4838 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4839 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4840
4841 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4842 QuicConfig config;
4843 connection_.SetFromConfig(config);
4844 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4845 QuicTime initial_ddl =
4846 clock_.ApproximateNow() +
4847 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4848 EXPECT_EQ(initial_ddl, connection_.GetTimeoutAlarm()->deadline());
4849 EXPECT_TRUE(connection_.connected());
4850
4851 // Immediately send the first packet, this is a rare case but test code will
4852 // hit this issue often as MockClock used for tests doesn't move with code
4853 // execution until manually adjusted.
4854 QuicPacketNumber last_packet;
4855 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4856 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4857
4858 // Advance the time and send the second packet to the peer.
4859 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
4860 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4861 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
4862
zhongyic1cab062019-06-19 12:02:24 -07004863 // Simulate the timeout alarm firing, the connection will be closed.
fkastenholz5d880a92019-06-21 09:01:56 -07004864 EXPECT_CALL(visitor_,
4865 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
zhongyic1cab062019-06-19 12:02:24 -07004866 clock_.AdvanceTime(initial_ddl - clock_.ApproximateNow());
4867 connection_.GetTimeoutAlarm()->Fire();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004868
4869 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4870 EXPECT_FALSE(connection_.connected());
4871
fayang9adfb532020-06-04 06:58:45 -07004872 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004873 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4874 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4875 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4876 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07004877 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004878}
4879
4880TEST_P(QuicConnectionTest, HandshakeTimeout) {
4881 // Use a shorter handshake timeout than idle timeout for this test.
4882 const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(5);
4883 connection_.SetNetworkTimeouts(timeout, timeout);
4884 EXPECT_TRUE(connection_.connected());
4885 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4886
4887 QuicTime handshake_timeout =
4888 clock_.ApproximateNow() + timeout - QuicTime::Delta::FromSeconds(1);
4889 EXPECT_EQ(handshake_timeout, connection_.GetTimeoutAlarm()->deadline());
4890 EXPECT_TRUE(connection_.connected());
4891
4892 // Send and ack new data 3 seconds later to lengthen the idle timeout.
4893 SendStreamDataToPeer(
dschinazi552accc2019-06-17 17:07:34 -07004894 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
4895 "GET /", 0, FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004896 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(3));
4897 QuicAckFrame frame = InitAckFrame(1);
4898 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4899 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4900 ProcessAckPacket(&frame);
4901
fayang2205d952020-05-12 13:45:56 -07004902 if (!GetQuicReloadableFlag(quic_use_idle_network_detector)) {
fayangb9c88442020-03-26 07:03:57 -07004903 // Fire early to verify it wouldn't timeout yet.
4904 connection_.GetTimeoutAlarm()->Fire();
4905 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004906 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4907 EXPECT_TRUE(connection_.connected());
4908
4909 clock_.AdvanceTime(timeout - QuicTime::Delta::FromSeconds(2));
4910
fkastenholz5d880a92019-06-21 09:01:56 -07004911 EXPECT_CALL(visitor_,
4912 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004913 // Simulate the timeout alarm firing.
4914 connection_.GetTimeoutAlarm()->Fire();
4915
4916 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4917 EXPECT_FALSE(connection_.connected());
4918
fayang9adfb532020-06-04 06:58:45 -07004919 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004920 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4921 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4922 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07004923 TestConnectionCloseQuicErrorCode(QUIC_HANDSHAKE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004924}
4925
4926TEST_P(QuicConnectionTest, PingAfterSend) {
QUICHE teamcd098022019-03-22 18:49:55 -07004927 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4928 return;
4929 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004930 EXPECT_TRUE(connection_.connected());
4931 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4932 .WillRepeatedly(Return(true));
4933 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4934
4935 // Advance to 5ms, and send a packet to the peer, which will set
4936 // the ping alarm.
4937 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4938 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4939 SendStreamDataToPeer(
dschinazi552accc2019-06-17 17:07:34 -07004940 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
4941 "GET /", 0, FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004942 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004943 EXPECT_EQ(QuicTime::Delta::FromSeconds(15),
4944 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004945
4946 // Now recevie an ACK of the previous packet, which will move the
4947 // ping alarm forward.
4948 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4949 QuicAckFrame frame = InitAckFrame(1);
4950 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4951 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4952 ProcessAckPacket(&frame);
4953 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4954 // The ping timer is set slightly less than 15 seconds in the future, because
4955 // of the 1s ping timer alarm granularity.
zhongyieef848f2019-10-18 07:09:37 -07004956 EXPECT_EQ(
4957 QuicTime::Delta::FromSeconds(15) - QuicTime::Delta::FromMilliseconds(5),
4958 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004959
4960 writer_->Reset();
4961 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15));
zhongyifbb25772019-04-10 16:54:08 -07004962 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004963 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07004964 size_t padding_frame_count = writer_->padding_frames().size();
4965 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004966 ASSERT_EQ(1u, writer_->ping_frames().size());
4967 writer_->Reset();
4968
4969 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4970 .WillRepeatedly(Return(false));
4971 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4972 SendAckPacketToPeer();
4973
4974 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4975}
4976
4977TEST_P(QuicConnectionTest, ReducedPingTimeout) {
QUICHE teamcd098022019-03-22 18:49:55 -07004978 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4979 return;
4980 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004981 EXPECT_TRUE(connection_.connected());
4982 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4983 .WillRepeatedly(Return(true));
4984 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4985
4986 // Use a reduced ping timeout for this connection.
4987 connection_.set_ping_timeout(QuicTime::Delta::FromSeconds(10));
4988
4989 // Advance to 5ms, and send a packet to the peer, which will set
4990 // the ping alarm.
4991 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4992 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4993 SendStreamDataToPeer(
dschinazi552accc2019-06-17 17:07:34 -07004994 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
4995 "GET /", 0, FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004996 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004997 EXPECT_EQ(QuicTime::Delta::FromSeconds(10),
4998 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004999
5000 // Now recevie an ACK of the previous packet, which will move the
5001 // ping alarm forward.
5002 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
5003 QuicAckFrame frame = InitAckFrame(1);
5004 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5005 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5006 ProcessAckPacket(&frame);
5007 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
5008 // The ping timer is set slightly less than 10 seconds in the future, because
5009 // of the 1s ping timer alarm granularity.
zhongyieef848f2019-10-18 07:09:37 -07005010 EXPECT_EQ(
5011 QuicTime::Delta::FromSeconds(10) - QuicTime::Delta::FromMilliseconds(5),
5012 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005013
5014 writer_->Reset();
5015 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
5016 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
5017 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
5018 }));
5019 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07005020 size_t padding_frame_count = writer_->padding_frames().size();
5021 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005022 ASSERT_EQ(1u, writer_->ping_frames().size());
5023 writer_->Reset();
5024
5025 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
5026 .WillRepeatedly(Return(false));
5027 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
5028 SendAckPacketToPeer();
5029
5030 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
5031}
5032
5033// Tests whether sending an MTU discovery packet to peer successfully causes the
5034// maximum packet size to increase.
5035TEST_P(QuicConnectionTest, SendMtuDiscoveryPacket) {
wub031d47c2019-11-21 08:04:07 -08005036 MtuDiscoveryTestInit();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005037
5038 // Send an MTU probe.
5039 const size_t new_mtu = kDefaultMaxPacketSize + 100;
5040 QuicByteCount mtu_probe_size;
5041 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5042 .WillOnce(SaveArg<3>(&mtu_probe_size));
5043 connection_.SendMtuDiscoveryPacket(new_mtu);
5044 EXPECT_EQ(new_mtu, mtu_probe_size);
5045 EXPECT_EQ(QuicPacketNumber(1u), creator_->packet_number());
5046
5047 // Send more than MTU worth of data. No acknowledgement was received so far,
5048 // so the MTU should be at its old value.
vasilvvc48c8712019-03-11 13:38:16 -07005049 const std::string data(kDefaultMaxPacketSize + 1, '.');
QUICHE teama6ef0a62019-03-07 20:34:33 -05005050 QuicByteCount size_before_mtu_change;
5051 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5052 .Times(2)
5053 .WillOnce(SaveArg<3>(&size_before_mtu_change))
5054 .WillOnce(Return());
5055 connection_.SendStreamDataWithString(3, data, 0, FIN);
5056 EXPECT_EQ(QuicPacketNumber(3u), creator_->packet_number());
5057 EXPECT_EQ(kDefaultMaxPacketSize, size_before_mtu_change);
5058
5059 // Acknowledge all packets so far.
5060 QuicAckFrame probe_ack = InitAckFrame(3);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005061 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5062 ProcessAckPacket(&probe_ack);
5063 EXPECT_EQ(new_mtu, connection_.max_packet_length());
5064
5065 // Send the same data again. Check that it fits into a single packet now.
5066 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
5067 connection_.SendStreamDataWithString(3, data, 0, FIN);
5068 EXPECT_EQ(QuicPacketNumber(4u), creator_->packet_number());
5069}
5070
wubb442b862020-01-31 08:16:21 -08005071// Verifies that when a MTU probe packet is sent and buffered in a batch writer,
5072// the writer is flushed immediately.
5073TEST_P(QuicConnectionTest, BatchWriterFlushedAfterMtuDiscoveryPacket) {
5074 writer_->SetBatchMode(true);
5075 MtuDiscoveryTestInit();
5076
5077 // Send an MTU probe.
5078 const size_t target_mtu = kDefaultMaxPacketSize + 100;
5079 QuicByteCount mtu_probe_size;
5080 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5081 .WillOnce(SaveArg<3>(&mtu_probe_size));
5082 const uint32_t prior_flush_attempts = writer_->flush_attempts();
5083 connection_.SendMtuDiscoveryPacket(target_mtu);
5084 EXPECT_EQ(target_mtu, mtu_probe_size);
wub18f47342020-03-16 15:56:03 -07005085 EXPECT_EQ(writer_->flush_attempts(), prior_flush_attempts + 1);
wubb442b862020-01-31 08:16:21 -08005086}
5087
QUICHE teama6ef0a62019-03-07 20:34:33 -05005088// Tests whether MTU discovery does not happen when it is not explicitly enabled
5089// by the connection options.
5090TEST_P(QuicConnectionTest, MtuDiscoveryDisabled) {
wub031d47c2019-11-21 08:04:07 -08005091 MtuDiscoveryTestInit();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005092
5093 const QuicPacketCount packets_between_probes_base = 10;
5094 set_packets_between_probes_base(packets_between_probes_base);
5095
5096 const QuicPacketCount number_of_packets = packets_between_probes_base * 2;
5097 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
5098 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5099 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5100 EXPECT_EQ(0u, connection_.mtu_probe_count());
5101 }
5102}
5103
wubf76cf2a2019-10-11 18:49:07 -07005104// Tests whether MTU discovery works when all probes are acknowledged on the
QUICHE teama6ef0a62019-03-07 20:34:33 -05005105// first try.
5106TEST_P(QuicConnectionTest, MtuDiscoveryEnabled) {
wub031d47c2019-11-21 08:04:07 -08005107 MtuDiscoveryTestInit();
nharperc6b99512019-09-19 11:13:48 -07005108
QUICHE teama6ef0a62019-03-07 20:34:33 -05005109 const QuicPacketCount packets_between_probes_base = 5;
5110 set_packets_between_probes_base(packets_between_probes_base);
5111
wubf76cf2a2019-10-11 18:49:07 -07005112 connection_.EnablePathMtuDiscovery(send_algorithm_);
5113
QUICHE teama6ef0a62019-03-07 20:34:33 -05005114 // Send enough packets so that the next one triggers path MTU discovery.
5115 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5116 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5117 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5118 }
5119
5120 // Trigger the probe.
5121 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5122 nullptr);
5123 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5124 QuicByteCount probe_size;
5125 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5126 .WillOnce(SaveArg<3>(&probe_size));
5127 connection_.GetMtuDiscoveryAlarm()->Fire();
wub173916e2019-11-27 14:36:24 -08005128
5129 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(),
5130 kMtuDiscoveryTargetPacketSizeHigh));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005131
5132 const QuicPacketNumber probe_packet_number =
5133 FirstSendingPacketNumber() + packets_between_probes_base;
5134 ASSERT_EQ(probe_packet_number, creator_->packet_number());
5135
5136 // Acknowledge all packets sent so far.
5137 QuicAckFrame probe_ack = InitAckFrame(probe_packet_number);
wubf76cf2a2019-10-11 18:49:07 -07005138 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5139 .Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005140 ProcessAckPacket(&probe_ack);
wubf76cf2a2019-10-11 18:49:07 -07005141 EXPECT_EQ(probe_size, connection_.max_packet_length());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005142 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5143
wubf76cf2a2019-10-11 18:49:07 -07005144 EXPECT_EQ(1u, connection_.mtu_probe_count());
5145
wubf76cf2a2019-10-11 18:49:07 -07005146 QuicStreamOffset stream_offset = packets_between_probes_base;
wubecb643f2020-03-19 08:58:46 -07005147 QuicByteCount last_probe_size = 0;
wubf76cf2a2019-10-11 18:49:07 -07005148 for (size_t num_probes = 1; num_probes < kMtuDiscoveryAttempts;
5149 ++num_probes) {
5150 // Send just enough packets without triggering the next probe.
5151 for (QuicPacketCount i = 0;
5152 i < (packets_between_probes_base << num_probes) - 1; ++i) {
5153 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5154 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5155 }
5156
5157 // Trigger the next probe.
5158 SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
5159 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5160 QuicByteCount new_probe_size;
5161 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5162 .WillOnce(SaveArg<3>(&new_probe_size));
5163 connection_.GetMtuDiscoveryAlarm()->Fire();
5164 EXPECT_THAT(new_probe_size,
5165 InRange(probe_size, kMtuDiscoveryTargetPacketSizeHigh));
5166 EXPECT_EQ(num_probes + 1, connection_.mtu_probe_count());
5167
5168 // Acknowledge all packets sent so far.
5169 QuicAckFrame probe_ack = InitAckFrame(creator_->packet_number());
5170 ProcessAckPacket(&probe_ack);
5171 EXPECT_EQ(new_probe_size, connection_.max_packet_length());
5172 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5173
wubecb643f2020-03-19 08:58:46 -07005174 last_probe_size = probe_size;
wubf76cf2a2019-10-11 18:49:07 -07005175 probe_size = new_probe_size;
5176 }
5177
5178 // The last probe size should be equal to the target.
5179 EXPECT_EQ(probe_size, kMtuDiscoveryTargetPacketSizeHigh);
wubecb643f2020-03-19 08:58:46 -07005180
wubae6581a2020-05-04 12:13:05 -07005181 writer_->SetShouldWriteFail();
wubecb643f2020-03-19 08:58:46 -07005182
wubae6581a2020-05-04 12:13:05 -07005183 // Ignore PACKET_WRITE_ERROR once.
5184 SendStreamDataToPeer(3, "(", stream_offset++, NO_FIN, nullptr);
5185 EXPECT_EQ(last_probe_size, connection_.max_packet_length());
5186 EXPECT_TRUE(connection_.connected());
wubecb643f2020-03-19 08:58:46 -07005187
wubae6581a2020-05-04 12:13:05 -07005188 // Close connection on another PACKET_WRITE_ERROR.
5189 EXPECT_CALL(visitor_, OnConnectionClosed(_, _))
5190 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
5191 SendStreamDataToPeer(3, ")", stream_offset++, NO_FIN, nullptr);
5192 EXPECT_EQ(last_probe_size, connection_.max_packet_length());
5193 EXPECT_FALSE(connection_.connected());
5194 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
5195 IsError(QUIC_PACKET_WRITE_ERROR));
wubf76cf2a2019-10-11 18:49:07 -07005196}
5197
wub748e20b2020-03-20 14:33:59 -07005198// After a successful MTU probe, one and only one write error should be ignored
5199// if it happened in QuicConnection::FlushPacket.
5200TEST_P(QuicConnectionTest,
5201 MtuDiscoveryIgnoreOneWriteErrorInFlushAfterSuccessfulProbes) {
5202 MtuDiscoveryTestInit();
5203 writer_->SetBatchMode(true);
5204
5205 const QuicPacketCount packets_between_probes_base = 5;
5206 set_packets_between_probes_base(packets_between_probes_base);
5207
5208 connection_.EnablePathMtuDiscovery(send_algorithm_);
5209
5210 const QuicByteCount original_max_packet_length =
5211 connection_.max_packet_length();
5212 // Send enough packets so that the next one triggers path MTU discovery.
5213 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5214 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5215 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5216 }
5217
5218 // Trigger the probe.
5219 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5220 nullptr);
5221 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5222 QuicByteCount probe_size;
5223 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5224 .WillOnce(SaveArg<3>(&probe_size));
5225 connection_.GetMtuDiscoveryAlarm()->Fire();
5226
5227 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(),
5228 kMtuDiscoveryTargetPacketSizeHigh));
5229
5230 const QuicPacketNumber probe_packet_number =
5231 FirstSendingPacketNumber() + packets_between_probes_base;
5232 ASSERT_EQ(probe_packet_number, creator_->packet_number());
5233
5234 // Acknowledge all packets sent so far.
5235 QuicAckFrame probe_ack = InitAckFrame(probe_packet_number);
5236 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5237 .Times(AnyNumber());
5238 ProcessAckPacket(&probe_ack);
5239 EXPECT_EQ(probe_size, connection_.max_packet_length());
5240 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5241
5242 EXPECT_EQ(1u, connection_.mtu_probe_count());
5243
wubae6581a2020-05-04 12:13:05 -07005244 writer_->SetShouldWriteFail();
wub748e20b2020-03-20 14:33:59 -07005245
wubae6581a2020-05-04 12:13:05 -07005246 // Ignore PACKET_WRITE_ERROR once.
5247 {
5248 QuicConnection::ScopedPacketFlusher flusher(&connection_);
5249 // flusher's destructor will call connection_.FlushPackets, which should
5250 // get a WRITE_STATUS_ERROR from the writer and ignore it.
wub748e20b2020-03-20 14:33:59 -07005251 }
wubae6581a2020-05-04 12:13:05 -07005252 EXPECT_EQ(original_max_packet_length, connection_.max_packet_length());
5253 EXPECT_TRUE(connection_.connected());
5254
5255 // Close connection on another PACKET_WRITE_ERROR.
5256 EXPECT_CALL(visitor_, OnConnectionClosed(_, _))
5257 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
5258 {
5259 QuicConnection::ScopedPacketFlusher flusher(&connection_);
5260 // flusher's destructor will call connection_.FlushPackets, which should
5261 // get a WRITE_STATUS_ERROR from the writer and ignore it.
5262 }
5263 EXPECT_EQ(original_max_packet_length, connection_.max_packet_length());
5264 EXPECT_FALSE(connection_.connected());
5265 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
5266 IsError(QUIC_PACKET_WRITE_ERROR));
wub748e20b2020-03-20 14:33:59 -07005267}
5268
wubf76cf2a2019-10-11 18:49:07 -07005269// Simulate the case where the first attempt to send a probe is write blocked,
5270// and after unblock, the second attempt returns a MSG_TOO_BIG error.
5271TEST_P(QuicConnectionTest, MtuDiscoveryWriteBlocked) {
wub031d47c2019-11-21 08:04:07 -08005272 MtuDiscoveryTestInit();
wubf76cf2a2019-10-11 18:49:07 -07005273
5274 const QuicPacketCount packets_between_probes_base = 5;
5275 set_packets_between_probes_base(packets_between_probes_base);
5276
5277 connection_.EnablePathMtuDiscovery(send_algorithm_);
5278
5279 // Send enough packets so that the next one triggers path MTU discovery.
5280 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5281 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005282 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5283 }
5284
wubf76cf2a2019-10-11 18:49:07 -07005285 QuicByteCount original_max_packet_length = connection_.max_packet_length();
5286
5287 // Trigger the probe.
5288 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5289 nullptr);
5290 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
fayange62e63c2019-12-04 07:16:25 -08005291 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
wubf76cf2a2019-10-11 18:49:07 -07005292 BlockOnNextWrite();
5293 EXPECT_EQ(0u, connection_.NumQueuedPackets());
5294 connection_.GetMtuDiscoveryAlarm()->Fire();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005295 EXPECT_EQ(1u, connection_.mtu_probe_count());
wubf76cf2a2019-10-11 18:49:07 -07005296 EXPECT_EQ(1u, connection_.NumQueuedPackets());
5297 ASSERT_TRUE(connection_.connected());
5298
5299 writer_->SetWritable();
5300 SimulateNextPacketTooLarge();
5301 connection_.OnCanWrite();
5302 EXPECT_EQ(0u, connection_.NumQueuedPackets());
5303 EXPECT_EQ(original_max_packet_length, connection_.max_packet_length());
5304 EXPECT_TRUE(connection_.connected());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005305}
5306
5307// Tests whether MTU discovery works correctly when the probes never get
5308// acknowledged.
5309TEST_P(QuicConnectionTest, MtuDiscoveryFailed) {
wub031d47c2019-11-21 08:04:07 -08005310 MtuDiscoveryTestInit();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005311
QUICHE teama6ef0a62019-03-07 20:34:33 -05005312 // Lower the number of probes between packets in order to make the test go
5313 // much faster.
5314 const QuicPacketCount packets_between_probes_base = 5;
5315 set_packets_between_probes_base(packets_between_probes_base);
5316
wubf76cf2a2019-10-11 18:49:07 -07005317 connection_.EnablePathMtuDiscovery(send_algorithm_);
5318
5319 const QuicTime::Delta rtt = QuicTime::Delta::FromMilliseconds(100);
5320
5321 EXPECT_EQ(packets_between_probes_base,
5322 QuicConnectionPeer::GetPacketsBetweenMtuProbes(&connection_));
5323
QUICHE teama6ef0a62019-03-07 20:34:33 -05005324 // This tests sends more packets than strictly necessary to make sure that if
5325 // the connection was to send more discovery packets than needed, those would
5326 // get caught as well.
5327 const QuicPacketCount number_of_packets =
5328 packets_between_probes_base * (1 << (kMtuDiscoveryAttempts + 1));
5329 std::vector<QuicPacketNumber> mtu_discovery_packets;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005330 // Called on many acks.
5331 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5332 .Times(AnyNumber());
5333 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
5334 SendStreamDataToPeer(3, "!", i, NO_FIN, nullptr);
5335 clock_.AdvanceTime(rtt);
5336
5337 // Receive an ACK, which marks all data packets as received, and all MTU
5338 // discovery packets as missing.
5339
5340 QuicAckFrame ack;
5341
5342 if (!mtu_discovery_packets.empty()) {
5343 QuicPacketNumber min_packet = *min_element(mtu_discovery_packets.begin(),
5344 mtu_discovery_packets.end());
5345 QuicPacketNumber max_packet = *max_element(mtu_discovery_packets.begin(),
5346 mtu_discovery_packets.end());
5347 ack.packets.AddRange(QuicPacketNumber(1), min_packet);
5348 ack.packets.AddRange(QuicPacketNumber(max_packet + 1),
5349 creator_->packet_number() + 1);
5350 ack.largest_acked = creator_->packet_number();
5351
5352 } else {
5353 ack.packets.AddRange(QuicPacketNumber(1), creator_->packet_number() + 1);
5354 ack.largest_acked = creator_->packet_number();
5355 }
5356
5357 ProcessAckPacket(&ack);
5358
5359 // Trigger MTU probe if it would be scheduled now.
5360 if (!connection_.GetMtuDiscoveryAlarm()->IsSet()) {
5361 continue;
5362 }
5363
5364 // Fire the alarm. The alarm should cause a packet to be sent.
5365 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5366 connection_.GetMtuDiscoveryAlarm()->Fire();
5367 // Record the packet number of the MTU discovery packet in order to
5368 // mark it as NACK'd.
5369 mtu_discovery_packets.push_back(creator_->packet_number());
5370 }
5371
5372 // Ensure the number of packets between probes grows exponentially by checking
5373 // it against the closed-form expression for the packet number.
5374 ASSERT_EQ(kMtuDiscoveryAttempts, mtu_discovery_packets.size());
5375 for (uint64_t i = 0; i < kMtuDiscoveryAttempts; i++) {
5376 // 2^0 + 2^1 + 2^2 + ... + 2^n = 2^(n + 1) - 1
5377 const QuicPacketCount packets_between_probes =
5378 packets_between_probes_base * ((1 << (i + 1)) - 1);
5379 EXPECT_EQ(QuicPacketNumber(packets_between_probes + (i + 1)),
5380 mtu_discovery_packets[i]);
5381 }
5382
5383 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5384 EXPECT_EQ(kDefaultMaxPacketSize, connection_.max_packet_length());
5385 EXPECT_EQ(kMtuDiscoveryAttempts, connection_.mtu_probe_count());
5386}
5387
wubf76cf2a2019-10-11 18:49:07 -07005388// Probe 3 times, the first one succeeds, then fails, then succeeds again.
5389TEST_P(QuicConnectionTest, MtuDiscoverySecondProbeFailed) {
wub031d47c2019-11-21 08:04:07 -08005390 MtuDiscoveryTestInit();
wubf76cf2a2019-10-11 18:49:07 -07005391
5392 const QuicPacketCount packets_between_probes_base = 5;
5393 set_packets_between_probes_base(packets_between_probes_base);
5394
5395 connection_.EnablePathMtuDiscovery(send_algorithm_);
5396
5397 // Send enough packets so that the next one triggers path MTU discovery.
5398 QuicStreamOffset stream_offset = 0;
5399 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5400 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5401 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5402 }
5403
5404 // Trigger the probe.
5405 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5406 nullptr);
5407 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5408 QuicByteCount probe_size;
5409 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5410 .WillOnce(SaveArg<3>(&probe_size));
5411 connection_.GetMtuDiscoveryAlarm()->Fire();
5412 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(),
5413 kMtuDiscoveryTargetPacketSizeHigh));
5414
5415 const QuicPacketNumber probe_packet_number =
5416 FirstSendingPacketNumber() + packets_between_probes_base;
5417 ASSERT_EQ(probe_packet_number, creator_->packet_number());
5418
5419 // Acknowledge all packets sent so far.
5420 QuicAckFrame first_ack = InitAckFrame(probe_packet_number);
wubf76cf2a2019-10-11 18:49:07 -07005421 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5422 .Times(AnyNumber());
5423 ProcessAckPacket(&first_ack);
5424 EXPECT_EQ(probe_size, connection_.max_packet_length());
5425 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5426
5427 EXPECT_EQ(1u, connection_.mtu_probe_count());
5428
5429 // Send just enough packets without triggering the second probe.
5430 for (QuicPacketCount i = 0; i < (packets_between_probes_base << 1) - 1; ++i) {
5431 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5432 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5433 }
5434
5435 // Trigger the second probe.
5436 SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
5437 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5438 QuicByteCount second_probe_size;
5439 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5440 .WillOnce(SaveArg<3>(&second_probe_size));
5441 connection_.GetMtuDiscoveryAlarm()->Fire();
5442 EXPECT_THAT(second_probe_size,
5443 InRange(probe_size, kMtuDiscoveryTargetPacketSizeHigh));
5444 EXPECT_EQ(2u, connection_.mtu_probe_count());
5445
5446 // Acknowledge all packets sent so far, except the second probe.
5447 QuicPacketNumber second_probe_packet_number = creator_->packet_number();
5448 QuicAckFrame second_ack = InitAckFrame(second_probe_packet_number - 1);
5449 ProcessAckPacket(&first_ack);
5450 EXPECT_EQ(probe_size, connection_.max_packet_length());
5451
5452 // Send just enough packets without triggering the third probe.
5453 for (QuicPacketCount i = 0; i < (packets_between_probes_base << 2) - 1; ++i) {
5454 SendStreamDataToPeer(3, "@", stream_offset++, NO_FIN, nullptr);
5455 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5456 }
5457
5458 // Trigger the third probe.
5459 SendStreamDataToPeer(3, "#", stream_offset++, NO_FIN, nullptr);
5460 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5461 QuicByteCount third_probe_size;
5462 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5463 .WillOnce(SaveArg<3>(&third_probe_size));
5464 connection_.GetMtuDiscoveryAlarm()->Fire();
5465 EXPECT_THAT(third_probe_size, InRange(probe_size, second_probe_size));
5466 EXPECT_EQ(3u, connection_.mtu_probe_count());
5467
5468 // Acknowledge all packets sent so far, except the second probe.
5469 QuicAckFrame third_ack =
5470 ConstructAckFrame(creator_->packet_number(), second_probe_packet_number);
5471 ProcessAckPacket(&third_ack);
5472 EXPECT_EQ(third_probe_size, connection_.max_packet_length());
5473}
5474
QUICHE teama6ef0a62019-03-07 20:34:33 -05005475// Tests whether MTU discovery works when the writer has a limit on how large a
5476// packet can be.
5477TEST_P(QuicConnectionTest, MtuDiscoveryWriterLimited) {
wub031d47c2019-11-21 08:04:07 -08005478 MtuDiscoveryTestInit();
nharperc6b99512019-09-19 11:13:48 -07005479
QUICHE teama6ef0a62019-03-07 20:34:33 -05005480 const QuicByteCount mtu_limit = kMtuDiscoveryTargetPacketSizeHigh - 1;
5481 writer_->set_max_packet_size(mtu_limit);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005482
5483 const QuicPacketCount packets_between_probes_base = 5;
5484 set_packets_between_probes_base(packets_between_probes_base);
5485
wubf76cf2a2019-10-11 18:49:07 -07005486 connection_.EnablePathMtuDiscovery(send_algorithm_);
5487
QUICHE teama6ef0a62019-03-07 20:34:33 -05005488 // Send enough packets so that the next one triggers path MTU discovery.
5489 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5490 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5491 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5492 }
5493
5494 // Trigger the probe.
5495 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5496 nullptr);
5497 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5498 QuicByteCount probe_size;
5499 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5500 .WillOnce(SaveArg<3>(&probe_size));
5501 connection_.GetMtuDiscoveryAlarm()->Fire();
wub173916e2019-11-27 14:36:24 -08005502
5503 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(), mtu_limit));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005504
5505 const QuicPacketNumber probe_sequence_number =
5506 FirstSendingPacketNumber() + packets_between_probes_base;
5507 ASSERT_EQ(probe_sequence_number, creator_->packet_number());
5508
5509 // Acknowledge all packets sent so far.
5510 QuicAckFrame probe_ack = InitAckFrame(probe_sequence_number);
wubf76cf2a2019-10-11 18:49:07 -07005511 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5512 .Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005513 ProcessAckPacket(&probe_ack);
wubf76cf2a2019-10-11 18:49:07 -07005514 EXPECT_EQ(probe_size, connection_.max_packet_length());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005515 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5516
wubf76cf2a2019-10-11 18:49:07 -07005517 EXPECT_EQ(1u, connection_.mtu_probe_count());
5518
wubf76cf2a2019-10-11 18:49:07 -07005519 QuicStreamOffset stream_offset = packets_between_probes_base;
5520 for (size_t num_probes = 1; num_probes < kMtuDiscoveryAttempts;
5521 ++num_probes) {
5522 // Send just enough packets without triggering the next probe.
5523 for (QuicPacketCount i = 0;
5524 i < (packets_between_probes_base << num_probes) - 1; ++i) {
5525 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5526 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5527 }
5528
5529 // Trigger the next probe.
5530 SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
5531 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5532 QuicByteCount new_probe_size;
5533 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5534 .WillOnce(SaveArg<3>(&new_probe_size));
5535 connection_.GetMtuDiscoveryAlarm()->Fire();
5536 EXPECT_THAT(new_probe_size, InRange(probe_size, mtu_limit));
5537 EXPECT_EQ(num_probes + 1, connection_.mtu_probe_count());
5538
5539 // Acknowledge all packets sent so far.
5540 QuicAckFrame probe_ack = InitAckFrame(creator_->packet_number());
5541 ProcessAckPacket(&probe_ack);
5542 EXPECT_EQ(new_probe_size, connection_.max_packet_length());
5543 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5544
5545 probe_size = new_probe_size;
5546 }
5547
5548 // The last probe size should be equal to the target.
5549 EXPECT_EQ(probe_size, mtu_limit);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005550}
5551
5552// Tests whether MTU discovery works when the writer returns an error despite
5553// advertising higher packet length.
5554TEST_P(QuicConnectionTest, MtuDiscoveryWriterFailed) {
wub031d47c2019-11-21 08:04:07 -08005555 MtuDiscoveryTestInit();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005556
5557 const QuicByteCount mtu_limit = kMtuDiscoveryTargetPacketSizeHigh - 1;
5558 const QuicByteCount initial_mtu = connection_.max_packet_length();
5559 EXPECT_LT(initial_mtu, mtu_limit);
5560 writer_->set_max_packet_size(mtu_limit);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005561
5562 const QuicPacketCount packets_between_probes_base = 5;
5563 set_packets_between_probes_base(packets_between_probes_base);
5564
wubf76cf2a2019-10-11 18:49:07 -07005565 connection_.EnablePathMtuDiscovery(send_algorithm_);
5566
QUICHE teama6ef0a62019-03-07 20:34:33 -05005567 // Send enough packets so that the next one triggers path MTU discovery.
5568 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5569 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5570 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5571 }
5572
5573 // Trigger the probe.
5574 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5575 nullptr);
5576 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5577 writer_->SimulateNextPacketTooLarge();
5578 connection_.GetMtuDiscoveryAlarm()->Fire();
5579 ASSERT_TRUE(connection_.connected());
5580
5581 // Send more data.
5582 QuicPacketNumber probe_number = creator_->packet_number();
5583 QuicPacketCount extra_packets = packets_between_probes_base * 3;
5584 for (QuicPacketCount i = 0; i < extra_packets; i++) {
5585 connection_.EnsureWritableAndSendStreamData5();
5586 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5587 }
5588
5589 // Acknowledge all packets sent so far, except for the lost probe.
5590 QuicAckFrame probe_ack =
5591 ConstructAckFrame(creator_->packet_number(), probe_number);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005592 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5593 ProcessAckPacket(&probe_ack);
5594 EXPECT_EQ(initial_mtu, connection_.max_packet_length());
5595
5596 // Send more packets, and ensure that none of them sets the alarm.
5597 for (QuicPacketCount i = 0; i < 4 * packets_between_probes_base; i++) {
5598 connection_.EnsureWritableAndSendStreamData5();
5599 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5600 }
5601
5602 EXPECT_EQ(initial_mtu, connection_.max_packet_length());
5603 EXPECT_EQ(1u, connection_.mtu_probe_count());
5604}
5605
5606TEST_P(QuicConnectionTest, NoMtuDiscoveryAfterConnectionClosed) {
wub031d47c2019-11-21 08:04:07 -08005607 MtuDiscoveryTestInit();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005608
QUICHE teama6ef0a62019-03-07 20:34:33 -05005609 const QuicPacketCount packets_between_probes_base = 10;
5610 set_packets_between_probes_base(packets_between_probes_base);
5611
wubf76cf2a2019-10-11 18:49:07 -07005612 connection_.EnablePathMtuDiscovery(send_algorithm_);
5613
QUICHE teama6ef0a62019-03-07 20:34:33 -05005614 // Send enough packets so that the next one triggers path MTU discovery.
5615 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5616 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5617 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5618 }
5619
5620 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5621 nullptr);
5622 EXPECT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5623
fkastenholz5d880a92019-06-21 09:01:56 -07005624 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005625 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
5626 ConnectionCloseBehavior::SILENT_CLOSE);
5627 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5628}
5629
dschinazi9a6194e2020-04-30 16:21:09 -07005630TEST_P(QuicConnectionTest, TimeoutAfterSendDuringHandshake) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005631 EXPECT_TRUE(connection_.connected());
5632 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5633 QuicConfig config;
5634 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005635
5636 const QuicTime::Delta initial_idle_timeout =
5637 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5638 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5639 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
5640
5641 // When we send a packet, the timeout will change to 5ms +
5642 // kInitialIdleTimeoutSecs.
5643 clock_.AdvanceTime(five_ms);
5644 SendStreamDataToPeer(
5645 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5646 0, FIN, nullptr);
fayang2205d952020-05-12 13:45:56 -07005647 if (GetQuicReloadableFlag(quic_use_idle_network_detector)) {
fayangb9c88442020-03-26 07:03:57 -07005648 EXPECT_EQ(default_timeout + five_ms,
5649 connection_.GetTimeoutAlarm()->deadline());
5650 } else {
5651 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5652 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005653
5654 // Now send more data. This will not move the timeout because
5655 // no data has been received since the previous write.
5656 clock_.AdvanceTime(five_ms);
5657 SendStreamDataToPeer(
5658 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5659 3, FIN, nullptr);
fayang2205d952020-05-12 13:45:56 -07005660 if (GetQuicReloadableFlag(quic_use_idle_network_detector)) {
fayangb9c88442020-03-26 07:03:57 -07005661 EXPECT_EQ(default_timeout + five_ms,
5662 connection_.GetTimeoutAlarm()->deadline());
5663 } else {
5664 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5665 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005666
5667 // The original alarm will fire. We should not time out because we had a
5668 // network event at t=5ms. The alarm will reregister.
5669 clock_.AdvanceTime(initial_idle_timeout - five_ms - five_ms);
5670 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
fayang2205d952020-05-12 13:45:56 -07005671 if (!GetQuicReloadableFlag(quic_use_idle_network_detector)) {
fayangb9c88442020-03-26 07:03:57 -07005672 connection_.GetTimeoutAlarm()->Fire();
5673 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005674 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5675 EXPECT_TRUE(connection_.connected());
5676 EXPECT_EQ(default_timeout + five_ms,
5677 connection_.GetTimeoutAlarm()->deadline());
5678
5679 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07005680 EXPECT_CALL(visitor_,
5681 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07005682 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005683 clock_.AdvanceTime(five_ms);
5684 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5685 connection_.GetTimeoutAlarm()->Fire();
5686 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5687 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005688 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005689}
5690
5691TEST_P(QuicConnectionTest, TimeoutAfterRetransmission) {
fayang5f135052019-08-22 17:59:40 -07005692 if (connection_.PtoEnabled()) {
5693 return;
5694 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005695 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5696 EXPECT_TRUE(connection_.connected());
5697 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5698 QuicConfig config;
5699 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005700
5701 const QuicTime start_time = clock_.Now();
5702 const QuicTime::Delta initial_idle_timeout =
5703 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5704 QuicTime default_timeout = clock_.Now() + initial_idle_timeout;
5705
5706 connection_.SetMaxTailLossProbes(0);
5707 const QuicTime default_retransmission_time =
5708 start_time + DefaultRetransmissionTime();
5709
5710 ASSERT_LT(default_retransmission_time, default_timeout);
5711
5712 // When we send a packet, the timeout will change to 5 ms +
5713 // kInitialIdleTimeoutSecs (but it will not reschedule the alarm).
5714 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5715 const QuicTime send_time = start_time + five_ms;
5716 clock_.AdvanceTime(five_ms);
5717 ASSERT_EQ(send_time, clock_.Now());
5718 SendStreamDataToPeer(
5719 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5720 0, FIN, nullptr);
fayang2205d952020-05-12 13:45:56 -07005721 if (GetQuicReloadableFlag(quic_use_idle_network_detector)) {
fayangb9c88442020-03-26 07:03:57 -07005722 EXPECT_EQ(default_timeout + five_ms,
5723 connection_.GetTimeoutAlarm()->deadline());
5724 } else {
5725 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5726 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005727
5728 // Move forward 5 ms and receive a packet, which will move the timeout
5729 // forward 5 ms more (but will not reschedule the alarm).
5730 const QuicTime receive_time = send_time + five_ms;
5731 clock_.AdvanceTime(receive_time - clock_.Now());
5732 ASSERT_EQ(receive_time, clock_.Now());
5733 ProcessPacket(1);
5734
5735 // Now move forward to the retransmission time and retransmit the
5736 // packet, which should move the timeout forward again (but will not
5737 // reschedule the alarm).
5738 EXPECT_EQ(default_retransmission_time + five_ms,
5739 connection_.GetRetransmissionAlarm()->deadline());
5740 // Simulate the retransmission alarm firing.
5741 const QuicTime rto_time = send_time + DefaultRetransmissionTime();
5742 const QuicTime final_timeout = rto_time + initial_idle_timeout;
5743 clock_.AdvanceTime(rto_time - clock_.Now());
5744 ASSERT_EQ(rto_time, clock_.Now());
5745 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _));
5746 connection_.GetRetransmissionAlarm()->Fire();
5747
5748 // Advance to the original timeout and fire the alarm. The connection should
5749 // timeout, and the alarm should be registered based on the time of the
5750 // retransmission.
5751 clock_.AdvanceTime(default_timeout - clock_.Now());
5752 ASSERT_EQ(default_timeout.ToDebuggingValue(),
5753 clock_.Now().ToDebuggingValue());
5754 EXPECT_EQ(default_timeout, clock_.Now());
fayang2205d952020-05-12 13:45:56 -07005755 if (!GetQuicReloadableFlag(quic_use_idle_network_detector)) {
fayangb9c88442020-03-26 07:03:57 -07005756 connection_.GetTimeoutAlarm()->Fire();
5757 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005758 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5759 EXPECT_TRUE(connection_.connected());
5760 ASSERT_EQ(final_timeout.ToDebuggingValue(),
5761 connection_.GetTimeoutAlarm()->deadline().ToDebuggingValue());
5762
5763 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07005764 EXPECT_CALL(visitor_,
5765 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07005766 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005767 clock_.AdvanceTime(final_timeout - clock_.Now());
5768 EXPECT_EQ(connection_.GetTimeoutAlarm()->deadline(), clock_.Now());
5769 EXPECT_EQ(final_timeout, clock_.Now());
5770 connection_.GetTimeoutAlarm()->Fire();
5771 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5772 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005773 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005774}
5775
dschinazi9a6194e2020-04-30 16:21:09 -07005776TEST_P(QuicConnectionTest, TimeoutAfterSendAfterHandshake) {
5777 // When the idle timeout fires, verify that by default we do not send any
5778 // connection close packets.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005779 EXPECT_TRUE(connection_.connected());
5780 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5781 QuicConfig config;
5782
5783 // Create a handshake message that also enables silent close.
5784 CryptoHandshakeMessage msg;
vasilvvc48c8712019-03-11 13:38:16 -07005785 std::string error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005786 QuicConfig client_config;
5787 client_config.SetInitialStreamFlowControlWindowToSend(
5788 kInitialStreamFlowControlWindowForTest);
5789 client_config.SetInitialSessionFlowControlWindowToSend(
5790 kInitialSessionFlowControlWindowForTest);
5791 client_config.SetIdleNetworkTimeout(
dschinazi027366e2020-05-01 14:31:19 -07005792 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs));
fkastenholzd3a1de92019-05-15 07:00:07 -07005793 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005794 const QuicErrorCode error =
5795 config.ProcessPeerHello(msg, CLIENT, &error_details);
bncf54082a2019-11-27 10:19:47 -08005796 EXPECT_THAT(error, IsQuicNoError());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005797
dschinazie7c38a52020-05-29 15:25:45 -07005798 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
5799 QuicConfigPeer::SetReceivedOriginalConnectionId(
5800 &config, connection_.connection_id());
5801 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
5802 &config, connection_.connection_id());
5803 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005804 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005805
5806 const QuicTime::Delta default_idle_timeout =
dschinazi027366e2020-05-01 14:31:19 -07005807 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs - 1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005808 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5809 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5810
5811 // When we send a packet, the timeout will change to 5ms +
5812 // kInitialIdleTimeoutSecs.
5813 clock_.AdvanceTime(five_ms);
5814 SendStreamDataToPeer(
5815 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5816 0, FIN, nullptr);
fayang2205d952020-05-12 13:45:56 -07005817 if (GetQuicReloadableFlag(quic_use_idle_network_detector)) {
fayangb9c88442020-03-26 07:03:57 -07005818 EXPECT_EQ(default_timeout + five_ms,
5819 connection_.GetTimeoutAlarm()->deadline());
5820 } else {
5821 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5822 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005823
5824 // Now send more data. This will not move the timeout because
5825 // no data has been received since the previous write.
5826 clock_.AdvanceTime(five_ms);
5827 SendStreamDataToPeer(
5828 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5829 3, FIN, nullptr);
fayang2205d952020-05-12 13:45:56 -07005830 if (GetQuicReloadableFlag(quic_use_idle_network_detector)) {
fayangb9c88442020-03-26 07:03:57 -07005831 EXPECT_EQ(default_timeout + five_ms,
5832 connection_.GetTimeoutAlarm()->deadline());
5833 } else {
5834 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5835 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005836
5837 // The original alarm will fire. We should not time out because we had a
5838 // network event at t=5ms. The alarm will reregister.
5839 clock_.AdvanceTime(default_idle_timeout - five_ms - five_ms);
5840 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
fayang2205d952020-05-12 13:45:56 -07005841 if (!GetQuicReloadableFlag(quic_use_idle_network_detector)) {
fayangb9c88442020-03-26 07:03:57 -07005842 connection_.GetTimeoutAlarm()->Fire();
5843 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005844 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5845 EXPECT_TRUE(connection_.connected());
5846 EXPECT_EQ(default_timeout + five_ms,
5847 connection_.GetTimeoutAlarm()->deadline());
5848
5849 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07005850 // This results in a SILENT_CLOSE, so the writer will not be invoked
5851 // and will not save the frame. Grab the frame from OnConnectionClosed
5852 // directly.
5853 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
5854 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
5855
QUICHE teama6ef0a62019-03-07 20:34:33 -05005856 clock_.AdvanceTime(five_ms);
5857 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5858 connection_.GetTimeoutAlarm()->Fire();
5859 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5860 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005861 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08005862 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
5863 IsError(QUIC_NETWORK_IDLE_TIMEOUT));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005864}
5865
5866TEST_P(QuicConnectionTest, TimeoutAfterSendSilentCloseAndTLP) {
fayang5f135052019-08-22 17:59:40 -07005867 if (connection_.PtoEnabled()) {
5868 return;
5869 }
dschinazi9a6194e2020-04-30 16:21:09 -07005870 // Same test as above, but sending TLPs causes a connection close to be sent.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005871 EXPECT_TRUE(connection_.connected());
5872 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5873 QuicConfig config;
5874
5875 // Create a handshake message that also enables silent close.
5876 CryptoHandshakeMessage msg;
vasilvvc48c8712019-03-11 13:38:16 -07005877 std::string error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005878 QuicConfig client_config;
5879 client_config.SetInitialStreamFlowControlWindowToSend(
5880 kInitialStreamFlowControlWindowForTest);
5881 client_config.SetInitialSessionFlowControlWindowToSend(
5882 kInitialSessionFlowControlWindowForTest);
5883 client_config.SetIdleNetworkTimeout(
dschinazi027366e2020-05-01 14:31:19 -07005884 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs));
fkastenholzd3a1de92019-05-15 07:00:07 -07005885 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005886 const QuicErrorCode error =
5887 config.ProcessPeerHello(msg, CLIENT, &error_details);
bncf54082a2019-11-27 10:19:47 -08005888 EXPECT_THAT(error, IsQuicNoError());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005889
5890 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005891
5892 const QuicTime::Delta default_idle_timeout =
dschinazi027366e2020-05-01 14:31:19 -07005893 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs - 1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005894 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5895 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5896
5897 // When we send a packet, the timeout will change to 5ms +
5898 // kInitialIdleTimeoutSecs.
5899 clock_.AdvanceTime(five_ms);
5900 SendStreamDataToPeer(
5901 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5902 0, FIN, nullptr);
fayang2205d952020-05-12 13:45:56 -07005903 if (GetQuicReloadableFlag(quic_use_idle_network_detector)) {
fayangb9c88442020-03-26 07:03:57 -07005904 EXPECT_EQ(default_timeout + five_ms,
5905 connection_.GetTimeoutAlarm()->deadline());
5906 } else {
5907 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5908 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005909
5910 // Retransmit the packet via tail loss probe.
5911 clock_.AdvanceTime(connection_.GetRetransmissionAlarm()->deadline() -
5912 clock_.Now());
5913 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _));
5914 connection_.GetRetransmissionAlarm()->Fire();
5915
5916 // This time, we should time out and send a connection close due to the TLP.
fkastenholz5d880a92019-06-21 09:01:56 -07005917 EXPECT_CALL(visitor_,
5918 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07005919 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005920 clock_.AdvanceTime(connection_.GetTimeoutAlarm()->deadline() -
5921 clock_.ApproximateNow() + five_ms);
5922 connection_.GetTimeoutAlarm()->Fire();
5923 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5924 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005925 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005926}
5927
5928TEST_P(QuicConnectionTest, TimeoutAfterSendSilentCloseWithOpenStreams) {
dschinazi9a6194e2020-04-30 16:21:09 -07005929 // Same test as above, but having open streams causes a connection close
5930 // to be sent.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005931 EXPECT_TRUE(connection_.connected());
5932 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5933 QuicConfig config;
5934
5935 // Create a handshake message that also enables silent close.
5936 CryptoHandshakeMessage msg;
vasilvvc48c8712019-03-11 13:38:16 -07005937 std::string error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005938 QuicConfig client_config;
5939 client_config.SetInitialStreamFlowControlWindowToSend(
5940 kInitialStreamFlowControlWindowForTest);
5941 client_config.SetInitialSessionFlowControlWindowToSend(
5942 kInitialSessionFlowControlWindowForTest);
5943 client_config.SetIdleNetworkTimeout(
dschinazi027366e2020-05-01 14:31:19 -07005944 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs));
fkastenholzd3a1de92019-05-15 07:00:07 -07005945 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005946 const QuicErrorCode error =
5947 config.ProcessPeerHello(msg, CLIENT, &error_details);
bncf54082a2019-11-27 10:19:47 -08005948 EXPECT_THAT(error, IsQuicNoError());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005949
dschinazie7c38a52020-05-29 15:25:45 -07005950 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
5951 QuicConfigPeer::SetReceivedOriginalConnectionId(
5952 &config, connection_.connection_id());
5953 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
5954 &config, connection_.connection_id());
5955 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005956 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005957
5958 const QuicTime::Delta default_idle_timeout =
dschinazi027366e2020-05-01 14:31:19 -07005959 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs - 1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005960 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5961 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5962
5963 // When we send a packet, the timeout will change to 5ms +
5964 // kInitialIdleTimeoutSecs.
5965 clock_.AdvanceTime(five_ms);
5966 SendStreamDataToPeer(
5967 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5968 0, FIN, nullptr);
fayang2205d952020-05-12 13:45:56 -07005969 if (GetQuicReloadableFlag(quic_use_idle_network_detector)) {
fayangb9c88442020-03-26 07:03:57 -07005970 EXPECT_EQ(default_timeout + five_ms,
5971 connection_.GetTimeoutAlarm()->deadline());
5972 } else {
5973 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5974 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005975
5976 // Indicate streams are still open.
5977 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
5978 .WillRepeatedly(Return(true));
5979
5980 // This time, we should time out and send a connection close due to the TLP.
fkastenholz5d880a92019-06-21 09:01:56 -07005981 EXPECT_CALL(visitor_,
5982 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07005983 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005984 clock_.AdvanceTime(connection_.GetTimeoutAlarm()->deadline() -
5985 clock_.ApproximateNow() + five_ms);
5986 connection_.GetTimeoutAlarm()->Fire();
5987 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5988 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005989 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005990}
5991
5992TEST_P(QuicConnectionTest, TimeoutAfterReceive) {
5993 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5994 EXPECT_TRUE(connection_.connected());
5995 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5996 QuicConfig config;
5997 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005998
5999 const QuicTime::Delta initial_idle_timeout =
6000 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
6001 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
6002 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
6003
6004 connection_.SendStreamDataWithString(
6005 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6006 0, NO_FIN);
6007 connection_.SendStreamDataWithString(
6008 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6009 3, NO_FIN);
6010
6011 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
6012 clock_.AdvanceTime(five_ms);
6013
6014 // When we receive a packet, the timeout will change to 5ms +
6015 // kInitialIdleTimeoutSecs.
6016 QuicAckFrame ack = InitAckFrame(2);
6017 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
6018 ProcessAckPacket(&ack);
6019
6020 // The original alarm will fire. We should not time out because we had a
6021 // network event at t=5ms. The alarm will reregister.
6022 clock_.AdvanceTime(initial_idle_timeout - five_ms);
6023 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
fayang2205d952020-05-12 13:45:56 -07006024 if (!GetQuicReloadableFlag(quic_use_idle_network_detector)) {
fayangb9c88442020-03-26 07:03:57 -07006025 connection_.GetTimeoutAlarm()->Fire();
6026 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006027 EXPECT_TRUE(connection_.connected());
6028 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
6029 EXPECT_EQ(default_timeout + five_ms,
6030 connection_.GetTimeoutAlarm()->deadline());
6031
6032 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07006033 EXPECT_CALL(visitor_,
6034 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07006035 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006036 clock_.AdvanceTime(five_ms);
6037 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
6038 connection_.GetTimeoutAlarm()->Fire();
6039 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
6040 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07006041 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006042}
6043
6044TEST_P(QuicConnectionTest, TimeoutAfterReceiveNotSendWhenUnacked) {
6045 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6046 EXPECT_TRUE(connection_.connected());
6047 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6048 QuicConfig config;
6049 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006050
6051 const QuicTime::Delta initial_idle_timeout =
6052 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
6053 connection_.SetNetworkTimeouts(
6054 QuicTime::Delta::Infinite(),
6055 initial_idle_timeout + QuicTime::Delta::FromSeconds(1));
6056 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
6057 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
6058
6059 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
6060 connection_.SendStreamDataWithString(
6061 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6062 0, NO_FIN);
6063 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
6064 connection_.SendStreamDataWithString(
6065 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6066 3, NO_FIN);
6067
6068 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
6069
6070 clock_.AdvanceTime(five_ms);
6071
6072 // When we receive a packet, the timeout will change to 5ms +
6073 // kInitialIdleTimeoutSecs.
6074 QuicAckFrame ack = InitAckFrame(2);
6075 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
6076 ProcessAckPacket(&ack);
6077
6078 // The original alarm will fire. We should not time out because we had a
6079 // network event at t=5ms. The alarm will reregister.
6080 clock_.AdvanceTime(initial_idle_timeout - five_ms);
6081 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
fayang2205d952020-05-12 13:45:56 -07006082 if (!GetQuicReloadableFlag(quic_use_idle_network_detector)) {
fayangb9c88442020-03-26 07:03:57 -07006083 connection_.GetTimeoutAlarm()->Fire();
6084 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006085 EXPECT_TRUE(connection_.connected());
6086 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
6087 EXPECT_EQ(default_timeout + five_ms,
6088 connection_.GetTimeoutAlarm()->deadline());
6089
6090 // Now, send packets while advancing the time and verify that the connection
6091 // eventually times out.
fkastenholz5d880a92019-06-21 09:01:56 -07006092 EXPECT_CALL(visitor_,
6093 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006094 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
6095 for (int i = 0; i < 100 && connection_.connected(); ++i) {
6096 QUIC_LOG(INFO) << "sending data packet";
6097 connection_.SendStreamDataWithString(
6098 GetNthClientInitiatedStreamId(1, connection_.transport_version()),
6099 "foo", 0, NO_FIN);
6100 connection_.GetTimeoutAlarm()->Fire();
6101 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
6102 }
6103 EXPECT_FALSE(connection_.connected());
6104 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07006105 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006106}
6107
6108TEST_P(QuicConnectionTest, TimeoutAfter5ClientRTOs) {
fayang5f135052019-08-22 17:59:40 -07006109 if (connection_.PtoEnabled()) {
6110 return;
6111 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006112 connection_.SetMaxTailLossProbes(2);
6113 EXPECT_TRUE(connection_.connected());
6114 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6115 QuicConfig config;
6116 QuicTagVector connection_options;
6117 connection_options.push_back(k5RTO);
6118 config.SetConnectionOptionsToSend(connection_options);
dschinazif7c6a912020-05-05 11:39:53 -07006119 QuicConfigPeer::SetNegotiated(&config, true);
fayang656cbb52020-06-09 13:29:35 -07006120 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangf78b6932020-06-08 08:36:45 -07006121 EXPECT_CALL(visitor_, GetHandshakeState())
6122 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
6123 }
dschinazie7c38a52020-05-29 15:25:45 -07006124 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
6125 QuicConfigPeer::SetReceivedOriginalConnectionId(
6126 &config, connection_.connection_id());
6127 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
6128 &config, connection_.connection_id());
6129 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006130 connection_.SetFromConfig(config);
6131
6132 // Send stream data.
6133 SendStreamDataToPeer(
6134 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6135 0, FIN, nullptr);
6136
6137 // Fire the retransmission alarm 6 times, twice for TLP and 4 times for RTO.
6138 for (int i = 0; i < 6; ++i) {
6139 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
6140 connection_.GetRetransmissionAlarm()->Fire();
6141 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
6142 EXPECT_TRUE(connection_.connected());
6143 }
fayang2205d952020-05-12 13:45:56 -07006144 EXPECT_CALL(visitor_, OnPathDegrading());
6145 connection_.PathDegradingTimeout();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006146
6147 EXPECT_EQ(2u, connection_.sent_packet_manager().GetConsecutiveTlpCount());
6148 EXPECT_EQ(4u, connection_.sent_packet_manager().GetConsecutiveRtoCount());
6149 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07006150 EXPECT_CALL(visitor_,
6151 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07006152 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
fayang2205d952020-05-12 13:45:56 -07006153 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
6154 connection_.GetBlackholeDetectorAlarm()->Fire();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006155 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
6156 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07006157 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006158}
6159
6160TEST_P(QuicConnectionTest, SendScheduler) {
6161 // Test that if we send a packet without delay, it is not queued.
6162 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
QUICHE team8c1daa22019-03-13 08:33:41 -07006163 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07006164 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006165 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
6166 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
QUICHE team6987b4a2019-03-15 16:23:04 -07006167 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05006168 HAS_RETRANSMITTABLE_DATA, false, false);
6169 EXPECT_EQ(0u, connection_.NumQueuedPackets());
6170}
6171
6172TEST_P(QuicConnectionTest, FailToSendFirstPacket) {
6173 // Test that the connection does not crash when it fails to send the first
6174 // packet at which point self_address_ might be uninitialized.
6175 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
fkastenholz5d880a92019-06-21 09:01:56 -07006176 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
QUICHE team8c1daa22019-03-13 08:33:41 -07006177 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07006178 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006179 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
6180 writer_->SetShouldWriteFail();
QUICHE team6987b4a2019-03-15 16:23:04 -07006181 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05006182 HAS_RETRANSMITTABLE_DATA, false, false);
6183}
6184
6185TEST_P(QuicConnectionTest, SendSchedulerEAGAIN) {
6186 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
QUICHE team8c1daa22019-03-13 08:33:41 -07006187 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07006188 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006189 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
6190 BlockOnNextWrite();
6191 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _))
6192 .Times(0);
QUICHE team6987b4a2019-03-15 16:23:04 -07006193 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05006194 HAS_RETRANSMITTABLE_DATA, false, false);
6195 EXPECT_EQ(1u, connection_.NumQueuedPackets());
6196}
6197
6198TEST_P(QuicConnectionTest, TestQueueLimitsOnSendStreamData) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006199 // Queue the first packet.
ianswett3085da82019-04-04 07:24:24 -07006200 size_t payload_length = connection_.max_packet_length();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006201 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(testing::Return(false));
vasilvvc48c8712019-03-11 13:38:16 -07006202 const std::string payload(payload_length, 'a');
ianswett3085da82019-04-04 07:24:24 -07006203 QuicStreamId first_bidi_stream_id(QuicUtils::GetFirstBidirectionalStreamId(
6204 connection_.version().transport_version, Perspective::IS_CLIENT));
6205 EXPECT_EQ(0u, connection_
6206 .SendStreamDataWithString(first_bidi_stream_id, payload, 0,
6207 NO_FIN)
QUICHE teama6ef0a62019-03-07 20:34:33 -05006208 .bytes_consumed);
6209 EXPECT_EQ(0u, connection_.NumQueuedPackets());
6210}
6211
ianswett3085da82019-04-04 07:24:24 -07006212TEST_P(QuicConnectionTest, SendingThreePackets) {
ianswett3085da82019-04-04 07:24:24 -07006213 // Make the payload twice the size of the packet, so 3 packets are written.
6214 size_t total_payload_length = 2 * connection_.max_packet_length();
vasilvvc48c8712019-03-11 13:38:16 -07006215 const std::string payload(total_payload_length, 'a');
ianswett3085da82019-04-04 07:24:24 -07006216 QuicStreamId first_bidi_stream_id(QuicUtils::GetFirstBidirectionalStreamId(
6217 connection_.version().transport_version, Perspective::IS_CLIENT));
6218 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
6219 EXPECT_EQ(payload.size(), connection_
6220 .SendStreamDataWithString(first_bidi_stream_id,
6221 payload, 0, NO_FIN)
6222 .bytes_consumed);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006223}
6224
6225TEST_P(QuicConnectionTest, LoopThroughSendingPacketsWithTruncation) {
6226 set_perspective(Perspective::IS_SERVER);
fayangd4291e42019-05-30 10:31:21 -07006227 if (!VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006228 // For IETF QUIC, encryption level will be switched to FORWARD_SECURE in
6229 // SendStreamDataWithString.
6230 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
6231 }
6232 // Set up a larger payload than will fit in one packet.
vasilvvc48c8712019-03-11 13:38:16 -07006233 const std::string payload(connection_.max_packet_length(), 'a');
QUICHE teama6ef0a62019-03-07 20:34:33 -05006234 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
6235
6236 // Now send some packets with no truncation.
6237 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
6238 EXPECT_EQ(payload.size(),
6239 connection_.SendStreamDataWithString(3, payload, 0, NO_FIN)
6240 .bytes_consumed);
6241 // Track the size of the second packet here. The overhead will be the largest
6242 // we see in this test, due to the non-truncated connection id.
6243 size_t non_truncated_packet_size = writer_->last_packet_size();
6244
6245 // Change to a 0 byte connection id.
6246 QuicConfig config;
6247 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
6248 connection_.SetFromConfig(config);
6249 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
6250 EXPECT_EQ(payload.size(),
6251 connection_.SendStreamDataWithString(3, payload, 1350, NO_FIN)
6252 .bytes_consumed);
fayangd4291e42019-05-30 10:31:21 -07006253 if (VersionHasIetfInvariantHeader(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006254 // Short header packets sent from server omit connection ID already, and
6255 // stream offset size increases from 0 to 2.
6256 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() - 2);
6257 } else {
6258 // Just like above, we save 8 bytes on payload, and 8 on truncation. -2
6259 // because stream offset size is 2 instead of 0.
6260 EXPECT_EQ(non_truncated_packet_size,
6261 writer_->last_packet_size() + 8 * 2 - 2);
6262 }
6263}
6264
6265TEST_P(QuicConnectionTest, SendDelayedAck) {
6266 QuicTime ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6267 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006268 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006269 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006270 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006271 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006272 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006273 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006274 // Process a packet from the non-crypto stream.
6275 frame1_.stream_id = 3;
6276
6277 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006278 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006279 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6280 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6281
6282 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006283 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006284 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6285 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07006286 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006287 connection_.GetAckAlarm()->Fire();
6288 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006289 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006290 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006291 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006292 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6293 } else {
nharper55fa6132019-05-07 19:37:21 -07006294 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006295 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6296 }
6297 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006298 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006299}
6300
6301TEST_P(QuicConnectionTest, SendDelayedAfterQuiescence) {
6302 QuicConnectionPeer::SetFastAckAfterQuiescence(&connection_, true);
6303
6304 // The beginning of the connection counts as quiescence.
ianswett8f90e512019-12-18 10:50:27 -08006305 QuicTime ack_time = clock_.ApproximateNow() + kAlarmGranularity;
QUICHE teama6ef0a62019-03-07 20:34:33 -05006306 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006307 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006308 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006309 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006310 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006311 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006312 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006313 // Process a packet from the non-crypto stream.
6314 frame1_.stream_id = 3;
6315
6316 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006317 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006318 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6319 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6320
6321 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006322 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006323 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6324 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07006325 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006326 connection_.GetAckAlarm()->Fire();
6327 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006328 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006329 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006330 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006331 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6332 } else {
nharper55fa6132019-05-07 19:37:21 -07006333 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006334 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6335 }
6336 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006337 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006338
6339 // Process another packet immedately after sending the ack and expect the
6340 // ack alarm to be set delayed ack time in the future.
6341 ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6342 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6343 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6344
6345 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006346 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006347 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6348 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07006349 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006350 connection_.GetAckAlarm()->Fire();
6351 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006352 padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006353 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006354 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006355 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6356 } else {
nharper55fa6132019-05-07 19:37:21 -07006357 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006358 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6359 }
6360 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006361 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006362
ianswett8f90e512019-12-18 10:50:27 -08006363 // Wait 1 second and ensure the ack alarm is set to 1ms in the future.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006364 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
6365 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
6366 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6367 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6368
6369 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006370 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006371 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6372}
6373
6374TEST_P(QuicConnectionTest, SendDelayedAckDecimation) {
6375 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6376 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION);
6377
6378 const size_t kMinRttMs = 40;
6379 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6380 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6381 QuicTime::Delta::Zero(), QuicTime::Zero());
6382 // The ack time should be based on min_rtt/4, since it's less than the
6383 // default delayed ack time.
6384 QuicTime ack_time = clock_.ApproximateNow() +
6385 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6386 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006387 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006388 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006389 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006390 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006391 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006392 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006393 // Process a packet from the non-crypto stream.
6394 frame1_.stream_id = 3;
6395
6396 // Process all the initial packets in order so there aren't missing packets.
6397 uint64_t kFirstDecimatedPacket = 101;
6398 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6399 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6400 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6401 }
fayang9adfb532020-06-04 06:58:45 -07006402 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006403 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006404 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006405 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6406 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6407 ENCRYPTION_ZERO_RTT);
6408
6409 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006410 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006411 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6412
6413 // The 10th received packet causes an ack to be sent.
6414 for (int i = 0; i < 9; ++i) {
fayang9adfb532020-06-04 06:58:45 -07006415 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006416 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6417 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6418 ENCRYPTION_ZERO_RTT);
6419 }
6420 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07006421 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006422 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07006423 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006424 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6425 } else {
nharperc32d8ab2019-10-09 11:09:06 -07006426 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006427 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6428 }
6429 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006430 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006431}
6432
6433TEST_P(QuicConnectionTest, SendDelayedAckAckDecimationAfterQuiescence) {
6434 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6435 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION);
6436 QuicConnectionPeer::SetFastAckAfterQuiescence(&connection_, true);
6437
6438 const size_t kMinRttMs = 40;
6439 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6440 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6441 QuicTime::Delta::Zero(), QuicTime::Zero());
6442
6443 // The beginning of the connection counts as quiescence.
6444 QuicTime ack_time =
6445 clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
6446 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006447 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006448 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006449 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006450 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006451 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006452 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006453 // Process a packet from the non-crypto stream.
6454 frame1_.stream_id = 3;
6455
6456 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006457 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006458 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6459 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6460
6461 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006462 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006463 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6464 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07006465 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006466 connection_.GetAckAlarm()->Fire();
6467 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006468 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006469 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006470 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006471 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6472 } else {
nharper55fa6132019-05-07 19:37:21 -07006473 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006474 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6475 }
6476 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006477 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006478
6479 // Process another packet immedately after sending the ack and expect the
6480 // ack alarm to be set delayed ack time in the future.
6481 ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6482 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6483 ProcessDataPacketAtLevel(2, !kHasStopWaiting, 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 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07006489 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006490 connection_.GetAckAlarm()->Fire();
6491 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006492 padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006493 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006494 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006495 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6496 } else {
nharper55fa6132019-05-07 19:37:21 -07006497 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006498 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6499 }
6500 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006501 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006502
6503 // Wait 1 second and enesure the ack alarm is set to 1ms in the future.
6504 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
6505 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
6506 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6507 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6508
6509 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006510 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006511 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6512
6513 // Process enough packets to get into ack decimation behavior.
6514 // The ack time should be based on min_rtt/4, since it's less than the
6515 // default delayed ack time.
6516 ack_time = clock_.ApproximateNow() +
6517 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6518 uint64_t kFirstDecimatedPacket = 101;
6519 for (unsigned int i = 0; i < kFirstDecimatedPacket - 4; ++i) {
6520 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6521 ProcessDataPacketAtLevel(4 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6522 }
fayang9adfb532020-06-04 06:58:45 -07006523 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006524 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006525 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006526 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6527 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6528 ENCRYPTION_ZERO_RTT);
6529
6530 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006531 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006532 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6533
6534 // The 10th received packet causes an ack to be sent.
6535 for (int i = 0; i < 9; ++i) {
fayang9adfb532020-06-04 06:58:45 -07006536 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006537 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6538 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6539 ENCRYPTION_ZERO_RTT);
6540 }
6541 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07006542 padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006543 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07006544 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006545 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6546 } else {
nharperc32d8ab2019-10-09 11:09:06 -07006547 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006548 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6549 }
6550 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006551 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006552
6553 // Wait 1 second and enesure the ack alarm is set to 1ms in the future.
6554 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
6555 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
6556 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6557 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 10, !kHasStopWaiting,
6558 ENCRYPTION_ZERO_RTT);
6559
6560 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006561 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006562 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6563}
6564
6565TEST_P(QuicConnectionTest, SendDelayedAckDecimationUnlimitedAggregation) {
6566 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6567 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6568 QuicConfig config;
6569 QuicTagVector connection_options;
6570 connection_options.push_back(kACKD);
6571 // No limit on the number of packets received before sending an ack.
6572 connection_options.push_back(kAKDU);
6573 config.SetConnectionOptionsToSend(connection_options);
6574 connection_.SetFromConfig(config);
6575
6576 const size_t kMinRttMs = 40;
6577 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6578 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6579 QuicTime::Delta::Zero(), QuicTime::Zero());
6580 // The ack time should be based on min_rtt/4, since it's less than the
6581 // default delayed ack time.
6582 QuicTime ack_time = clock_.ApproximateNow() +
6583 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6584 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006585 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006586 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006587 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006588 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006589 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006590 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006591 // Process a packet from the non-crypto stream.
6592 frame1_.stream_id = 3;
6593
6594 // Process all the initial packets in order so there aren't missing packets.
6595 uint64_t kFirstDecimatedPacket = 101;
6596 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6597 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6598 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6599 }
fayang9adfb532020-06-04 06:58:45 -07006600 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006601 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006602 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006603 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6604 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6605 ENCRYPTION_ZERO_RTT);
6606
6607 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006608 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006609 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6610
6611 // 18 packets will not cause an ack to be sent. 19 will because when
6612 // stop waiting frames are in use, we ack every 20 packets no matter what.
6613 for (int i = 0; i < 18; ++i) {
fayang9adfb532020-06-04 06:58:45 -07006614 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006615 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6616 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6617 ENCRYPTION_ZERO_RTT);
6618 }
6619 // The delayed ack timer should still be set to the expected deadline.
fayang9adfb532020-06-04 06:58:45 -07006620 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006621 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6622}
6623
6624TEST_P(QuicConnectionTest, SendDelayedAckDecimationEighthRtt) {
6625 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6626 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION);
6627 QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
6628
6629 const size_t kMinRttMs = 40;
6630 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6631 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6632 QuicTime::Delta::Zero(), QuicTime::Zero());
6633 // The ack time should be based on min_rtt/8, since it's less than the
6634 // default delayed ack time.
6635 QuicTime ack_time = clock_.ApproximateNow() +
6636 QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
6637 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006638 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006639 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006640 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006641 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006642 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006643 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006644 // Process a packet from the non-crypto stream.
6645 frame1_.stream_id = 3;
6646
6647 // Process all the initial packets in order so there aren't missing packets.
6648 uint64_t kFirstDecimatedPacket = 101;
6649 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6650 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6651 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6652 }
fayang9adfb532020-06-04 06:58:45 -07006653 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006654 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006655 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006656 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6657 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6658 ENCRYPTION_ZERO_RTT);
6659
6660 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006661 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006662 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6663
6664 // The 10th received packet causes an ack to be sent.
6665 for (int i = 0; i < 9; ++i) {
fayang9adfb532020-06-04 06:58:45 -07006666 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006667 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6668 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6669 ENCRYPTION_ZERO_RTT);
6670 }
6671 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07006672 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006673 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07006674 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006675 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6676 } else {
nharperc32d8ab2019-10-09 11:09:06 -07006677 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006678 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6679 }
6680 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006681 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006682}
6683
6684TEST_P(QuicConnectionTest, SendDelayedAckDecimationWithReordering) {
6685 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6686 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6687
6688 const size_t kMinRttMs = 40;
6689 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6690 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6691 QuicTime::Delta::Zero(), QuicTime::Zero());
6692 // The ack time should be based on min_rtt/4, since it's less than the
6693 // default delayed ack time.
6694 QuicTime ack_time = clock_.ApproximateNow() +
6695 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6696 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006697 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006698 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006699 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006700 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006701 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006702 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006703 // Process a packet from the non-crypto stream.
6704 frame1_.stream_id = 3;
6705
6706 // Process all the initial packets in order so there aren't missing packets.
6707 uint64_t kFirstDecimatedPacket = 101;
6708 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6709 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6710 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6711 }
fayang9adfb532020-06-04 06:58:45 -07006712 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006713
6714 // Receive one packet out of order and then the rest in order.
6715 // The loop leaves a one packet gap between acks sent to simulate some loss.
6716 for (int j = 0; j < 3; ++j) {
6717 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6718 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6719 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 9 + (j * 11),
6720 !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6721 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
fayang9adfb532020-06-04 06:58:45 -07006722 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006723 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6724
6725 // The 10th received packet causes an ack to be sent.
6726 writer_->Reset();
6727 for (int i = 0; i < 9; ++i) {
fayang9adfb532020-06-04 06:58:45 -07006728 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006729 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6730 // The ACK shouldn't be sent until the 10th packet is processed.
6731 EXPECT_TRUE(writer_->ack_frames().empty());
6732 ProcessDataPacketAtLevel(kFirstDecimatedPacket + i + (j * 11),
6733 !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6734 }
6735 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07006736 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006737 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07006738 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006739 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6740 } else {
nharperc32d8ab2019-10-09 11:09:06 -07006741 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006742 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6743 }
6744 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006745 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006746 }
6747}
6748
6749TEST_P(QuicConnectionTest, SendDelayedAckDecimationWithLargeReordering) {
6750 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6751 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6752
6753 const size_t kMinRttMs = 40;
6754 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6755 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6756 QuicTime::Delta::Zero(), QuicTime::Zero());
6757 // The ack time should be based on min_rtt/4, since it's less than the
6758 // default delayed ack time.
6759 QuicTime ack_time = clock_.ApproximateNow() +
6760 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6761 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006762 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006763 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006764 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006765 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006766 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006767 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006768 // Process a packet from the non-crypto stream.
6769 frame1_.stream_id = 3;
6770
6771 // Process all the initial packets in order so there aren't missing packets.
6772 uint64_t kFirstDecimatedPacket = 101;
6773 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6774 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6775 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6776 }
fayang9adfb532020-06-04 06:58:45 -07006777 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006778 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006779 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006780 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6781 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6782 ENCRYPTION_ZERO_RTT);
6783
6784 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006785 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006786 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6787
6788 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6789 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6790 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 19, !kHasStopWaiting,
6791 ENCRYPTION_ZERO_RTT);
6792 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
fayang9adfb532020-06-04 06:58:45 -07006793 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006794 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6795
6796 // The 10th received packet causes an ack to be sent.
6797 for (int i = 0; i < 8; ++i) {
fayang9adfb532020-06-04 06:58:45 -07006798 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006799 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6800 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6801 ENCRYPTION_ZERO_RTT);
6802 }
6803 // Check that ack is sent and that delayed ack alarm is reset.
6804 if (GetParam().no_stop_waiting) {
fayang58f71072019-11-05 08:47:02 -08006805 EXPECT_EQ(writer_->padding_frames().size() + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006806 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6807 } else {
6808 EXPECT_EQ(2u, writer_->frame_count());
6809 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6810 }
6811 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006812 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006813
6814 // The next packet received in order will cause an immediate ack,
6815 // because it fills a hole.
fayang9adfb532020-06-04 06:58:45 -07006816 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006817 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6818 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 10, !kHasStopWaiting,
6819 ENCRYPTION_ZERO_RTT);
6820 // Check that ack is sent and that delayed ack alarm is reset.
6821 if (GetParam().no_stop_waiting) {
fayang58f71072019-11-05 08:47:02 -08006822 EXPECT_EQ(writer_->padding_frames().size() + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006823 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6824 } else {
6825 EXPECT_EQ(2u, writer_->frame_count());
6826 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6827 }
6828 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006829 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006830}
6831
6832TEST_P(QuicConnectionTest, SendDelayedAckDecimationWithReorderingEighthRtt) {
6833 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6834 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6835 QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
6836
6837 const size_t kMinRttMs = 40;
6838 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6839 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6840 QuicTime::Delta::Zero(), QuicTime::Zero());
6841 // The ack time should be based on min_rtt/8, since it's less than the
6842 // default delayed ack time.
6843 QuicTime ack_time = clock_.ApproximateNow() +
6844 QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
6845 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006846 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006847 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006848 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006849 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006850 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006851 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006852 // Process a packet from the non-crypto stream.
6853 frame1_.stream_id = 3;
6854
6855 // Process all the initial packets in order so there aren't missing packets.
6856 uint64_t kFirstDecimatedPacket = 101;
6857 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6858 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6859 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6860 }
fayang9adfb532020-06-04 06:58:45 -07006861 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006862 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006863 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006864 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6865 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6866 ENCRYPTION_ZERO_RTT);
6867
6868 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006869 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006870 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6871
6872 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6873 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6874 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 9, !kHasStopWaiting,
6875 ENCRYPTION_ZERO_RTT);
6876 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
fayang9adfb532020-06-04 06:58:45 -07006877 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006878 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6879
6880 // The 10th received packet causes an ack to be sent.
6881 for (int i = 0; i < 8; ++i) {
fayang9adfb532020-06-04 06:58:45 -07006882 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006883 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6884 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6885 ENCRYPTION_ZERO_RTT);
6886 }
6887 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07006888 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006889 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07006890 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006891 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6892 } else {
nharperc32d8ab2019-10-09 11:09:06 -07006893 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006894 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6895 }
6896 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006897 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006898}
6899
6900TEST_P(QuicConnectionTest,
6901 SendDelayedAckDecimationWithLargeReorderingEighthRtt) {
6902 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6903 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6904 QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
6905
6906 const size_t kMinRttMs = 40;
6907 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6908 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6909 QuicTime::Delta::Zero(), QuicTime::Zero());
6910 // The ack time should be based on min_rtt/8, since it's less than the
6911 // default delayed ack time.
6912 QuicTime ack_time = clock_.ApproximateNow() +
6913 QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
6914 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006915 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006916 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006917 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006918 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006919 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006920 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006921 // Process a packet from the non-crypto stream.
6922 frame1_.stream_id = 3;
6923
6924 // Process all the initial packets in order so there aren't missing packets.
6925 uint64_t kFirstDecimatedPacket = 101;
6926 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6927 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6928 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6929 }
fayang9adfb532020-06-04 06:58:45 -07006930 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006931 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006932 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006933 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6934 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6935 ENCRYPTION_ZERO_RTT);
6936
6937 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006938 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006939 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6940
6941 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6942 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6943 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 19, !kHasStopWaiting,
6944 ENCRYPTION_ZERO_RTT);
6945 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
fayang9adfb532020-06-04 06:58:45 -07006946 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006947 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6948
6949 // The 10th received packet causes an ack to be sent.
6950 for (int i = 0; i < 8; ++i) {
fayang9adfb532020-06-04 06:58:45 -07006951 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006952 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6953 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6954 ENCRYPTION_ZERO_RTT);
6955 }
6956 // Check that ack is sent and that delayed ack alarm is reset.
6957 if (GetParam().no_stop_waiting) {
fayang58f71072019-11-05 08:47:02 -08006958 EXPECT_EQ(writer_->padding_frames().size() + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006959 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6960 } else {
6961 EXPECT_EQ(2u, writer_->frame_count());
6962 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6963 }
6964 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006965 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006966
6967 // The next packet received in order will cause an immediate ack,
6968 // because it fills a hole.
fayang9adfb532020-06-04 06:58:45 -07006969 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006970 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6971 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 10, !kHasStopWaiting,
6972 ENCRYPTION_ZERO_RTT);
6973 // Check that ack is sent and that delayed ack alarm is reset.
6974 if (GetParam().no_stop_waiting) {
fayang58f71072019-11-05 08:47:02 -08006975 EXPECT_EQ(writer_->padding_frames().size() + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006976 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6977 } else {
6978 EXPECT_EQ(2u, writer_->frame_count());
6979 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6980 }
6981 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006982 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006983}
6984
6985TEST_P(QuicConnectionTest, SendDelayedAckOnHandshakeConfirmed) {
6986 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6987 ProcessPacket(1);
6988 // Check that ack is sent and that delayed ack alarm is set.
fayang9adfb532020-06-04 06:58:45 -07006989 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006990 QuicTime ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6991 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6992
6993 // Completing the handshake as the server does nothing.
6994 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_SERVER);
6995 connection_.OnHandshakeComplete();
fayang9adfb532020-06-04 06:58:45 -07006996 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006997 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6998
6999 // Complete the handshake as the client decreases the delayed ack time to 0ms.
7000 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_CLIENT);
7001 connection_.OnHandshakeComplete();
fayang9adfb532020-06-04 06:58:45 -07007002 EXPECT_TRUE(connection_.HasPendingAcks());
fayangb296fb82020-02-11 08:14:28 -08007003 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7004 EXPECT_EQ(clock_.ApproximateNow() + DefaultDelayedAckTime(),
7005 connection_.GetAckAlarm()->deadline());
7006 } else {
7007 EXPECT_EQ(clock_.ApproximateNow(), connection_.GetAckAlarm()->deadline());
7008 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007009}
7010
7011TEST_P(QuicConnectionTest, SendDelayedAckOnSecondPacket) {
7012 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7013 ProcessPacket(1);
7014 ProcessPacket(2);
7015 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07007016 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05007017 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07007018 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007019 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
7020 } else {
nharper55fa6132019-05-07 19:37:21 -07007021 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007022 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
7023 }
7024 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07007025 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007026}
7027
7028TEST_P(QuicConnectionTest, NoAckOnOldNacks) {
7029 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang6dba4902019-06-17 10:04:23 -07007030 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007031 ProcessPacket(2);
7032 size_t frames_per_ack = GetParam().no_stop_waiting ? 1 : 2;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007033
7034 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7035 ProcessPacket(3);
nharper55fa6132019-05-07 19:37:21 -07007036 size_t padding_frame_count = writer_->padding_frames().size();
7037 EXPECT_EQ(padding_frame_count + frames_per_ack, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007038 EXPECT_FALSE(writer_->ack_frames().empty());
7039 writer_->Reset();
7040
fayang6dba4902019-06-17 10:04:23 -07007041 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007042 ProcessPacket(4);
fayang6dba4902019-06-17 10:04:23 -07007043 EXPECT_EQ(0u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007044
7045 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7046 ProcessPacket(5);
nharper55fa6132019-05-07 19:37:21 -07007047 padding_frame_count = writer_->padding_frames().size();
7048 EXPECT_EQ(padding_frame_count + frames_per_ack, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007049 EXPECT_FALSE(writer_->ack_frames().empty());
7050 writer_->Reset();
7051
7052 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
7053 // Now only set the timer on the 6th packet, instead of sending another ack.
7054 ProcessPacket(6);
nharper55fa6132019-05-07 19:37:21 -07007055 padding_frame_count = writer_->padding_frames().size();
7056 EXPECT_EQ(padding_frame_count, writer_->frame_count());
fayang9adfb532020-06-04 06:58:45 -07007057 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007058}
7059
7060TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingPacket) {
7061 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
QUICHE team8c1daa22019-03-13 08:33:41 -07007062 EXPECT_CALL(visitor_, OnStreamFrame(_));
7063 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07007064 std::make_unique<TaggingEncrypter>(0x01));
zhongyi546cc452019-04-12 15:27:49 -07007065 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07007066 std::make_unique<StrictTaggingDecrypter>(0x01));
nharper2c9f02a2019-05-08 10:25:50 -07007067 ProcessDataPacket(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007068 connection_.SendStreamDataWithString(
7069 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
7070 0, NO_FIN);
7071 // Check that ack is bundled with outgoing data and that delayed ack
7072 // alarm is reset.
7073 if (GetParam().no_stop_waiting) {
7074 EXPECT_EQ(2u, writer_->frame_count());
7075 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
7076 } else {
7077 EXPECT_EQ(3u, writer_->frame_count());
7078 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
7079 }
7080 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07007081 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007082}
7083
7084TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingCryptoPacket) {
7085 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayangc31c9952019-06-05 13:54:48 -07007086 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
7087 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
7088 } else {
7089 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7090 }
7091 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
nharper46833c32019-05-15 21:33:05 -07007092 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007093 // Check that ack is bundled with outgoing crypto data.
7094 if (GetParam().no_stop_waiting) {
7095 EXPECT_EQ(3u, writer_->frame_count());
7096 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
7097 } else {
7098 EXPECT_EQ(4u, writer_->frame_count());
7099 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
7100 }
fayang9adfb532020-06-04 06:58:45 -07007101 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007102}
7103
7104TEST_P(QuicConnectionTest, BlockAndBufferOnFirstCHLOPacketOfTwo) {
7105 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7106 ProcessPacket(1);
7107 BlockOnNextWrite();
7108 writer_->set_is_write_blocked_data_buffered(true);
fayang6a258412020-05-28 08:57:12 -07007109 if (GetQuicReloadableFlag(quic_move_amplification_limit) &&
7110 QuicVersionUsesCryptoFrames(connection_.transport_version())) {
7111 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7112 } else {
7113 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
7114 }
nharper46833c32019-05-15 21:33:05 -07007115 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007116 EXPECT_TRUE(writer_->IsWriteBlocked());
7117 EXPECT_FALSE(connection_.HasQueuedData());
nharper46833c32019-05-15 21:33:05 -07007118 connection_.SendCryptoDataWithString("bar", 3);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007119 EXPECT_TRUE(writer_->IsWriteBlocked());
fayang6a258412020-05-28 08:57:12 -07007120 if (GetQuicReloadableFlag(quic_move_amplification_limit) &&
7121 QuicVersionUsesCryptoFrames(connection_.transport_version())) {
7122 // CRYPTO frames are not flushed when writer is blocked.
7123 EXPECT_FALSE(connection_.HasQueuedData());
7124 } else {
7125 EXPECT_TRUE(connection_.HasQueuedData());
7126 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007127}
7128
7129TEST_P(QuicConnectionTest, BundleAckForSecondCHLO) {
7130 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07007131 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007132 EXPECT_CALL(visitor_, OnCanWrite())
7133 .WillOnce(IgnoreResult(InvokeWithoutArgs(
7134 &connection_, &TestConnection::SendCryptoStreamData)));
7135 // Process a packet from the crypto stream, which is frame1_'s default.
7136 // Receiving the CHLO as packet 2 first will cause the connection to
7137 // immediately send an ack, due to the packet gap.
fayangc31c9952019-06-05 13:54:48 -07007138 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
7139 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
7140 } else {
7141 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7142 }
7143 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007144 // Check that ack is sent and that delayed ack alarm is reset.
7145 if (GetParam().no_stop_waiting) {
7146 EXPECT_EQ(3u, writer_->frame_count());
7147 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
7148 } else {
7149 EXPECT_EQ(4u, writer_->frame_count());
7150 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
7151 }
QUICHE teamea740082019-03-11 17:58:43 -07007152 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007153 EXPECT_EQ(1u, writer_->stream_frames().size());
7154 } else {
7155 EXPECT_EQ(1u, writer_->crypto_frames().size());
7156 }
7157 EXPECT_EQ(1u, writer_->padding_frames().size());
7158 ASSERT_FALSE(writer_->ack_frames().empty());
7159 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(writer_->ack_frames().front()));
fayang9adfb532020-06-04 06:58:45 -07007160 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007161}
7162
7163TEST_P(QuicConnectionTest, BundleAckForSecondCHLOTwoPacketReject) {
7164 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07007165 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007166
7167 // Process two packets from the crypto stream, which is frame1_'s default,
7168 // simulating a 2 packet reject.
7169 {
fayangc31c9952019-06-05 13:54:48 -07007170 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
7171 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
7172 } else {
7173 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7174 }
7175 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007176 // Send the new CHLO when the REJ is processed.
fayangc31c9952019-06-05 13:54:48 -07007177 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
7178 EXPECT_CALL(visitor_, OnCryptoFrame(_))
7179 .WillOnce(IgnoreResult(InvokeWithoutArgs(
7180 &connection_, &TestConnection::SendCryptoStreamData)));
7181 } else {
7182 EXPECT_CALL(visitor_, OnStreamFrame(_))
7183 .WillOnce(IgnoreResult(InvokeWithoutArgs(
7184 &connection_, &TestConnection::SendCryptoStreamData)));
7185 }
7186 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007187 }
7188 // Check that ack is sent and that delayed ack alarm is reset.
7189 if (GetParam().no_stop_waiting) {
7190 EXPECT_EQ(3u, writer_->frame_count());
7191 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
7192 } else {
7193 EXPECT_EQ(4u, writer_->frame_count());
7194 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
7195 }
QUICHE teamea740082019-03-11 17:58:43 -07007196 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007197 EXPECT_EQ(1u, writer_->stream_frames().size());
7198 } else {
7199 EXPECT_EQ(1u, writer_->crypto_frames().size());
7200 }
7201 EXPECT_EQ(1u, writer_->padding_frames().size());
7202 ASSERT_FALSE(writer_->ack_frames().empty());
7203 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(writer_->ack_frames().front()));
fayang9adfb532020-06-04 06:58:45 -07007204 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007205}
7206
7207TEST_P(QuicConnectionTest, BundleAckWithDataOnIncomingAck) {
7208 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7209 connection_.SendStreamDataWithString(
7210 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
7211 0, NO_FIN);
7212 connection_.SendStreamDataWithString(
7213 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
7214 3, NO_FIN);
7215 // Ack the second packet, which will retransmit the first packet.
7216 QuicAckFrame ack = ConstructAckFrame(2, 1);
7217 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07007218 lost_packets.push_back(
7219 LostPacket(QuicPacketNumber(1), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007220 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07007221 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
7222 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007223 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7224 ProcessAckPacket(&ack);
nharper55fa6132019-05-07 19:37:21 -07007225 size_t padding_frame_count = writer_->padding_frames().size();
7226 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007227 EXPECT_EQ(1u, writer_->stream_frames().size());
7228 writer_->Reset();
7229
7230 // Now ack the retransmission, which will both raise the high water mark
7231 // and see if there is more data to send.
7232 ack = ConstructAckFrame(3, 1);
7233 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
7234 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7235 ProcessAckPacket(&ack);
7236
7237 // Check that no packet is sent and the ack alarm isn't set.
7238 EXPECT_EQ(0u, writer_->frame_count());
fayang9adfb532020-06-04 06:58:45 -07007239 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007240 writer_->Reset();
7241
7242 // Send the same ack, but send both data and an ack together.
7243 ack = ConstructAckFrame(3, 1);
7244 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
7245 EXPECT_CALL(visitor_, OnCanWrite())
7246 .WillOnce(IgnoreResult(InvokeWithoutArgs(
7247 &connection_, &TestConnection::EnsureWritableAndSendStreamData5)));
7248 ProcessAckPacket(&ack);
7249
7250 // Check that ack is bundled with outgoing data and the delayed ack
7251 // alarm is reset.
7252 if (GetParam().no_stop_waiting) {
fayang8a27b0f2019-11-04 11:27:40 -08007253 // Do not ACK acks.
7254 EXPECT_EQ(1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007255 } else {
7256 EXPECT_EQ(3u, writer_->frame_count());
7257 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
7258 }
fayang8a27b0f2019-11-04 11:27:40 -08007259 if (GetParam().no_stop_waiting) {
fayang03916692019-05-22 17:57:18 -07007260 EXPECT_TRUE(writer_->ack_frames().empty());
7261 } else {
7262 EXPECT_FALSE(writer_->ack_frames().empty());
7263 EXPECT_EQ(QuicPacketNumber(3u),
7264 LargestAcked(writer_->ack_frames().front()));
7265 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007266 EXPECT_EQ(1u, writer_->stream_frames().size());
fayang9adfb532020-06-04 06:58:45 -07007267 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007268}
7269
7270TEST_P(QuicConnectionTest, NoAckSentForClose) {
7271 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7272 ProcessPacket(1);
fkastenholz5d880a92019-06-21 09:01:56 -07007273 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
7274 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007275 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
7276 ProcessClosePacket(2);
fkastenholz5d880a92019-06-21 09:01:56 -07007277 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007278 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7279 IsError(QUIC_PEER_GOING_AWAY));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007280}
7281
7282TEST_P(QuicConnectionTest, SendWhenDisconnected) {
7283 EXPECT_TRUE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07007284 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7285 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007286 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
7287 ConnectionCloseBehavior::SILENT_CLOSE);
7288 EXPECT_FALSE(connection_.connected());
ianswettfc16a2b2020-05-18 16:05:49 -07007289 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
QUICHE team8c1daa22019-03-13 08:33:41 -07007290 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07007291 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007292 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
7293 .Times(0);
QUICHE team6987b4a2019-03-15 16:23:04 -07007294 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05007295 HAS_RETRANSMITTABLE_DATA, false, false);
fkastenholz5d880a92019-06-21 09:01:56 -07007296 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007297 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7298 IsError(QUIC_PEER_GOING_AWAY));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007299}
7300
7301TEST_P(QuicConnectionTest, SendConnectivityProbingWhenDisconnected) {
7302 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
fayangc31c9952019-06-05 13:54:48 -07007303 if (!IsDefaultTestConfiguration()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007304 return;
7305 }
7306
7307 EXPECT_TRUE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07007308 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7309 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007310 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
7311 ConnectionCloseBehavior::SILENT_CLOSE);
7312 EXPECT_FALSE(connection_.connected());
ianswettfc16a2b2020-05-18 16:05:49 -07007313 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007314
7315 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
7316 .Times(0);
7317
7318 EXPECT_QUIC_BUG(connection_.SendConnectivityProbingPacket(
7319 writer_.get(), connection_.peer_address()),
7320 "Not sending connectivity probing packet as connection is "
7321 "disconnected.");
fkastenholz5d880a92019-06-21 09:01:56 -07007322 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007323 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7324 IsError(QUIC_PEER_GOING_AWAY));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007325}
7326
7327TEST_P(QuicConnectionTest, WriteBlockedAfterClientSendsConnectivityProbe) {
dschinazi1c6e5922020-06-19 10:35:03 -07007328 PathProbeTestInit(Perspective::IS_CLIENT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007329 TestPacketWriter probing_writer(version(), &clock_);
7330 // Block next write so that sending connectivity probe will encounter a
7331 // blocked write when send a connectivity probe to the peer.
7332 probing_writer.BlockOnNextWrite();
7333 // Connection will not be marked as write blocked as connectivity probe only
7334 // affects the probing_writer which is not the default.
7335 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
7336
7337 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
7338 .Times(1);
7339 connection_.SendConnectivityProbingPacket(&probing_writer,
7340 connection_.peer_address());
7341}
7342
7343TEST_P(QuicConnectionTest, WriterBlockedAfterServerSendsConnectivityProbe) {
dschinazi1c6e5922020-06-19 10:35:03 -07007344 PathProbeTestInit(Perspective::IS_SERVER);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007345
7346 // Block next write so that sending connectivity probe will encounter a
7347 // blocked write when send a connectivity probe to the peer.
7348 writer_->BlockOnNextWrite();
7349 // Connection will be marked as write blocked as server uses the default
7350 // writer to send connectivity probes.
7351 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
7352
7353 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
7354 .Times(1);
7355 connection_.SendConnectivityProbingPacket(writer_.get(),
7356 connection_.peer_address());
7357}
7358
7359TEST_P(QuicConnectionTest, WriterErrorWhenClientSendsConnectivityProbe) {
dschinazi1c6e5922020-06-19 10:35:03 -07007360 PathProbeTestInit(Perspective::IS_CLIENT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007361 TestPacketWriter probing_writer(version(), &clock_);
7362 probing_writer.SetShouldWriteFail();
7363
7364 // Connection should not be closed if a connectivity probe is failed to be
7365 // sent.
fkastenholz5d880a92019-06-21 09:01:56 -07007366 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007367
7368 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
7369 .Times(0);
7370 connection_.SendConnectivityProbingPacket(&probing_writer,
7371 connection_.peer_address());
7372}
7373
7374TEST_P(QuicConnectionTest, WriterErrorWhenServerSendsConnectivityProbe) {
dschinazi1c6e5922020-06-19 10:35:03 -07007375 PathProbeTestInit(Perspective::IS_SERVER);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007376
7377 writer_->SetShouldWriteFail();
7378 // Connection should not be closed if a connectivity probe is failed to be
7379 // sent.
fkastenholz5d880a92019-06-21 09:01:56 -07007380 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007381
7382 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
7383 .Times(0);
7384 connection_.SendConnectivityProbingPacket(writer_.get(),
7385 connection_.peer_address());
7386}
7387
7388TEST_P(QuicConnectionTest, PublicReset) {
fayangc31c9952019-06-05 13:54:48 -07007389 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007390 return;
7391 }
7392 QuicPublicResetPacket header;
7393 // Public reset packet in only built by server.
7394 header.connection_id = connection_id_;
7395 std::unique_ptr<QuicEncryptedPacket> packet(
7396 framer_.BuildPublicResetPacket(header));
7397 std::unique_ptr<QuicReceivedPacket> received(
7398 ConstructReceivedPacket(*packet, QuicTime::Zero()));
fkastenholz5d880a92019-06-21 09:01:56 -07007399 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
7400 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007401 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
fkastenholz5d880a92019-06-21 09:01:56 -07007402 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007403 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7404 IsError(QUIC_PUBLIC_RESET));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007405}
7406
7407TEST_P(QuicConnectionTest, IetfStatelessReset) {
fayangc31c9952019-06-05 13:54:48 -07007408 if (!VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007409 return;
7410 }
7411 const QuicUint128 kTestStatelessResetToken = 1010101;
7412 QuicConfig config;
7413 QuicConfigPeer::SetReceivedStatelessResetToken(&config,
7414 kTestStatelessResetToken);
7415 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7416 connection_.SetFromConfig(config);
7417 std::unique_ptr<QuicEncryptedPacket> packet(
7418 QuicFramer::BuildIetfStatelessResetPacket(connection_id_,
7419 kTestStatelessResetToken));
7420 std::unique_ptr<QuicReceivedPacket> received(
7421 ConstructReceivedPacket(*packet, QuicTime::Zero()));
renjietang7f483b52020-05-20 14:30:47 -07007422 EXPECT_CALL(visitor_, ValidateStatelessReset(_, _)).WillOnce(Return(true));
fkastenholz5d880a92019-06-21 09:01:56 -07007423 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
7424 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007425 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
fkastenholz5d880a92019-06-21 09:01:56 -07007426 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007427 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7428 IsError(QUIC_PUBLIC_RESET));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007429}
7430
7431TEST_P(QuicConnectionTest, GoAway) {
fkastenholz305e1732019-06-18 05:01:22 -07007432 if (VersionHasIetfQuicFrames(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007433 // GoAway is not available in version 99.
7434 return;
7435 }
7436
7437 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7438
wub8a5dafa2020-05-13 12:30:17 -07007439 QuicGoAwayFrame* goaway = new QuicGoAwayFrame();
7440 goaway->last_good_stream_id = 1;
7441 goaway->error_code = QUIC_PEER_GOING_AWAY;
7442 goaway->reason_phrase = "Going away.";
QUICHE teama6ef0a62019-03-07 20:34:33 -05007443 EXPECT_CALL(visitor_, OnGoAway(_));
wub8a5dafa2020-05-13 12:30:17 -07007444 ProcessGoAwayPacket(goaway);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007445}
7446
7447TEST_P(QuicConnectionTest, WindowUpdate) {
7448 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7449
wub8a5dafa2020-05-13 12:30:17 -07007450 QuicWindowUpdateFrame* window_update = new QuicWindowUpdateFrame();
7451 window_update->stream_id = 3;
7452 window_update->max_data = 1234;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007453 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
wub8a5dafa2020-05-13 12:30:17 -07007454 ProcessFramePacket(QuicFrame(window_update));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007455}
7456
7457TEST_P(QuicConnectionTest, Blocked) {
7458 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7459
wub8a5dafa2020-05-13 12:30:17 -07007460 QuicBlockedFrame* blocked = new QuicBlockedFrame();
7461 blocked->stream_id = 3;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007462 EXPECT_CALL(visitor_, OnBlockedFrame(_));
wub8a5dafa2020-05-13 12:30:17 -07007463 ProcessFramePacket(QuicFrame(blocked));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007464 EXPECT_EQ(1u, connection_.GetStats().blocked_frames_received);
7465 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7466}
7467
7468TEST_P(QuicConnectionTest, ZeroBytePacket) {
7469 // Don't close the connection for zero byte packets.
fkastenholz5d880a92019-06-21 09:01:56 -07007470 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007471 QuicReceivedPacket encrypted(nullptr, 0, QuicTime::Zero());
7472 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, encrypted);
7473}
7474
7475TEST_P(QuicConnectionTest, MissingPacketsBeforeLeastUnacked) {
fayangd4291e42019-05-30 10:31:21 -07007476 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007477 return;
7478 }
7479 // Set the packet number of the ack packet to be least unacked (4).
7480 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 3);
7481 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7482 ProcessStopWaitingPacket(InitStopWaitingFrame(4));
fayangc31c9952019-06-05 13:54:48 -07007483 EXPECT_FALSE(connection_.ack_frame().packets.Empty());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007484}
7485
QUICHE teama6ef0a62019-03-07 20:34:33 -05007486TEST_P(QuicConnectionTest, ClientHandlesVersionNegotiation) {
dschinazi48ac9192019-07-31 00:07:26 -07007487 // All supported versions except the one the connection supports.
7488 ParsedQuicVersionVector versions;
7489 for (auto version : AllSupportedVersions()) {
7490 if (version != connection_.version()) {
7491 versions.push_back(version);
7492 }
7493 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007494
7495 // Send a version negotiation packet.
7496 std::unique_ptr<QuicEncryptedPacket> encrypted(
dschinazib417d602019-05-29 13:08:45 -07007497 QuicFramer::BuildVersionNegotiationPacket(
7498 connection_id_, EmptyQuicConnectionId(),
fayangd4291e42019-05-30 10:31:21 -07007499 VersionHasIetfInvariantHeader(connection_.transport_version()),
dschinazi48ac9192019-07-31 00:07:26 -07007500 connection_.version().HasLengthPrefixedConnectionIds(), versions));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007501 std::unique_ptr<QuicReceivedPacket> received(
7502 ConstructReceivedPacket(*encrypted, QuicTime::Zero()));
fkastenholz5d880a92019-06-21 09:01:56 -07007503 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7504 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
fayang95cef072019-10-10 12:44:14 -07007505 // Verify no connection close packet gets sent.
7506 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007507 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
fayang9ed391a2019-06-20 11:16:59 -07007508 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07007509 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007510 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7511 IsError(QUIC_INVALID_VERSION));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007512}
7513
7514TEST_P(QuicConnectionTest, BadVersionNegotiation) {
7515 // Send a version negotiation packet with the version the client started with.
7516 // It should be rejected.
fkastenholz5d880a92019-06-21 09:01:56 -07007517 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7518 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007519 std::unique_ptr<QuicEncryptedPacket> encrypted(
dschinazib417d602019-05-29 13:08:45 -07007520 QuicFramer::BuildVersionNegotiationPacket(
7521 connection_id_, EmptyQuicConnectionId(),
fayangd4291e42019-05-30 10:31:21 -07007522 VersionHasIetfInvariantHeader(connection_.transport_version()),
dschinazi48ac9192019-07-31 00:07:26 -07007523 connection_.version().HasLengthPrefixedConnectionIds(),
QUICHE teama6ef0a62019-03-07 20:34:33 -05007524 AllSupportedVersions()));
7525 std::unique_ptr<QuicReceivedPacket> received(
7526 ConstructReceivedPacket(*encrypted, QuicTime::Zero()));
7527 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
fkastenholz5d880a92019-06-21 09:01:56 -07007528 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007529 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7530 IsError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007531}
7532
7533TEST_P(QuicConnectionTest, CheckSendStats) {
fayang5f135052019-08-22 17:59:40 -07007534 if (connection_.PtoEnabled()) {
7535 return;
7536 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007537 connection_.SetMaxTailLossProbes(0);
7538
7539 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7540 connection_.SendStreamDataWithString(3, "first", 0, NO_FIN);
7541 size_t first_packet_size = writer_->last_packet_size();
7542
7543 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7544 connection_.SendStreamDataWithString(5, "second", 0, NO_FIN);
7545 size_t second_packet_size = writer_->last_packet_size();
7546
7547 // 2 retransmissions due to rto, 1 due to explicit nack.
7548 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
7549 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
7550
7551 // Retransmit due to RTO.
7552 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
7553 connection_.GetRetransmissionAlarm()->Fire();
7554
7555 // Retransmit due to explicit nacks.
7556 QuicAckFrame nack_three =
7557 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)},
7558 {QuicPacketNumber(4), QuicPacketNumber(5)}});
7559
7560 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07007561 lost_packets.push_back(
7562 LostPacket(QuicPacketNumber(1), kMaxOutgoingPacketSize));
7563 lost_packets.push_back(
7564 LostPacket(QuicPacketNumber(3), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007565 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07007566 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
7567 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007568 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007569 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7570 ProcessAckPacket(&nack_three);
7571
7572 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
7573 .WillOnce(Return(QuicBandwidth::Zero()));
7574
7575 const QuicConnectionStats& stats = connection_.GetStats();
7576 // For IETF QUIC, version is not included as the encryption level switches to
7577 // FORWARD_SECURE in SendStreamDataWithString.
7578 size_t save_on_version =
fayangd4291e42019-05-30 10:31:21 -07007579 VersionHasIetfInvariantHeader(GetParam().version.transport_version)
7580 ? 0
7581 : kQuicVersionSize;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007582 EXPECT_EQ(3 * first_packet_size + 2 * second_packet_size - save_on_version,
7583 stats.bytes_sent);
7584 EXPECT_EQ(5u, stats.packets_sent);
7585 EXPECT_EQ(2 * first_packet_size + second_packet_size - save_on_version,
7586 stats.bytes_retransmitted);
7587 EXPECT_EQ(3u, stats.packets_retransmitted);
7588 EXPECT_EQ(1u, stats.rto_count);
7589 EXPECT_EQ(kDefaultMaxPacketSize, stats.max_packet_size);
7590}
7591
7592TEST_P(QuicConnectionTest, ProcessFramesIfPacketClosedConnection) {
7593 // Construct a packet with stream frame and connection close frame.
7594 QuicPacketHeader header;
dschinazi5e1a7b22019-07-31 12:23:21 -07007595 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
QUICHE team2252b702019-05-14 23:55:14 -04007596 header.source_connection_id = connection_id_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007597 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
fayangd4291e42019-05-30 10:31:21 -07007598 if (!VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04007599 header.source_connection_id_included = CONNECTION_ID_PRESENT;
7600 }
7601 } else {
7602 header.destination_connection_id = connection_id_;
fayangd4291e42019-05-30 10:31:21 -07007603 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04007604 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
7605 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007606 }
7607 header.packet_number = QuicPacketNumber(1);
7608 header.version_flag = false;
7609
fkastenholz488a4622019-08-26 06:24:46 -07007610 QuicErrorCode kQuicErrorCode = QUIC_PEER_GOING_AWAY;
7611 // This QuicConnectionCloseFrame will default to being for a Google QUIC
7612 // close. If doing IETF QUIC then set fields appropriately for CC/T or CC/A,
7613 // depending on the mapping.
fkastenholz591814c2019-09-06 12:11:46 -07007614 QuicConnectionCloseFrame qccf(peer_framer_.transport_version(),
7615 kQuicErrorCode, "",
7616 /*transport_close_frame_type=*/0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007617 QuicFrames frames;
7618 frames.push_back(QuicFrame(frame1_));
7619 frames.push_back(QuicFrame(&qccf));
7620 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
7621 EXPECT_TRUE(nullptr != packet);
dschinazi66dea072019-04-09 11:41:06 -07007622 char buffer[kMaxOutgoingPacketSize];
nharperc6b99512019-09-19 11:13:48 -07007623 size_t encrypted_length = peer_framer_.EncryptPayload(
7624 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
7625 kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007626
fkastenholz5d880a92019-06-21 09:01:56 -07007627 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
7628 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007629 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7630 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7631
7632 connection_.ProcessUdpPacket(
7633 kSelfAddress, kPeerAddress,
7634 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
fkastenholz5d880a92019-06-21 09:01:56 -07007635 EXPECT_EQ(1, connection_close_frame_count_);
bnc77e77b82020-04-05 10:36:49 -07007636 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
bncf54082a2019-11-27 10:19:47 -08007637 IsError(QUIC_PEER_GOING_AWAY));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007638}
7639
7640TEST_P(QuicConnectionTest, SelectMutualVersion) {
7641 connection_.SetSupportedVersions(AllSupportedVersions());
7642 // Set the connection to speak the lowest quic version.
7643 connection_.set_version(QuicVersionMin());
7644 EXPECT_EQ(QuicVersionMin(), connection_.version());
7645
7646 // Pass in available versions which includes a higher mutually supported
7647 // version. The higher mutually supported version should be selected.
7648 ParsedQuicVersionVector supported_versions = AllSupportedVersions();
7649 EXPECT_TRUE(connection_.SelectMutualVersion(supported_versions));
7650 EXPECT_EQ(QuicVersionMax(), connection_.version());
7651
7652 // Expect that the lowest version is selected.
7653 // Ensure the lowest supported version is less than the max, unless they're
7654 // the same.
7655 ParsedQuicVersionVector lowest_version_vector;
7656 lowest_version_vector.push_back(QuicVersionMin());
7657 EXPECT_TRUE(connection_.SelectMutualVersion(lowest_version_vector));
7658 EXPECT_EQ(QuicVersionMin(), connection_.version());
7659
7660 // Shouldn't be able to find a mutually supported version.
7661 ParsedQuicVersionVector unsupported_version;
7662 unsupported_version.push_back(UnsupportedQuicVersion());
7663 EXPECT_FALSE(connection_.SelectMutualVersion(unsupported_version));
7664}
7665
7666TEST_P(QuicConnectionTest, ConnectionCloseWhenWritable) {
7667 EXPECT_FALSE(writer_->IsWriteBlocked());
7668
7669 // Send a packet.
7670 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7671 EXPECT_EQ(0u, connection_.NumQueuedPackets());
7672 EXPECT_EQ(1u, writer_->packets_write_attempts());
7673
7674 TriggerConnectionClose();
rch39c88ab2019-10-16 19:24:40 -07007675 EXPECT_LE(2u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007676}
7677
7678TEST_P(QuicConnectionTest, ConnectionCloseGettingWriteBlocked) {
7679 BlockOnNextWrite();
7680 TriggerConnectionClose();
7681 EXPECT_EQ(1u, writer_->packets_write_attempts());
7682 EXPECT_TRUE(writer_->IsWriteBlocked());
7683}
7684
7685TEST_P(QuicConnectionTest, ConnectionCloseWhenWriteBlocked) {
7686 BlockOnNextWrite();
7687 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7688 EXPECT_EQ(1u, connection_.NumQueuedPackets());
7689 EXPECT_EQ(1u, writer_->packets_write_attempts());
7690 EXPECT_TRUE(writer_->IsWriteBlocked());
7691 TriggerConnectionClose();
7692 EXPECT_EQ(1u, writer_->packets_write_attempts());
7693}
7694
7695TEST_P(QuicConnectionTest, OnPacketSentDebugVisitor) {
dschinazi1c6e5922020-06-19 10:35:03 -07007696 PathProbeTestInit(Perspective::IS_CLIENT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007697 MockQuicConnectionDebugVisitor debug_visitor;
7698 connection_.set_debug_visitor(&debug_visitor);
7699
fayangcff885a2019-10-22 07:39:04 -07007700 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007701 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7702
fayangcff885a2019-10-22 07:39:04 -07007703 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007704 connection_.SendConnectivityProbingPacket(writer_.get(),
7705 connection_.peer_address());
7706}
7707
7708TEST_P(QuicConnectionTest, OnPacketHeaderDebugVisitor) {
7709 QuicPacketHeader header;
7710 header.packet_number = QuicPacketNumber(1);
fayangd4291e42019-05-30 10:31:21 -07007711 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007712 header.form = IETF_QUIC_LONG_HEADER_PACKET;
7713 }
7714
7715 MockQuicConnectionDebugVisitor debug_visitor;
7716 connection_.set_debug_visitor(&debug_visitor);
7717 EXPECT_CALL(debug_visitor, OnPacketHeader(Ref(header))).Times(1);
7718 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(1);
7719 EXPECT_CALL(debug_visitor, OnSuccessfulVersionNegotiation(_)).Times(1);
7720 connection_.OnPacketHeader(header);
7721}
7722
7723TEST_P(QuicConnectionTest, Pacing) {
7724 TestConnection server(connection_id_, kSelfAddress, helper_.get(),
7725 alarm_factory_.get(), writer_.get(),
7726 Perspective::IS_SERVER, version());
7727 TestConnection client(connection_id_, kPeerAddress, helper_.get(),
7728 alarm_factory_.get(), writer_.get(),
7729 Perspective::IS_CLIENT, version());
7730 EXPECT_FALSE(QuicSentPacketManagerPeer::UsingPacing(
7731 static_cast<const QuicSentPacketManager*>(
7732 &client.sent_packet_manager())));
7733 EXPECT_FALSE(QuicSentPacketManagerPeer::UsingPacing(
7734 static_cast<const QuicSentPacketManager*>(
7735 &server.sent_packet_manager())));
7736}
7737
7738TEST_P(QuicConnectionTest, WindowUpdateInstigateAcks) {
7739 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7740
7741 // Send a WINDOW_UPDATE frame.
wub8a5dafa2020-05-13 12:30:17 -07007742 QuicWindowUpdateFrame* window_update = new QuicWindowUpdateFrame();
7743 window_update->stream_id = 3;
7744 window_update->max_data = 1234;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007745 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
wub8a5dafa2020-05-13 12:30:17 -07007746 ProcessFramePacket(QuicFrame(window_update));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007747
7748 // Ensure that this has caused the ACK alarm to be set.
fayang9adfb532020-06-04 06:58:45 -07007749 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007750}
7751
7752TEST_P(QuicConnectionTest, BlockedFrameInstigateAcks) {
7753 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7754
7755 // Send a BLOCKED frame.
wub8a5dafa2020-05-13 12:30:17 -07007756 QuicBlockedFrame* blocked = new QuicBlockedFrame();
7757 blocked->stream_id = 3;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007758 EXPECT_CALL(visitor_, OnBlockedFrame(_));
wub8a5dafa2020-05-13 12:30:17 -07007759 ProcessFramePacket(QuicFrame(blocked));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007760
7761 // Ensure that this has caused the ACK alarm to be set.
fayang9adfb532020-06-04 06:58:45 -07007762 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007763}
7764
7765TEST_P(QuicConnectionTest, ReevaluateTimeUntilSendOnAck) {
7766 // Enable pacing.
7767 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7768 QuicConfig config;
7769 connection_.SetFromConfig(config);
7770
7771 // Send two packets. One packet is not sufficient because if it gets acked,
7772 // there will be no packets in flight after that and the pacer will always
7773 // allow the next packet in that situation.
7774 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7775 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
7776 connection_.SendStreamDataWithString(
7777 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
7778 0, NO_FIN);
7779 connection_.SendStreamDataWithString(
7780 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "bar",
7781 3, NO_FIN);
7782 connection_.OnCanWrite();
7783
7784 // Schedule the next packet for a few milliseconds in future.
7785 QuicSentPacketManagerPeer::DisablePacerBursts(manager_);
7786 QuicTime scheduled_pacing_time =
7787 clock_.Now() + QuicTime::Delta::FromMilliseconds(5);
7788 QuicSentPacketManagerPeer::SetNextPacedPacketTime(manager_,
7789 scheduled_pacing_time);
7790
7791 // Send a packet and have it be blocked by congestion control.
7792 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(false));
7793 connection_.SendStreamDataWithString(
7794 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "baz",
7795 6, NO_FIN);
7796 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
7797
7798 // Process an ack and the send alarm will be set to the new 5ms delay.
7799 QuicAckFrame ack = InitAckFrame(1);
7800 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
7801 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7802 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
7803 ProcessAckPacket(&ack);
nharper55fa6132019-05-07 19:37:21 -07007804 size_t padding_frame_count = writer_->padding_frames().size();
7805 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007806 EXPECT_EQ(1u, writer_->stream_frames().size());
7807 EXPECT_TRUE(connection_.GetSendAlarm()->IsSet());
7808 EXPECT_EQ(scheduled_pacing_time, connection_.GetSendAlarm()->deadline());
7809 writer_->Reset();
7810}
7811
7812TEST_P(QuicConnectionTest, SendAcksImmediately) {
QUICHE teamcd098022019-03-22 18:49:55 -07007813 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7814 return;
7815 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007816 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7817 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7818 ProcessDataPacket(1);
7819 CongestionBlockWrites();
7820 SendAckPacketToPeer();
7821}
7822
7823TEST_P(QuicConnectionTest, SendPingImmediately) {
7824 MockQuicConnectionDebugVisitor debug_visitor;
7825 connection_.set_debug_visitor(&debug_visitor);
7826
7827 CongestionBlockWrites();
fayang93cc53a2019-08-22 12:47:30 -07007828 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007829 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
fayangcff885a2019-10-22 07:39:04 -07007830 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007831 EXPECT_CALL(debug_visitor, OnPingSent()).Times(1);
7832 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
7833 EXPECT_FALSE(connection_.HasQueuedData());
7834}
7835
7836TEST_P(QuicConnectionTest, SendBlockedImmediately) {
7837 MockQuicConnectionDebugVisitor debug_visitor;
7838 connection_.set_debug_visitor(&debug_visitor);
7839
fayang93cc53a2019-08-22 12:47:30 -07007840 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007841 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
fayangcff885a2019-10-22 07:39:04 -07007842 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007843 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7844 connection_.SendControlFrame(QuicFrame(new QuicBlockedFrame(1, 3)));
7845 EXPECT_EQ(1u, connection_.GetStats().blocked_frames_sent);
7846 EXPECT_FALSE(connection_.HasQueuedData());
7847}
7848
fayang93cc53a2019-08-22 12:47:30 -07007849TEST_P(QuicConnectionTest, FailedToSendBlockedFrames) {
7850 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
7851 return;
7852 }
7853 MockQuicConnectionDebugVisitor debug_visitor;
7854 connection_.set_debug_visitor(&debug_visitor);
7855 QuicBlockedFrame blocked(1, 3);
7856
7857 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
fayangcff885a2019-10-22 07:39:04 -07007858 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(0);
fayang93cc53a2019-08-22 12:47:30 -07007859 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7860 connection_.SendControlFrame(QuicFrame(&blocked));
7861 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7862 EXPECT_FALSE(connection_.HasQueuedData());
7863}
7864
QUICHE teama6ef0a62019-03-07 20:34:33 -05007865TEST_P(QuicConnectionTest, SendingUnencryptedStreamDataFails) {
7866 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
7867 if (!IsDefaultTestConfiguration()) {
7868 return;
7869 }
7870
fkastenholz5d880a92019-06-21 09:01:56 -07007871 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7872 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007873 struct iovec iov;
7874 MakeIOVector("", &iov);
7875 EXPECT_QUIC_BUG(connection_.SaveAndSendStreamData(3, &iov, 1, 0, 0, FIN),
fayang49523232019-05-03 06:28:22 -07007876 "Cannot send stream data with level: ENCRYPTION_INITIAL");
QUICHE teama6ef0a62019-03-07 20:34:33 -05007877 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07007878 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007879 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7880 IsError(QUIC_ATTEMPT_TO_SEND_UNENCRYPTED_STREAM_DATA));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007881}
7882
7883TEST_P(QuicConnectionTest, SetRetransmissionAlarmForCryptoPacket) {
7884 EXPECT_TRUE(connection_.connected());
7885 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
7886
7887 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7888 connection_.SendCryptoStreamData();
7889
7890 // Verify retransmission timer is correctly set after crypto packet has been
7891 // sent.
7892 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
7893 QuicTime retransmission_time =
7894 QuicConnectionPeer::GetSentPacketManager(&connection_)
7895 ->GetRetransmissionTime();
7896 EXPECT_NE(retransmission_time, clock_.ApproximateNow());
7897 EXPECT_EQ(retransmission_time,
7898 connection_.GetRetransmissionAlarm()->deadline());
7899
7900 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7901 connection_.GetRetransmissionAlarm()->Fire();
7902}
7903
vasilvv693d5b02019-04-09 21:58:56 -07007904// Includes regression test for b/69979024.
zhongyi3ae832d2020-06-15 13:03:31 -07007905TEST_P(QuicConnectionTest, PathDegradingDetectionForNonCryptoPackets) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007906 EXPECT_TRUE(connection_.connected());
fayangb59c6f12020-03-23 15:06:14 -07007907 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007908 EXPECT_FALSE(connection_.IsPathDegrading());
7909
7910 const char data[] = "data";
7911 size_t data_size = strlen(data);
7912 QuicStreamOffset offset = 0;
7913
7914 for (int i = 0; i < 2; ++i) {
7915 // Send a packet. Now there's a retransmittable packet on the wire, so the
zhongyi3ae832d2020-06-15 13:03:31 -07007916 // path degrading detection should be set.
QUICHE teama6ef0a62019-03-07 20:34:33 -05007917 connection_.SendStreamDataWithString(
7918 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
7919 offset, NO_FIN);
7920 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07007921 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
zhongyi3ae832d2020-06-15 13:03:31 -07007922 // Check the deadline of the path degrading detection.
QUICHE teama6ef0a62019-03-07 20:34:33 -05007923 QuicTime::Delta delay =
7924 QuicConnectionPeer::GetSentPacketManager(&connection_)
7925 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07007926 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7927 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007928
zhongyi3ae832d2020-06-15 13:03:31 -07007929 // Send a second packet. The path degrading detection's deadline should
7930 // remain the same.
vasilvv693d5b02019-04-09 21:58:56 -07007931 // Regression test for b/69979024.
QUICHE teama6ef0a62019-03-07 20:34:33 -05007932 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
fayang2205d952020-05-12 13:45:56 -07007933 QuicTime prev_deadline =
7934 connection_.GetBlackholeDetectorAlarm()->deadline();
QUICHE teama6ef0a62019-03-07 20:34:33 -05007935 connection_.SendStreamDataWithString(
7936 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
7937 offset, NO_FIN);
7938 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07007939 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
fayang2205d952020-05-12 13:45:56 -07007940 EXPECT_EQ(prev_deadline,
7941 connection_.GetBlackholeDetectorAlarm()->deadline());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007942
7943 // Now receive an ACK of the first packet. This should advance the path
zhongyi3ae832d2020-06-15 13:03:31 -07007944 // degrading detection's deadline since forward progress has been made.
QUICHE teama6ef0a62019-03-07 20:34:33 -05007945 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7946 if (i == 0) {
7947 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7948 }
7949 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7950 QuicAckFrame frame = InitAckFrame(
7951 {{QuicPacketNumber(1u + 2u * i), QuicPacketNumber(2u + 2u * i)}});
7952 ProcessAckPacket(&frame);
fayangb59c6f12020-03-23 15:06:14 -07007953 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
zhongyi3ae832d2020-06-15 13:03:31 -07007954 // Check the deadline of the path degrading detection.
QUICHE teama6ef0a62019-03-07 20:34:33 -05007955 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7956 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07007957 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7958 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007959
7960 if (i == 0) {
7961 // Now receive an ACK of the second packet. Since there are no more
7962 // retransmittable packets on the wire, this should cancel the path
zhongyi3ae832d2020-06-15 13:03:31 -07007963 // degrading detection.
QUICHE teama6ef0a62019-03-07 20:34:33 -05007964 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7965 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7966 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
7967 ProcessAckPacket(&frame);
fayangb59c6f12020-03-23 15:06:14 -07007968 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007969 } else {
7970 // Advance time to the path degrading alarm's deadline and simulate
7971 // firing the alarm.
7972 clock_.AdvanceTime(delay);
7973 EXPECT_CALL(visitor_, OnPathDegrading());
fayangb59c6f12020-03-23 15:06:14 -07007974 connection_.PathDegradingTimeout();
7975 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007976 }
7977 }
7978 EXPECT_TRUE(connection_.IsPathDegrading());
7979}
7980
7981TEST_P(QuicConnectionTest, RetransmittableOnWireSetsPingAlarm) {
7982 const QuicTime::Delta retransmittable_on_wire_timeout =
7983 QuicTime::Delta::FromMilliseconds(50);
zhongyi79ace162019-10-21 15:57:09 -07007984 connection_.set_initial_retransmittable_on_wire_timeout(
QUICHE teama6ef0a62019-03-07 20:34:33 -05007985 retransmittable_on_wire_timeout);
7986
7987 EXPECT_TRUE(connection_.connected());
7988 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7989 .WillRepeatedly(Return(true));
7990
fayangb59c6f12020-03-23 15:06:14 -07007991 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007992 EXPECT_FALSE(connection_.IsPathDegrading());
7993 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
7994
7995 const char data[] = "data";
7996 size_t data_size = strlen(data);
7997 QuicStreamOffset offset = 0;
7998
7999 // Send a packet.
8000 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8001 offset += data_size;
8002 // Now there's a retransmittable packet on the wire, so the path degrading
8003 // alarm should be set.
8004 // The retransmittable-on-wire alarm should not be set.
fayangb59c6f12020-03-23 15:06:14 -07008005 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008006 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
8007 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07008008 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
8009 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008010 ASSERT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8011 // The ping alarm is set for the ping timeout, not the shorter
8012 // retransmittable_on_wire_timeout.
8013 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8014 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
zhongyieef848f2019-10-18 07:09:37 -07008015 EXPECT_EQ(ping_delay,
8016 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008017
8018 // Now receive an ACK of the packet.
8019 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8020 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8021 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8022 QuicAckFrame frame =
8023 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8024 ProcessAckPacket(&frame);
8025 // No more retransmittable packets on the wire, so the path degrading alarm
8026 // should be cancelled, and the ping alarm should be set to the
8027 // retransmittable_on_wire_timeout.
fayangb59c6f12020-03-23 15:06:14 -07008028 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008029 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07008030 EXPECT_EQ(retransmittable_on_wire_timeout,
8031 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008032
8033 // Simulate firing the ping alarm and sending a PING.
8034 clock_.AdvanceTime(retransmittable_on_wire_timeout);
8035 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8036 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
8037 }));
8038 connection_.GetPingAlarm()->Fire();
8039
8040 // Now there's a retransmittable packet (PING) on the wire, so the path
8041 // degrading alarm should be set.
fayangb59c6f12020-03-23 15:06:14 -07008042 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008043 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
8044 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07008045 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
8046 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008047}
8048
8049// This test verifies that the connection marks path as degrading and does not
8050// spin timer to detect path degrading when a new packet is sent on the
8051// degraded path.
zhongyi3ae832d2020-06-15 13:03:31 -07008052TEST_P(QuicConnectionTest, NoPathDegradingDetectionIfPathIsDegrading) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008053 EXPECT_TRUE(connection_.connected());
fayangb59c6f12020-03-23 15:06:14 -07008054 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008055 EXPECT_FALSE(connection_.IsPathDegrading());
8056
8057 const char data[] = "data";
8058 size_t data_size = strlen(data);
8059 QuicStreamOffset offset = 0;
8060
8061 // Send the first packet. Now there's a retransmittable packet on the wire, so
8062 // the path degrading alarm should be set.
8063 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8064 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07008065 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
zhongyi3ae832d2020-06-15 13:03:31 -07008066 // Check the deadline of the path degrading detection.
QUICHE teama6ef0a62019-03-07 20:34:33 -05008067 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
8068 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07008069 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
8070 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008071
zhongyi3ae832d2020-06-15 13:03:31 -07008072 // Send a second packet. The path degrading detection's deadline should remain
QUICHE teama6ef0a62019-03-07 20:34:33 -05008073 // the same.
8074 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
fayang2205d952020-05-12 13:45:56 -07008075 QuicTime prev_deadline = connection_.GetBlackholeDetectorAlarm()->deadline();
QUICHE teama6ef0a62019-03-07 20:34:33 -05008076 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8077 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07008078 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
fayang2205d952020-05-12 13:45:56 -07008079 EXPECT_EQ(prev_deadline, connection_.GetBlackholeDetectorAlarm()->deadline());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008080
8081 // Now receive an ACK of the first packet. This should advance the path
zhongyi3ae832d2020-06-15 13:03:31 -07008082 // degrading detection's deadline since forward progress has been made.
QUICHE teama6ef0a62019-03-07 20:34:33 -05008083 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8084 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8085 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8086 QuicAckFrame frame =
8087 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
8088 ProcessAckPacket(&frame);
fayangb59c6f12020-03-23 15:06:14 -07008089 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008090 // Check the deadline of the path degrading alarm.
8091 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
8092 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07008093 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
8094 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008095
zhongyi3ae832d2020-06-15 13:03:31 -07008096 // Advance time to the path degrading detection's deadline and simulate
8097 // firing the path degrading detection. This path will be considered as
QUICHE teama6ef0a62019-03-07 20:34:33 -05008098 // degrading.
8099 clock_.AdvanceTime(delay);
8100 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
fayangb59c6f12020-03-23 15:06:14 -07008101 connection_.PathDegradingTimeout();
8102 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008103 EXPECT_TRUE(connection_.IsPathDegrading());
8104
8105 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
fayangb59c6f12020-03-23 15:06:14 -07008106 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
zhongyi3ae832d2020-06-15 13:03:31 -07008107 // Send a third packet. The path degrading detection is no longer set but path
QUICHE teama6ef0a62019-03-07 20:34:33 -05008108 // should still be marked as degrading.
8109 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8110 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07008111 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008112 EXPECT_TRUE(connection_.IsPathDegrading());
8113}
8114
8115// This test verifies that the connection unmarks path as degrarding and spins
8116// the timer to detect future path degrading when forward progress is made
8117// after path has been marked degrading.
8118TEST_P(QuicConnectionTest, UnmarkPathDegradingOnForwardProgress) {
8119 EXPECT_TRUE(connection_.connected());
fayangb59c6f12020-03-23 15:06:14 -07008120 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008121 EXPECT_FALSE(connection_.IsPathDegrading());
8122
8123 const char data[] = "data";
8124 size_t data_size = strlen(data);
8125 QuicStreamOffset offset = 0;
8126
8127 // Send the first packet. Now there's a retransmittable packet on the wire, so
8128 // the path degrading alarm should be set.
8129 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8130 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07008131 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008132 // Check the deadline of the path degrading alarm.
8133 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
8134 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07008135 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
8136 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008137
8138 // Send a second packet. The path degrading alarm's deadline should remain
8139 // the same.
8140 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
fayang2205d952020-05-12 13:45:56 -07008141 QuicTime prev_deadline = connection_.GetBlackholeDetectorAlarm()->deadline();
QUICHE teama6ef0a62019-03-07 20:34:33 -05008142 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8143 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07008144 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
fayang2205d952020-05-12 13:45:56 -07008145 EXPECT_EQ(prev_deadline, connection_.GetBlackholeDetectorAlarm()->deadline());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008146
8147 // Now receive an ACK of the first packet. This should advance the path
8148 // degrading alarm's deadline since forward progress has been made.
8149 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8150 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8151 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8152 QuicAckFrame frame =
8153 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
8154 ProcessAckPacket(&frame);
fayangb59c6f12020-03-23 15:06:14 -07008155 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008156 // Check the deadline of the path degrading alarm.
8157 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
8158 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07008159 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
8160 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008161
8162 // Advance time to the path degrading alarm's deadline and simulate
8163 // firing the alarm.
8164 clock_.AdvanceTime(delay);
8165 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
fayangb59c6f12020-03-23 15:06:14 -07008166 connection_.PathDegradingTimeout();
8167 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008168 EXPECT_TRUE(connection_.IsPathDegrading());
8169
8170 // Send a third packet. The path degrading alarm is no longer set but path
8171 // should still be marked as degrading.
8172 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
fayangb59c6f12020-03-23 15:06:14 -07008173 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008174 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8175 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07008176 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008177 EXPECT_TRUE(connection_.IsPathDegrading());
8178
8179 // Now receive an ACK of the second packet. This should unmark the path as
8180 // degrading. And will set a timer to detect new path degrading.
8181 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8182 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
zhongyief1d6752020-06-11 16:19:28 -07008183 EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading()).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008184 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8185 ProcessAckPacket(&frame);
8186 EXPECT_FALSE(connection_.IsPathDegrading());
fayangb59c6f12020-03-23 15:06:14 -07008187 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008188}
8189
8190TEST_P(QuicConnectionTest, NoPathDegradingOnServer) {
QUICHE teamcd098022019-03-22 18:49:55 -07008191 if (connection_.SupportsMultiplePacketNumberSpaces()) {
8192 return;
8193 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008194 set_perspective(Perspective::IS_SERVER);
8195 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
8196
8197 EXPECT_FALSE(connection_.IsPathDegrading());
fayangb59c6f12020-03-23 15:06:14 -07008198 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008199
8200 // Send data.
8201 const char data[] = "data";
8202 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
8203 EXPECT_FALSE(connection_.IsPathDegrading());
fayangb59c6f12020-03-23 15:06:14 -07008204 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008205
8206 // Ack data.
8207 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
QUICHE teama6ef0a62019-03-07 20:34:33 -05008208 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8209 QuicAckFrame frame =
8210 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
8211 ProcessAckPacket(&frame);
8212 EXPECT_FALSE(connection_.IsPathDegrading());
fayangb59c6f12020-03-23 15:06:14 -07008213 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008214}
8215
8216TEST_P(QuicConnectionTest, NoPathDegradingAfterSendingAck) {
QUICHE teamcd098022019-03-22 18:49:55 -07008217 if (connection_.SupportsMultiplePacketNumberSpaces()) {
8218 return;
8219 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008220 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8221 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
8222 ProcessDataPacket(1);
8223 SendAckPacketToPeer();
8224 EXPECT_FALSE(connection_.sent_packet_manager().unacked_packets().empty());
8225 EXPECT_FALSE(connection_.sent_packet_manager().HasInFlightPackets());
8226 EXPECT_FALSE(connection_.IsPathDegrading());
fayangb59c6f12020-03-23 15:06:14 -07008227 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008228}
8229
8230TEST_P(QuicConnectionTest, MultipleCallsToCloseConnection) {
8231 // Verifies that multiple calls to CloseConnection do not
8232 // result in multiple attempts to close the connection - it will be marked as
8233 // disconnected after the first call.
fkastenholz5d880a92019-06-21 09:01:56 -07008234 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008235 connection_.CloseConnection(QUIC_NO_ERROR, "no reason",
8236 ConnectionCloseBehavior::SILENT_CLOSE);
8237 connection_.CloseConnection(QUIC_NO_ERROR, "no reason",
8238 ConnectionCloseBehavior::SILENT_CLOSE);
8239}
8240
8241TEST_P(QuicConnectionTest, ServerReceivesChloOnNonCryptoStream) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008242 set_perspective(Perspective::IS_SERVER);
8243 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
8244
8245 CryptoHandshakeMessage message;
8246 CryptoFramer framer;
8247 message.set_tag(kCHLO);
QUICHE team3fe6a8b2019-03-14 09:10:38 -07008248 std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008249 frame1_.stream_id = 10;
8250 frame1_.data_buffer = data->data();
8251 frame1_.data_length = data->length();
8252
fkastenholz5d880a92019-06-21 09:01:56 -07008253 EXPECT_CALL(visitor_,
8254 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05008255 ForceProcessFramePacket(QuicFrame(frame1_));
fkastenholz5d880a92019-06-21 09:01:56 -07008256 TestConnectionCloseQuicErrorCode(QUIC_MAYBE_CORRUPTED_MEMORY);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008257}
8258
8259TEST_P(QuicConnectionTest, ClientReceivesRejOnNonCryptoStream) {
8260 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8261
8262 CryptoHandshakeMessage message;
8263 CryptoFramer framer;
8264 message.set_tag(kREJ);
QUICHE team3fe6a8b2019-03-14 09:10:38 -07008265 std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008266 frame1_.stream_id = 10;
8267 frame1_.data_buffer = data->data();
8268 frame1_.data_length = data->length();
8269
fkastenholz5d880a92019-06-21 09:01:56 -07008270 EXPECT_CALL(visitor_,
8271 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05008272 ForceProcessFramePacket(QuicFrame(frame1_));
fkastenholz5d880a92019-06-21 09:01:56 -07008273 TestConnectionCloseQuicErrorCode(QUIC_MAYBE_CORRUPTED_MEMORY);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008274}
8275
8276TEST_P(QuicConnectionTest, CloseConnectionOnPacketTooLarge) {
8277 SimulateNextPacketTooLarge();
8278 // A connection close packet is sent
fkastenholz5d880a92019-06-21 09:01:56 -07008279 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
QUICHE teama6ef0a62019-03-07 20:34:33 -05008280 .Times(1);
8281 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
fkastenholz5d880a92019-06-21 09:01:56 -07008282 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008283}
8284
8285TEST_P(QuicConnectionTest, AlwaysGetPacketTooLarge) {
8286 // Test even we always get packet too large, we do not infinitely try to send
8287 // close packet.
8288 AlwaysGetPacketTooLarge();
fkastenholz5d880a92019-06-21 09:01:56 -07008289 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
QUICHE teama6ef0a62019-03-07 20:34:33 -05008290 .Times(1);
8291 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
fkastenholz5d880a92019-06-21 09:01:56 -07008292 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008293}
8294
nharperef468962019-07-02 14:15:38 -07008295TEST_P(QuicConnectionTest, CloseConnectionOnQueuedWriteError) {
nharperef468962019-07-02 14:15:38 -07008296 // Regression test for crbug.com/979507.
8297 //
8298 // If we get a write error when writing queued packets, we should attempt to
8299 // send a connection close packet, but if sending that fails, it shouldn't get
8300 // queued.
8301
8302 // Queue a packet to write.
8303 BlockOnNextWrite();
8304 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
8305 EXPECT_EQ(1u, connection_.NumQueuedPackets());
8306
8307 // Configure writer to always fail.
8308 AlwaysGetPacketTooLarge();
8309
8310 // Expect that we attempt to close the connection exactly once.
8311 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
8312 .Times(1);
8313
8314 // Unblock the writes and actually send.
8315 writer_->SetWritable();
8316 connection_.OnCanWrite();
8317 EXPECT_EQ(0u, connection_.NumQueuedPackets());
8318
8319 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
8320}
8321
QUICHE teama6ef0a62019-03-07 20:34:33 -05008322// Verify that if connection has no outstanding data, it notifies the send
8323// algorithm after the write.
8324TEST_P(QuicConnectionTest, SendDataAndBecomeApplicationLimited) {
8325 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
8326 {
8327 InSequence seq;
8328 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
8329 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
8330 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
8331 .WillRepeatedly(Return(false));
8332 }
8333
8334 connection_.SendStreamData3();
8335}
8336
8337// Verify that the connection does not become app-limited if there is
8338// outstanding data to send after the write.
8339TEST_P(QuicConnectionTest, NotBecomeApplicationLimitedIfMoreDataAvailable) {
8340 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
8341 {
8342 InSequence seq;
8343 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
8344 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
8345 }
8346
8347 connection_.SendStreamData3();
8348}
8349
8350// Verify that the connection does not become app-limited after blocked write
8351// even if there is outstanding data to send after the write.
8352TEST_P(QuicConnectionTest, NotBecomeApplicationLimitedDueToWriteBlock) {
8353 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
8354 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
8355 BlockOnNextWrite();
8356
fayange62e63c2019-12-04 07:16:25 -08008357 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008358 connection_.SendStreamData3();
8359
8360 // Now unblock the writer, become congestion control blocked,
8361 // and ensure we become app-limited after writing.
8362 writer_->SetWritable();
8363 CongestionBlockWrites();
8364 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(false));
fayange62e63c2019-12-04 07:16:25 -08008365 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
fayang2ce66082019-10-02 06:29:04 -07008366 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008367 connection_.OnCanWrite();
8368}
8369
8370// Test the mode in which the link is filled up with probing retransmissions if
8371// the connection becomes application-limited.
8372TEST_P(QuicConnectionTest, SendDataWhenApplicationLimited) {
8373 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8374 EXPECT_CALL(*send_algorithm_, ShouldSendProbingPacket())
8375 .WillRepeatedly(Return(true));
8376 {
8377 InSequence seq;
8378 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
8379 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
8380 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
8381 .WillRepeatedly(Return(false));
8382 }
QUICHE teamb8343252019-04-29 13:58:01 -07008383 EXPECT_CALL(visitor_, SendProbingData()).WillRepeatedly([this] {
8384 return connection_.sent_packet_manager().MaybeRetransmitOldestPacket(
8385 PROBING_RETRANSMISSION);
8386 });
QUICHE teama6ef0a62019-03-07 20:34:33 -05008387 // Fix congestion window to be 20,000 bytes.
8388 EXPECT_CALL(*send_algorithm_, CanSend(Ge(20000u)))
8389 .WillRepeatedly(Return(false));
8390 EXPECT_CALL(*send_algorithm_, CanSend(Lt(20000u)))
8391 .WillRepeatedly(Return(true));
8392
8393 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
8394 ASSERT_EQ(0u, connection_.GetStats().packets_sent);
8395 connection_.set_fill_up_link_during_probing(true);
fayangedf9ad52020-03-05 13:49:18 -08008396 EXPECT_CALL(visitor_, GetHandshakeState())
8397 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
QUICHE teama6ef0a62019-03-07 20:34:33 -05008398 connection_.OnHandshakeComplete();
8399 connection_.SendStreamData3();
8400
8401 // We expect a lot of packets from a 20 kbyte window.
8402 EXPECT_GT(connection_.GetStats().packets_sent, 10u);
8403 // Ensure that the packets are padded.
8404 QuicByteCount average_packet_size =
8405 connection_.GetStats().bytes_sent / connection_.GetStats().packets_sent;
8406 EXPECT_GT(average_packet_size, 1000u);
8407
8408 // Acknowledge all packets sent, except for the last one.
8409 QuicAckFrame ack = InitAckFrame(
8410 connection_.sent_packet_manager().GetLargestSentPacket() - 1);
8411 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
8412 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8413
8414 // Ensure that since we no longer have retransmittable bytes in flight, this
8415 // will not cause any responses to be sent.
8416 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8417 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
8418 ProcessAckPacket(&ack);
8419}
8420
rchd672c6d2019-11-27 15:30:54 -08008421TEST_P(QuicConnectionTest, DoNotForceSendingAckOnPacketTooLarge) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008422 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8423 // Send an ack by simulating delayed ack alarm firing.
8424 ProcessPacket(1);
fayang9adfb532020-06-04 06:58:45 -07008425 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008426 connection_.GetAckAlarm()->Fire();
8427 // Simulate data packet causes write error.
fkastenholz5d880a92019-06-21 09:01:56 -07008428 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05008429 SimulateNextPacketTooLarge();
8430 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
rchd672c6d2019-11-27 15:30:54 -08008431 EXPECT_EQ(1u, writer_->connection_close_frames().size());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008432 // Ack frame is not bundled in connection close packet.
8433 EXPECT_TRUE(writer_->ack_frames().empty());
rchd672c6d2019-11-27 15:30:54 -08008434 if (writer_->padding_frames().empty()) {
8435 EXPECT_EQ(1u, writer_->frame_count());
8436 } else {
8437 EXPECT_EQ(2u, writer_->frame_count());
8438 }
8439
fkastenholz5d880a92019-06-21 09:01:56 -07008440 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008441}
8442
rchd672c6d2019-11-27 15:30:54 -08008443TEST_P(QuicConnectionTest, CloseConnectionAllLevels) {
fayangc303bfd2020-02-11 09:19:54 -08008444 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8445 return;
8446 }
rchd672c6d2019-11-27 15:30:54 -08008447
8448 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
8449 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
8450 connection_.CloseConnection(
8451 kQuicErrorCode, "Some random error message",
8452 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
8453
8454 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
8455
8456 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
8457 EXPECT_EQ(1u, writer_->connection_close_frames().size());
8458
8459 if (!connection_.version().CanSendCoalescedPackets()) {
8460 // Each connection close packet should be sent in distinct UDP packets.
8461 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
8462 writer_->connection_close_packets());
8463 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
8464 writer_->packets_write_attempts());
8465 return;
8466 }
8467
8468 // A single UDP packet should be sent with multiple connection close packets
8469 // coalesced together.
8470 EXPECT_EQ(1u, writer_->packets_write_attempts());
8471
8472 // Only the first packet has been processed yet.
8473 EXPECT_EQ(1u, writer_->connection_close_packets());
8474
8475 // ProcessPacket resets the visitor and frees the coalesced packet.
8476 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
8477 auto packet = writer_->coalesced_packet()->Clone();
8478 writer_->framer()->ProcessPacket(*packet);
8479 EXPECT_EQ(1u, writer_->connection_close_packets());
8480 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
8481}
8482
8483TEST_P(QuicConnectionTest, CloseConnectionOneLevel) {
fayangc303bfd2020-02-11 09:19:54 -08008484 if (connection_.SupportsMultiplePacketNumberSpaces()) {
8485 return;
8486 }
rchd672c6d2019-11-27 15:30:54 -08008487
8488 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
8489 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
8490 connection_.CloseConnection(
8491 kQuicErrorCode, "Some random error message",
8492 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
8493
8494 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
8495
8496 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
8497 EXPECT_EQ(1u, writer_->connection_close_frames().size());
8498 EXPECT_EQ(1u, writer_->connection_close_packets());
8499 EXPECT_EQ(1u, writer_->packets_write_attempts());
8500 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
8501}
8502
fayang9abdfec2020-02-13 12:34:58 -08008503TEST_P(QuicConnectionTest, DoNotPadServerInitialConnectionClose) {
8504 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8505 return;
8506 }
8507 set_perspective(Perspective::IS_SERVER);
8508
8509 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
8510 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
8511 connection_.CloseConnection(
8512 kQuicErrorCode, "Some random error message",
8513 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
8514
8515 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
8516
8517 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
8518 EXPECT_EQ(1u, writer_->connection_close_frames().size());
8519 EXPECT_TRUE(writer_->padding_frames().empty());
8520 EXPECT_EQ(ENCRYPTION_INITIAL, writer_->framer()->last_decrypted_level());
8521}
8522
QUICHE teama6ef0a62019-03-07 20:34:33 -05008523// Regression test for b/63620844.
8524TEST_P(QuicConnectionTest, FailedToWriteHandshakePacket) {
8525 SimulateNextPacketTooLarge();
fkastenholz5d880a92019-06-21 09:01:56 -07008526 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
QUICHE teama6ef0a62019-03-07 20:34:33 -05008527 .Times(1);
fkastenholz5d880a92019-06-21 09:01:56 -07008528
QUICHE teama6ef0a62019-03-07 20:34:33 -05008529 connection_.SendCryptoStreamData();
fkastenholz5d880a92019-06-21 09:01:56 -07008530 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008531}
8532
8533TEST_P(QuicConnectionTest, MaxPacingRate) {
8534 EXPECT_EQ(0, connection_.MaxPacingRate().ToBytesPerSecond());
8535 connection_.SetMaxPacingRate(QuicBandwidth::FromBytesPerSecond(100));
8536 EXPECT_EQ(100, connection_.MaxPacingRate().ToBytesPerSecond());
8537}
8538
8539TEST_P(QuicConnectionTest, ClientAlwaysSendConnectionId) {
8540 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
8541 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8542 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
8543 EXPECT_EQ(CONNECTION_ID_PRESENT,
8544 writer_->last_packet_header().destination_connection_id_included);
8545
8546 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8547 QuicConfig config;
8548 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
8549 connection_.SetFromConfig(config);
8550
8551 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8552 connection_.SendStreamDataWithString(3, "bar", 3, NO_FIN);
8553 // Verify connection id is still sent in the packet.
8554 EXPECT_EQ(CONNECTION_ID_PRESENT,
8555 writer_->last_packet_header().destination_connection_id_included);
8556}
8557
8558TEST_P(QuicConnectionTest, SendProbingRetransmissions) {
8559 MockQuicConnectionDebugVisitor debug_visitor;
8560 connection_.set_debug_visitor(&debug_visitor);
8561
8562 const QuicStreamId stream_id = 2;
8563 QuicPacketNumber last_packet;
8564 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
8565 SendStreamDataToPeer(stream_id, "bar", 3, NO_FIN, &last_packet);
8566 SendStreamDataToPeer(stream_id, "test", 6, NO_FIN, &last_packet);
8567
8568 const QuicByteCount old_bytes_in_flight =
8569 connection_.sent_packet_manager().GetBytesInFlight();
8570
8571 // Allow 9 probing retransmissions to be sent.
8572 {
8573 InSequence seq;
8574 EXPECT_CALL(*send_algorithm_, CanSend(_))
8575 .Times(9 * 2)
8576 .WillRepeatedly(Return(true));
8577 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(Return(false));
8578 }
8579 // Expect them retransmitted in cyclic order (foo, bar, test, foo, bar...).
8580 QuicPacketCount sent_count = 0;
fayangcff885a2019-10-22 07:39:04 -07008581 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _))
QUICHE teama6ef0a62019-03-07 20:34:33 -05008582 .WillRepeatedly(Invoke([this, &sent_count](const SerializedPacket&,
QUICHE teama6ef0a62019-03-07 20:34:33 -05008583 TransmissionType, QuicTime) {
8584 ASSERT_EQ(1u, writer_->stream_frames().size());
fayang58f71072019-11-05 08:47:02 -08008585 if (connection_.version().CanSendCoalescedPackets()) {
8586 // There is a delay of sending coalesced packet, so (6, 0, 3, 6,
8587 // 0...).
8588 EXPECT_EQ(3 * ((sent_count + 2) % 3),
8589 writer_->stream_frames()[0]->offset);
8590 } else {
8591 // Identify the frames by stream offset (0, 3, 6, 0, 3...).
8592 EXPECT_EQ(3 * (sent_count % 3), writer_->stream_frames()[0]->offset);
8593 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008594 sent_count++;
8595 }));
8596 EXPECT_CALL(*send_algorithm_, ShouldSendProbingPacket())
8597 .WillRepeatedly(Return(true));
QUICHE teamb8343252019-04-29 13:58:01 -07008598 EXPECT_CALL(visitor_, SendProbingData()).WillRepeatedly([this] {
8599 return connection_.sent_packet_manager().MaybeRetransmitOldestPacket(
8600 PROBING_RETRANSMISSION);
8601 });
QUICHE teama6ef0a62019-03-07 20:34:33 -05008602
8603 connection_.SendProbingRetransmissions();
8604
8605 // Ensure that the in-flight has increased.
8606 const QuicByteCount new_bytes_in_flight =
8607 connection_.sent_packet_manager().GetBytesInFlight();
8608 EXPECT_GT(new_bytes_in_flight, old_bytes_in_flight);
8609}
8610
8611// Ensure that SendProbingRetransmissions() does not retransmit anything when
8612// there are no outstanding packets.
8613TEST_P(QuicConnectionTest,
8614 SendProbingRetransmissionsFailsWhenNothingToRetransmit) {
8615 ASSERT_TRUE(connection_.sent_packet_manager().unacked_packets().empty());
8616
8617 MockQuicConnectionDebugVisitor debug_visitor;
8618 connection_.set_debug_visitor(&debug_visitor);
fayangcff885a2019-10-22 07:39:04 -07008619 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008620 EXPECT_CALL(*send_algorithm_, ShouldSendProbingPacket())
8621 .WillRepeatedly(Return(true));
QUICHE teamb8343252019-04-29 13:58:01 -07008622 EXPECT_CALL(visitor_, SendProbingData()).WillRepeatedly([this] {
8623 return connection_.sent_packet_manager().MaybeRetransmitOldestPacket(
8624 PROBING_RETRANSMISSION);
8625 });
QUICHE teama6ef0a62019-03-07 20:34:33 -05008626
8627 connection_.SendProbingRetransmissions();
8628}
8629
8630TEST_P(QuicConnectionTest, PingAfterLastRetransmittablePacketAcked) {
8631 const QuicTime::Delta retransmittable_on_wire_timeout =
8632 QuicTime::Delta::FromMilliseconds(50);
zhongyi79ace162019-10-21 15:57:09 -07008633 connection_.set_initial_retransmittable_on_wire_timeout(
QUICHE teama6ef0a62019-03-07 20:34:33 -05008634 retransmittable_on_wire_timeout);
8635
8636 EXPECT_TRUE(connection_.connected());
8637 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8638 .WillRepeatedly(Return(true));
8639
8640 const char data[] = "data";
8641 size_t data_size = strlen(data);
8642 QuicStreamOffset offset = 0;
8643
8644 // Advance 5ms, send a retransmittable packet to the peer.
8645 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8646 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8647 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8648 offset += data_size;
8649 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8650 // The ping alarm is set for the ping timeout, not the shorter
8651 // retransmittable_on_wire_timeout.
8652 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8653 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
zhongyieef848f2019-10-18 07:09:37 -07008654 EXPECT_EQ(ping_delay,
8655 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008656
8657 // Advance 5ms, send a second retransmittable packet to the peer.
8658 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8659 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8660 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8661 offset += data_size;
8662 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8663
8664 // Now receive an ACK of the first packet. This should not set the
8665 // retransmittable-on-wire alarm since packet 2 is still on the wire.
8666 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8667 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8668 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8669 QuicAckFrame frame =
8670 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8671 ProcessAckPacket(&frame);
8672 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8673 // The ping alarm is set for the ping timeout, not the shorter
8674 // retransmittable_on_wire_timeout.
8675 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8676 // The ping alarm has a 1 second granularity, and the clock has been advanced
8677 // 10ms since it was originally set.
zhongyieef848f2019-10-18 07:09:37 -07008678 EXPECT_EQ(ping_delay - QuicTime::Delta::FromMilliseconds(10),
8679 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008680
8681 // Now receive an ACK of the second packet. This should set the
8682 // retransmittable-on-wire alarm now that no retransmittable packets are on
8683 // the wire.
8684 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8685 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8686 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8687 ProcessAckPacket(&frame);
8688 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07008689 EXPECT_EQ(retransmittable_on_wire_timeout,
8690 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008691
8692 // Now receive a duplicate ACK of the second packet. This should not update
8693 // the ping alarm.
8694 QuicTime prev_deadline = connection_.GetPingAlarm()->deadline();
8695 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8696 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8697 ProcessAckPacket(&frame);
8698 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8699 EXPECT_EQ(prev_deadline, connection_.GetPingAlarm()->deadline());
8700
8701 // Now receive a non-ACK packet. This should not update the ping alarm.
8702 prev_deadline = connection_.GetPingAlarm()->deadline();
8703 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8704 ProcessPacket(4);
8705 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8706 EXPECT_EQ(prev_deadline, connection_.GetPingAlarm()->deadline());
8707
8708 // Simulate the alarm firing and check that a PING is sent.
8709 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8710 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
8711 }));
8712 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07008713 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05008714 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07008715 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008716 } else {
nharper55fa6132019-05-07 19:37:21 -07008717 EXPECT_EQ(padding_frame_count + 3u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008718 }
8719 ASSERT_EQ(1u, writer_->ping_frames().size());
8720}
8721
8722TEST_P(QuicConnectionTest, NoPingIfRetransmittablePacketSent) {
8723 const QuicTime::Delta retransmittable_on_wire_timeout =
8724 QuicTime::Delta::FromMilliseconds(50);
zhongyi79ace162019-10-21 15:57:09 -07008725 connection_.set_initial_retransmittable_on_wire_timeout(
QUICHE teama6ef0a62019-03-07 20:34:33 -05008726 retransmittable_on_wire_timeout);
8727
8728 EXPECT_TRUE(connection_.connected());
8729 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8730 .WillRepeatedly(Return(true));
8731
8732 const char data[] = "data";
8733 size_t data_size = strlen(data);
8734 QuicStreamOffset offset = 0;
8735
8736 // Advance 5ms, send a retransmittable packet to the peer.
8737 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8738 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8739 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8740 offset += data_size;
8741 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8742 // The ping alarm is set for the ping timeout, not the shorter
8743 // retransmittable_on_wire_timeout.
8744 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8745 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
zhongyieef848f2019-10-18 07:09:37 -07008746 EXPECT_EQ(ping_delay,
8747 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008748
8749 // Now receive an ACK of the first packet. This should set the
8750 // retransmittable-on-wire alarm now that no retransmittable packets are on
8751 // the wire.
8752 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8753 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8754 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8755 QuicAckFrame frame =
8756 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8757 ProcessAckPacket(&frame);
8758 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07008759 EXPECT_EQ(retransmittable_on_wire_timeout,
8760 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008761
8762 // Before the alarm fires, send another retransmittable packet. This should
8763 // cancel the retransmittable-on-wire alarm since now there's a
8764 // retransmittable packet on the wire.
8765 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8766 offset += data_size;
8767 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8768
8769 // Now receive an ACK of the second packet. This should set the
8770 // retransmittable-on-wire alarm now that no retransmittable packets are on
8771 // the wire.
8772 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8773 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8774 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8775 ProcessAckPacket(&frame);
8776 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07008777 EXPECT_EQ(retransmittable_on_wire_timeout,
8778 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008779
8780 // Simulate the alarm firing and check that a PING is sent.
8781 writer_->Reset();
8782 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8783 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
8784 }));
8785 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07008786 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05008787 if (GetParam().no_stop_waiting) {
fayang8a27b0f2019-11-04 11:27:40 -08008788 // Do not ACK acks.
8789 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008790 } else {
nharper55fa6132019-05-07 19:37:21 -07008791 EXPECT_EQ(padding_frame_count + 3u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008792 }
8793 ASSERT_EQ(1u, writer_->ping_frames().size());
8794}
8795
zhongyi79ace162019-10-21 15:57:09 -07008796// When there is no stream data received but are open streams, send the
8797// first few consecutive pings with aggressive retransmittable-on-wire
8798// timeout. Exponentially back off the retransmittable-on-wire ping timeout
8799// afterwards until it exceeds the default ping timeout.
8800TEST_P(QuicConnectionTest, BackOffRetransmittableOnWireTimeout) {
8801 int max_aggressive_retransmittable_on_wire_ping_count = 5;
8802 SetQuicFlag(FLAGS_quic_max_aggressive_retransmittable_on_wire_ping_count,
8803 max_aggressive_retransmittable_on_wire_ping_count);
8804 const QuicTime::Delta initial_retransmittable_on_wire_timeout =
8805 QuicTime::Delta::FromMilliseconds(200);
8806 connection_.set_initial_retransmittable_on_wire_timeout(
8807 initial_retransmittable_on_wire_timeout);
8808
8809 EXPECT_TRUE(connection_.connected());
8810 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8811 .WillRepeatedly(Return(true));
8812
8813 const char data[] = "data";
8814 // Advance 5ms, send a retransmittable data packet to the peer.
8815 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8816 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8817 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
8818 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8819 // The ping alarm is set for the ping timeout, not the shorter
8820 // retransmittable_on_wire_timeout.
8821 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8822 EXPECT_EQ(connection_.ping_timeout(),
8823 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8824
8825 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
8826 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
8827 .Times(AnyNumber());
8828
8829 // Verify that the first few consecutive retransmittable on wire pings are
8830 // sent with aggressive timeout.
8831 for (int i = 0; i <= max_aggressive_retransmittable_on_wire_ping_count; i++) {
8832 // Receive an ACK of the previous packet. This should set the ping alarm
8833 // with the initial retransmittable-on-wire timeout.
8834 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8835 QuicPacketNumber ack_num = creator_->packet_number();
8836 QuicAckFrame frame = InitAckFrame(
8837 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8838 ProcessAckPacket(&frame);
8839 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8840 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8841 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8842 // Simulate the alarm firing and check that a PING is sent.
8843 writer_->Reset();
8844 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8845 SendPing();
8846 }));
8847 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8848 connection_.GetPingAlarm()->Fire();
8849 }
8850
8851 QuicTime::Delta retransmittable_on_wire_timeout =
8852 initial_retransmittable_on_wire_timeout;
8853
8854 // Verify subsequent pings are sent with timeout that is exponentially backed
8855 // off.
8856 while (retransmittable_on_wire_timeout * 2 < connection_.ping_timeout()) {
8857 // Receive an ACK for the previous PING. This should set the
8858 // ping alarm with backed off retransmittable-on-wire timeout.
8859 retransmittable_on_wire_timeout = retransmittable_on_wire_timeout * 2;
8860 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8861 QuicPacketNumber ack_num = creator_->packet_number();
8862 QuicAckFrame frame = InitAckFrame(
8863 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8864 ProcessAckPacket(&frame);
8865 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8866 EXPECT_EQ(retransmittable_on_wire_timeout,
8867 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8868
8869 // Simulate the alarm firing and check that a PING is sent.
8870 writer_->Reset();
8871 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8872 SendPing();
8873 }));
8874 clock_.AdvanceTime(retransmittable_on_wire_timeout);
8875 connection_.GetPingAlarm()->Fire();
8876 }
8877
8878 // The ping alarm is set with default ping timeout.
8879 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8880 EXPECT_EQ(connection_.ping_timeout(),
8881 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8882
8883 // Receive an ACK for the previous PING. The ping alarm is set with an
8884 // earlier deadline.
8885 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8886 QuicPacketNumber ack_num = creator_->packet_number();
8887 QuicAckFrame frame = InitAckFrame(
8888 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8889 ProcessAckPacket(&frame);
8890 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8891 EXPECT_EQ(connection_.ping_timeout() - QuicTime::Delta::FromMilliseconds(5),
8892 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8893}
8894
8895// This test verify that the count of consecutive aggressive pings is reset
8896// when new data is received. And it also verifies the connection resets
8897// the exponential back-off of the retransmittable-on-wire ping timeout
8898// after receiving new stream data.
8899TEST_P(QuicConnectionTest, ResetBackOffRetransmitableOnWireTimeout) {
8900 int max_aggressive_retransmittable_on_wire_ping_count = 3;
8901 SetQuicFlag(FLAGS_quic_max_aggressive_retransmittable_on_wire_ping_count, 3);
8902 const QuicTime::Delta initial_retransmittable_on_wire_timeout =
8903 QuicTime::Delta::FromMilliseconds(200);
8904 connection_.set_initial_retransmittable_on_wire_timeout(
8905 initial_retransmittable_on_wire_timeout);
8906
8907 EXPECT_TRUE(connection_.connected());
8908 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8909 .WillRepeatedly(Return(true));
8910 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
8911 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
8912 .Times(AnyNumber());
8913
8914 const char data[] = "data";
8915 // Advance 5ms, send a retransmittable data packet to the peer.
8916 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8917 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8918 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
8919 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8920 // The ping alarm is set for the ping timeout, not the shorter
8921 // retransmittable_on_wire_timeout.
8922 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8923 EXPECT_EQ(connection_.ping_timeout(),
8924 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8925
8926 // Receive an ACK of the first packet. This should set the ping alarm with
8927 // initial retransmittable-on-wire timeout since there is no retransmittable
8928 // packet on the wire.
8929 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8930 QuicAckFrame frame =
8931 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8932 ProcessAckPacket(&frame);
8933 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8934 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8935 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8936
8937 // Simulate the alarm firing and check that a PING is sent.
8938 writer_->Reset();
8939 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
8940 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8941 connection_.GetPingAlarm()->Fire();
8942
8943 // Receive an ACK for the previous PING. Ping alarm will be set with
8944 // aggressive timeout.
8945 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8946 QuicPacketNumber ack_num = creator_->packet_number();
8947 frame = InitAckFrame(
8948 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8949 ProcessAckPacket(&frame);
8950 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8951 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8952 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8953
8954 // Process a data packet.
8955 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
8956 ProcessDataPacket(peer_creator_.packet_number() + 1);
8957 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_,
8958 peer_creator_.packet_number() + 1);
8959 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8960 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8961
8962 // Verify the count of consecutive aggressive pings is reset.
8963 for (int i = 0; i < max_aggressive_retransmittable_on_wire_ping_count; i++) {
8964 // Receive an ACK of the previous packet. This should set the ping alarm
8965 // with the initial retransmittable-on-wire timeout.
8966 QuicPacketNumber ack_num = creator_->packet_number();
8967 QuicAckFrame frame = InitAckFrame(
8968 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8969 ProcessAckPacket(&frame);
8970 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8971 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8972 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8973 // Simulate the alarm firing and check that a PING is sent.
8974 writer_->Reset();
8975 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8976 SendPing();
8977 }));
8978 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8979 connection_.GetPingAlarm()->Fire();
8980 // Advance 5ms to receive next packet.
8981 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8982 }
8983
8984 // Receive another ACK for the previous PING. This should set the
8985 // ping alarm with backed off retransmittable-on-wire timeout.
8986 ack_num = creator_->packet_number();
8987 frame = InitAckFrame(
8988 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8989 ProcessAckPacket(&frame);
8990 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8991 EXPECT_EQ(initial_retransmittable_on_wire_timeout * 2,
8992 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8993
8994 writer_->Reset();
8995 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
8996 clock_.AdvanceTime(2 * initial_retransmittable_on_wire_timeout);
8997 connection_.GetPingAlarm()->Fire();
8998
8999 // Process another data packet and a new ACK packet. The ping alarm is set
9000 // with aggressive ping timeout again.
9001 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
9002 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
9003 ProcessDataPacket(peer_creator_.packet_number() + 1);
9004 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_,
9005 peer_creator_.packet_number() + 1);
9006 ack_num = creator_->packet_number();
9007 frame = InitAckFrame(
9008 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
9009 ProcessAckPacket(&frame);
9010 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
9011 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
9012 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
9013}
9014
QUICHE teama6ef0a62019-03-07 20:34:33 -05009015TEST_P(QuicConnectionTest, ValidStatelessResetToken) {
9016 const QuicUint128 kTestToken = 1010101;
9017 const QuicUint128 kWrongTestToken = 1010100;
9018 QuicConfig config;
9019 // No token has been received.
9020 EXPECT_FALSE(connection_.IsValidStatelessResetToken(kTestToken));
9021
9022 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(2);
9023 // Token is different from received token.
9024 QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestToken);
9025 connection_.SetFromConfig(config);
9026 EXPECT_FALSE(connection_.IsValidStatelessResetToken(kWrongTestToken));
9027
9028 QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestToken);
9029 connection_.SetFromConfig(config);
9030 EXPECT_TRUE(connection_.IsValidStatelessResetToken(kTestToken));
9031}
9032
9033TEST_P(QuicConnectionTest, WriteBlockedWithInvalidAck) {
9034 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayange62e63c2019-12-04 07:16:25 -08009035 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05009036 BlockOnNextWrite();
fayange62e63c2019-12-04 07:16:25 -08009037 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05009038 connection_.SendStreamDataWithString(5, "foo", 0, FIN);
9039 // This causes connection to be closed because packet 1 has not been sent yet.
9040 QuicAckFrame frame = InitAckFrame(1);
fayange62e63c2019-12-04 07:16:25 -08009041 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05009042 ProcessAckPacket(1, &frame);
fayange62e63c2019-12-04 07:16:25 -08009043 EXPECT_EQ(0, connection_close_frame_count_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05009044}
9045
9046TEST_P(QuicConnectionTest, SendMessage) {
fayangc31c9952019-06-05 13:54:48 -07009047 if (!VersionSupportsMessageFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05009048 return;
9049 }
dschinazied459c02020-05-07 16:12:23 -07009050 if (connection_.version().UsesTls()) {
9051 QuicConfig config;
9052 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
9053 &config, kMaxAcceptedDatagramFrameSize);
9054 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9055 connection_.SetFromConfig(config);
9056 }
ianswettb239f862019-04-05 09:15:06 -07009057 std::string message(connection_.GetCurrentLargestMessagePayload() * 2, 'a');
dmcardlecf0bfcf2019-12-13 08:08:21 -08009058 quiche::QuicheStringPiece message_data(message);
QUICHE teama6ef0a62019-03-07 20:34:33 -05009059 QuicMemSliceStorage storage(nullptr, 0, nullptr, 0);
9060 {
fayanga4b37b22019-06-18 13:37:47 -07009061 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05009062 connection_.SendStreamData3();
9063 // Send a message which cannot fit into current open packet, and 2 packets
9064 // get sent, one contains stream frame, and the other only contains the
9065 // message frame.
9066 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
QUICHE team350e9e62019-11-19 13:16:24 -08009067 EXPECT_EQ(MESSAGE_STATUS_SUCCESS,
9068 connection_.SendMessage(
9069 1,
9070 MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(),
dmcardlecf0bfcf2019-12-13 08:08:21 -08009071 quiche::QuicheStringPiece(
QUICHE team350e9e62019-11-19 13:16:24 -08009072 message_data.data(),
9073 connection_.GetCurrentLargestMessagePayload()),
9074 &storage),
9075 false));
QUICHE teama6ef0a62019-03-07 20:34:33 -05009076 }
9077 // Fail to send a message if connection is congestion control blocked.
9078 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(Return(false));
QUICHE team350e9e62019-11-19 13:16:24 -08009079 EXPECT_EQ(MESSAGE_STATUS_BLOCKED,
9080 connection_.SendMessage(
9081 2,
9082 MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(),
9083 "message", &storage),
9084 false));
QUICHE teama6ef0a62019-03-07 20:34:33 -05009085
9086 // Always fail to send a message which cannot fit into one packet.
9087 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE team350e9e62019-11-19 13:16:24 -08009088 EXPECT_EQ(MESSAGE_STATUS_TOO_LARGE,
9089 connection_.SendMessage(
9090 3,
9091 MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(),
dmcardlecf0bfcf2019-12-13 08:08:21 -08009092 quiche::QuicheStringPiece(
QUICHE team350e9e62019-11-19 13:16:24 -08009093 message_data.data(),
9094 connection_.GetCurrentLargestMessagePayload() + 1),
9095 &storage),
9096 false));
QUICHE teama6ef0a62019-03-07 20:34:33 -05009097}
9098
dschinazied459c02020-05-07 16:12:23 -07009099TEST_P(QuicConnectionTest, GetCurrentLargestMessagePayload) {
9100 if (!connection_.version().SupportsMessageFrames()) {
9101 return;
9102 }
9103 // Force use of this encrypter to simplify test expectations by making sure
9104 // that the encryption overhead is constant across versions.
9105 connection_.SetEncrypter(ENCRYPTION_INITIAL,
9106 std::make_unique<TaggingEncrypter>(0x00));
9107 QuicPacketLength expected_largest_payload = 1319;
9108 if (connection_.version().SendsVariableLengthPacketNumberInLongHeader()) {
9109 expected_largest_payload += 3;
9110 }
9111 if (connection_.version().HasLongHeaderLengths()) {
9112 expected_largest_payload -= 2;
9113 }
9114 if (connection_.version().HasLengthPrefixedConnectionIds()) {
9115 expected_largest_payload -= 1;
9116 }
9117 if (connection_.version().UsesTls()) {
9118 // QUIC+TLS disallows DATAGRAM/MESSAGE frames before the handshake.
9119 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), 0);
9120 QuicConfig config;
9121 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
9122 &config, kMaxAcceptedDatagramFrameSize);
9123 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9124 connection_.SetFromConfig(config);
9125 // Verify the value post-handshake.
9126 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(),
9127 expected_largest_payload);
9128 } else {
9129 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(),
9130 expected_largest_payload);
9131 }
9132}
9133
9134TEST_P(QuicConnectionTest, GetGuaranteedLargestMessagePayload) {
9135 if (!connection_.version().SupportsMessageFrames()) {
9136 return;
9137 }
9138 // Force use of this encrypter to simplify test expectations by making sure
9139 // that the encryption overhead is constant across versions.
9140 connection_.SetEncrypter(ENCRYPTION_INITIAL,
9141 std::make_unique<TaggingEncrypter>(0x00));
9142 QuicPacketLength expected_largest_payload = 1319;
9143 if (connection_.version().HasLongHeaderLengths()) {
9144 expected_largest_payload -= 2;
9145 }
9146 if (connection_.version().HasLengthPrefixedConnectionIds()) {
9147 expected_largest_payload -= 1;
9148 }
9149 if (connection_.version().UsesTls()) {
9150 // QUIC+TLS disallows DATAGRAM/MESSAGE frames before the handshake.
9151 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(), 0);
9152 QuicConfig config;
9153 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
9154 &config, kMaxAcceptedDatagramFrameSize);
9155 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9156 connection_.SetFromConfig(config);
9157 // Verify the value post-handshake.
9158 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(),
9159 expected_largest_payload);
9160 } else {
9161 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(),
9162 expected_largest_payload);
9163 }
9164}
9165
9166TEST_P(QuicConnectionTest, LimitedLargestMessagePayload) {
9167 if (!connection_.version().SupportsMessageFrames() ||
9168 !connection_.version().UsesTls()) {
9169 return;
9170 }
9171 constexpr QuicPacketLength kFrameSizeLimit = 1000;
9172 constexpr QuicPacketLength kPayloadSizeLimit =
9173 kFrameSizeLimit - kQuicFrameTypeSize;
9174 // QUIC+TLS disallows DATAGRAM/MESSAGE frames before the handshake.
9175 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), 0);
9176 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(), 0);
9177 QuicConfig config;
9178 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(&config, kFrameSizeLimit);
9179 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9180 connection_.SetFromConfig(config);
9181 // Verify the value post-handshake.
9182 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), kPayloadSizeLimit);
9183 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(),
9184 kPayloadSizeLimit);
9185}
9186
QUICHE teama6ef0a62019-03-07 20:34:33 -05009187// Test to check that the path challenge/path response logic works
9188// correctly. This test is only for version-99
9189TEST_P(QuicConnectionTest, PathChallengeResponse) {
fkastenholz305e1732019-06-18 05:01:22 -07009190 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05009191 return;
9192 }
9193 // First check if we can probe from server to client and back
9194 set_perspective(Perspective::IS_SERVER);
9195 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
9196
9197 // Create and send the probe request (PATH_CHALLENGE frame).
9198 // SendConnectivityProbingPacket ends up calling
9199 // TestPacketWriter::WritePacket() which in turns receives and parses the
9200 // packet by calling framer_.ProcessPacket() -- which in turn calls
9201 // SimpleQuicFramer::OnPathChallengeFrame(). SimpleQuicFramer saves
9202 // the packet in writer_->path_challenge_frames()
9203 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9204 connection_.SendConnectivityProbingPacket(writer_.get(),
9205 connection_.peer_address());
9206 // Save the random contents of the challenge for later comparison to the
9207 // response.
nharper55fa6132019-05-07 19:37:21 -07009208 ASSERT_GE(writer_->path_challenge_frames().size(), 1u);
QUICHE teama6ef0a62019-03-07 20:34:33 -05009209 QuicPathFrameBuffer challenge_data =
9210 writer_->path_challenge_frames().front().data_buffer;
9211
9212 // Normally, QuicConnection::OnPathChallengeFrame and OnPaddingFrame would be
9213 // called and it will perform actions to ensure that the rest of the protocol
9214 // is performed (specifically, call UpdatePacketContent to say that this is a
9215 // path challenge so that when QuicConnection::OnPacketComplete is called
9216 // (again, out of the framer), the response is generated). Simulate those
9217 // calls so that the right internal state is set up for generating
9218 // the response.
9219 EXPECT_TRUE(connection_.OnPathChallengeFrame(
9220 writer_->path_challenge_frames().front()));
9221 EXPECT_TRUE(connection_.OnPaddingFrame(writer_->padding_frames().front()));
9222 // Cause the response to be created and sent. Result is that the response
9223 // should be stashed in writer's path_response_frames.
9224 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9225 connection_.SendConnectivityProbingResponsePacket(connection_.peer_address());
9226
9227 // The final check is to ensure that the random data in the response matches
9228 // the random data from the challenge.
9229 EXPECT_EQ(0, memcmp(&challenge_data,
9230 &(writer_->path_response_frames().front().data_buffer),
9231 sizeof(challenge_data)));
9232}
9233
zhongyi2da16be2020-06-17 11:05:23 -07009234TEST_P(QuicConnectionTest,
9235 RestartPathDegradingDetectionAfterMigrationWithProbe) {
9236 // TODO(b/150095484): add test coverage for IETF to verify that client takes
9237 // PATH RESPONSE with peer address change as correct validation on the new
9238 // path.
9239 if (GetParam().version.HasIetfQuicFrames()) {
9240 return;
9241 }
9242 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
dschinazi1c6e5922020-06-19 10:35:03 -07009243 PathProbeTestInit(Perspective::IS_CLIENT);
zhongyi2da16be2020-06-17 11:05:23 -07009244
9245 // Clear direct_peer_address and effective_peer_address.
9246 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
9247 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
9248 QuicSocketAddress());
9249 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
9250
9251 EXPECT_TRUE(connection_.connected());
9252 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
9253 .WillRepeatedly(Return(true));
9254 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
9255 EXPECT_FALSE(connection_.IsPathDegrading());
9256 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
9257
9258 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9259 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9260 } else {
9261 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
9262 }
9263 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
9264 kPeerAddress);
9265 EXPECT_EQ(kPeerAddress, connection_.peer_address());
9266 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
9267
9268 // Send data and verify the path degrading detection is set.
9269 const char data[] = "data";
9270 size_t data_size = strlen(data);
9271 QuicStreamOffset offset = 0;
9272 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
9273 offset += data_size;
9274
9275 // Verify the path degrading detection is in progress.
9276 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
9277 EXPECT_FALSE(connection_.IsPathDegrading());
9278 QuicTime ddl = connection_.GetBlackholeDetectorAlarm()->deadline();
9279
9280 // Simulate the firing of path degrading.
9281 clock_.AdvanceTime(ddl - clock_.ApproximateNow());
9282 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
9283 connection_.PathDegradingTimeout();
9284 EXPECT_TRUE(connection_.IsPathDegrading());
9285 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
9286
9287 // Simulate path degrading handling by sending a probe on an alternet path.
9288 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
9289 TestPacketWriter probing_writer(version(), &clock_);
9290 connection_.SendConnectivityProbingPacket(&probing_writer,
9291 connection_.peer_address());
9292 // Verify that path degrading detection is not reset.
9293 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
9294
9295 // Simulate successful path degrading handling by receiving probe response.
9296 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
9297
9298 if (!GetParam().version.HasIetfQuicFrames()) {
9299 EXPECT_CALL(visitor_,
9300 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
9301 .Times(1);
9302 } else {
9303 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
9304 }
9305 const QuicSocketAddress kNewSelfAddress =
9306 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
9307
9308 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
9309 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
9310 QuicEncryptedPacket(probing_packet->encrypted_buffer,
9311 probing_packet->encrypted_length),
9312 clock_.Now()));
9313 uint64_t num_probing_received =
9314 connection_.GetStats().num_connectivity_probing_received;
9315 ProcessReceivedPacket(kNewSelfAddress, kPeerAddress, *received);
9316
9317 EXPECT_EQ(num_probing_received + 1,
9318 connection_.GetStats().num_connectivity_probing_received);
9319 EXPECT_EQ(kPeerAddress, connection_.peer_address());
9320 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
9321 EXPECT_TRUE(connection_.IsPathDegrading());
9322
9323 // Verify new path degrading detection is activated.
9324 EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading()).Times(1);
9325 connection_.OnSuccessfulMigrationAfterProbing();
9326 EXPECT_FALSE(connection_.IsPathDegrading());
9327 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
9328}
9329
QUICHE teama6ef0a62019-03-07 20:34:33 -05009330// Regression test for b/110259444
9331TEST_P(QuicConnectionTest, DoNotScheduleSpuriousAckAlarm) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05009332 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9333 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
9334 writer_->SetWriteBlocked();
9335
9336 ProcessPacket(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05009337 // Verify ack alarm is set.
fayang9adfb532020-06-04 06:58:45 -07009338 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05009339 // Fire the ack alarm, verify no packet is sent because the writer is blocked.
9340 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9341 connection_.GetAckAlarm()->Fire();
9342
9343 writer_->SetWritable();
9344 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9345 ProcessPacket(2);
9346 // Verify ack alarm is not set.
fayang9adfb532020-06-04 06:58:45 -07009347 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05009348}
9349
9350TEST_P(QuicConnectionTest, DisablePacingOffloadConnectionOptions) {
9351 EXPECT_FALSE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
9352 writer_->set_supports_release_time(true);
9353 QuicConfig config;
9354 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9355 connection_.SetFromConfig(config);
9356 EXPECT_TRUE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
9357
9358 QuicTagVector connection_options;
9359 connection_options.push_back(kNPCO);
9360 config.SetConnectionOptionsToSend(connection_options);
9361 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9362 connection_.SetFromConfig(config);
9363 // Verify pacing offload is disabled.
9364 EXPECT_FALSE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
9365}
9366
9367// Regression test for b/110259444
9368// Get a path response without having issued a path challenge...
9369TEST_P(QuicConnectionTest, OrphanPathResponse) {
9370 QuicPathFrameBuffer data = {{0, 1, 2, 3, 4, 5, 6, 7}};
9371
9372 QuicPathResponseFrame frame(99, data);
9373 EXPECT_TRUE(connection_.OnPathResponseFrame(frame));
9374 // If PATH_RESPONSE was accepted (payload matches the payload saved
9375 // in QuicConnection::transmitted_connectivity_probe_payload_) then
9376 // current_packet_content_ would be set to FIRST_FRAME_IS_PING.
9377 // Since this PATH_RESPONSE does not match, current_packet_content_
9378 // must not be FIRST_FRAME_IS_PING.
9379 EXPECT_NE(QuicConnection::FIRST_FRAME_IS_PING,
9380 QuicConnectionPeer::GetCurrentPacketContent(&connection_));
9381}
9382
9383// Regression test for b/120791670
9384TEST_P(QuicConnectionTest, StopProcessingGQuicPacketInIetfQuicConnection) {
9385 // This test mimics a problematic scenario where an IETF QUIC connection
9386 // receives a Google QUIC packet and continue processing it using Google QUIC
9387 // wire format.
fayangd4291e42019-05-30 10:31:21 -07009388 if (!VersionHasIetfInvariantHeader(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05009389 return;
9390 }
9391 set_perspective(Perspective::IS_SERVER);
nharper46833c32019-05-15 21:33:05 -07009392 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07009393 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
9394 } else {
nharper46833c32019-05-15 21:33:05 -07009395 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
9396 }
wub8a5dafa2020-05-13 12:30:17 -07009397 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
9398 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05009399
9400 // Let connection process a Google QUIC packet.
9401 peer_framer_.set_version_for_tests(
9402 ParsedQuicVersion(PROTOCOL_QUIC_CRYPTO, QUIC_VERSION_43));
QUICHE team8c1daa22019-03-13 08:33:41 -07009403 std::unique_ptr<QuicPacket> packet(
QUICHE team6987b4a2019-03-15 16:23:04 -07009404 ConstructDataPacket(2, !kHasStopWaiting, ENCRYPTION_INITIAL));
dschinazi66dea072019-04-09 11:41:06 -07009405 char buffer[kMaxOutgoingPacketSize];
9406 size_t encrypted_length =
9407 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(2),
9408 *packet, buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05009409 // Make sure no stream frame is processed.
9410 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(0);
9411 connection_.ProcessUdpPacket(
9412 kSelfAddress, kPeerAddress,
9413 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
9414
9415 EXPECT_EQ(2u, connection_.GetStats().packets_received);
9416 EXPECT_EQ(1u, connection_.GetStats().packets_processed);
9417}
9418
9419TEST_P(QuicConnectionTest, AcceptPacketNumberZero) {
fkastenholz305e1732019-06-18 05:01:22 -07009420 if (!VersionHasIetfQuicFrames(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05009421 return;
9422 }
9423 // Set first_sending_packet_number to be 0 to allow successfully processing
9424 // acks which ack packet number 0.
9425 QuicFramerPeer::SetFirstSendingPacketNumber(writer_->framer()->framer(), 0);
9426 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9427
9428 ProcessPacket(0);
fayangc31c9952019-06-05 13:54:48 -07009429 EXPECT_EQ(QuicPacketNumber(0), LargestAcked(connection_.ack_frame()));
9430 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05009431
9432 ProcessPacket(1);
fayangc31c9952019-06-05 13:54:48 -07009433 EXPECT_EQ(QuicPacketNumber(1), LargestAcked(connection_.ack_frame()));
9434 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05009435
9436 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07009437 EXPECT_EQ(QuicPacketNumber(2), LargestAcked(connection_.ack_frame()));
9438 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05009439}
9440
QUICHE teamcd098022019-03-22 18:49:55 -07009441TEST_P(QuicConnectionTest, MultiplePacketNumberSpacesBasicSending) {
9442 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
9443 return;
9444 }
9445 use_tagging_decrypter();
9446 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07009447 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teamcd098022019-03-22 18:49:55 -07009448
9449 connection_.SendCryptoStreamData();
9450 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9451 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
9452 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
9453 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9454 QuicAckFrame frame1 = InitAckFrame(1);
9455 // Received ACK for packet 1.
9456 ProcessFramePacketAtLevel(30, QuicFrame(&frame1), ENCRYPTION_INITIAL);
9457
9458 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(4);
9459 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
9460 NO_FIN);
9461 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 4,
9462 NO_FIN);
9463 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
9464 8, NO_FIN);
9465 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
9466 12, FIN);
9467 // Received ACK for packets 2, 4, 5.
9468 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
9469 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
9470 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9471 QuicAckFrame frame2 =
9472 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)},
9473 {QuicPacketNumber(4), QuicPacketNumber(6)}});
9474 // Make sure although the same packet number is used, but they are in
9475 // different packet number spaces.
9476 ProcessFramePacketAtLevel(30, QuicFrame(&frame2), ENCRYPTION_FORWARD_SECURE);
9477}
9478
9479TEST_P(QuicConnectionTest, PeerAcksPacketsInWrongPacketNumberSpace) {
9480 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
9481 return;
9482 }
9483 use_tagging_decrypter();
9484 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07009485 std::make_unique<TaggingEncrypter>(0x01));
rch39c88ab2019-10-16 19:24:40 -07009486 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
9487 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teamcd098022019-03-22 18:49:55 -07009488
9489 connection_.SendCryptoStreamData();
9490 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9491 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
9492 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
9493 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9494 QuicAckFrame frame1 = InitAckFrame(1);
9495 // Received ACK for packet 1.
9496 ProcessFramePacketAtLevel(30, QuicFrame(&frame1), ENCRYPTION_INITIAL);
9497
9498 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
9499 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
9500 NO_FIN);
9501 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 4,
9502 NO_FIN);
9503
9504 // Received ACK for packets 2 and 3 in wrong packet number space.
9505 QuicAckFrame invalid_ack =
9506 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(4)}});
fkastenholz5d880a92019-06-21 09:01:56 -07009507 EXPECT_CALL(visitor_,
9508 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07009509 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teamcd098022019-03-22 18:49:55 -07009510 ProcessFramePacketAtLevel(300, QuicFrame(&invalid_ack), ENCRYPTION_INITIAL);
fkastenholz5d880a92019-06-21 09:01:56 -07009511 TestConnectionCloseQuicErrorCode(QUIC_INVALID_ACK_DATA);
QUICHE teamcd098022019-03-22 18:49:55 -07009512}
9513
9514TEST_P(QuicConnectionTest, MultiplePacketNumberSpacesBasicReceiving) {
9515 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
9516 return;
9517 }
9518 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
nharper46833c32019-05-15 21:33:05 -07009519 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9520 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9521 }
QUICHE teamcd098022019-03-22 18:49:55 -07009522 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
9523 use_tagging_decrypter();
9524 // Receives packet 1000 in initial data.
nharper46833c32019-05-15 21:33:05 -07009525 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
fayang9adfb532020-06-04 06:58:45 -07009526 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teamcd098022019-03-22 18:49:55 -07009527 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07009528 std::make_unique<TaggingEncrypter>(0x02));
zhongyi546cc452019-04-12 15:27:49 -07009529 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07009530 std::make_unique<StrictTaggingDecrypter>(0x02));
QUICHE teamcd098022019-03-22 18:49:55 -07009531 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07009532 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teamcd098022019-03-22 18:49:55 -07009533 // Receives packet 1000 in application data.
9534 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
fayang9adfb532020-06-04 06:58:45 -07009535 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teamcd098022019-03-22 18:49:55 -07009536 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
9537 NO_FIN);
9538 // Verify application data ACK gets bundled with outgoing data.
9539 EXPECT_EQ(2u, writer_->frame_count());
9540 // Make sure ACK alarm is still set because initial data is not ACKed.
fayang9adfb532020-06-04 06:58:45 -07009541 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teamcd098022019-03-22 18:49:55 -07009542 // Receive packet 1001 in application data.
9543 ProcessDataPacketAtLevel(1001, false, ENCRYPTION_ZERO_RTT);
9544 clock_.AdvanceTime(DefaultRetransmissionTime());
9545 // Simulates ACK alarm fires and verify two ACKs are flushed.
9546 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
9547 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07009548 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teamcd098022019-03-22 18:49:55 -07009549 connection_.GetAckAlarm()->Fire();
fayang9adfb532020-06-04 06:58:45 -07009550 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teamcd098022019-03-22 18:49:55 -07009551 // Receives more packets in application data.
9552 ProcessDataPacketAtLevel(1002, false, ENCRYPTION_ZERO_RTT);
fayang9adfb532020-06-04 06:58:45 -07009553 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teamcd098022019-03-22 18:49:55 -07009554
9555 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07009556 std::make_unique<TaggingEncrypter>(0x02));
zhongyi546cc452019-04-12 15:27:49 -07009557 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07009558 std::make_unique<StrictTaggingDecrypter>(0x02));
QUICHE teamcd098022019-03-22 18:49:55 -07009559 // Verify zero rtt and forward secure packets get acked in the same packet.
9560 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
nharper2c9f02a2019-05-08 10:25:50 -07009561 ProcessDataPacket(1003);
fayang9adfb532020-06-04 06:58:45 -07009562 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teamcd098022019-03-22 18:49:55 -07009563}
9564
QUICHE team552f71f2019-03-23 15:37:59 -07009565TEST_P(QuicConnectionTest, CancelAckAlarmOnWriteBlocked) {
9566 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
9567 return;
9568 }
9569 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
nharper46833c32019-05-15 21:33:05 -07009570 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9571 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9572 }
QUICHE team552f71f2019-03-23 15:37:59 -07009573 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
9574 use_tagging_decrypter();
9575 // Receives packet 1000 in initial data.
nharper46833c32019-05-15 21:33:05 -07009576 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
fayang9adfb532020-06-04 06:58:45 -07009577 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE team552f71f2019-03-23 15:37:59 -07009578 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07009579 std::make_unique<TaggingEncrypter>(0x02));
zhongyi546cc452019-04-12 15:27:49 -07009580 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07009581 std::make_unique<StrictTaggingDecrypter>(0x02));
QUICHE team552f71f2019-03-23 15:37:59 -07009582 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07009583 std::make_unique<TaggingEncrypter>(0x02));
QUICHE team552f71f2019-03-23 15:37:59 -07009584 // Receives packet 1000 in application data.
9585 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
fayang9adfb532020-06-04 06:58:45 -07009586 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE team552f71f2019-03-23 15:37:59 -07009587
9588 writer_->SetWriteBlocked();
9589 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AnyNumber());
9590 // Simulates ACK alarm fires and verify no ACK is flushed because of write
9591 // blocked.
9592 clock_.AdvanceTime(DefaultDelayedAckTime());
9593 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9594 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07009595 std::make_unique<TaggingEncrypter>(0x02));
QUICHE team552f71f2019-03-23 15:37:59 -07009596 connection_.GetAckAlarm()->Fire();
9597 // Verify ACK alarm is not set.
fayang9adfb532020-06-04 06:58:45 -07009598 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE team552f71f2019-03-23 15:37:59 -07009599
9600 writer_->SetWritable();
9601 // Verify 2 ACKs are sent when connection gets unblocked.
9602 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
9603 connection_.OnCanWrite();
fayang9adfb532020-06-04 06:58:45 -07009604 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE team552f71f2019-03-23 15:37:59 -07009605}
9606
dschinazi346b7ce2019-06-05 01:38:18 -07009607// Make sure a packet received with the right client connection ID is processed.
9608TEST_P(QuicConnectionTest, ValidClientConnectionId) {
dschinazi346b7ce2019-06-05 01:38:18 -07009609 if (!framer_.version().SupportsClientConnectionIds()) {
9610 return;
9611 }
9612 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9613 connection_.set_client_connection_id(TestConnectionId(0x33));
9614 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_FORWARD_SECURE);
9615 header.destination_connection_id = TestConnectionId(0x33);
9616 header.destination_connection_id_included = CONNECTION_ID_PRESENT;
9617 header.source_connection_id_included = CONNECTION_ID_ABSENT;
9618 QuicFrames frames;
9619 QuicPingFrame ping_frame;
9620 QuicPaddingFrame padding_frame;
9621 frames.push_back(QuicFrame(ping_frame));
9622 frames.push_back(QuicFrame(padding_frame));
9623 std::unique_ptr<QuicPacket> packet =
9624 BuildUnsizedDataPacket(&framer_, header, frames);
9625 char buffer[kMaxOutgoingPacketSize];
9626 size_t encrypted_length = peer_framer_.EncryptPayload(
9627 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
9628 kMaxOutgoingPacketSize);
9629 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9630 false);
9631 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9632 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9633 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9634}
9635
9636// Make sure a packet received with a different client connection ID is dropped.
9637TEST_P(QuicConnectionTest, InvalidClientConnectionId) {
dschinazi346b7ce2019-06-05 01:38:18 -07009638 if (!framer_.version().SupportsClientConnectionIds()) {
9639 return;
9640 }
9641 connection_.set_client_connection_id(TestConnectionId(0x33));
9642 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_FORWARD_SECURE);
9643 header.destination_connection_id = TestConnectionId(0xbad);
9644 header.destination_connection_id_included = CONNECTION_ID_PRESENT;
9645 header.source_connection_id_included = CONNECTION_ID_ABSENT;
9646 QuicFrames frames;
9647 QuicPingFrame ping_frame;
9648 QuicPaddingFrame padding_frame;
9649 frames.push_back(QuicFrame(ping_frame));
9650 frames.push_back(QuicFrame(padding_frame));
9651 std::unique_ptr<QuicPacket> packet =
9652 BuildUnsizedDataPacket(&framer_, header, frames);
9653 char buffer[kMaxOutgoingPacketSize];
9654 size_t encrypted_length = peer_framer_.EncryptPayload(
9655 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
9656 kMaxOutgoingPacketSize);
9657 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9658 false);
9659 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9660 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9661 EXPECT_EQ(1u, connection_.GetStats().packets_dropped);
9662}
9663
9664// Make sure the first packet received with a different client connection ID on
9665// the server is processed and it changes the client connection ID.
9666TEST_P(QuicConnectionTest, UpdateClientConnectionIdFromFirstPacket) {
dschinazi346b7ce2019-06-05 01:38:18 -07009667 if (!framer_.version().SupportsClientConnectionIds()) {
9668 return;
9669 }
dschinazi346b7ce2019-06-05 01:38:18 -07009670 set_perspective(Perspective::IS_SERVER);
9671 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_INITIAL);
9672 header.source_connection_id = TestConnectionId(0x33);
9673 header.source_connection_id_included = CONNECTION_ID_PRESENT;
9674 QuicFrames frames;
9675 QuicPingFrame ping_frame;
9676 QuicPaddingFrame padding_frame;
9677 frames.push_back(QuicFrame(ping_frame));
9678 frames.push_back(QuicFrame(padding_frame));
9679 std::unique_ptr<QuicPacket> packet =
9680 BuildUnsizedDataPacket(&framer_, header, frames);
9681 char buffer[kMaxOutgoingPacketSize];
nharperc6b99512019-09-19 11:13:48 -07009682 size_t encrypted_length =
9683 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(1),
9684 *packet, buffer, kMaxOutgoingPacketSize);
dschinazi346b7ce2019-06-05 01:38:18 -07009685 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9686 false);
9687 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9688 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9689 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9690 EXPECT_EQ(TestConnectionId(0x33), connection_.client_connection_id());
9691}
9692
fayang40ec3ac2019-06-05 09:07:54 -07009693// Regression test for b/134416344.
9694TEST_P(QuicConnectionTest, CheckConnectedBeforeFlush) {
9695 // This test mimics a scenario where a connection processes 2 packets and the
9696 // 2nd packet contains connection close frame. When the 2nd flusher goes out
9697 // of scope, a delayed ACK is pending, and ACK alarm should not be scheduled
9698 // because connection is disconnected.
9699 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fkastenholz5d880a92019-06-21 09:01:56 -07009700 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
fayang40ec3ac2019-06-05 09:07:54 -07009701 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
fkastenholz88d08f42019-09-06 07:38:04 -07009702 const QuicErrorCode kErrorCode = QUIC_INTERNAL_ERROR;
fayang40ec3ac2019-06-05 09:07:54 -07009703 std::unique_ptr<QuicConnectionCloseFrame> connection_close_frame(
fkastenholz591814c2019-09-06 12:11:46 -07009704 new QuicConnectionCloseFrame(connection_.transport_version(), kErrorCode,
9705 "",
9706 /*transport_close_frame_type=*/0));
9707
fayang40ec3ac2019-06-05 09:07:54 -07009708 // Received 2 packets.
fayang40ec3ac2019-06-05 09:07:54 -07009709 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
fayang40ec3ac2019-06-05 09:07:54 -07009710 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9711 } else {
fayang40ec3ac2019-06-05 09:07:54 -07009712 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
9713 }
wub8a5dafa2020-05-13 12:30:17 -07009714 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
9715 kPeerAddress);
fayang9adfb532020-06-04 06:58:45 -07009716 EXPECT_TRUE(connection_.HasPendingAcks());
wub8a5dafa2020-05-13 12:30:17 -07009717 ProcessFramePacketWithAddresses(QuicFrame(connection_close_frame.release()),
fayang40ec3ac2019-06-05 09:07:54 -07009718 kSelfAddress, kPeerAddress);
fayang0f0c4e62019-07-16 08:55:54 -07009719 // Verify ack alarm is not set.
fayang9adfb532020-06-04 06:58:45 -07009720 EXPECT_FALSE(connection_.HasPendingAcks());
fayang40ec3ac2019-06-05 09:07:54 -07009721}
9722
dschinazi8d551132019-08-02 19:17:16 -07009723// Verify that a packet containing three coalesced packets is parsed correctly.
9724TEST_P(QuicConnectionTest, CoalescedPacket) {
9725 if (!QuicVersionHasLongHeaderLengths(connection_.transport_version())) {
9726 // Coalesced packets can only be encoded using long header lengths.
9727 return;
9728 }
9729 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9730 EXPECT_TRUE(connection_.connected());
9731 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9732 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(3);
9733 } else {
9734 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(3);
9735 }
9736
9737 uint64_t packet_numbers[3] = {1, 2, 3};
9738 EncryptionLevel encryption_levels[3] = {
9739 ENCRYPTION_INITIAL, ENCRYPTION_INITIAL, ENCRYPTION_FORWARD_SECURE};
9740 char buffer[kMaxOutgoingPacketSize] = {};
9741 size_t total_encrypted_length = 0;
9742 for (int i = 0; i < 3; i++) {
9743 QuicPacketHeader header =
9744 ConstructPacketHeader(packet_numbers[i], encryption_levels[i]);
9745 QuicFrames frames;
9746 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9747 frames.push_back(QuicFrame(&crypto_frame_));
9748 } else {
9749 frames.push_back(QuicFrame(frame1_));
9750 }
9751 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
9752 peer_creator_.set_encryption_level(encryption_levels[i]);
9753 size_t encrypted_length = peer_framer_.EncryptPayload(
9754 encryption_levels[i], QuicPacketNumber(packet_numbers[i]), *packet,
9755 buffer + total_encrypted_length,
9756 sizeof(buffer) - total_encrypted_length);
9757 EXPECT_GT(encrypted_length, 0u);
9758 total_encrypted_length += encrypted_length;
9759 }
9760 connection_.ProcessUdpPacket(
9761 kSelfAddress, kPeerAddress,
9762 QuicReceivedPacket(buffer, total_encrypted_length, clock_.Now(), false));
9763 if (connection_.GetSendAlarm()->IsSet()) {
9764 connection_.GetSendAlarm()->Fire();
9765 }
9766
9767 EXPECT_TRUE(connection_.connected());
9768}
9769
dschinazi66fc0242019-08-16 10:00:25 -07009770// Regression test for crbug.com/992831.
9771TEST_P(QuicConnectionTest, CoalescedPacketThatSavesFrames) {
9772 if (!QuicVersionHasLongHeaderLengths(connection_.transport_version())) {
9773 // Coalesced packets can only be encoded using long header lengths.
9774 return;
9775 }
9776 if (connection_.SupportsMultiplePacketNumberSpaces()) {
9777 // TODO(b/129151114) Enable this test with multiple packet number spaces.
9778 return;
9779 }
9780 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9781 EXPECT_TRUE(connection_.connected());
9782 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9783 EXPECT_CALL(visitor_, OnCryptoFrame(_))
9784 .Times(3)
9785 .WillRepeatedly([this](const QuicCryptoFrame& /*frame*/) {
9786 // QuicFrame takes ownership of the QuicBlockedFrame.
9787 connection_.SendControlFrame(QuicFrame(new QuicBlockedFrame(1, 3)));
9788 });
9789 } else {
9790 EXPECT_CALL(visitor_, OnStreamFrame(_))
9791 .Times(3)
9792 .WillRepeatedly([this](const QuicStreamFrame& /*frame*/) {
9793 // QuicFrame takes ownership of the QuicBlockedFrame.
9794 connection_.SendControlFrame(QuicFrame(new QuicBlockedFrame(1, 3)));
9795 });
9796 }
9797
9798 uint64_t packet_numbers[3] = {1, 2, 3};
9799 EncryptionLevel encryption_levels[3] = {
9800 ENCRYPTION_INITIAL, ENCRYPTION_INITIAL, ENCRYPTION_FORWARD_SECURE};
9801 char buffer[kMaxOutgoingPacketSize] = {};
9802 size_t total_encrypted_length = 0;
9803 for (int i = 0; i < 3; i++) {
9804 QuicPacketHeader header =
9805 ConstructPacketHeader(packet_numbers[i], encryption_levels[i]);
9806 QuicFrames frames;
9807 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9808 frames.push_back(QuicFrame(&crypto_frame_));
9809 } else {
9810 frames.push_back(QuicFrame(frame1_));
9811 }
9812 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
9813 peer_creator_.set_encryption_level(encryption_levels[i]);
9814 size_t encrypted_length = peer_framer_.EncryptPayload(
9815 encryption_levels[i], QuicPacketNumber(packet_numbers[i]), *packet,
9816 buffer + total_encrypted_length,
9817 sizeof(buffer) - total_encrypted_length);
9818 EXPECT_GT(encrypted_length, 0u);
9819 total_encrypted_length += encrypted_length;
9820 }
9821 connection_.ProcessUdpPacket(
9822 kSelfAddress, kPeerAddress,
9823 QuicReceivedPacket(buffer, total_encrypted_length, clock_.Now(), false));
9824 if (connection_.GetSendAlarm()->IsSet()) {
9825 connection_.GetSendAlarm()->Fire();
9826 }
9827
9828 EXPECT_TRUE(connection_.connected());
9829
9830 SendAckPacketToPeer();
9831}
9832
fayangd3016832019-08-08 07:24:45 -07009833// Regresstion test for b/138962304.
9834TEST_P(QuicConnectionTest, RtoAndWriteBlocked) {
fayangd3016832019-08-08 07:24:45 -07009835 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9836
9837 QuicStreamId stream_id = 2;
9838 QuicPacketNumber last_data_packet;
9839 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
9840 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9841
9842 // Writer gets blocked.
9843 writer_->SetWriteBlocked();
9844
9845 // Cancel the stream.
9846 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9847 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
fayang67f82272019-08-14 16:08:45 -07009848 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
9849 .WillRepeatedly(
9850 Invoke(&notifier_, &SimpleSessionNotifier::WillingToWrite));
fayangd3016832019-08-08 07:24:45 -07009851 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9852
9853 // Retransmission timer fires in RTO mode.
9854 connection_.GetRetransmissionAlarm()->Fire();
9855 // Verify no packets get flushed when writer is blocked.
9856 EXPECT_EQ(0u, connection_.NumQueuedPackets());
9857}
9858
9859// Regresstion test for b/138962304.
9860TEST_P(QuicConnectionTest, TlpAndWriteBlocked) {
fayangd3016832019-08-08 07:24:45 -07009861 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9862 connection_.SetMaxTailLossProbes(1);
9863
9864 QuicStreamId stream_id = 2;
9865 QuicPacketNumber last_data_packet;
9866 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
9867 SendStreamDataToPeer(4, "foo", 0, NO_FIN, &last_data_packet);
9868 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9869
9870 // Writer gets blocked.
9871 writer_->SetWriteBlocked();
9872
9873 // Cancel stream 2.
9874 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9875 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
9876 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9877
fayange62e63c2019-12-04 07:16:25 -08009878 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
fayangd3016832019-08-08 07:24:45 -07009879 // Retransmission timer fires in TLP mode.
9880 connection_.GetRetransmissionAlarm()->Fire();
9881 // Verify one packets is forced flushed when writer is blocked.
9882 EXPECT_EQ(1u, connection_.NumQueuedPackets());
9883}
9884
fayang67f82272019-08-14 16:08:45 -07009885// Regresstion test for b/139375344.
9886TEST_P(QuicConnectionTest, RtoForcesSendingPing) {
fayangcff885a2019-10-22 07:39:04 -07009887 if (connection_.PtoEnabled()) {
fayang67f82272019-08-14 16:08:45 -07009888 return;
9889 }
9890 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9891 connection_.SetMaxTailLossProbes(2);
9892 EXPECT_EQ(0u, connection_.GetStats().tlp_count);
9893 EXPECT_EQ(0u, connection_.GetStats().rto_count);
9894
9895 SendStreamDataToPeer(2, "foo", 0, NO_FIN, nullptr);
9896 QuicTime retransmission_time =
9897 connection_.GetRetransmissionAlarm()->deadline();
9898 EXPECT_NE(QuicTime::Zero(), retransmission_time);
9899 // TLP fires.
9900 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
9901 clock_.AdvanceTime(retransmission_time - clock_.Now());
9902 connection_.GetRetransmissionAlarm()->Fire();
9903 EXPECT_EQ(1u, connection_.GetStats().tlp_count);
9904 EXPECT_EQ(0u, connection_.GetStats().rto_count);
9905 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9906
9907 // Packet 1 gets acked.
9908 QuicAckFrame frame = InitAckFrame(1);
9909 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
9910 ProcessAckPacket(1, &frame);
9911 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9912 retransmission_time = connection_.GetRetransmissionAlarm()->deadline();
9913
9914 // RTO fires, verify a PING packet gets sent because there is no data to send.
9915 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(3), _, _));
9916 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
9917 clock_.AdvanceTime(retransmission_time - clock_.Now());
9918 connection_.GetRetransmissionAlarm()->Fire();
9919 EXPECT_EQ(1u, connection_.GetStats().tlp_count);
9920 EXPECT_EQ(1u, connection_.GetStats().rto_count);
9921 EXPECT_EQ(1u, writer_->ping_frames().size());
9922}
9923
fayangce0a3162019-08-15 09:05:36 -07009924TEST_P(QuicConnectionTest, ProbeTimeout) {
fayangce0a3162019-08-15 09:05:36 -07009925 QuicConfig config;
9926 QuicTagVector connection_options;
9927 connection_options.push_back(k2PTO);
9928 config.SetConnectionOptionsToSend(connection_options);
9929 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9930 connection_.SetFromConfig(config);
9931 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9932
9933 QuicStreamId stream_id = 2;
9934 QuicPacketNumber last_packet;
9935 SendStreamDataToPeer(stream_id, "foooooo", 0, NO_FIN, &last_packet);
9936 SendStreamDataToPeer(stream_id, "foooooo", 7, NO_FIN, &last_packet);
9937 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9938
9939 // Reset stream.
9940 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9941 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9942
9943 // Fire the PTO and verify only the RST_STREAM is resent, not stream data.
9944 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9945 connection_.GetRetransmissionAlarm()->Fire();
9946 EXPECT_EQ(0u, writer_->stream_frames().size());
9947 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
9948 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9949}
9950
fayang97ce41e2019-10-07 08:37:29 -07009951TEST_P(QuicConnectionTest, CloseConnectionAfter6ClientPTOs) {
fayang97ce41e2019-10-07 08:37:29 -07009952 QuicConfig config;
9953 QuicTagVector connection_options;
9954 connection_options.push_back(k1PTO);
9955 connection_options.push_back(k6PTO);
9956 config.SetConnectionOptionsToSend(connection_options);
dschinazif7c6a912020-05-05 11:39:53 -07009957 QuicConfigPeer::SetNegotiated(&config, true);
dschinazie7c38a52020-05-29 15:25:45 -07009958 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
9959 QuicConfigPeer::SetReceivedOriginalConnectionId(
9960 &config, connection_.connection_id());
9961 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
9962 &config, connection_.connection_id());
9963 }
fayang97ce41e2019-10-07 08:37:29 -07009964 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9965 connection_.SetFromConfig(config);
fayang656cbb52020-06-09 13:29:35 -07009966 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangaa4f3f22020-06-05 16:22:00 -07009967 EXPECT_CALL(visitor_, GetHandshakeState())
9968 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
9969 }
fayang97ce41e2019-10-07 08:37:29 -07009970 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9971
9972 // Send stream data.
9973 SendStreamDataToPeer(
9974 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
9975 0, FIN, nullptr);
9976
fayang97ce41e2019-10-07 08:37:29 -07009977 // Fire the retransmission alarm 5 times.
9978 for (int i = 0; i < 5; ++i) {
ianswett825b48b2020-05-11 06:25:04 -07009979 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
fayang97ce41e2019-10-07 08:37:29 -07009980 connection_.GetRetransmissionAlarm()->Fire();
9981 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
9982 EXPECT_TRUE(connection_.connected());
9983 }
fayang2205d952020-05-12 13:45:56 -07009984 EXPECT_CALL(visitor_, OnPathDegrading());
9985 connection_.PathDegradingTimeout();
fayang97ce41e2019-10-07 08:37:29 -07009986
9987 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveTlpCount());
9988 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveRtoCount());
9989 EXPECT_EQ(5u, connection_.sent_packet_manager().GetConsecutivePtoCount());
9990 // Closes connection on 6th PTO.
ianswett825b48b2020-05-11 06:25:04 -07009991 // May send multiple connecction close packets with multiple PN spaces.
9992 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
fayang97ce41e2019-10-07 08:37:29 -07009993 EXPECT_CALL(visitor_,
9994 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
fayang2205d952020-05-12 13:45:56 -07009995 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
9996 connection_.GetBlackholeDetectorAlarm()->Fire();
fayang97ce41e2019-10-07 08:37:29 -07009997 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
9998 EXPECT_FALSE(connection_.connected());
9999 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
10000}
10001
fayangce0a3162019-08-15 09:05:36 -070010002TEST_P(QuicConnectionTest, CloseConnectionAfter7ClientPTOs) {
fayangce0a3162019-08-15 09:05:36 -070010003 QuicConfig config;
10004 QuicTagVector connection_options;
10005 connection_options.push_back(k2PTO);
10006 connection_options.push_back(k7PTO);
10007 config.SetConnectionOptionsToSend(connection_options);
dschinazif7c6a912020-05-05 11:39:53 -070010008 QuicConfigPeer::SetNegotiated(&config, true);
dschinazie7c38a52020-05-29 15:25:45 -070010009 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
10010 QuicConfigPeer::SetReceivedOriginalConnectionId(
10011 &config, connection_.connection_id());
10012 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
10013 &config, connection_.connection_id());
10014 }
fayangce0a3162019-08-15 09:05:36 -070010015 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10016 connection_.SetFromConfig(config);
fayang656cbb52020-06-09 13:29:35 -070010017 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangaa4f3f22020-06-05 16:22:00 -070010018 EXPECT_CALL(visitor_, GetHandshakeState())
10019 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
10020 }
fayangce0a3162019-08-15 09:05:36 -070010021 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
10022
10023 // Send stream data.
10024 SendStreamDataToPeer(
10025 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
10026 0, FIN, nullptr);
10027
10028 // Fire the retransmission alarm 6 times.
10029 for (int i = 0; i < 6; ++i) {
10030 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
10031 connection_.GetRetransmissionAlarm()->Fire();
10032 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
10033 EXPECT_TRUE(connection_.connected());
10034 }
fayang2205d952020-05-12 13:45:56 -070010035 EXPECT_CALL(visitor_, OnPathDegrading());
10036 connection_.PathDegradingTimeout();
fayangce0a3162019-08-15 09:05:36 -070010037
10038 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveTlpCount());
10039 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveRtoCount());
10040 EXPECT_EQ(6u, connection_.sent_packet_manager().GetConsecutivePtoCount());
10041 // Closes connection on 7th PTO.
10042 EXPECT_CALL(visitor_,
10043 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -070010044 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
fayang2205d952020-05-12 13:45:56 -070010045 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
10046 connection_.GetBlackholeDetectorAlarm()->Fire();
fayangce0a3162019-08-15 09:05:36 -070010047 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
10048 EXPECT_FALSE(connection_.connected());
10049 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
10050}
10051
10052TEST_P(QuicConnectionTest, CloseConnectionAfter8ClientPTOs) {
fayangce0a3162019-08-15 09:05:36 -070010053 QuicConfig config;
10054 QuicTagVector connection_options;
10055 connection_options.push_back(k2PTO);
10056 connection_options.push_back(k8PTO);
dschinazif7c6a912020-05-05 11:39:53 -070010057 QuicConfigPeer::SetNegotiated(&config, true);
dschinazie7c38a52020-05-29 15:25:45 -070010058 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
10059 QuicConfigPeer::SetReceivedOriginalConnectionId(
10060 &config, connection_.connection_id());
10061 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
10062 &config, connection_.connection_id());
10063 }
fayangce0a3162019-08-15 09:05:36 -070010064 config.SetConnectionOptionsToSend(connection_options);
10065 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10066 connection_.SetFromConfig(config);
fayang656cbb52020-06-09 13:29:35 -070010067 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangaa4f3f22020-06-05 16:22:00 -070010068 EXPECT_CALL(visitor_, GetHandshakeState())
10069 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
10070 }
fayangce0a3162019-08-15 09:05:36 -070010071 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
10072
10073 // Send stream data.
10074 SendStreamDataToPeer(
10075 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
10076 0, FIN, nullptr);
10077
10078 // Fire the retransmission alarm 7 times.
10079 for (int i = 0; i < 7; ++i) {
10080 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
10081 connection_.GetRetransmissionAlarm()->Fire();
10082 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
10083 EXPECT_TRUE(connection_.connected());
10084 }
fayang2205d952020-05-12 13:45:56 -070010085 EXPECT_CALL(visitor_, OnPathDegrading());
10086 connection_.PathDegradingTimeout();
fayangce0a3162019-08-15 09:05:36 -070010087
10088 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveTlpCount());
10089 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveRtoCount());
10090 EXPECT_EQ(7u, connection_.sent_packet_manager().GetConsecutivePtoCount());
10091 // Closes connection on 8th PTO.
10092 EXPECT_CALL(visitor_,
10093 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -070010094 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
fayang2205d952020-05-12 13:45:56 -070010095 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
10096 connection_.GetBlackholeDetectorAlarm()->Fire();
fayangce0a3162019-08-15 09:05:36 -070010097 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
10098 EXPECT_FALSE(connection_.connected());
10099 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
10100}
10101
fayang5f135052019-08-22 17:59:40 -070010102TEST_P(QuicConnectionTest, DeprecateHandshakeMode) {
10103 if (!connection_.version().SupportsAntiAmplificationLimit()) {
10104 return;
10105 }
10106 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10107 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
10108
10109 // Send CHLO.
10110 connection_.SendCryptoStreamData();
10111 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
10112
10113 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
10114 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
10115 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
10116 QuicAckFrame frame1 = InitAckFrame(1);
10117 // Received ACK for packet 1.
10118 ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL);
10119
10120 // Verify retransmission alarm is still set because handshake is not
10121 // confirmed although there is nothing in flight.
10122 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
10123 EXPECT_EQ(0u, connection_.GetStats().pto_count);
10124 EXPECT_EQ(0u, connection_.GetStats().crypto_retransmit_count);
10125
10126 // PTO fires, verify a PING packet gets sent because there is no data to send.
fayang5d011982020-05-13 14:14:38 -070010127 EXPECT_CALL(*send_algorithm_,
10128 OnPacketSent(_, _,
10129 GetQuicReloadableFlag(quic_default_on_pto)
10130 ? QuicPacketNumber(2)
10131 : QuicPacketNumber(3),
10132 _, _));
fayang5f135052019-08-22 17:59:40 -070010133 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
10134 connection_.GetRetransmissionAlarm()->Fire();
10135 EXPECT_EQ(1u, connection_.GetStats().pto_count);
fayangaf9903b2020-05-14 14:34:28 -070010136 EXPECT_EQ(1u, connection_.GetStats().crypto_retransmit_count);
fayang5f135052019-08-22 17:59:40 -070010137 EXPECT_EQ(1u, writer_->ping_frames().size());
10138}
10139
10140TEST_P(QuicConnectionTest, AntiAmplificationLimit) {
10141 if (!connection_.version().SupportsAntiAmplificationLimit()) {
10142 return;
10143 }
fayang5f135052019-08-22 17:59:40 -070010144 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10145
10146 set_perspective(Perspective::IS_SERVER);
10147 // Verify no data can be sent at the beginning because bytes received is 0.
10148 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
10149 connection_.SendCryptoDataWithString("foo", 0);
fayang6a258412020-05-28 08:57:12 -070010150 if (GetQuicReloadableFlag(quic_move_amplification_limit)) {
10151 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
10152 EXPECT_FALSE(connection_.CanWrite(NO_RETRANSMITTABLE_DATA));
10153 }
fayang5f135052019-08-22 17:59:40 -070010154 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
10155
10156 // Receives packet 1.
10157 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
10158
10159 const size_t anti_amplification_factor =
fayang6a258412020-05-28 08:57:12 -070010160 connection_.anti_amplification_factor();
fayang5f135052019-08-22 17:59:40 -070010161 // Verify now packets can be sent.
10162 for (size_t i = 0; i < anti_amplification_factor; ++i) {
10163 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10164 connection_.SendCryptoDataWithString("foo", i * 3);
10165 // Verify retransmission alarm is not set if throttled by anti-amplification
10166 // limit.
10167 EXPECT_EQ(i != anti_amplification_factor - 1,
10168 connection_.GetRetransmissionAlarm()->IsSet());
10169 }
10170 // Verify server is throttled by anti-amplification limit.
10171 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
10172 connection_.SendCryptoDataWithString("foo", anti_amplification_factor * 3);
10173
10174 // Receives packet 2.
10175 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
10176 // Verify more packets can be sent.
10177 for (size_t i = anti_amplification_factor; i < anti_amplification_factor * 2;
10178 ++i) {
10179 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10180 connection_.SendCryptoDataWithString("foo", i * 3);
10181 }
10182 // Verify server is throttled by anti-amplification limit.
10183 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
10184 connection_.SendCryptoDataWithString("foo",
10185 2 * anti_amplification_factor * 3);
10186
10187 ProcessPacket(3);
10188 // Verify anti-amplification limit is gone after address validation.
10189 for (size_t i = 0; i < 100; ++i) {
10190 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10191 connection_.SendStreamDataWithString(3, "first", i * 0, NO_FIN);
10192 }
10193}
10194
fayang6a258412020-05-28 08:57:12 -070010195TEST_P(QuicConnectionTest, AckPendingWithAmplificationLimited) {
10196 if (!connection_.version().SupportsAntiAmplificationLimit() ||
10197 !GetQuicReloadableFlag(quic_move_amplification_limit)) {
10198 return;
10199 }
10200 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10201 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(AnyNumber());
10202 set_perspective(Perspective::IS_SERVER);
10203 use_tagging_decrypter();
10204 connection_.SetEncrypter(ENCRYPTION_INITIAL,
10205 std::make_unique<TaggingEncrypter>(0x01));
10206 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10207 // Receives packet 1.
10208 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
10209 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10210 std::make_unique<TaggingEncrypter>(0x02));
10211 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
fayang9adfb532020-06-04 06:58:45 -070010212 EXPECT_TRUE(connection_.HasPendingAcks());
fayang6a258412020-05-28 08:57:12 -070010213 // Send response in different encryption level and cause amplification factor
10214 // throttled.
10215 size_t i = 0;
10216 while (connection_.CanWrite(HAS_RETRANSMITTABLE_DATA)) {
10217 connection_.SendCryptoDataWithString(std::string(1024, 'a'), i * 1024,
10218 ENCRYPTION_HANDSHAKE);
10219 ++i;
10220 }
10221 // Verify ACK is still pending.
fayang9adfb532020-06-04 06:58:45 -070010222 EXPECT_TRUE(connection_.HasPendingAcks());
fayang6a258412020-05-28 08:57:12 -070010223
10224 // Fire ACK alarm and verify ACK cannot be sent due to amplification factor.
10225 clock_.AdvanceTime(connection_.GetAckAlarm()->deadline() - clock_.Now());
10226 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
10227 connection_.GetAckAlarm()->Fire();
10228 // Verify ACK alarm is cancelled.
fayang9adfb532020-06-04 06:58:45 -070010229 EXPECT_FALSE(connection_.HasPendingAcks());
fayang6a258412020-05-28 08:57:12 -070010230
10231 // Receives packet 2 and verify ACK gets flushed.
10232 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10233 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
10234 EXPECT_FALSE(writer_->ack_frames().empty());
10235}
10236
fkastenholza3660102019-08-28 05:19:24 -070010237TEST_P(QuicConnectionTest, ConnectionCloseFrameType) {
10238 if (!VersionHasIetfQuicFrames(version().transport_version)) {
10239 // Test relevent only for IETF QUIC.
10240 return;
10241 }
10242 const QuicErrorCode kQuicErrorCode = IETF_QUIC_PROTOCOL_VIOLATION;
10243 // Use the (unknown) frame type of 9999 to avoid triggering any logic
10244 // which might be associated with the processing of a known frame type.
10245 const uint64_t kTransportCloseFrameType = 9999u;
10246 QuicFramerPeer::set_current_received_frame_type(
10247 QuicConnectionPeer::GetFramer(&connection_), kTransportCloseFrameType);
10248 // Do a transport connection close
10249 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10250 connection_.CloseConnection(
10251 kQuicErrorCode, "Some random error message",
10252 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10253 const std::vector<QuicConnectionCloseFrame>& connection_close_frames =
10254 writer_->connection_close_frames();
10255 ASSERT_EQ(1u, connection_close_frames.size());
10256 EXPECT_EQ(IETF_QUIC_TRANSPORT_CONNECTION_CLOSE,
10257 connection_close_frames[0].close_type);
bnc77e77b82020-04-05 10:36:49 -070010258 EXPECT_EQ(kQuicErrorCode, connection_close_frames[0].quic_error_code);
fkastenholza3660102019-08-28 05:19:24 -070010259 EXPECT_EQ(kTransportCloseFrameType,
10260 connection_close_frames[0].transport_close_frame_type);
10261}
10262
fayang0fcbf352019-08-30 11:15:58 -070010263// Regression test for b/137401387 and b/138962304.
10264TEST_P(QuicConnectionTest, RtoPacketAsTwo) {
fayangcff885a2019-10-22 07:39:04 -070010265 if (connection_.PtoEnabled()) {
fayang0fcbf352019-08-30 11:15:58 -070010266 return;
10267 }
10268 connection_.SetMaxTailLossProbes(1);
10269 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10270 std::string stream_data(3000, 's');
10271 // Send packets 1 - 66 and exhaust cwnd.
10272 for (size_t i = 0; i < 22; ++i) {
10273 // 3 packets for each stream, the first 2 are guaranteed to be full packets.
10274 SendStreamDataToPeer(i + 2, stream_data, 0, FIN, nullptr);
10275 }
10276 CongestionBlockWrites();
10277
10278 // Fires TLP. Please note, this tail loss probe has 1 byte less stream data
10279 // compared to packet 1 because packet number length increases.
10280 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(67), _, _));
10281 connection_.GetRetransmissionAlarm()->Fire();
10282 // Fires RTO. Please note, although packets 2 and 3 *should* be RTOed, but
10283 // packet 2 gets RTOed to two packets because packet number length increases.
10284 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(68), _, _));
10285 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(69), _, _));
10286 connection_.GetRetransmissionAlarm()->Fire();
10287
10288 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10289 // Resets all streams except 2 and ack packets 1 and 2. Now, packet 3 is the
10290 // only one containing retransmittable frames.
10291 for (size_t i = 1; i < 22; ++i) {
10292 notifier_.OnStreamReset(i + 2, QUIC_STREAM_CANCELLED);
10293 }
10294 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
10295 QuicAckFrame frame =
10296 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(3)}});
10297 ProcessAckPacket(1, &frame);
10298 CongestionUnblockWrites();
10299
10300 // Fires TLP, verify a PING gets sent because packet 3 is marked
10301 // RTO_RETRANSMITTED.
10302 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(70), _, _));
10303 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
10304 connection_.GetRetransmissionAlarm()->Fire();
10305}
10306
fayang4c1c2362019-09-13 07:20:01 -070010307TEST_P(QuicConnectionTest, PtoSkipsPacketNumber) {
fayang4c1c2362019-09-13 07:20:01 -070010308 QuicConfig config;
10309 QuicTagVector connection_options;
10310 connection_options.push_back(k1PTO);
10311 connection_options.push_back(kPTOS);
10312 config.SetConnectionOptionsToSend(connection_options);
10313 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10314 connection_.SetFromConfig(config);
10315 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
10316
10317 QuicStreamId stream_id = 2;
10318 QuicPacketNumber last_packet;
10319 SendStreamDataToPeer(stream_id, "foooooo", 0, NO_FIN, &last_packet);
10320 SendStreamDataToPeer(stream_id, "foooooo", 7, NO_FIN, &last_packet);
10321 EXPECT_EQ(QuicPacketNumber(2), last_packet);
10322 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
10323
10324 // Fire PTO and verify the PTO retransmission skips one packet number.
10325 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10326 connection_.GetRetransmissionAlarm()->Fire();
10327 EXPECT_EQ(1u, writer_->stream_frames().size());
10328 EXPECT_EQ(QuicPacketNumber(4), writer_->last_packet_header().packet_number);
10329 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
10330}
10331
fayang58f71072019-11-05 08:47:02 -080010332TEST_P(QuicConnectionTest, SendCoalescedPackets) {
10333 if (!connection_.version().CanSendCoalescedPackets()) {
10334 return;
10335 }
fayang6100ab72020-03-18 13:16:25 -070010336 MockQuicConnectionDebugVisitor debug_visitor;
10337 connection_.set_debug_visitor(&debug_visitor);
10338 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(3);
10339 EXPECT_CALL(debug_visitor, OnCoalescedPacketSent(_, _)).Times(1);
fayang44ae4e92020-04-28 13:09:42 -070010340 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
fayang58f71072019-11-05 08:47:02 -080010341 {
10342 QuicConnection::ScopedPacketFlusher flusher(&connection_);
10343 use_tagging_decrypter();
10344 connection_.SetEncrypter(ENCRYPTION_INITIAL,
10345 std::make_unique<TaggingEncrypter>(0x01));
10346 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10347 connection_.SendCryptoDataWithString("foo", 0);
10348 // Verify this packet is on hold.
10349 EXPECT_EQ(0u, writer_->packets_write_attempts());
10350
10351 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10352 std::make_unique<TaggingEncrypter>(0x02));
10353 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10354 connection_.SendCryptoDataWithString("bar", 3);
10355 EXPECT_EQ(0u, writer_->packets_write_attempts());
10356
10357 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
10358 std::make_unique<TaggingEncrypter>(0x03));
10359 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10360 SendStreamDataToPeer(2, "baz", 3, NO_FIN, nullptr);
10361 }
10362 // Verify all 3 packets are coalesced in the same UDP datagram.
10363 EXPECT_EQ(1u, writer_->packets_write_attempts());
10364 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
10365 // Verify the packet is padded to full.
10366 EXPECT_EQ(connection_.max_packet_length(), writer_->last_packet_size());
10367
10368 // Verify packet process.
10369 EXPECT_EQ(1u, writer_->crypto_frames().size());
10370 EXPECT_EQ(0u, writer_->stream_frames().size());
10371 // Verify there is coalesced packet.
10372 EXPECT_NE(nullptr, writer_->coalesced_packet());
10373}
10374
fayang01062942020-01-22 07:23:23 -080010375TEST_P(QuicConnectionTest, ClientReceivedHandshakeDone) {
10376 if (!connection_.version().HasHandshakeDone()) {
10377 return;
10378 }
10379 EXPECT_CALL(visitor_, OnHandshakeDoneReceived());
10380 QuicFrames frames;
10381 frames.push_back(QuicFrame(QuicHandshakeDoneFrame()));
10382 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10383 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10384}
10385
10386TEST_P(QuicConnectionTest, ServerReceivedHandshakeDone) {
10387 if (!connection_.version().HasHandshakeDone()) {
10388 return;
10389 }
10390 set_perspective(Perspective::IS_SERVER);
10391 EXPECT_CALL(visitor_, OnHandshakeDoneReceived()).Times(0);
10392 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10393 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
10394 QuicFrames frames;
10395 frames.push_back(QuicFrame(QuicHandshakeDoneFrame()));
10396 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10397 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10398 EXPECT_EQ(1, connection_close_frame_count_);
10399 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
10400 IsError(IETF_QUIC_PROTOCOL_VIOLATION));
10401}
10402
fayang18ff23b2020-01-28 09:19:00 -080010403TEST_P(QuicConnectionTest, MultiplePacketNumberSpacePto) {
10404 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10405 return;
10406 }
10407 use_tagging_decrypter();
10408 // Send handshake packet.
10409 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10410 std::make_unique<TaggingEncrypter>(0x02));
10411 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
fayang44ae4e92020-04-28 13:09:42 -070010412 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
fayang18ff23b2020-01-28 09:19:00 -080010413 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
10414 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
10415
10416 // Send application data.
10417 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
10418 0, NO_FIN);
10419 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
10420 QuicTime retransmission_time =
10421 connection_.GetRetransmissionAlarm()->deadline();
10422 EXPECT_NE(QuicTime::Zero(), retransmission_time);
10423
10424 // Retransmit handshake data.
10425 clock_.AdvanceTime(retransmission_time - clock_.Now());
fayang5d011982020-05-13 14:14:38 -070010426 EXPECT_CALL(*send_algorithm_,
10427 OnPacketSent(_, _,
10428 GetQuicReloadableFlag(quic_default_on_pto)
10429 ? QuicPacketNumber(3)
10430 : QuicPacketNumber(4),
10431 _, _));
fayang44ae4e92020-04-28 13:09:42 -070010432 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
fayang18ff23b2020-01-28 09:19:00 -080010433 connection_.GetRetransmissionAlarm()->Fire();
10434 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
10435
10436 // Send application data.
10437 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
10438 4, NO_FIN);
10439 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
10440 retransmission_time = connection_.GetRetransmissionAlarm()->deadline();
10441 EXPECT_NE(QuicTime::Zero(), retransmission_time);
10442
10443 // Retransmit handshake data again.
10444 clock_.AdvanceTime(retransmission_time - clock_.Now());
fayang5d011982020-05-13 14:14:38 -070010445 EXPECT_CALL(*send_algorithm_,
10446 OnPacketSent(_, _,
10447 GetQuicReloadableFlag(quic_default_on_pto)
10448 ? QuicPacketNumber(5)
10449 : QuicPacketNumber(7),
10450 _, _));
fayang44ae4e92020-04-28 13:09:42 -070010451 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
fayang18ff23b2020-01-28 09:19:00 -080010452 connection_.GetRetransmissionAlarm()->Fire();
10453 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
10454
10455 // Discard handshake key.
10456 connection_.OnHandshakeComplete();
10457 retransmission_time = connection_.GetRetransmissionAlarm()->deadline();
10458 EXPECT_NE(QuicTime::Zero(), retransmission_time);
10459
10460 // Retransmit application data.
10461 clock_.AdvanceTime(retransmission_time - clock_.Now());
fayang5d011982020-05-13 14:14:38 -070010462 EXPECT_CALL(*send_algorithm_,
10463 OnPacketSent(_, _,
10464 GetQuicReloadableFlag(quic_default_on_pto)
10465 ? QuicPacketNumber(6)
10466 : QuicPacketNumber(9),
10467 _, _));
fayang18ff23b2020-01-28 09:19:00 -080010468 connection_.GetRetransmissionAlarm()->Fire();
10469 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
10470}
10471
dschinazie7c38a52020-05-29 15:25:45 -070010472void QuicConnectionTest::TestClientRetryHandling(
10473 bool invalid_retry_tag,
10474 bool missing_original_id_in_config,
10475 bool wrong_original_id_in_config,
10476 bool missing_retry_id_in_config,
10477 bool wrong_retry_id_in_config) {
dschinazi39e5e552020-05-06 13:55:24 -070010478 if (invalid_retry_tag) {
dschinazie7c38a52020-05-29 15:25:45 -070010479 ASSERT_FALSE(missing_original_id_in_config);
10480 ASSERT_FALSE(wrong_original_id_in_config);
10481 ASSERT_FALSE(missing_retry_id_in_config);
10482 ASSERT_FALSE(wrong_retry_id_in_config);
dschinazi39e5e552020-05-06 13:55:24 -070010483 } else {
dschinazie7c38a52020-05-29 15:25:45 -070010484 ASSERT_FALSE(missing_original_id_in_config && wrong_original_id_in_config);
10485 ASSERT_FALSE(missing_retry_id_in_config && wrong_retry_id_in_config);
dschinazi39e5e552020-05-06 13:55:24 -070010486 }
dschinazi278efae2020-01-28 17:03:09 -080010487 if (!version().HasRetryIntegrityTag()) {
10488 return;
10489 }
dschinazi39e5e552020-05-06 13:55:24 -070010490
10491 // These values come from draft-ietf-quic-tls Appendix A.4.
10492 char retry_packet25[] = {
10493 0xff, 0xff, 0x00, 0x00, 0x19, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a,
10494 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x1e, 0x5e, 0xc5, 0xb0,
10495 0x14, 0xcb, 0xb1, 0xf0, 0xfd, 0x93, 0xdf, 0x40, 0x48, 0xc4, 0x46, 0xa6};
10496 char retry_packet27[] = {
10497 0xff, 0xff, 0x00, 0x00, 0x1b, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a,
10498 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0xa5, 0x23, 0xcb, 0x5b,
10499 0xa5, 0x24, 0x69, 0x5f, 0x65, 0x69, 0xf2, 0x93, 0xa1, 0x35, 0x9d, 0x8e};
dschinazi2c78aac2020-05-21 17:21:58 -070010500 char retry_packet28[] = {
10501 0xff, 0xff, 0x00, 0x00, 0x1c, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a,
10502 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0xf7, 0x1a, 0x5f, 0x12,
10503 0xaf, 0xe3, 0xec, 0xf8, 0x00, 0x1a, 0x92, 0x0e, 0x6f, 0xdf, 0x1d, 0x63};
dschinazib3fed9e2020-06-11 11:59:33 -070010504 char retry_packet29[] = {
10505 0xff, 0xff, 0x00, 0x00, 0x1d, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a,
10506 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0xd1, 0x69, 0x26, 0xd8,
10507 0x1f, 0x6f, 0x9c, 0xa2, 0x95, 0x3a, 0x8a, 0xa4, 0x57, 0x5e, 0x1e, 0x49};
dschinazi39e5e552020-05-06 13:55:24 -070010508
10509 char* retry_packet;
10510 size_t retry_packet_length;
dschinazib3fed9e2020-06-11 11:59:33 -070010511 if (version() == ParsedQuicVersion::Draft29()) {
10512 retry_packet = retry_packet29;
10513 retry_packet_length = QUICHE_ARRAYSIZE(retry_packet29);
10514 } else if (version() == ParsedQuicVersion::Draft28()) {
dschinazi2c78aac2020-05-21 17:21:58 -070010515 retry_packet = retry_packet28;
10516 retry_packet_length = QUICHE_ARRAYSIZE(retry_packet28);
dschinazib3fed9e2020-06-11 11:59:33 -070010517 } else if (version() == ParsedQuicVersion::Draft27()) {
dschinazi39e5e552020-05-06 13:55:24 -070010518 retry_packet = retry_packet27;
10519 retry_packet_length = QUICHE_ARRAYSIZE(retry_packet27);
dschinazib3fed9e2020-06-11 11:59:33 -070010520 } else if (version() == ParsedQuicVersion::Draft25()) {
dschinazi39e5e552020-05-06 13:55:24 -070010521 retry_packet = retry_packet25;
10522 retry_packet_length = QUICHE_ARRAYSIZE(retry_packet25);
10523 } else {
dschinazi278efae2020-01-28 17:03:09 -080010524 // TODO(dschinazi) generate retry packets for all versions once we have
10525 // server-side support for generating these programmatically.
10526 return;
10527 }
10528
dschinazi278efae2020-01-28 17:03:09 -080010529 char original_connection_id_bytes[] = {0x83, 0x94, 0xc8, 0xf0,
10530 0x3e, 0x51, 0x57, 0x08};
10531 char new_connection_id_bytes[] = {0xf0, 0x67, 0xa5, 0x50,
10532 0x2a, 0x42, 0x62, 0xb5};
10533 char retry_token_bytes[] = {0x74, 0x6f, 0x6b, 0x65, 0x6e};
10534
10535 QuicConnectionId original_connection_id(
10536 original_connection_id_bytes,
10537 QUICHE_ARRAYSIZE(original_connection_id_bytes));
10538 QuicConnectionId new_connection_id(new_connection_id_bytes,
10539 QUICHE_ARRAYSIZE(new_connection_id_bytes));
10540
10541 std::string retry_token(retry_token_bytes,
10542 QUICHE_ARRAYSIZE(retry_token_bytes));
10543
dschinazi39e5e552020-05-06 13:55:24 -070010544 if (invalid_retry_tag) {
10545 // Flip the last bit of the retry packet to prevent the integrity tag
10546 // from validating correctly.
10547 retry_packet[retry_packet_length - 1] ^= 1;
dschinazi278efae2020-01-28 17:03:09 -080010548 }
10549
dschinazi39e5e552020-05-06 13:55:24 -070010550 QuicConnectionId config_original_connection_id = original_connection_id;
dschinazie7c38a52020-05-29 15:25:45 -070010551 if (wrong_original_id_in_config) {
dschinazi39e5e552020-05-06 13:55:24 -070010552 // Flip the first bit of the connection ID.
10553 ASSERT_FALSE(config_original_connection_id.IsEmpty());
10554 config_original_connection_id.mutable_data()[0] ^= 0x80;
10555 }
dschinazie7c38a52020-05-29 15:25:45 -070010556 QuicConnectionId config_retry_source_connection_id = new_connection_id;
10557 if (wrong_retry_id_in_config) {
10558 // Flip the first bit of the connection ID.
10559 ASSERT_FALSE(config_retry_source_connection_id.IsEmpty());
10560 config_retry_source_connection_id.mutable_data()[0] ^= 0x80;
10561 }
dschinazi278efae2020-01-28 17:03:09 -080010562
dschinazi39e5e552020-05-06 13:55:24 -070010563 // Make sure the connection uses the connection ID from the test vectors,
10564 QuicConnectionPeer::SetServerConnectionId(&connection_,
10565 original_connection_id);
dschinazi278efae2020-01-28 17:03:09 -080010566
dschinazi39e5e552020-05-06 13:55:24 -070010567 // Process the RETRY packet.
10568 connection_.ProcessUdpPacket(
10569 kSelfAddress, kPeerAddress,
10570 QuicReceivedPacket(retry_packet, retry_packet_length, clock_.Now()));
10571
10572 if (invalid_retry_tag) {
10573 // Make sure we refuse to process a RETRY with invalid tag.
10574 EXPECT_FALSE(connection_.GetStats().retry_packet_processed);
10575 EXPECT_EQ(connection_.connection_id(), original_connection_id);
dschinazi278efae2020-01-28 17:03:09 -080010576 EXPECT_TRUE(QuicPacketCreatorPeer::GetRetryToken(
dschinazi39e5e552020-05-06 13:55:24 -070010577 QuicConnectionPeer::GetPacketCreator(&connection_))
dschinazi278efae2020-01-28 17:03:09 -080010578 .empty());
dschinazi39e5e552020-05-06 13:55:24 -070010579 return;
dschinazi278efae2020-01-28 17:03:09 -080010580 }
dschinazi39e5e552020-05-06 13:55:24 -070010581
10582 // Make sure we correctly parsed the RETRY.
10583 EXPECT_TRUE(connection_.GetStats().retry_packet_processed);
10584 EXPECT_EQ(connection_.connection_id(), new_connection_id);
10585 EXPECT_EQ(QuicPacketCreatorPeer::GetRetryToken(
10586 QuicConnectionPeer::GetPacketCreator(&connection_)),
10587 retry_token);
10588 // Make sure our fake framer has the new post-retry INITIAL keys.
10589 writer_->framer()->framer()->SetInitialObfuscators(new_connection_id);
10590
10591 // Test validating the original_connection_id from the config.
10592 QuicConfig received_config;
10593 QuicConfigPeer::SetNegotiated(&received_config, true);
dschinazie7c38a52020-05-29 15:25:45 -070010594 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
10595 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
10596 &received_config, connection_.connection_id());
10597 if (!missing_retry_id_in_config) {
10598 QuicConfigPeer::SetReceivedRetrySourceConnectionId(
10599 &received_config, config_retry_source_connection_id);
10600 }
10601 }
10602 if (!missing_original_id_in_config) {
dschinazi39e5e552020-05-06 13:55:24 -070010603 QuicConfigPeer::SetReceivedOriginalConnectionId(
10604 &received_config, config_original_connection_id);
10605 }
dschinazie7c38a52020-05-29 15:25:45 -070010606
10607 if (missing_original_id_in_config || wrong_original_id_in_config ||
10608 missing_retry_id_in_config || wrong_retry_id_in_config) {
dschinazi39e5e552020-05-06 13:55:24 -070010609 EXPECT_CALL(visitor_,
10610 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10611 .Times(1);
10612 } else {
10613 EXPECT_CALL(visitor_,
10614 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10615 .Times(0);
10616 }
10617 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
10618 connection_.SetFromConfig(received_config);
dschinazie7c38a52020-05-29 15:25:45 -070010619 if (missing_original_id_in_config || wrong_original_id_in_config ||
10620 missing_retry_id_in_config || wrong_retry_id_in_config) {
10621 ASSERT_FALSE(connection_.connected());
dschinazi39e5e552020-05-06 13:55:24 -070010622 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
10623 } else {
10624 EXPECT_TRUE(connection_.connected());
10625 }
10626}
10627
10628TEST_P(QuicConnectionTest, ClientParsesRetry) {
10629 TestClientRetryHandling(/*invalid_retry_tag=*/false,
dschinazie7c38a52020-05-29 15:25:45 -070010630 /*missing_original_id_in_config=*/false,
10631 /*wrong_original_id_in_config=*/false,
10632 /*missing_retry_id_in_config=*/false,
10633 /*wrong_retry_id_in_config=*/false);
dschinazi39e5e552020-05-06 13:55:24 -070010634}
10635
dschinazie7c38a52020-05-29 15:25:45 -070010636TEST_P(QuicConnectionTest, ClientParsesRetryInvalidTag) {
dschinazi39e5e552020-05-06 13:55:24 -070010637 TestClientRetryHandling(/*invalid_retry_tag=*/true,
dschinazie7c38a52020-05-29 15:25:45 -070010638 /*missing_original_id_in_config=*/false,
10639 /*wrong_original_id_in_config=*/false,
10640 /*missing_retry_id_in_config=*/false,
10641 /*wrong_retry_id_in_config=*/false);
dschinazi39e5e552020-05-06 13:55:24 -070010642}
10643
dschinazie7c38a52020-05-29 15:25:45 -070010644TEST_P(QuicConnectionTest, ClientParsesRetryMissingOriginalId) {
dschinazi39e5e552020-05-06 13:55:24 -070010645 TestClientRetryHandling(/*invalid_retry_tag=*/false,
dschinazie7c38a52020-05-29 15:25:45 -070010646 /*missing_original_id_in_config=*/true,
10647 /*wrong_original_id_in_config=*/false,
10648 /*missing_retry_id_in_config=*/false,
10649 /*wrong_retry_id_in_config=*/false);
dschinazi39e5e552020-05-06 13:55:24 -070010650}
10651
dschinazie7c38a52020-05-29 15:25:45 -070010652TEST_P(QuicConnectionTest, ClientParsesRetryWrongOriginalId) {
dschinazi39e5e552020-05-06 13:55:24 -070010653 TestClientRetryHandling(/*invalid_retry_tag=*/false,
dschinazie7c38a52020-05-29 15:25:45 -070010654 /*missing_original_id_in_config=*/false,
10655 /*wrong_original_id_in_config=*/true,
10656 /*missing_retry_id_in_config=*/false,
10657 /*wrong_retry_id_in_config=*/false);
10658}
10659
10660TEST_P(QuicConnectionTest, ClientParsesRetryMissingRetryId) {
10661 if (!connection_.version().AuthenticatesHandshakeConnectionIds()) {
10662 // Versions that do not authenticate connection IDs never send the
10663 // retry_source_connection_id transport parameter.
10664 return;
10665 }
10666 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10667 /*missing_original_id_in_config=*/false,
10668 /*wrong_original_id_in_config=*/false,
10669 /*missing_retry_id_in_config=*/true,
10670 /*wrong_retry_id_in_config=*/false);
10671}
10672
10673TEST_P(QuicConnectionTest, ClientParsesRetryWrongRetryId) {
10674 if (!connection_.version().AuthenticatesHandshakeConnectionIds()) {
10675 // Versions that do not authenticate connection IDs never send the
10676 // retry_source_connection_id transport parameter.
10677 return;
10678 }
10679 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10680 /*missing_original_id_in_config=*/false,
10681 /*wrong_original_id_in_config=*/false,
10682 /*missing_retry_id_in_config=*/false,
10683 /*wrong_retry_id_in_config=*/true);
dschinazi39e5e552020-05-06 13:55:24 -070010684}
10685
10686TEST_P(QuicConnectionTest, ClientReceivesOriginalConnectionIdWithoutRetry) {
dschinazie7c38a52020-05-29 15:25:45 -070010687 if (!connection_.version().UsesTls()) {
10688 // QUIC+TLS is required to transmit connection ID transport parameters.
10689 return;
10690 }
10691 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
10692 // Versions that authenticate connection IDs always send the
10693 // original_destination_connection_id transport parameter.
10694 return;
10695 }
10696 // Make sure that receiving the original_destination_connection_id transport
10697 // parameter fails the handshake when no RETRY packet was received before it.
dschinazi39e5e552020-05-06 13:55:24 -070010698 QuicConfig received_config;
10699 QuicConfigPeer::SetNegotiated(&received_config, true);
10700 QuicConfigPeer::SetReceivedOriginalConnectionId(&received_config,
10701 TestConnectionId(0x12345));
10702 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
10703 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10704 .Times(1);
10705 connection_.SetFromConfig(received_config);
10706 EXPECT_FALSE(connection_.connected());
10707 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
dschinazi278efae2020-01-28 17:03:09 -080010708}
10709
dschinazie7c38a52020-05-29 15:25:45 -070010710TEST_P(QuicConnectionTest, ClientReceivesRetrySourceConnectionIdWithoutRetry) {
10711 if (!connection_.version().AuthenticatesHandshakeConnectionIds()) {
10712 // Versions that do not authenticate connection IDs never send the
10713 // retry_source_connection_id transport parameter.
10714 return;
10715 }
10716 // Make sure that receiving the retry_source_connection_id transport parameter
10717 // fails the handshake when no RETRY packet was received before it.
10718 QuicConfig received_config;
10719 QuicConfigPeer::SetNegotiated(&received_config, true);
10720 QuicConfigPeer::SetReceivedRetrySourceConnectionId(&received_config,
10721 TestConnectionId(0x12345));
10722 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
10723 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10724 .Times(1);
10725 connection_.SetFromConfig(received_config);
10726 EXPECT_FALSE(connection_.connected());
10727 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
10728}
10729
fayang0e3035e2020-02-03 13:30:36 -080010730// Regression test for http://crbug/1047977
10731TEST_P(QuicConnectionTest, MaxStreamsFrameCausesConnectionClose) {
10732 if (!VersionHasIetfQuicFrames(connection_.transport_version())) {
10733 return;
10734 }
10735 // Received frame causes connection close.
10736 EXPECT_CALL(visitor_, OnMaxStreamsFrame(_))
10737 .WillOnce(InvokeWithoutArgs([this]() {
10738 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10739 connection_.CloseConnection(
10740 QUIC_TOO_MANY_BUFFERED_CONTROL_FRAMES, "error",
10741 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10742 return true;
10743 }));
10744 QuicFrames frames;
10745 frames.push_back(QuicFrame(QuicMaxStreamsFrame()));
10746 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10747 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10748}
10749
10750TEST_P(QuicConnectionTest, StreamsBlockedFrameCausesConnectionClose) {
10751 if (!VersionHasIetfQuicFrames(connection_.transport_version())) {
10752 return;
10753 }
10754 // Received frame causes connection close.
10755 EXPECT_CALL(visitor_, OnStreamsBlockedFrame(_))
10756 .WillOnce(InvokeWithoutArgs([this]() {
10757 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10758 connection_.CloseConnection(
10759 QUIC_TOO_MANY_BUFFERED_CONTROL_FRAMES, "error",
10760 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10761 return true;
10762 }));
10763 QuicFrames frames;
10764 frames.push_back(
10765 QuicFrame(QuicStreamsBlockedFrame(kInvalidControlFrameId, 10, false)));
10766 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10767 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10768}
10769
fayang79400d52020-02-13 10:13:05 -080010770TEST_P(QuicConnectionTest,
10771 BundleAckWithConnectionCloseMultiplePacketNumberSpace) {
10772 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10773 return;
10774 }
10775 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10776 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10777 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
10778 // Receives packet 1000 in initial data.
10779 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
10780 // Receives packet 2000 in application data.
10781 ProcessDataPacketAtLevel(2000, false, ENCRYPTION_FORWARD_SECURE);
10782 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10783 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
10784 connection_.CloseConnection(
10785 kQuicErrorCode, "Some random error message",
10786 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10787
10788 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
10789
10790 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
10791 EXPECT_EQ(1u, writer_->connection_close_frames().size());
10792 // Verify ack is bundled.
10793 EXPECT_EQ(1u, writer_->ack_frames().size());
10794
10795 if (!connection_.version().CanSendCoalescedPackets()) {
10796 // Each connection close packet should be sent in distinct UDP packets.
10797 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
10798 writer_->connection_close_packets());
10799 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
10800 writer_->packets_write_attempts());
10801 return;
10802 }
10803
10804 // A single UDP packet should be sent with multiple connection close packets
10805 // coalesced together.
10806 EXPECT_EQ(1u, writer_->packets_write_attempts());
10807
10808 // Only the first packet has been processed yet.
10809 EXPECT_EQ(1u, writer_->connection_close_packets());
10810
10811 // ProcessPacket resets the visitor and frees the coalesced packet.
10812 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
10813 auto packet = writer_->coalesced_packet()->Clone();
10814 writer_->framer()->ProcessPacket(*packet);
10815 EXPECT_EQ(1u, writer_->connection_close_packets());
10816 EXPECT_EQ(1u, writer_->connection_close_frames().size());
10817 // Verify ack is bundled.
10818 EXPECT_EQ(1u, writer_->ack_frames().size());
10819 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
10820}
10821
fayang61453cb2020-03-11 11:32:26 -070010822// Regression test for b/151220135.
10823TEST_P(QuicConnectionTest, SendPingWhenSkipPacketNumberForPto) {
10824 if (!VersionSupportsMessageFrames(connection_.transport_version())) {
10825 return;
10826 }
10827 QuicConfig config;
10828 QuicTagVector connection_options;
10829 connection_options.push_back(kPTOS);
10830 connection_options.push_back(k1PTO);
10831 config.SetConnectionOptionsToSend(connection_options);
dschinazied459c02020-05-07 16:12:23 -070010832 if (connection_.version().UsesTls()) {
10833 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
10834 &config, kMaxAcceptedDatagramFrameSize);
10835 }
fayang61453cb2020-03-11 11:32:26 -070010836 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10837 connection_.SetFromConfig(config);
10838 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
10839
10840 EXPECT_EQ(MESSAGE_STATUS_SUCCESS, SendMessage("message"));
10841 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
10842
fayang80f9cc62020-04-22 08:08:20 -070010843 // PTO fires, verify a PING packet gets sent because there is no data to
10844 // send.
10845 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(3), _, _));
10846 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
fayang61453cb2020-03-11 11:32:26 -070010847 connection_.GetRetransmissionAlarm()->Fire();
fayang80f9cc62020-04-22 08:08:20 -070010848 EXPECT_EQ(1u, connection_.GetStats().pto_count);
10849 EXPECT_EQ(0u, connection_.GetStats().crypto_retransmit_count);
10850 EXPECT_EQ(1u, writer_->ping_frames().size());
fayang61453cb2020-03-11 11:32:26 -070010851}
10852
fayangcc210e72020-05-05 14:41:34 -070010853// Regression test for b/155757133
10854TEST_P(QuicConnectionTest, DonotChangeQueuedAcks) {
10855 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10856 return;
10857 }
10858 const size_t kMinRttMs = 40;
10859 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
10860 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
10861 QuicTime::Delta::Zero(), QuicTime::Zero());
10862 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10863 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
10864 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10865
10866 ProcessPacket(2);
10867 ProcessPacket(3);
10868 ProcessPacket(4);
10869 // Process a packet containing stream frame followed by ACK of packets 1.
10870 QuicFrames frames;
10871 frames.push_back(QuicFrame(QuicStreamFrame(
10872 QuicUtils::GetFirstBidirectionalStreamId(
10873 connection_.version().transport_version, Perspective::IS_CLIENT),
10874 false, 0u, quiche::QuicheStringPiece())));
10875 QuicAckFrame ack_frame = InitAckFrame(1);
10876 frames.push_back(QuicFrame(&ack_frame));
10877 // Receiving stream frame causes something to send.
10878 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([this]() {
10879 connection_.SendControlFrame(QuicFrame(new QuicWindowUpdateFrame(1, 0, 0)));
10880 // Verify now the queued ACK contains packet number 2.
10881 EXPECT_TRUE(QuicPacketCreatorPeer::QueuedFrames(
10882 QuicConnectionPeer::GetPacketCreator(&connection_))[0]
10883 .ack_frame->packets.Contains(QuicPacketNumber(2)));
10884 }));
10885 ProcessFramesPacketAtLevel(9, frames, ENCRYPTION_FORWARD_SECURE);
10886 if (GetQuicReloadableFlag(quic_donot_change_queued_ack)) {
10887 EXPECT_TRUE(writer_->ack_frames()[0].packets.Contains(QuicPacketNumber(2)));
10888 } else {
10889 // ACK frame changes mid packet serialiation!
10890 EXPECT_FALSE(
10891 writer_->ack_frames()[0].packets.Contains(QuicPacketNumber(2)));
10892 }
10893}
10894
fayange9304002020-05-07 11:57:48 -070010895TEST_P(QuicConnectionTest, DonotExtendIdleTimeOnUndecryptablePackets) {
10896 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10897 QuicConfig config;
10898 connection_.SetFromConfig(config);
10899 // Subtract a second from the idle timeout on the client side.
10900 QuicTime initial_deadline =
10901 clock_.ApproximateNow() +
10902 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
10903 EXPECT_EQ(initial_deadline, connection_.GetTimeoutAlarm()->deadline());
10904
10905 // Received an undecryptable packet.
10906 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
10907 const uint8_t tag = 0x07;
10908 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
10909 std::make_unique<TaggingEncrypter>(tag));
10910 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
fayang2205d952020-05-12 13:45:56 -070010911 if (GetQuicReloadableFlag(quic_extend_idle_time_on_decryptable_packets)) {
fayange9304002020-05-07 11:57:48 -070010912 // Verify deadline does not get extended.
10913 EXPECT_EQ(initial_deadline, connection_.GetTimeoutAlarm()->deadline());
10914 }
10915 if (GetQuicReloadableFlag(quic_extend_idle_time_on_decryptable_packets)) {
10916 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
10917 } else {
10918 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
10919 }
10920 QuicTime::Delta delay = initial_deadline - clock_.ApproximateNow();
10921 clock_.AdvanceTime(delay);
fayang2205d952020-05-12 13:45:56 -070010922 if (GetQuicReloadableFlag(quic_extend_idle_time_on_decryptable_packets)) {
fayange9304002020-05-07 11:57:48 -070010923 connection_.GetTimeoutAlarm()->Fire();
10924 }
10925 if (GetQuicReloadableFlag(quic_extend_idle_time_on_decryptable_packets)) {
10926 // Verify connection gets closed.
10927 EXPECT_FALSE(connection_.connected());
10928 } else {
10929 // Verify the timeout alarm deadline is updated.
10930 EXPECT_TRUE(connection_.connected());
10931 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
10932 }
10933}
10934
fayang9f430a52020-05-08 07:28:33 -070010935TEST_P(QuicConnectionTest, BundleAckWithImmediateResponse) {
10936 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10937 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10938
10939 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([this]() {
10940 connection_.SendControlFrame(QuicFrame(new QuicWindowUpdateFrame(1, 0, 0)));
10941 }));
10942 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10943 ProcessDataPacket(1);
fayang9f430a52020-05-08 07:28:33 -070010944 if (GetQuicReloadableFlag(quic_advance_ack_timeout_update)) {
10945 // Verify ACK is bundled with WINDOW_UPDATE.
10946 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -070010947 EXPECT_FALSE(connection_.HasPendingAcks());
fayang9f430a52020-05-08 07:28:33 -070010948 } else {
10949 // ACK is pending.
10950 EXPECT_TRUE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -070010951 EXPECT_TRUE(connection_.HasPendingAcks());
fayang9f430a52020-05-08 07:28:33 -070010952 }
10953}
10954
fayangf44a6672020-05-27 12:51:45 -070010955TEST_P(QuicConnectionTest, AckAlarmFiresEarly) {
10956 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10957 return;
10958 }
10959 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10960 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
10961 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10962 }
10963 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
10964 use_tagging_decrypter();
10965 // Receives packet 1000 in initial data.
10966 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
fayang9adfb532020-06-04 06:58:45 -070010967 EXPECT_TRUE(connection_.HasPendingAcks());
fayangf44a6672020-05-27 12:51:45 -070010968
10969 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
10970 std::make_unique<TaggingEncrypter>(0x02));
10971 SetDecrypter(ENCRYPTION_ZERO_RTT,
10972 std::make_unique<StrictTaggingDecrypter>(0x02));
10973 connection_.SetEncrypter(ENCRYPTION_INITIAL,
10974 std::make_unique<TaggingEncrypter>(0x02));
10975 // Receives packet 1000 in application data.
10976 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
fayang9adfb532020-06-04 06:58:45 -070010977 EXPECT_TRUE(connection_.HasPendingAcks());
fayangf44a6672020-05-27 12:51:45 -070010978 // Verify ACK deadline does not change.
10979 EXPECT_EQ(clock_.ApproximateNow() + kAlarmGranularity,
10980 connection_.GetAckAlarm()->deadline());
10981
10982 // Ack alarm fires early.
10983 if (GetQuicReloadableFlag(quic_always_send_earliest_ack)) {
10984 // Verify the earliest ACK is flushed.
10985 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10986 } else {
10987 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
10988 }
10989 connection_.GetAckAlarm()->Fire();
fayang9adfb532020-06-04 06:58:45 -070010990 EXPECT_TRUE(connection_.HasPendingAcks());
fayangf44a6672020-05-27 12:51:45 -070010991 if (GetQuicReloadableFlag(quic_always_send_earliest_ack)) {
10992 EXPECT_EQ(clock_.ApproximateNow() + DefaultDelayedAckTime(),
10993 connection_.GetAckAlarm()->deadline());
10994 } else {
10995 // No forward progress has been made.
10996 EXPECT_EQ(clock_.ApproximateNow() + kAlarmGranularity,
10997 connection_.GetAckAlarm()->deadline());
10998 }
10999}
11000
fayangf78b6932020-06-08 08:36:45 -070011001TEST_P(QuicConnectionTest, ClientOnlyBlackholeDetectionClient) {
fayang656cbb52020-06-09 13:29:35 -070011002 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangf78b6932020-06-08 08:36:45 -070011003 return;
11004 }
11005 QuicConfig config;
11006 QuicTagVector connection_options;
11007 connection_options.push_back(kCBHD);
11008 config.SetConnectionOptionsToSend(connection_options);
11009 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11010 connection_.SetFromConfig(config);
11011 EXPECT_CALL(visitor_, GetHandshakeState())
11012 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
11013 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
11014 // Send stream data.
11015 SendStreamDataToPeer(
11016 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
11017 0, FIN, nullptr);
11018 // Verify blackhole detection is in progress.
11019 EXPECT_TRUE(connection_.GetBlackholeDetectorAlarm()->IsSet());
11020}
11021
11022TEST_P(QuicConnectionTest, ClientOnlyBlackholeDetectionServer) {
fayang656cbb52020-06-09 13:29:35 -070011023 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangf78b6932020-06-08 08:36:45 -070011024 return;
11025 }
11026 set_perspective(Perspective::IS_SERVER);
11027 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
11028 if (version().SupportsAntiAmplificationLimit()) {
11029 QuicConnectionPeer::SetAddressValidated(&connection_);
11030 }
11031 QuicConfig config;
11032 QuicTagVector connection_options;
11033 connection_options.push_back(kCBHD);
11034 config.SetInitialReceivedConnectionOptions(connection_options);
11035 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11036 connection_.SetFromConfig(config);
11037 EXPECT_CALL(visitor_, GetHandshakeState())
11038 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
11039 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
11040 // Send stream data.
11041 SendStreamDataToPeer(
11042 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
11043 0, FIN, nullptr);
11044 // Verify blackhole detection is disabled.
11045 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
11046}
11047
11048TEST_P(QuicConnectionTest, 2RtoBlackholeDetection) {
fayang656cbb52020-06-09 13:29:35 -070011049 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangf78b6932020-06-08 08:36:45 -070011050 return;
11051 }
11052 QuicConfig config;
11053 QuicTagVector connection_options;
11054 connection_options.push_back(k2RTO);
11055 config.SetConnectionOptionsToSend(connection_options);
11056 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11057 connection_.SetFromConfig(config);
11058 const size_t kMinRttMs = 40;
11059 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
11060 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
11061 QuicTime::Delta::Zero(), QuicTime::Zero());
11062 EXPECT_CALL(visitor_, GetHandshakeState())
11063 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
11064 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
11065 // Send stream data.
11066 SendStreamDataToPeer(
11067 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
11068 0, FIN, nullptr);
11069 // Verify blackhole delay is expected.
11070 EXPECT_EQ(clock_.Now() +
11071 connection_.sent_packet_manager().GetNetworkBlackholeDelay(2),
11072 QuicConnectionPeer::GetBlackholeDetectionDeadline(&connection_));
11073}
11074
11075TEST_P(QuicConnectionTest, 3RtoBlackholeDetection) {
fayang656cbb52020-06-09 13:29:35 -070011076 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangf78b6932020-06-08 08:36:45 -070011077 return;
11078 }
11079 QuicConfig config;
11080 QuicTagVector connection_options;
11081 connection_options.push_back(k3RTO);
11082 config.SetConnectionOptionsToSend(connection_options);
11083 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11084 connection_.SetFromConfig(config);
11085 const size_t kMinRttMs = 40;
11086 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
11087 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
11088 QuicTime::Delta::Zero(), QuicTime::Zero());
11089 EXPECT_CALL(visitor_, GetHandshakeState())
11090 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
11091 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
11092 // Send stream data.
11093 SendStreamDataToPeer(
11094 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
11095 0, FIN, nullptr);
11096 // Verify blackhole delay is expected.
11097 EXPECT_EQ(clock_.Now() +
11098 connection_.sent_packet_manager().GetNetworkBlackholeDelay(3),
11099 QuicConnectionPeer::GetBlackholeDetectionDeadline(&connection_));
11100}
11101
11102TEST_P(QuicConnectionTest, 4RtoBlackholeDetection) {
fayang656cbb52020-06-09 13:29:35 -070011103 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangf78b6932020-06-08 08:36:45 -070011104 return;
11105 }
11106 QuicConfig config;
11107 QuicTagVector connection_options;
11108 connection_options.push_back(k4RTO);
11109 config.SetConnectionOptionsToSend(connection_options);
11110 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11111 connection_.SetFromConfig(config);
11112 const size_t kMinRttMs = 40;
11113 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
11114 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
11115 QuicTime::Delta::Zero(), QuicTime::Zero());
11116 EXPECT_CALL(visitor_, GetHandshakeState())
11117 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
11118 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
11119 // Send stream data.
11120 SendStreamDataToPeer(
11121 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
11122 0, FIN, nullptr);
11123 // Verify blackhole delay is expected.
11124 EXPECT_EQ(clock_.Now() +
11125 connection_.sent_packet_manager().GetNetworkBlackholeDelay(4),
11126 QuicConnectionPeer::GetBlackholeDetectionDeadline(&connection_));
11127}
11128
11129TEST_P(QuicConnectionTest, 6RtoBlackholeDetection) {
fayang656cbb52020-06-09 13:29:35 -070011130 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangf78b6932020-06-08 08:36:45 -070011131 return;
11132 }
11133 QuicConfig config;
11134 QuicTagVector connection_options;
11135 connection_options.push_back(k6RTO);
11136 config.SetConnectionOptionsToSend(connection_options);
11137 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11138 connection_.SetFromConfig(config);
11139 const size_t kMinRttMs = 40;
11140 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
11141 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
11142 QuicTime::Delta::Zero(), QuicTime::Zero());
11143 EXPECT_CALL(visitor_, GetHandshakeState())
11144 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
11145 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
11146 // Send stream data.
11147 SendStreamDataToPeer(
11148 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
11149 0, FIN, nullptr);
11150 // Verify blackhole delay is expected.
11151 EXPECT_EQ(clock_.Now() +
11152 connection_.sent_packet_manager().GetNetworkBlackholeDelay(6),
11153 QuicConnectionPeer::GetBlackholeDetectionDeadline(&connection_));
11154}
11155
fayang656cbb52020-06-09 13:29:35 -070011156// Regresstion test for b/158491591.
11157TEST_P(QuicConnectionTest, MadeForwardProgressOnDiscardingKeys) {
11158 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
11159 return;
11160 }
11161 use_tagging_decrypter();
11162 // Send handshake packet.
11163 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
11164 std::make_unique<TaggingEncrypter>(0x02));
11165 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11166 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
11167 QuicConfig config;
11168 QuicTagVector connection_options;
11169 connection_options.push_back(k5RTO);
11170 config.SetConnectionOptionsToSend(connection_options);
11171 QuicConfigPeer::SetNegotiated(&config, true);
11172 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
11173 EXPECT_CALL(visitor_, GetHandshakeState())
11174 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
11175 }
11176 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
11177 QuicConfigPeer::SetReceivedOriginalConnectionId(
11178 &config, connection_.connection_id());
11179 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
11180 &config, connection_.connection_id());
11181 }
11182 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11183 connection_.SetFromConfig(config);
11184
11185 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
11186 EXPECT_TRUE(connection_.BlackholeDetectionInProgress());
11187 // Discard handshake keys.
11188 connection_.OnHandshakeComplete();
11189 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
11190 // Verify blackhole detection stops.
11191 EXPECT_FALSE(connection_.BlackholeDetectionInProgress());
11192 } else {
11193 // Problematic: although there is nothing in flight, blackhole detection is
11194 // still in progress.
11195 EXPECT_TRUE(connection_.BlackholeDetectionInProgress());
11196 }
11197}
11198
fayang750b54f2020-06-18 06:26:54 -070011199TEST_P(QuicConnectionTest, ProcessUndecryptablePacketsBasedOnEncryptionLevel) {
11200 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
11201 return;
11202 }
11203 // SetFromConfig is always called after construction from InitializeSession.
11204 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
11205 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11206 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(AnyNumber());
11207 QuicConfig config;
11208 connection_.SetFromConfig(config);
11209 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
11210 connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
11211 use_tagging_decrypter();
11212
11213 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
11214 std::make_unique<TaggingEncrypter>(0x01));
11215 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
11216 std::make_unique<TaggingEncrypter>(0x02));
11217
11218 for (uint64_t i = 1; i <= 3; ++i) {
11219 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
11220 }
11221 ProcessDataPacketAtLevel(4, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
11222 for (uint64_t j = 5; j <= 7; ++j) {
11223 ProcessDataPacketAtLevel(j, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
11224 }
11225 EXPECT_EQ(7u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
11226 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
11227 SetDecrypter(ENCRYPTION_HANDSHAKE,
11228 std::make_unique<StrictTaggingDecrypter>(0x01));
11229 EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
11230 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11231 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
11232 std::make_unique<TaggingEncrypter>(0x01));
11233 if (GetQuicReloadableFlag(quic_fix_undecryptable_packets)) {
11234 // Verify all ENCRYPTION_HANDSHAKE packets get processed.
11235 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(6);
11236 } else {
11237 // Verify packets before 4 get processed.
11238 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(3);
11239 }
11240 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
11241 EXPECT_EQ(4u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
11242
11243 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
11244 std::make_unique<StrictTaggingDecrypter>(0x02));
11245 EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
11246 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
11247 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
11248 std::make_unique<TaggingEncrypter>(0x02));
11249 if (GetQuicReloadableFlag(quic_fix_undecryptable_packets)) {
11250 // Verify the 1-RTT packet gets processed.
11251 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
11252 } else {
11253 // Verify all packets get processed.
11254 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(4);
11255 }
11256 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
11257 EXPECT_EQ(0u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
11258}
11259
fayang7d4b0172020-06-18 14:05:45 -070011260TEST_P(QuicConnectionTest, BundleInitialDataWithInitialAck) {
11261 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
11262 return;
11263 }
11264 set_perspective(Perspective::IS_SERVER);
11265 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
11266 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
11267 }
11268 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
11269 use_tagging_decrypter();
11270 // Receives packet 1000 in initial data.
11271 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
11272 EXPECT_TRUE(connection_.HasPendingAcks());
11273
11274 connection_.SetEncrypter(ENCRYPTION_INITIAL,
11275 std::make_unique<TaggingEncrypter>(0x01));
11276 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
11277 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
11278 QuicTime expected_pto_time =
11279 connection_.sent_packet_manager().GetRetransmissionTime();
11280
11281 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
11282 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
11283 std::make_unique<TaggingEncrypter>(0x02));
11284 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11285 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
11286 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
11287 // Verify PTO time does not change.
11288 EXPECT_EQ(expected_pto_time,
11289 connection_.sent_packet_manager().GetRetransmissionTime());
11290
11291 // Receives packet 1001 in initial data.
11292 ProcessCryptoPacketAtLevel(1001, ENCRYPTION_INITIAL);
11293 EXPECT_TRUE(connection_.HasPendingAcks());
11294 // Receives packet 1002 in initial data.
11295 ProcessCryptoPacketAtLevel(1002, ENCRYPTION_INITIAL);
11296 EXPECT_FALSE(writer_->ack_frames().empty());
11297 if (GetQuicReloadableFlag(quic_bundle_crypto_data_with_initial_ack)) {
11298 // Verify CRYPTO frame is bundled with INITIAL ACK.
11299 EXPECT_FALSE(writer_->crypto_frames().empty());
11300 // Verify PTO time changes.
11301 EXPECT_NE(expected_pto_time,
11302 connection_.sent_packet_manager().GetRetransmissionTime());
11303 } else {
11304 EXPECT_TRUE(writer_->crypto_frames().empty());
11305 // Verify PTO time does not change.
11306 EXPECT_EQ(expected_pto_time,
11307 connection_.sent_packet_manager().GetRetransmissionTime());
11308 }
11309}
11310
QUICHE teama6ef0a62019-03-07 20:34:33 -050011311} // namespace
11312} // namespace test
11313} // namespace quic