blob: b9f1fc55bb6a6e64e59ccb0968856ed3d9341070 [file] [log] [blame]
QUICHE teama6ef0a62019-03-07 20:34:33 -05001// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "net/third_party/quiche/src/quic/core/quic_connection.h"
6
7#include <errno.h>
zhongyi546cc452019-04-12 15:27:49 -07008
QUICHE teama6ef0a62019-03-07 20:34:33 -05009#include <memory>
10#include <ostream>
zhongyi9e843642019-04-12 09:04:54 -070011#include <string>
zhongyi546cc452019-04-12 15:27:49 -070012#include <utility>
zhongyi9e843642019-04-12 09:04:54 -070013
QUICHE teama6ef0a62019-03-07 20:34:33 -050014#include "net/third_party/quiche/src/quic/core/congestion_control/loss_detection_interface.h"
15#include "net/third_party/quiche/src/quic/core/congestion_control/send_algorithm_interface.h"
zhongyi546cc452019-04-12 15:27:49 -070016#include "net/third_party/quiche/src/quic/core/crypto/null_decrypter.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050017#include "net/third_party/quiche/src/quic/core/crypto/null_encrypter.h"
18#include "net/third_party/quiche/src/quic/core/crypto/quic_decrypter.h"
19#include "net/third_party/quiche/src/quic/core/crypto/quic_encrypter.h"
20#include "net/third_party/quiche/src/quic/core/quic_connection_id.h"
wub50d4c712020-05-19 15:48:28 -070021#include "net/third_party/quiche/src/quic/core/quic_constants.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050022#include "net/third_party/quiche/src/quic/core/quic_packets.h"
23#include "net/third_party/quiche/src/quic/core/quic_simple_buffer_allocator.h"
24#include "net/third_party/quiche/src/quic/core/quic_types.h"
25#include "net/third_party/quiche/src/quic/core/quic_utils.h"
dschinazi278efae2020-01-28 17:03:09 -080026#include "net/third_party/quiche/src/quic/core/quic_versions.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050027#include "net/third_party/quiche/src/quic/platform/api/quic_error_code_wrappers.h"
28#include "net/third_party/quiche/src/quic/platform/api/quic_expect_bug.h"
29#include "net/third_party/quiche/src/quic/platform/api/quic_flags.h"
30#include "net/third_party/quiche/src/quic/platform/api/quic_logging.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050031#include "net/third_party/quiche/src/quic/platform/api/quic_reference_counted.h"
renjietang5b245892020-05-18 11:57:26 -070032#include "net/third_party/quiche/src/quic/platform/api/quic_socket_address.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050033#include "net/third_party/quiche/src/quic/platform/api/quic_test.h"
34#include "net/third_party/quiche/src/quic/test_tools/mock_clock.h"
35#include "net/third_party/quiche/src/quic/test_tools/mock_random.h"
36#include "net/third_party/quiche/src/quic/test_tools/quic_config_peer.h"
37#include "net/third_party/quiche/src/quic/test_tools/quic_connection_peer.h"
38#include "net/third_party/quiche/src/quic/test_tools/quic_framer_peer.h"
39#include "net/third_party/quiche/src/quic/test_tools/quic_packet_creator_peer.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050040#include "net/third_party/quiche/src/quic/test_tools/quic_sent_packet_manager_peer.h"
41#include "net/third_party/quiche/src/quic/test_tools/quic_test_utils.h"
42#include "net/third_party/quiche/src/quic/test_tools/simple_data_producer.h"
43#include "net/third_party/quiche/src/quic/test_tools/simple_quic_framer.h"
44#include "net/third_party/quiche/src/quic/test_tools/simple_session_notifier.h"
dschinazi278efae2020-01-28 17:03:09 -080045#include "net/third_party/quiche/src/common/platform/api/quiche_arraysize.h"
dmcardlecf0bfcf2019-12-13 08:08:21 -080046#include "net/third_party/quiche/src/common/platform/api/quiche_str_cat.h"
47#include "net/third_party/quiche/src/common/platform/api/quiche_string_piece.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050048
49using testing::_;
50using testing::AnyNumber;
51using testing::AtLeast;
52using testing::DoAll;
QUICHE teama6ef0a62019-03-07 20:34:33 -050053using testing::Ge;
54using testing::IgnoreResult;
55using testing::InSequence;
56using testing::Invoke;
57using testing::InvokeWithoutArgs;
58using testing::Lt;
59using testing::Ref;
60using testing::Return;
61using testing::SaveArg;
62using testing::SetArgPointee;
63using testing::StrictMock;
64
65namespace quic {
66namespace test {
67namespace {
68
nharper55fa6132019-05-07 19:37:21 -070069const char data1[] = "foo data";
70const char data2[] = "bar data";
QUICHE teama6ef0a62019-03-07 20:34:33 -050071
72const bool kHasStopWaiting = true;
73
74const int kDefaultRetransmissionTimeMs = 500;
75
QUICHE team548d51b2019-03-14 10:06:54 -070076DiversificationNonce kTestDiversificationNonce = {
77 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a',
78 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b',
79 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b',
80};
81
QUICHE teama6ef0a62019-03-07 20:34:33 -050082const QuicSocketAddress kPeerAddress =
83 QuicSocketAddress(QuicIpAddress::Loopback6(),
84 /*port=*/12345);
85const QuicSocketAddress kSelfAddress =
86 QuicSocketAddress(QuicIpAddress::Loopback6(),
87 /*port=*/443);
88
QUICHE teama6ef0a62019-03-07 20:34:33 -050089QuicStreamId GetNthClientInitiatedStreamId(int n,
90 QuicTransportVersion version) {
dschinazi552accc2019-06-17 17:07:34 -070091 return QuicUtils::GetFirstBidirectionalStreamId(version,
92 Perspective::IS_CLIENT) +
93 n * 2;
QUICHE teama6ef0a62019-03-07 20:34:33 -050094}
95
QUICHE team8c1daa22019-03-13 08:33:41 -070096QuicLongHeaderType EncryptionlevelToLongHeaderType(EncryptionLevel level) {
97 switch (level) {
QUICHE team6987b4a2019-03-15 16:23:04 -070098 case ENCRYPTION_INITIAL:
QUICHE team8c1daa22019-03-13 08:33:41 -070099 return INITIAL;
QUICHE team88ea0082019-03-15 10:05:26 -0700100 case ENCRYPTION_HANDSHAKE:
101 return HANDSHAKE;
QUICHE team8c1daa22019-03-13 08:33:41 -0700102 case ENCRYPTION_ZERO_RTT:
103 return ZERO_RTT_PROTECTED;
104 case ENCRYPTION_FORWARD_SECURE:
105 DCHECK(false);
106 return INVALID_PACKET_TYPE;
107 default:
108 DCHECK(false);
109 return INVALID_PACKET_TYPE;
110 }
111}
112
QUICHE teama6ef0a62019-03-07 20:34:33 -0500113// TaggingEncrypter appends kTagSize bytes of |tag| to the end of each message.
114class TaggingEncrypter : public QuicEncrypter {
115 public:
116 explicit TaggingEncrypter(uint8_t tag) : tag_(tag) {}
117 TaggingEncrypter(const TaggingEncrypter&) = delete;
118 TaggingEncrypter& operator=(const TaggingEncrypter&) = delete;
119
120 ~TaggingEncrypter() override {}
121
122 // QuicEncrypter interface.
dmcardlecf0bfcf2019-12-13 08:08:21 -0800123 bool SetKey(quiche::QuicheStringPiece /*key*/) override { return true; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500124
dmcardlecf0bfcf2019-12-13 08:08:21 -0800125 bool SetNoncePrefix(quiche::QuicheStringPiece /*nonce_prefix*/) override {
dschinazi17d42422019-06-18 16:35:07 -0700126 return true;
127 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500128
dmcardlecf0bfcf2019-12-13 08:08:21 -0800129 bool SetIV(quiche::QuicheStringPiece /*iv*/) override { return true; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500130
dmcardlecf0bfcf2019-12-13 08:08:21 -0800131 bool SetHeaderProtectionKey(quiche::QuicheStringPiece /*key*/) override {
132 return true;
133 }
QUICHE team2d187972019-03-19 16:23:47 -0700134
dschinazi17d42422019-06-18 16:35:07 -0700135 bool EncryptPacket(uint64_t /*packet_number*/,
dmcardlecf0bfcf2019-12-13 08:08:21 -0800136 quiche::QuicheStringPiece /*associated_data*/,
137 quiche::QuicheStringPiece plaintext,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500138 char* output,
139 size_t* output_length,
140 size_t max_output_length) override {
141 const size_t len = plaintext.size() + kTagSize;
142 if (max_output_length < len) {
143 return false;
144 }
145 // Memmove is safe for inplace encryption.
146 memmove(output, plaintext.data(), plaintext.size());
147 output += plaintext.size();
148 memset(output, tag_, kTagSize);
149 *output_length = len;
150 return true;
151 }
152
dschinazi17d42422019-06-18 16:35:07 -0700153 std::string GenerateHeaderProtectionMask(
dmcardlecf0bfcf2019-12-13 08:08:21 -0800154 quiche::QuicheStringPiece /*sample*/) override {
QUICHE team2d187972019-03-19 16:23:47 -0700155 return std::string(5, 0);
156 }
157
QUICHE teama6ef0a62019-03-07 20:34:33 -0500158 size_t GetKeySize() const override { return 0; }
159 size_t GetNoncePrefixSize() const override { return 0; }
160 size_t GetIVSize() const override { return 0; }
161
162 size_t GetMaxPlaintextSize(size_t ciphertext_size) const override {
163 return ciphertext_size - kTagSize;
164 }
165
166 size_t GetCiphertextSize(size_t plaintext_size) const override {
167 return plaintext_size + kTagSize;
168 }
169
dmcardlecf0bfcf2019-12-13 08:08:21 -0800170 quiche::QuicheStringPiece GetKey() const override {
171 return quiche::QuicheStringPiece();
172 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500173
dmcardlecf0bfcf2019-12-13 08:08:21 -0800174 quiche::QuicheStringPiece GetNoncePrefix() const override {
175 return quiche::QuicheStringPiece();
176 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500177
178 private:
179 enum {
180 kTagSize = 12,
181 };
182
183 const uint8_t tag_;
184};
185
186// TaggingDecrypter ensures that the final kTagSize bytes of the message all
187// have the same value and then removes them.
188class TaggingDecrypter : public QuicDecrypter {
189 public:
190 ~TaggingDecrypter() override {}
191
192 // QuicDecrypter interface
dmcardlecf0bfcf2019-12-13 08:08:21 -0800193 bool SetKey(quiche::QuicheStringPiece /*key*/) override { return true; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500194
dmcardlecf0bfcf2019-12-13 08:08:21 -0800195 bool SetNoncePrefix(quiche::QuicheStringPiece /*nonce_prefix*/) override {
dschinazi17d42422019-06-18 16:35:07 -0700196 return true;
197 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500198
dmcardlecf0bfcf2019-12-13 08:08:21 -0800199 bool SetIV(quiche::QuicheStringPiece /*iv*/) override { return true; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500200
dmcardlecf0bfcf2019-12-13 08:08:21 -0800201 bool SetHeaderProtectionKey(quiche::QuicheStringPiece /*key*/) override {
202 return true;
203 }
QUICHE team2d187972019-03-19 16:23:47 -0700204
dmcardlecf0bfcf2019-12-13 08:08:21 -0800205 bool SetPreliminaryKey(quiche::QuicheStringPiece /*key*/) override {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500206 QUIC_BUG << "should not be called";
207 return false;
208 }
209
dschinazi17d42422019-06-18 16:35:07 -0700210 bool SetDiversificationNonce(const DiversificationNonce& /*key*/) override {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500211 return true;
212 }
213
dschinazi17d42422019-06-18 16:35:07 -0700214 bool DecryptPacket(uint64_t /*packet_number*/,
dmcardlecf0bfcf2019-12-13 08:08:21 -0800215 quiche::QuicheStringPiece /*associated_data*/,
216 quiche::QuicheStringPiece ciphertext,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500217 char* output,
218 size_t* output_length,
dschinazi17d42422019-06-18 16:35:07 -0700219 size_t /*max_output_length*/) override {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500220 if (ciphertext.size() < kTagSize) {
221 return false;
222 }
223 if (!CheckTag(ciphertext, GetTag(ciphertext))) {
224 return false;
225 }
226 *output_length = ciphertext.size() - kTagSize;
227 memcpy(output, ciphertext.data(), *output_length);
228 return true;
229 }
230
QUICHE team2d187972019-03-19 16:23:47 -0700231 std::string GenerateHeaderProtectionMask(
dschinazi17d42422019-06-18 16:35:07 -0700232 QuicDataReader* /*sample_reader*/) override {
QUICHE team2d187972019-03-19 16:23:47 -0700233 return std::string(5, 0);
234 }
235
QUICHE teama6ef0a62019-03-07 20:34:33 -0500236 size_t GetKeySize() const override { return 0; }
nharper965e5922019-09-23 22:33:54 -0700237 size_t GetNoncePrefixSize() const override { return 0; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500238 size_t GetIVSize() const override { return 0; }
dmcardlecf0bfcf2019-12-13 08:08:21 -0800239 quiche::QuicheStringPiece GetKey() const override {
240 return quiche::QuicheStringPiece();
241 }
242 quiche::QuicheStringPiece GetNoncePrefix() const override {
243 return quiche::QuicheStringPiece();
244 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500245 // Use a distinct value starting with 0xFFFFFF, which is never used by TLS.
246 uint32_t cipher_id() const override { return 0xFFFFFFF0; }
247
248 protected:
dmcardlecf0bfcf2019-12-13 08:08:21 -0800249 virtual uint8_t GetTag(quiche::QuicheStringPiece ciphertext) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500250 return ciphertext.data()[ciphertext.size() - 1];
251 }
252
253 private:
254 enum {
255 kTagSize = 12,
256 };
257
dmcardlecf0bfcf2019-12-13 08:08:21 -0800258 bool CheckTag(quiche::QuicheStringPiece ciphertext, uint8_t tag) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500259 for (size_t i = ciphertext.size() - kTagSize; i < ciphertext.size(); i++) {
260 if (ciphertext.data()[i] != tag) {
261 return false;
262 }
263 }
264
265 return true;
266 }
267};
268
269// StringTaggingDecrypter ensures that the final kTagSize bytes of the message
270// match the expected value.
271class StrictTaggingDecrypter : public TaggingDecrypter {
272 public:
273 explicit StrictTaggingDecrypter(uint8_t tag) : tag_(tag) {}
274 ~StrictTaggingDecrypter() override {}
275
276 // TaggingQuicDecrypter
dmcardlecf0bfcf2019-12-13 08:08:21 -0800277 uint8_t GetTag(quiche::QuicheStringPiece /*ciphertext*/) override {
278 return tag_;
279 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500280
281 // Use a distinct value starting with 0xFFFFFF, which is never used by TLS.
282 uint32_t cipher_id() const override { return 0xFFFFFFF1; }
283
284 private:
285 const uint8_t tag_;
286};
287
288class TestConnectionHelper : public QuicConnectionHelperInterface {
289 public:
290 TestConnectionHelper(MockClock* clock, MockRandom* random_generator)
291 : clock_(clock), random_generator_(random_generator) {
292 clock_->AdvanceTime(QuicTime::Delta::FromSeconds(1));
293 }
294 TestConnectionHelper(const TestConnectionHelper&) = delete;
295 TestConnectionHelper& operator=(const TestConnectionHelper&) = delete;
296
297 // QuicConnectionHelperInterface
298 const QuicClock* GetClock() const override { return clock_; }
299
300 QuicRandom* GetRandomGenerator() override { return random_generator_; }
301
302 QuicBufferAllocator* GetStreamSendBufferAllocator() override {
303 return &buffer_allocator_;
304 }
305
306 private:
307 MockClock* clock_;
308 MockRandom* random_generator_;
309 SimpleBufferAllocator buffer_allocator_;
310};
311
312class TestAlarmFactory : public QuicAlarmFactory {
313 public:
314 class TestAlarm : public QuicAlarm {
315 public:
316 explicit TestAlarm(QuicArenaScopedPtr<QuicAlarm::Delegate> delegate)
317 : QuicAlarm(std::move(delegate)) {}
318
319 void SetImpl() override {}
320 void CancelImpl() override {}
321 using QuicAlarm::Fire;
322 };
323
324 TestAlarmFactory() {}
325 TestAlarmFactory(const TestAlarmFactory&) = delete;
326 TestAlarmFactory& operator=(const TestAlarmFactory&) = delete;
327
328 QuicAlarm* CreateAlarm(QuicAlarm::Delegate* delegate) override {
329 return new TestAlarm(QuicArenaScopedPtr<QuicAlarm::Delegate>(delegate));
330 }
331
332 QuicArenaScopedPtr<QuicAlarm> CreateAlarm(
333 QuicArenaScopedPtr<QuicAlarm::Delegate> delegate,
334 QuicConnectionArena* arena) override {
335 return arena->New<TestAlarm>(std::move(delegate));
336 }
337};
338
339class TestPacketWriter : public QuicPacketWriter {
wub50d4c712020-05-19 15:48:28 -0700340 struct PacketBuffer {
341 QUIC_CACHELINE_ALIGNED char buffer[1500];
342 bool in_use = false;
343 };
344
QUICHE teama6ef0a62019-03-07 20:34:33 -0500345 public:
346 TestPacketWriter(ParsedQuicVersion version, MockClock* clock)
347 : version_(version),
348 framer_(SupportedVersions(version_), Perspective::IS_SERVER),
wubb442b862020-01-31 08:16:21 -0800349 clock_(clock) {
dschinazib953d022019-08-01 18:05:58 -0700350 QuicFramerPeer::SetLastSerializedServerConnectionId(framer_.framer(),
351 TestConnectionId());
nharperc6b99512019-09-19 11:13:48 -0700352 framer_.framer()->SetInitialObfuscators(TestConnectionId());
wub50d4c712020-05-19 15:48:28 -0700353
354 for (int i = 0; i < 128; ++i) {
355 PacketBuffer* p = new PacketBuffer();
356 packet_buffer_pool_.push_back(p);
357 packet_buffer_pool_index_[p->buffer] = p;
358 packet_buffer_free_list_.push_back(p);
359 }
dschinazib953d022019-08-01 18:05:58 -0700360 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500361 TestPacketWriter(const TestPacketWriter&) = delete;
362 TestPacketWriter& operator=(const TestPacketWriter&) = delete;
363
wub50d4c712020-05-19 15:48:28 -0700364 ~TestPacketWriter() override {
365 EXPECT_EQ(packet_buffer_pool_.size(), packet_buffer_free_list_.size())
366 << packet_buffer_pool_.size() - packet_buffer_free_list_.size()
367 << " out of " << packet_buffer_pool_.size()
368 << " packet buffers have been leaked.";
369 for (auto p : packet_buffer_pool_) {
370 delete p;
371 }
372 }
373
QUICHE teama6ef0a62019-03-07 20:34:33 -0500374 // QuicPacketWriter interface
375 WriteResult WritePacket(const char* buffer,
376 size_t buf_len,
dschinazi17d42422019-06-18 16:35:07 -0700377 const QuicIpAddress& /*self_address*/,
378 const QuicSocketAddress& /*peer_address*/,
379 PerPacketOptions* /*options*/) override {
wub50d4c712020-05-19 15:48:28 -0700380 // If the buffer is allocated from the pool, return it back to the pool.
381 // Note the buffer content doesn't change.
382 if (packet_buffer_pool_index_.find(const_cast<char*>(buffer)) !=
383 packet_buffer_pool_index_.end()) {
384 FreePacketBuffer(buffer);
385 }
386
QUICHE teama6ef0a62019-03-07 20:34:33 -0500387 QuicEncryptedPacket packet(buffer, buf_len);
388 ++packets_write_attempts_;
389
390 if (packet.length() >= sizeof(final_bytes_of_last_packet_)) {
391 final_bytes_of_previous_packet_ = final_bytes_of_last_packet_;
392 memcpy(&final_bytes_of_last_packet_, packet.data() + packet.length() - 4,
393 sizeof(final_bytes_of_last_packet_));
394 }
395
396 if (use_tagging_decrypter_) {
zhongyi546cc452019-04-12 15:27:49 -0700397 if (framer_.framer()->version().KnowsWhichDecrypterToUse()) {
vasilvv0fc587f2019-09-06 13:33:08 -0700398 framer_.framer()->InstallDecrypter(
399 ENCRYPTION_INITIAL, std::make_unique<TaggingDecrypter>());
400 framer_.framer()->InstallDecrypter(
fayang18ff23b2020-01-28 09:19:00 -0800401 ENCRYPTION_HANDSHAKE, std::make_unique<TaggingDecrypter>());
402 framer_.framer()->InstallDecrypter(
vasilvv0fc587f2019-09-06 13:33:08 -0700403 ENCRYPTION_ZERO_RTT, std::make_unique<TaggingDecrypter>());
404 framer_.framer()->InstallDecrypter(
405 ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingDecrypter>());
zhongyi546cc452019-04-12 15:27:49 -0700406 } else {
407 framer_.framer()->SetDecrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -0700408 std::make_unique<TaggingDecrypter>());
zhongyi546cc452019-04-12 15:27:49 -0700409 }
410 } else if (framer_.framer()->version().KnowsWhichDecrypterToUse()) {
411 framer_.framer()->InstallDecrypter(
412 ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -0700413 std::make_unique<NullDecrypter>(Perspective::IS_SERVER));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500414 }
dschinazi39e5e552020-05-06 13:55:24 -0700415 EXPECT_TRUE(framer_.ProcessPacket(packet))
416 << framer_.framer()->detailed_error();
QUICHE teama6ef0a62019-03-07 20:34:33 -0500417 if (block_on_next_write_) {
418 write_blocked_ = true;
419 block_on_next_write_ = false;
420 }
421 if (next_packet_too_large_) {
422 next_packet_too_large_ = false;
423 return WriteResult(WRITE_STATUS_ERROR, QUIC_EMSGSIZE);
424 }
425 if (always_get_packet_too_large_) {
426 return WriteResult(WRITE_STATUS_ERROR, QUIC_EMSGSIZE);
427 }
428 if (IsWriteBlocked()) {
429 return WriteResult(is_write_blocked_data_buffered_
430 ? WRITE_STATUS_BLOCKED_DATA_BUFFERED
431 : WRITE_STATUS_BLOCKED,
432 0);
433 }
434
435 if (ShouldWriteFail()) {
436 return WriteResult(WRITE_STATUS_ERROR, 0);
437 }
438
439 last_packet_size_ = packet.length();
440 last_packet_header_ = framer_.header();
rchd672c6d2019-11-27 15:30:54 -0800441 if (!framer_.connection_close_frames().empty()) {
442 ++connection_close_packets_;
443 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500444 if (!write_pause_time_delta_.IsZero()) {
445 clock_->AdvanceTime(write_pause_time_delta_);
446 }
wubb442b862020-01-31 08:16:21 -0800447 if (is_batch_mode_) {
448 bytes_buffered_ += last_packet_size_;
449 return WriteResult(WRITE_STATUS_OK, 0);
450 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500451 return WriteResult(WRITE_STATUS_OK, last_packet_size_);
452 }
453
454 bool ShouldWriteFail() { return write_should_fail_; }
455
456 bool IsWriteBlocked() const override { return write_blocked_; }
457
458 void SetWriteBlocked() { write_blocked_ = true; }
459
460 void SetWritable() override { write_blocked_ = false; }
461
462 void SetShouldWriteFail() { write_should_fail_ = true; }
463
464 QuicByteCount GetMaxPacketSize(
465 const QuicSocketAddress& /*peer_address*/) const override {
466 return max_packet_size_;
467 }
468
dschinazi61eb6432019-06-14 16:27:16 -0700469 bool SupportsReleaseTime() const override { return supports_release_time_; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500470
471 bool IsBatchMode() const override { return is_batch_mode_; }
472
wub50d4c712020-05-19 15:48:28 -0700473 QuicPacketBuffer GetNextWriteLocation(
dschinazi17d42422019-06-18 16:35:07 -0700474 const QuicIpAddress& /*self_address*/,
475 const QuicSocketAddress& /*peer_address*/) override {
wub50d4c712020-05-19 15:48:28 -0700476 if (GetQuicReloadableFlag(quic_avoid_leak_writer_buffer)) {
477 return {AllocPacketBuffer(),
478 [this](const char* p) { FreePacketBuffer(p); }};
479 }
480 // Do not use writer buffer for serializing packets.
481 return {nullptr, nullptr};
QUICHE teama6ef0a62019-03-07 20:34:33 -0500482 }
483
484 WriteResult Flush() override {
wubb442b862020-01-31 08:16:21 -0800485 flush_attempts_++;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500486 if (block_on_next_flush_) {
487 block_on_next_flush_ = false;
488 SetWriteBlocked();
489 return WriteResult(WRITE_STATUS_BLOCKED, /*errno*/ -1);
490 }
wub748e20b2020-03-20 14:33:59 -0700491 if (write_should_fail_) {
492 return WriteResult(WRITE_STATUS_ERROR, /*errno*/ -1);
493 }
wubb442b862020-01-31 08:16:21 -0800494 int bytes_flushed = bytes_buffered_;
495 bytes_buffered_ = 0;
496 return WriteResult(WRITE_STATUS_OK, bytes_flushed);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500497 }
498
499 void BlockOnNextFlush() { block_on_next_flush_ = true; }
500
501 void BlockOnNextWrite() { block_on_next_write_ = true; }
502
503 void SimulateNextPacketTooLarge() { next_packet_too_large_ = true; }
504
505 void AlwaysGetPacketTooLarge() { always_get_packet_too_large_ = true; }
506
507 // Sets the amount of time that the writer should before the actual write.
508 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
509 write_pause_time_delta_ = delta;
510 }
511
512 void SetBatchMode(bool new_value) { is_batch_mode_ = new_value; }
513
514 const QuicPacketHeader& header() { return framer_.header(); }
515
516 size_t frame_count() const { return framer_.num_frames(); }
517
518 const std::vector<QuicAckFrame>& ack_frames() const {
519 return framer_.ack_frames();
520 }
521
522 const std::vector<QuicStopWaitingFrame>& stop_waiting_frames() const {
523 return framer_.stop_waiting_frames();
524 }
525
526 const std::vector<QuicConnectionCloseFrame>& connection_close_frames() const {
527 return framer_.connection_close_frames();
528 }
529
530 const std::vector<QuicRstStreamFrame>& rst_stream_frames() const {
531 return framer_.rst_stream_frames();
532 }
533
534 const std::vector<std::unique_ptr<QuicStreamFrame>>& stream_frames() const {
535 return framer_.stream_frames();
536 }
537
538 const std::vector<std::unique_ptr<QuicCryptoFrame>>& crypto_frames() const {
539 return framer_.crypto_frames();
540 }
541
542 const std::vector<QuicPingFrame>& ping_frames() const {
543 return framer_.ping_frames();
544 }
545
546 const std::vector<QuicMessageFrame>& message_frames() const {
547 return framer_.message_frames();
548 }
549
550 const std::vector<QuicWindowUpdateFrame>& window_update_frames() const {
551 return framer_.window_update_frames();
552 }
553
554 const std::vector<QuicPaddingFrame>& padding_frames() const {
555 return framer_.padding_frames();
556 }
557
558 const std::vector<QuicPathChallengeFrame>& path_challenge_frames() const {
559 return framer_.path_challenge_frames();
560 }
561
562 const std::vector<QuicPathResponseFrame>& path_response_frames() const {
563 return framer_.path_response_frames();
564 }
565
fayang58f71072019-11-05 08:47:02 -0800566 const QuicEncryptedPacket* coalesced_packet() const {
567 return framer_.coalesced_packet();
568 }
569
QUICHE teama6ef0a62019-03-07 20:34:33 -0500570 size_t last_packet_size() { return last_packet_size_; }
571
572 const QuicPacketHeader& last_packet_header() const {
573 return last_packet_header_;
574 }
575
576 const QuicVersionNegotiationPacket* version_negotiation_packet() {
577 return framer_.version_negotiation_packet();
578 }
579
580 void set_is_write_blocked_data_buffered(bool buffered) {
581 is_write_blocked_data_buffered_ = buffered;
582 }
583
584 void set_perspective(Perspective perspective) {
585 // We invert perspective here, because the framer needs to parse packets
586 // we send.
587 QuicFramerPeer::SetPerspective(framer_.framer(),
nharper4eba09b2019-06-26 20:17:25 -0700588 QuicUtils::InvertPerspective(perspective));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500589 }
590
591 // final_bytes_of_last_packet_ returns the last four bytes of the previous
592 // packet as a little-endian, uint32_t. This is intended to be used with a
593 // TaggingEncrypter so that tests can determine which encrypter was used for
594 // a given packet.
595 uint32_t final_bytes_of_last_packet() { return final_bytes_of_last_packet_; }
596
597 // Returns the final bytes of the second to last packet.
598 uint32_t final_bytes_of_previous_packet() {
599 return final_bytes_of_previous_packet_;
600 }
601
602 void use_tagging_decrypter() { use_tagging_decrypter_ = true; }
603
wubb442b862020-01-31 08:16:21 -0800604 uint32_t packets_write_attempts() const { return packets_write_attempts_; }
605
606 uint32_t flush_attempts() const { return flush_attempts_; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500607
rchd672c6d2019-11-27 15:30:54 -0800608 uint32_t connection_close_packets() const {
609 return connection_close_packets_;
610 }
611
QUICHE teama6ef0a62019-03-07 20:34:33 -0500612 void Reset() { framer_.Reset(); }
613
614 void SetSupportedVersions(const ParsedQuicVersionVector& versions) {
615 framer_.SetSupportedVersions(versions);
616 }
617
618 void set_max_packet_size(QuicByteCount max_packet_size) {
619 max_packet_size_ = max_packet_size;
620 }
621
622 void set_supports_release_time(bool supports_release_time) {
623 supports_release_time_ = supports_release_time;
624 }
625
626 SimpleQuicFramer* framer() { return &framer_; }
627
628 private:
wub50d4c712020-05-19 15:48:28 -0700629 char* AllocPacketBuffer() {
630 PacketBuffer* p = packet_buffer_free_list_.front();
631 EXPECT_FALSE(p->in_use);
632 p->in_use = true;
633 packet_buffer_free_list_.pop_front();
634 return p->buffer;
635 }
636
637 void FreePacketBuffer(const char* buffer) {
638 auto iter = packet_buffer_pool_index_.find(const_cast<char*>(buffer));
639 ASSERT_TRUE(iter != packet_buffer_pool_index_.end());
640 PacketBuffer* p = iter->second;
641 ASSERT_TRUE(p->in_use);
642 p->in_use = false;
643 packet_buffer_free_list_.push_back(p);
644 }
645
QUICHE teama6ef0a62019-03-07 20:34:33 -0500646 ParsedQuicVersion version_;
647 SimpleQuicFramer framer_;
wubb442b862020-01-31 08:16:21 -0800648 size_t last_packet_size_ = 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500649 QuicPacketHeader last_packet_header_;
wubb442b862020-01-31 08:16:21 -0800650 bool write_blocked_ = false;
651 bool write_should_fail_ = false;
652 bool block_on_next_flush_ = false;
653 bool block_on_next_write_ = false;
654 bool next_packet_too_large_ = false;
655 bool always_get_packet_too_large_ = false;
656 bool is_write_blocked_data_buffered_ = false;
657 bool is_batch_mode_ = false;
658 // Number of times Flush() was called.
659 uint32_t flush_attempts_ = 0;
660 // (Batch mode only) Number of bytes buffered in writer. It is used as the
661 // return value of a successful Flush().
662 uint32_t bytes_buffered_ = 0;
663 uint32_t final_bytes_of_last_packet_ = 0;
664 uint32_t final_bytes_of_previous_packet_ = 0;
665 bool use_tagging_decrypter_ = false;
666 uint32_t packets_write_attempts_ = 0;
667 uint32_t connection_close_packets_ = 0;
668 MockClock* clock_ = nullptr;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500669 // If non-zero, the clock will pause during WritePacket for this amount of
670 // time.
wubb442b862020-01-31 08:16:21 -0800671 QuicTime::Delta write_pause_time_delta_ = QuicTime::Delta::Zero();
672 QuicByteCount max_packet_size_ = kMaxOutgoingPacketSize;
673 bool supports_release_time_ = false;
wub50d4c712020-05-19 15:48:28 -0700674 // Used to verify writer-allocated packet buffers are properly released.
675 std::vector<PacketBuffer*> packet_buffer_pool_;
676 // Buffer address => Address of the owning PacketBuffer.
677 QuicHashMap<char*, PacketBuffer*> packet_buffer_pool_index_;
678 // Indices in packet_buffer_pool_ that are not allocated.
679 std::list<PacketBuffer*> packet_buffer_free_list_;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500680};
681
682class TestConnection : public QuicConnection {
683 public:
684 TestConnection(QuicConnectionId connection_id,
685 QuicSocketAddress address,
686 TestConnectionHelper* helper,
687 TestAlarmFactory* alarm_factory,
688 TestPacketWriter* writer,
689 Perspective perspective,
690 ParsedQuicVersion version)
691 : QuicConnection(connection_id,
692 address,
693 helper,
694 alarm_factory,
695 writer,
696 /* owns_writer= */ false,
697 perspective,
698 SupportedVersions(version)),
699 notifier_(nullptr) {
700 writer->set_perspective(perspective);
701 SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -0700702 std::make_unique<NullEncrypter>(perspective));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500703 SetDataProducer(&producer_);
704 }
705 TestConnection(const TestConnection&) = delete;
706 TestConnection& operator=(const TestConnection&) = delete;
707
QUICHE teama6ef0a62019-03-07 20:34:33 -0500708 void SetSendAlgorithm(SendAlgorithmInterface* send_algorithm) {
709 QuicConnectionPeer::SetSendAlgorithm(this, send_algorithm);
710 }
711
712 void SetLossAlgorithm(LossDetectionInterface* loss_algorithm) {
713 QuicConnectionPeer::SetLossAlgorithm(this, loss_algorithm);
714 }
715
dschinazi17d42422019-06-18 16:35:07 -0700716 void SendPacket(EncryptionLevel /*level*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500717 uint64_t packet_number,
718 std::unique_ptr<QuicPacket> packet,
719 HasRetransmittableData retransmittable,
720 bool has_ack,
721 bool has_pending_frames) {
fayang58f71072019-11-05 08:47:02 -0800722 ScopedPacketFlusher flusher(this);
dschinazi66dea072019-04-09 11:41:06 -0700723 char buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -0500724 size_t encrypted_length =
725 QuicConnectionPeer::GetFramer(this)->EncryptPayload(
QUICHE team6987b4a2019-03-15 16:23:04 -0700726 ENCRYPTION_INITIAL, QuicPacketNumber(packet_number), *packet,
dschinazi66dea072019-04-09 11:41:06 -0700727 buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500728 SerializedPacket serialized_packet(
729 QuicPacketNumber(packet_number), PACKET_4BYTE_PACKET_NUMBER, buffer,
730 encrypted_length, has_ack, has_pending_frames);
731 if (retransmittable == HAS_RETRANSMITTABLE_DATA) {
732 serialized_packet.retransmittable_frames.push_back(
fayang58f71072019-11-05 08:47:02 -0800733 QuicFrame(QuicPingFrame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500734 }
wub8a5dafa2020-05-13 12:30:17 -0700735 OnSerializedPacket(std::move(serialized_packet));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500736 }
737
738 QuicConsumedData SaveAndSendStreamData(QuicStreamId id,
739 const struct iovec* iov,
740 int iov_count,
741 size_t total_length,
742 QuicStreamOffset offset,
743 StreamSendingState state) {
fayanga4b37b22019-06-18 13:37:47 -0700744 ScopedPacketFlusher flusher(this);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500745 producer_.SaveStreamData(id, iov, iov_count, 0u, total_length);
746 if (notifier_ != nullptr) {
747 return notifier_->WriteOrBufferData(id, total_length, state);
748 }
749 return QuicConnection::SendStreamData(id, total_length, offset, state);
750 }
751
752 QuicConsumedData SendStreamDataWithString(QuicStreamId id,
dmcardlecf0bfcf2019-12-13 08:08:21 -0800753 quiche::QuicheStringPiece data,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500754 QuicStreamOffset offset,
755 StreamSendingState state) {
fayanga4b37b22019-06-18 13:37:47 -0700756 ScopedPacketFlusher flusher(this);
nharper46833c32019-05-15 21:33:05 -0700757 if (!QuicUtils::IsCryptoStreamId(transport_version(), id) &&
QUICHE team6987b4a2019-03-15 16:23:04 -0700758 this->encryption_level() == ENCRYPTION_INITIAL) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500759 this->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
fayangfa3b1d62019-11-18 08:02:13 -0800760 if (perspective() == Perspective::IS_CLIENT && !IsHandshakeComplete()) {
fayang5f135052019-08-22 17:59:40 -0700761 OnHandshakeComplete();
762 }
763 if (version().SupportsAntiAmplificationLimit()) {
764 QuicConnectionPeer::SetAddressValidated(this);
765 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500766 }
767 struct iovec iov;
768 MakeIOVector(data, &iov);
769 return SaveAndSendStreamData(id, &iov, 1, data.length(), offset, state);
770 }
771
QUICHE teamcd098022019-03-22 18:49:55 -0700772 QuicConsumedData SendApplicationDataAtLevel(EncryptionLevel encryption_level,
773 QuicStreamId id,
dmcardlecf0bfcf2019-12-13 08:08:21 -0800774 quiche::QuicheStringPiece data,
QUICHE teamcd098022019-03-22 18:49:55 -0700775 QuicStreamOffset offset,
776 StreamSendingState state) {
fayanga4b37b22019-06-18 13:37:47 -0700777 ScopedPacketFlusher flusher(this);
QUICHE teamcd098022019-03-22 18:49:55 -0700778 DCHECK(encryption_level >= ENCRYPTION_ZERO_RTT);
vasilvv0fc587f2019-09-06 13:33:08 -0700779 SetEncrypter(encryption_level, std::make_unique<TaggingEncrypter>(0x01));
QUICHE teamcd098022019-03-22 18:49:55 -0700780 SetDefaultEncryptionLevel(encryption_level);
781 struct iovec iov;
782 MakeIOVector(data, &iov);
783 return SaveAndSendStreamData(id, &iov, 1, data.length(), offset, state);
784 }
785
QUICHE teama6ef0a62019-03-07 20:34:33 -0500786 QuicConsumedData SendStreamData3() {
787 return SendStreamDataWithString(
788 GetNthClientInitiatedStreamId(1, transport_version()), "food", 0,
789 NO_FIN);
790 }
791
792 QuicConsumedData SendStreamData5() {
793 return SendStreamDataWithString(
794 GetNthClientInitiatedStreamId(2, transport_version()), "food2", 0,
795 NO_FIN);
796 }
797
798 // Ensures the connection can write stream data before writing.
799 QuicConsumedData EnsureWritableAndSendStreamData5() {
ianswettfc16a2b2020-05-18 16:05:49 -0700800 EXPECT_TRUE(CanWrite(HAS_RETRANSMITTABLE_DATA));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500801 return SendStreamData5();
802 }
803
804 // The crypto stream has special semantics so that it is not blocked by a
805 // congestion window limitation, and also so that it gets put into a separate
806 // packet (so that it is easier to reason about a crypto frame not being
807 // split needlessly across packet boundaries). As a result, we have separate
808 // tests for some cases for this stream.
809 QuicConsumedData SendCryptoStreamData() {
810 QuicStreamOffset offset = 0;
dmcardlecf0bfcf2019-12-13 08:08:21 -0800811 quiche::QuicheStringPiece data("chlo");
fayang2ce66082019-10-02 06:29:04 -0700812 if (!QuicVersionUsesCryptoFrames(transport_version())) {
813 return SendCryptoDataWithString(data, offset);
814 }
815 producer_.SaveCryptoData(ENCRYPTION_INITIAL, offset, data);
816 size_t bytes_written;
817 if (notifier_) {
818 bytes_written =
819 notifier_->WriteCryptoData(ENCRYPTION_INITIAL, data.length(), offset);
820 } else {
821 bytes_written = QuicConnection::SendCryptoData(ENCRYPTION_INITIAL,
822 data.length(), offset);
823 }
824 return QuicConsumedData(bytes_written, /*fin_consumed*/ false);
nharper46833c32019-05-15 21:33:05 -0700825 }
826
dmcardlecf0bfcf2019-12-13 08:08:21 -0800827 QuicConsumedData SendCryptoDataWithString(quiche::QuicheStringPiece data,
nharper46833c32019-05-15 21:33:05 -0700828 QuicStreamOffset offset) {
fayang18ff23b2020-01-28 09:19:00 -0800829 return SendCryptoDataWithString(data, offset, ENCRYPTION_INITIAL);
830 }
831
832 QuicConsumedData SendCryptoDataWithString(quiche::QuicheStringPiece data,
833 QuicStreamOffset offset,
834 EncryptionLevel encryption_level) {
QUICHE teamea740082019-03-11 17:58:43 -0700835 if (!QuicVersionUsesCryptoFrames(transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500836 return SendStreamDataWithString(
837 QuicUtils::GetCryptoStreamId(transport_version()), data, offset,
838 NO_FIN);
839 }
fayang18ff23b2020-01-28 09:19:00 -0800840 producer_.SaveCryptoData(encryption_level, offset, data);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500841 size_t bytes_written;
842 if (notifier_) {
843 bytes_written =
fayang18ff23b2020-01-28 09:19:00 -0800844 notifier_->WriteCryptoData(encryption_level, data.length(), offset);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500845 } else {
fayang18ff23b2020-01-28 09:19:00 -0800846 bytes_written = QuicConnection::SendCryptoData(encryption_level,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500847 data.length(), offset);
848 }
849 return QuicConsumedData(bytes_written, /*fin_consumed*/ false);
850 }
851
852 void set_version(ParsedQuicVersion version) {
853 QuicConnectionPeer::GetFramer(this)->set_version(version);
854 }
855
856 void SetSupportedVersions(const ParsedQuicVersionVector& versions) {
857 QuicConnectionPeer::GetFramer(this)->SetSupportedVersions(versions);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500858 writer()->SetSupportedVersions(versions);
859 }
860
861 void set_perspective(Perspective perspective) {
862 writer()->set_perspective(perspective);
863 QuicConnectionPeer::SetPerspective(this, perspective);
864 }
865
866 // Enable path MTU discovery. Assumes that the test is performed from the
wub031d47c2019-11-21 08:04:07 -0800867 // server perspective and the higher value of MTU target is used.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500868 void EnablePathMtuDiscovery(MockSendAlgorithm* send_algorithm) {
wub031d47c2019-11-21 08:04:07 -0800869 ASSERT_EQ(Perspective::IS_SERVER, perspective());
QUICHE teama6ef0a62019-03-07 20:34:33 -0500870
871 QuicConfig config;
872 QuicTagVector connection_options;
873 connection_options.push_back(kMTUH);
wub031d47c2019-11-21 08:04:07 -0800874 config.SetInitialReceivedConnectionOptions(connection_options);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500875 EXPECT_CALL(*send_algorithm, SetFromConfig(_, _));
876 SetFromConfig(config);
877
878 // Normally, the pacing would be disabled in the test, but calling
879 // SetFromConfig enables it. Set nearly-infinite bandwidth to make the
880 // pacing algorithm work.
881 EXPECT_CALL(*send_algorithm, PacingRate(_))
882 .WillRepeatedly(Return(QuicBandwidth::Infinite()));
883 }
884
885 TestAlarmFactory::TestAlarm* GetAckAlarm() {
886 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
887 QuicConnectionPeer::GetAckAlarm(this));
888 }
889
890 TestAlarmFactory::TestAlarm* GetPingAlarm() {
891 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
892 QuicConnectionPeer::GetPingAlarm(this));
893 }
894
895 TestAlarmFactory::TestAlarm* GetRetransmissionAlarm() {
896 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
897 QuicConnectionPeer::GetRetransmissionAlarm(this));
898 }
899
900 TestAlarmFactory::TestAlarm* GetSendAlarm() {
901 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
902 QuicConnectionPeer::GetSendAlarm(this));
903 }
904
905 TestAlarmFactory::TestAlarm* GetTimeoutAlarm() {
906 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
fayang3a58dc42020-06-29 11:27:14 -0700907 QuicConnectionPeer::GetIdleNetworkDetectorAlarm(this));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500908 }
909
910 TestAlarmFactory::TestAlarm* GetMtuDiscoveryAlarm() {
911 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
912 QuicConnectionPeer::GetMtuDiscoveryAlarm(this));
913 }
914
QUICHE teama6ef0a62019-03-07 20:34:33 -0500915 TestAlarmFactory::TestAlarm* GetProcessUndecryptablePacketsAlarm() {
916 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
917 QuicConnectionPeer::GetProcessUndecryptablePacketsAlarm(this));
918 }
919
fayangb59c6f12020-03-23 15:06:14 -0700920 TestAlarmFactory::TestAlarm* GetBlackholeDetectorAlarm() {
fayangb59c6f12020-03-23 15:06:14 -0700921 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
922 QuicConnectionPeer::GetBlackholeDetectorAlarm(this));
923 }
924
925 void PathDegradingTimeout() {
926 DCHECK(PathDegradingDetectionInProgress());
fayang2205d952020-05-12 13:45:56 -0700927 GetBlackholeDetectorAlarm()->Fire();
fayangb59c6f12020-03-23 15:06:14 -0700928 }
929
930 bool PathDegradingDetectionInProgress() {
fayang2205d952020-05-12 13:45:56 -0700931 return QuicConnectionPeer::GetPathDegradingDeadline(this).IsInitialized();
fayangb59c6f12020-03-23 15:06:14 -0700932 }
933
934 bool BlackholeDetectionInProgress() {
fayangb59c6f12020-03-23 15:06:14 -0700935 return QuicConnectionPeer::GetBlackholeDetectionDeadline(this)
936 .IsInitialized();
937 }
938
QUICHE teama6ef0a62019-03-07 20:34:33 -0500939 void SetMaxTailLossProbes(size_t max_tail_loss_probes) {
940 QuicSentPacketManagerPeer::SetMaxTailLossProbes(
941 QuicConnectionPeer::GetSentPacketManager(this), max_tail_loss_probes);
942 }
943
944 QuicByteCount GetBytesInFlight() {
ianswett9f459cb2019-04-21 06:39:59 -0700945 return QuicConnectionPeer::GetSentPacketManager(this)->GetBytesInFlight();
QUICHE teama6ef0a62019-03-07 20:34:33 -0500946 }
947
948 void set_notifier(SimpleSessionNotifier* notifier) { notifier_ = notifier; }
949
950 void ReturnEffectivePeerAddressForNextPacket(const QuicSocketAddress& addr) {
vasilvv0fc587f2019-09-06 13:33:08 -0700951 next_effective_peer_addr_ = std::make_unique<QuicSocketAddress>(addr);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500952 }
953
fayang5f135052019-08-22 17:59:40 -0700954 bool PtoEnabled() {
955 if (QuicConnectionPeer::GetSentPacketManager(this)->pto_enabled()) {
956 // PTO mode is default enabled for T099. And TLP/RTO related tests are
957 // stale.
fayang5d011982020-05-13 14:14:38 -0700958 DCHECK(PROTOCOL_TLS1_3 == version().handshake_protocol ||
959 GetQuicReloadableFlag(quic_default_on_pto));
fayang5f135052019-08-22 17:59:40 -0700960 return true;
961 }
962 return false;
963 }
964
nharper46833c32019-05-15 21:33:05 -0700965 SimpleDataProducer* producer() { return &producer_; }
966
QUICHE teama6ef0a62019-03-07 20:34:33 -0500967 using QuicConnection::active_effective_peer_migration_type;
968 using QuicConnection::IsCurrentPacketConnectivityProbing;
969 using QuicConnection::SelectMutualVersion;
970 using QuicConnection::SendProbingRetransmissions;
971 using QuicConnection::set_defer_send_in_response_to_packets;
972
973 protected:
974 QuicSocketAddress GetEffectivePeerAddressFromCurrentPacket() const override {
975 if (next_effective_peer_addr_) {
976 return *std::move(next_effective_peer_addr_);
977 }
978 return QuicConnection::GetEffectivePeerAddressFromCurrentPacket();
979 }
980
981 private:
982 TestPacketWriter* writer() {
983 return static_cast<TestPacketWriter*>(QuicConnection::writer());
984 }
985
986 SimpleDataProducer producer_;
987
988 SimpleSessionNotifier* notifier_;
989
990 std::unique_ptr<QuicSocketAddress> next_effective_peer_addr_;
991};
992
993enum class AckResponse { kDefer, kImmediate };
994
995// Run tests with combinations of {ParsedQuicVersion, AckResponse}.
996struct TestParams {
997 TestParams(ParsedQuicVersion version,
998 AckResponse ack_response,
999 bool no_stop_waiting)
1000 : version(version),
1001 ack_response(ack_response),
1002 no_stop_waiting(no_stop_waiting) {}
1003
QUICHE teama6ef0a62019-03-07 20:34:33 -05001004 ParsedQuicVersion version;
1005 AckResponse ack_response;
1006 bool no_stop_waiting;
1007};
1008
dschinazi142051a2019-09-18 18:17:29 -07001009// Used by ::testing::PrintToStringParamName().
1010std::string PrintToString(const TestParams& p) {
dmcardlecf0bfcf2019-12-13 08:08:21 -08001011 return quiche::QuicheStrCat(
dschinazi142051a2019-09-18 18:17:29 -07001012 ParsedQuicVersionToString(p.version), "_",
1013 (p.ack_response == AckResponse::kDefer ? "defer" : "immediate"), "_",
1014 (p.no_stop_waiting ? "No" : ""), "StopWaiting");
1015}
1016
QUICHE teama6ef0a62019-03-07 20:34:33 -05001017// Constructs various test permutations.
1018std::vector<TestParams> GetTestParams() {
1019 QuicFlagSaver flags;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001020 std::vector<TestParams> params;
1021 ParsedQuicVersionVector all_supported_versions = AllSupportedVersions();
1022 for (size_t i = 0; i < all_supported_versions.size(); ++i) {
1023 for (AckResponse ack_response :
1024 {AckResponse::kDefer, AckResponse::kImmediate}) {
dschinazi142051a2019-09-18 18:17:29 -07001025 params.push_back(
1026 TestParams(all_supported_versions[i], ack_response, true));
1027 if (!VersionHasIetfInvariantHeader(
1028 all_supported_versions[i].transport_version)) {
fayangd4291e42019-05-30 10:31:21 -07001029 params.push_back(
dschinazi142051a2019-09-18 18:17:29 -07001030 TestParams(all_supported_versions[i], ack_response, false));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001031 }
1032 }
1033 }
1034 return params;
1035}
1036
1037class QuicConnectionTest : public QuicTestWithParam<TestParams> {
fkastenholz5d880a92019-06-21 09:01:56 -07001038 public:
1039 // For tests that do silent connection closes, no such packet is generated. In
1040 // order to verify the contents of the OnConnectionClosed upcall, EXPECTs
1041 // should invoke this method, saving the frame, and then the test can verify
1042 // the contents.
1043 void SaveConnectionCloseFrame(const QuicConnectionCloseFrame& frame,
1044 ConnectionCloseSource /*source*/) {
1045 saved_connection_close_frame_ = frame;
1046 connection_close_frame_count_++;
1047 }
1048
QUICHE teama6ef0a62019-03-07 20:34:33 -05001049 protected:
1050 QuicConnectionTest()
1051 : connection_id_(TestConnectionId()),
1052 framer_(SupportedVersions(version()),
1053 QuicTime::Zero(),
1054 Perspective::IS_CLIENT,
1055 connection_id_.length()),
1056 send_algorithm_(new StrictMock<MockSendAlgorithm>),
1057 loss_algorithm_(new MockLossAlgorithm()),
1058 helper_(new TestConnectionHelper(&clock_, &random_generator_)),
1059 alarm_factory_(new TestAlarmFactory()),
1060 peer_framer_(SupportedVersions(version()),
1061 QuicTime::Zero(),
1062 Perspective::IS_SERVER,
1063 connection_id_.length()),
1064 peer_creator_(connection_id_,
1065 &peer_framer_,
1066 /*delegate=*/nullptr),
1067 writer_(new TestPacketWriter(version(), &clock_)),
1068 connection_(connection_id_,
1069 kPeerAddress,
1070 helper_.get(),
1071 alarm_factory_.get(),
1072 writer_.get(),
1073 Perspective::IS_CLIENT,
1074 version()),
1075 creator_(QuicConnectionPeer::GetPacketCreator(&connection_)),
QUICHE teama6ef0a62019-03-07 20:34:33 -05001076 manager_(QuicConnectionPeer::GetSentPacketManager(&connection_)),
dmcardlecf0bfcf2019-12-13 08:08:21 -08001077 frame1_(0, false, 0, quiche::QuicheStringPiece(data1)),
1078 frame2_(0, false, 3, quiche::QuicheStringPiece(data2)),
1079 crypto_frame_(ENCRYPTION_INITIAL, 0, quiche::QuicheStringPiece(data1)),
QUICHE teama6ef0a62019-03-07 20:34:33 -05001080 packet_number_length_(PACKET_4BYTE_PACKET_NUMBER),
1081 connection_id_included_(CONNECTION_ID_PRESENT),
fkastenholz5d880a92019-06-21 09:01:56 -07001082 notifier_(&connection_),
1083 connection_close_frame_count_(0) {
dschinazi142051a2019-09-18 18:17:29 -07001084 QUIC_DVLOG(2) << "QuicConnectionTest(" << PrintToString(GetParam()) << ")";
QUICHE teama6ef0a62019-03-07 20:34:33 -05001085 connection_.set_defer_send_in_response_to_packets(GetParam().ack_response ==
1086 AckResponse::kDefer);
nharperc6b99512019-09-19 11:13:48 -07001087 framer_.SetInitialObfuscators(TestConnectionId());
1088 connection_.InstallInitialCrypters(TestConnectionId());
1089 CrypterPair crypters;
1090 CryptoUtils::CreateInitialObfuscators(Perspective::IS_SERVER, version(),
1091 TestConnectionId(), &crypters);
1092 peer_creator_.SetEncrypter(ENCRYPTION_INITIAL,
1093 std::move(crypters.encrypter));
1094 if (version().KnowsWhichDecrypterToUse()) {
1095 peer_framer_.InstallDecrypter(ENCRYPTION_INITIAL,
1096 std::move(crypters.decrypter));
1097 } else {
1098 peer_framer_.SetDecrypter(ENCRYPTION_INITIAL,
1099 std::move(crypters.decrypter));
1100 }
nharper2c9f02a2019-05-08 10:25:50 -07001101 for (EncryptionLevel level :
1102 {ENCRYPTION_ZERO_RTT, ENCRYPTION_FORWARD_SECURE}) {
1103 peer_creator_.SetEncrypter(
vasilvv0fc587f2019-09-06 13:33:08 -07001104 level, std::make_unique<NullEncrypter>(peer_framer_.perspective()));
nharper2c9f02a2019-05-08 10:25:50 -07001105 }
dschinazi7b9278c2019-05-20 07:36:21 -07001106 QuicFramerPeer::SetLastSerializedServerConnectionId(
QUICHE teama6ef0a62019-03-07 20:34:33 -05001107 QuicConnectionPeer::GetFramer(&connection_), connection_id_);
nharperc6b99512019-09-19 11:13:48 -07001108 QuicFramerPeer::SetLastWrittenPacketNumberLength(
1109 QuicConnectionPeer::GetFramer(&connection_), packet_number_length_);
fayangd4291e42019-05-30 10:31:21 -07001110 if (VersionHasIetfInvariantHeader(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001111 EXPECT_TRUE(QuicConnectionPeer::GetNoStopWaitingFrames(&connection_));
1112 } else {
1113 QuicConnectionPeer::SetNoStopWaitingFrames(&connection_,
1114 GetParam().no_stop_waiting);
1115 }
nharper46833c32019-05-15 21:33:05 -07001116 QuicStreamId stream_id;
1117 if (QuicVersionUsesCryptoFrames(version().transport_version)) {
1118 stream_id = QuicUtils::GetFirstBidirectionalStreamId(
1119 version().transport_version, Perspective::IS_CLIENT);
1120 } else {
1121 stream_id = QuicUtils::GetCryptoStreamId(version().transport_version);
1122 }
1123 frame1_.stream_id = stream_id;
1124 frame2_.stream_id = stream_id;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001125 connection_.set_visitor(&visitor_);
fayangcff885a2019-10-22 07:39:04 -07001126 connection_.SetSessionNotifier(&notifier_);
1127 connection_.set_notifier(&notifier_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001128 connection_.SetSendAlgorithm(send_algorithm_);
1129 connection_.SetLossAlgorithm(loss_algorithm_.get());
1130 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
1131 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1132 .Times(AnyNumber());
wubf4ab9652020-02-20 14:45:43 -08001133 EXPECT_CALL(*send_algorithm_, OnPacketNeutered(_)).Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -05001134 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
1135 .WillRepeatedly(Return(kDefaultTCPMSS));
1136 EXPECT_CALL(*send_algorithm_, PacingRate(_))
1137 .WillRepeatedly(Return(QuicBandwidth::Zero()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001138 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
1139 .Times(AnyNumber())
1140 .WillRepeatedly(Return(QuicBandwidth::Zero()));
wub5cd49592019-11-25 15:17:13 -08001141 EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_))
1142 .Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -05001143 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
1144 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
1145 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
1146 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).Times(AnyNumber());
fayangd58736d2019-11-27 13:35:31 -08001147 EXPECT_CALL(visitor_, OnPacketDecrypted(_)).Times(AnyNumber());
fayangcff885a2019-10-22 07:39:04 -07001148 EXPECT_CALL(visitor_, OnCanWrite())
1149 .WillRepeatedly(Invoke(&notifier_, &SimpleSessionNotifier::OnCanWrite));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001150 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
1151 .WillRepeatedly(Return(false));
1152 EXPECT_CALL(visitor_, OnCongestionWindowChange(_)).Times(AnyNumber());
zhongyi83161e42019-08-19 09:06:25 -07001153 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(AnyNumber());
wub256b2d62019-11-25 08:46:55 -08001154 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
fayang2f2915d2020-01-24 06:47:15 -08001155 EXPECT_CALL(visitor_, OnOneRttPacketAcknowledged())
1156 .Times(testing::AtMost(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001157 EXPECT_CALL(*loss_algorithm_, GetLossTimeout())
1158 .WillRepeatedly(Return(QuicTime::Zero()));
1159 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
1160 .Times(AnyNumber());
fayang5014e922020-01-22 12:28:11 -08001161 EXPECT_CALL(visitor_, GetHandshakeState())
1162 .WillRepeatedly(Return(HANDSHAKE_START));
zhongyi546cc452019-04-12 15:27:49 -07001163 if (connection_.version().KnowsWhichDecrypterToUse()) {
1164 connection_.InstallDecrypter(
1165 ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07001166 std::make_unique<NullDecrypter>(Perspective::IS_CLIENT));
zhongyi546cc452019-04-12 15:27:49 -07001167 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001168 }
1169
1170 QuicConnectionTest(const QuicConnectionTest&) = delete;
1171 QuicConnectionTest& operator=(const QuicConnectionTest&) = delete;
1172
1173 ParsedQuicVersion version() { return GetParam().version; }
1174
QUICHE teama6ef0a62019-03-07 20:34:33 -05001175 QuicStopWaitingFrame* stop_waiting() {
1176 QuicConnectionPeer::PopulateStopWaitingFrame(&connection_, &stop_waiting_);
1177 return &stop_waiting_;
1178 }
1179
1180 QuicPacketNumber least_unacked() {
1181 if (writer_->stop_waiting_frames().empty()) {
1182 return QuicPacketNumber();
1183 }
1184 return writer_->stop_waiting_frames()[0].least_unacked;
1185 }
1186
1187 void use_tagging_decrypter() { writer_->use_tagging_decrypter(); }
1188
zhongyi546cc452019-04-12 15:27:49 -07001189 void SetDecrypter(EncryptionLevel level,
1190 std::unique_ptr<QuicDecrypter> decrypter) {
1191 if (connection_.version().KnowsWhichDecrypterToUse()) {
1192 connection_.InstallDecrypter(level, std::move(decrypter));
1193 connection_.RemoveDecrypter(ENCRYPTION_INITIAL);
1194 } else {
1195 connection_.SetDecrypter(level, std::move(decrypter));
1196 }
1197 }
1198
QUICHE teama6ef0a62019-03-07 20:34:33 -05001199 void ProcessPacket(uint64_t number) {
1200 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
1201 ProcessDataPacket(number);
1202 if (connection_.GetSendAlarm()->IsSet()) {
1203 connection_.GetSendAlarm()->Fire();
1204 }
1205 }
1206
1207 void ProcessReceivedPacket(const QuicSocketAddress& self_address,
1208 const QuicSocketAddress& peer_address,
1209 const QuicReceivedPacket& packet) {
1210 connection_.ProcessUdpPacket(self_address, peer_address, packet);
1211 if (connection_.GetSendAlarm()->IsSet()) {
1212 connection_.GetSendAlarm()->Fire();
1213 }
1214 }
1215
wub8a5dafa2020-05-13 12:30:17 -07001216 QuicFrame MakeCryptoFrame() const {
1217 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1218 return QuicFrame(new QuicCryptoFrame(crypto_frame_));
1219 }
1220 return QuicFrame(QuicStreamFrame(
1221 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
1222 0u, quiche::QuicheStringPiece()));
1223 }
1224
QUICHE teama6ef0a62019-03-07 20:34:33 -05001225 void ProcessFramePacket(QuicFrame frame) {
1226 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
1227 }
1228
1229 void ProcessFramePacketWithAddresses(QuicFrame frame,
1230 QuicSocketAddress self_address,
1231 QuicSocketAddress peer_address) {
1232 QuicFrames frames;
1233 frames.push_back(QuicFrame(frame));
zhongyif06ca342020-02-24 14:11:13 -08001234 return ProcessFramesPacketWithAddresses(frames, self_address, peer_address);
1235 }
1236
1237 void ProcessFramesPacketWithAddresses(QuicFrames frames,
1238 QuicSocketAddress self_address,
1239 QuicSocketAddress peer_address) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001240 QuicPacketCreatorPeer::SetSendVersionInPacket(
wub031d47c2019-11-21 08:04:07 -08001241 &peer_creator_,
1242 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_) <
1243 ENCRYPTION_FORWARD_SECURE &&
1244 connection_.perspective() == Perspective::IS_SERVER);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001245
dschinazi66dea072019-04-09 11:41:06 -07001246 char buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05001247 SerializedPacket serialized_packet =
dschinazi66dea072019-04-09 11:41:06 -07001248 QuicPacketCreatorPeer::SerializeAllFrames(
1249 &peer_creator_, frames, buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001250 connection_.ProcessUdpPacket(
1251 self_address, peer_address,
1252 QuicReceivedPacket(serialized_packet.encrypted_buffer,
1253 serialized_packet.encrypted_length, clock_.Now()));
1254 if (connection_.GetSendAlarm()->IsSet()) {
1255 connection_.GetSendAlarm()->Fire();
1256 }
1257 }
1258
1259 // Bypassing the packet creator is unrealistic, but allows us to process
1260 // packets the QuicPacketCreator won't allow us to create.
1261 void ForceProcessFramePacket(QuicFrame frame) {
1262 QuicFrames frames;
1263 frames.push_back(QuicFrame(frame));
zhongyi546cc452019-04-12 15:27:49 -07001264 bool send_version = connection_.perspective() == Perspective::IS_SERVER;
1265 if (connection_.version().KnowsWhichDecrypterToUse()) {
1266 send_version = true;
1267 }
1268 QuicPacketCreatorPeer::SetSendVersionInPacket(&peer_creator_, send_version);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001269 QuicPacketHeader header;
1270 QuicPacketCreatorPeer::FillPacketHeader(&peer_creator_, &header);
dschinazi66dea072019-04-09 11:41:06 -07001271 char encrypted_buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05001272 size_t length = peer_framer_.BuildDataPacket(
dschinazi66dea072019-04-09 11:41:06 -07001273 header, frames, encrypted_buffer, kMaxOutgoingPacketSize,
1274 ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001275 DCHECK_GT(length, 0u);
1276
1277 const size_t encrypted_length = peer_framer_.EncryptInPlace(
QUICHE team6987b4a2019-03-15 16:23:04 -07001278 ENCRYPTION_INITIAL, header.packet_number,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001279 GetStartOfEncryptedData(peer_framer_.version().transport_version,
1280 header),
dschinazi66dea072019-04-09 11:41:06 -07001281 length, kMaxOutgoingPacketSize, encrypted_buffer);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001282 DCHECK_GT(encrypted_length, 0u);
1283
1284 connection_.ProcessUdpPacket(
1285 kSelfAddress, kPeerAddress,
1286 QuicReceivedPacket(encrypted_buffer, encrypted_length, clock_.Now()));
1287 }
1288
1289 size_t ProcessFramePacketAtLevel(uint64_t number,
1290 QuicFrame frame,
1291 EncryptionLevel level) {
fayang01062942020-01-22 07:23:23 -08001292 QuicFrames frames;
1293 frames.push_back(frame);
1294 return ProcessFramesPacketAtLevel(number, frames, level);
1295 }
1296
1297 size_t ProcessFramesPacketAtLevel(uint64_t number,
1298 const QuicFrames& frames,
1299 EncryptionLevel level) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001300 QuicPacketHeader header;
1301 header.destination_connection_id = connection_id_;
1302 header.packet_number_length = packet_number_length_;
1303 header.destination_connection_id_included = connection_id_included_;
dschinazi5e1a7b22019-07-31 12:23:21 -07001304 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001305 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1306 }
zhongyi546cc452019-04-12 15:27:49 -07001307 if (level == ENCRYPTION_INITIAL &&
1308 peer_framer_.version().KnowsWhichDecrypterToUse()) {
1309 header.version_flag = true;
nharperd43f1d62019-07-01 15:18:20 -07001310 if (QuicVersionHasLongHeaderLengths(peer_framer_.transport_version())) {
1311 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
1312 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
1313 }
QUICHE team2252b702019-05-14 23:55:14 -04001314 }
dschinazi5e1a7b22019-07-31 12:23:21 -07001315 if (header.version_flag &&
QUICHE team2252b702019-05-14 23:55:14 -04001316 peer_framer_.perspective() == Perspective::IS_SERVER) {
1317 header.source_connection_id = connection_id_;
1318 header.source_connection_id_included = CONNECTION_ID_PRESENT;
zhongyi546cc452019-04-12 15:27:49 -07001319 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001320 header.packet_number = QuicPacketNumber(number);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001321 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
QUICHE teamcd098022019-03-22 18:49:55 -07001322 // Set the correct encryption level and encrypter on peer_creator and
1323 // peer_framer, respectively.
1324 peer_creator_.set_encryption_level(level);
1325 if (QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_) >
1326 ENCRYPTION_INITIAL) {
1327 peer_framer_.SetEncrypter(
1328 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
vasilvv0fc587f2019-09-06 13:33:08 -07001329 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teamcd098022019-03-22 18:49:55 -07001330 // Set the corresponding decrypter.
zhongyi546cc452019-04-12 15:27:49 -07001331 if (connection_.version().KnowsWhichDecrypterToUse()) {
1332 connection_.InstallDecrypter(
1333 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
vasilvv0fc587f2019-09-06 13:33:08 -07001334 std::make_unique<StrictTaggingDecrypter>(0x01));
zhongyi546cc452019-04-12 15:27:49 -07001335 connection_.RemoveDecrypter(ENCRYPTION_INITIAL);
1336 } else {
1337 connection_.SetDecrypter(
1338 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
vasilvv0fc587f2019-09-06 13:33:08 -07001339 std::make_unique<StrictTaggingDecrypter>(0x01));
zhongyi546cc452019-04-12 15:27:49 -07001340 }
QUICHE teamcd098022019-03-22 18:49:55 -07001341 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001342
dschinazi66dea072019-04-09 11:41:06 -07001343 char buffer[kMaxOutgoingPacketSize];
1344 size_t encrypted_length =
1345 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
1346 buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001347 connection_.ProcessUdpPacket(
1348 kSelfAddress, kPeerAddress,
QUICHE teamcd098022019-03-22 18:49:55 -07001349 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1350 if (connection_.GetSendAlarm()->IsSet()) {
1351 connection_.GetSendAlarm()->Fire();
1352 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001353 return encrypted_length;
1354 }
1355
1356 size_t ProcessDataPacket(uint64_t number) {
nharper2c9f02a2019-05-08 10:25:50 -07001357 return ProcessDataPacketAtLevel(number, false, ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001358 }
1359
1360 size_t ProcessDataPacket(QuicPacketNumber packet_number) {
nharper2c9f02a2019-05-08 10:25:50 -07001361 return ProcessDataPacketAtLevel(packet_number, false,
1362 ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001363 }
1364
1365 size_t ProcessDataPacketAtLevel(QuicPacketNumber packet_number,
1366 bool has_stop_waiting,
1367 EncryptionLevel level) {
1368 return ProcessDataPacketAtLevel(packet_number.ToUint64(), has_stop_waiting,
1369 level);
1370 }
1371
fayanga39d0362020-06-22 08:57:35 -07001372 size_t ProcessCryptoPacketAtLevel(uint64_t number, EncryptionLevel level) {
1373 QuicPacketHeader header = ConstructPacketHeader(number, level);
nharper46833c32019-05-15 21:33:05 -07001374 QuicFrames frames;
1375 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1376 frames.push_back(QuicFrame(&crypto_frame_));
1377 } else {
1378 frames.push_back(QuicFrame(frame1_));
1379 }
fayang5f135052019-08-22 17:59:40 -07001380 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
nharper46833c32019-05-15 21:33:05 -07001381 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
1382 char buffer[kMaxOutgoingPacketSize];
fayanga39d0362020-06-22 08:57:35 -07001383 peer_creator_.set_encryption_level(level);
1384 size_t encrypted_length =
1385 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
1386 buffer, kMaxOutgoingPacketSize);
nharper46833c32019-05-15 21:33:05 -07001387 connection_.ProcessUdpPacket(
1388 kSelfAddress, kPeerAddress,
1389 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1390 if (connection_.GetSendAlarm()->IsSet()) {
1391 connection_.GetSendAlarm()->Fire();
1392 }
1393 return encrypted_length;
1394 }
1395
QUICHE teama6ef0a62019-03-07 20:34:33 -05001396 size_t ProcessDataPacketAtLevel(uint64_t number,
1397 bool has_stop_waiting,
1398 EncryptionLevel level) {
1399 std::unique_ptr<QuicPacket> packet(
QUICHE team8c1daa22019-03-13 08:33:41 -07001400 ConstructDataPacket(number, has_stop_waiting, level));
dschinazi66dea072019-04-09 11:41:06 -07001401 char buffer[kMaxOutgoingPacketSize];
QUICHE teamcd098022019-03-22 18:49:55 -07001402 peer_creator_.set_encryption_level(level);
dschinazi66dea072019-04-09 11:41:06 -07001403 size_t encrypted_length =
1404 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
1405 buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001406 connection_.ProcessUdpPacket(
1407 kSelfAddress, kPeerAddress,
1408 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1409 if (connection_.GetSendAlarm()->IsSet()) {
1410 connection_.GetSendAlarm()->Fire();
1411 }
1412 return encrypted_length;
1413 }
1414
1415 void ProcessClosePacket(uint64_t number) {
1416 std::unique_ptr<QuicPacket> packet(ConstructClosePacket(number));
dschinazi66dea072019-04-09 11:41:06 -07001417 char buffer[kMaxOutgoingPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07001418 size_t encrypted_length = peer_framer_.EncryptPayload(
nharperc6b99512019-09-19 11:13:48 -07001419 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(number), *packet, buffer,
dschinazi66dea072019-04-09 11:41:06 -07001420 kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001421 connection_.ProcessUdpPacket(
1422 kSelfAddress, kPeerAddress,
1423 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
1424 }
1425
1426 QuicByteCount SendStreamDataToPeer(QuicStreamId id,
dmcardlecf0bfcf2019-12-13 08:08:21 -08001427 quiche::QuicheStringPiece data,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001428 QuicStreamOffset offset,
1429 StreamSendingState state,
1430 QuicPacketNumber* last_packet) {
1431 QuicByteCount packet_size;
fayang0fcbf352019-08-30 11:15:58 -07001432 // Save the last packet's size.
QUICHE teama6ef0a62019-03-07 20:34:33 -05001433 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
fayang0fcbf352019-08-30 11:15:58 -07001434 .Times(AnyNumber())
1435 .WillRepeatedly(SaveArg<3>(&packet_size));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001436 connection_.SendStreamDataWithString(id, data, offset, state);
1437 if (last_packet != nullptr) {
1438 *last_packet = creator_->packet_number();
1439 }
1440 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1441 .Times(AnyNumber());
1442 return packet_size;
1443 }
1444
1445 void SendAckPacketToPeer() {
1446 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1447 {
fayanga4b37b22019-06-18 13:37:47 -07001448 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001449 connection_.SendAck();
1450 }
1451 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1452 .Times(AnyNumber());
1453 }
1454
1455 void SendRstStream(QuicStreamId id,
1456 QuicRstStreamErrorCode error,
1457 QuicStreamOffset bytes_written) {
fayangcff885a2019-10-22 07:39:04 -07001458 notifier_.WriteOrBufferRstStream(id, error, bytes_written);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001459 connection_.OnStreamReset(id, error);
1460 }
1461
fayangcff885a2019-10-22 07:39:04 -07001462 void SendPing() { notifier_.WriteOrBufferPing(); }
zhongyifbb25772019-04-10 16:54:08 -07001463
fayang61453cb2020-03-11 11:32:26 -07001464 MessageStatus SendMessage(quiche::QuicheStringPiece message) {
1465 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1466 QuicMemSliceStorage storage(nullptr, 0, nullptr, 0);
1467 return connection_.SendMessage(
1468 1,
1469 MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(), message,
1470 &storage),
1471 false);
1472 }
1473
QUICHE teama6ef0a62019-03-07 20:34:33 -05001474 void ProcessAckPacket(uint64_t packet_number, QuicAckFrame* frame) {
1475 if (packet_number > 1) {
1476 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, packet_number - 1);
1477 } else {
1478 QuicPacketCreatorPeer::ClearPacketNumber(&peer_creator_);
1479 }
1480 ProcessFramePacket(QuicFrame(frame));
1481 }
1482
1483 void ProcessAckPacket(QuicAckFrame* frame) {
1484 ProcessFramePacket(QuicFrame(frame));
1485 }
1486
1487 void ProcessStopWaitingPacket(QuicStopWaitingFrame frame) {
1488 ProcessFramePacket(QuicFrame(frame));
1489 }
1490
1491 size_t ProcessStopWaitingPacketAtLevel(uint64_t number,
1492 QuicStopWaitingFrame frame,
dschinazi17d42422019-06-18 16:35:07 -07001493 EncryptionLevel /*level*/) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001494 return ProcessFramePacketAtLevel(number, QuicFrame(frame),
1495 ENCRYPTION_ZERO_RTT);
1496 }
1497
1498 void ProcessGoAwayPacket(QuicGoAwayFrame* frame) {
1499 ProcessFramePacket(QuicFrame(frame));
1500 }
1501
1502 bool IsMissing(uint64_t number) {
fayangc31c9952019-06-05 13:54:48 -07001503 return IsAwaitingPacket(connection_.ack_frame(), QuicPacketNumber(number),
QUICHE teama6ef0a62019-03-07 20:34:33 -05001504 QuicPacketNumber());
1505 }
1506
1507 std::unique_ptr<QuicPacket> ConstructPacket(const QuicPacketHeader& header,
1508 const QuicFrames& frames) {
1509 auto packet = BuildUnsizedDataPacket(&peer_framer_, header, frames);
1510 EXPECT_NE(nullptr, packet.get());
1511 return packet;
1512 }
1513
nharper46833c32019-05-15 21:33:05 -07001514 QuicPacketHeader ConstructPacketHeader(uint64_t number,
1515 EncryptionLevel level) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001516 QuicPacketHeader header;
fayangd4291e42019-05-30 10:31:21 -07001517 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version()) &&
QUICHE team8c1daa22019-03-13 08:33:41 -07001518 level < ENCRYPTION_FORWARD_SECURE) {
1519 // Set long header type accordingly.
1520 header.version_flag = true;
nharperc6b99512019-09-19 11:13:48 -07001521 header.form = IETF_QUIC_LONG_HEADER_PACKET;
QUICHE team8c1daa22019-03-13 08:33:41 -07001522 header.long_packet_type = EncryptionlevelToLongHeaderType(level);
1523 if (QuicVersionHasLongHeaderLengths(
1524 peer_framer_.version().transport_version)) {
1525 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
1526 if (header.long_packet_type == INITIAL) {
1527 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
1528 }
1529 }
1530 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001531 // Set connection_id to peer's in memory representation as this data packet
1532 // is created by peer_framer.
dschinazi5e1a7b22019-07-31 12:23:21 -07001533 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
QUICHE team2252b702019-05-14 23:55:14 -04001534 header.source_connection_id = connection_id_;
1535 header.source_connection_id_included = connection_id_included_;
1536 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1537 } else {
1538 header.destination_connection_id = connection_id_;
1539 header.destination_connection_id_included = connection_id_included_;
1540 }
fayangd4291e42019-05-30 10:31:21 -07001541 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version()) &&
QUICHE teama6ef0a62019-03-07 20:34:33 -05001542 peer_framer_.perspective() == Perspective::IS_SERVER) {
1543 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
QUICHE team8c1daa22019-03-13 08:33:41 -07001544 if (header.version_flag) {
1545 header.source_connection_id = connection_id_;
1546 header.source_connection_id_included = CONNECTION_ID_PRESENT;
1547 if (GetParam().version.handshake_protocol == PROTOCOL_QUIC_CRYPTO &&
1548 header.long_packet_type == ZERO_RTT_PROTECTED) {
QUICHE team548d51b2019-03-14 10:06:54 -07001549 header.nonce = &kTestDiversificationNonce;
QUICHE team8c1daa22019-03-13 08:33:41 -07001550 }
1551 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001552 }
QUICHE team2252b702019-05-14 23:55:14 -04001553 header.packet_number_length = packet_number_length_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001554 header.packet_number = QuicPacketNumber(number);
nharper46833c32019-05-15 21:33:05 -07001555 return header;
1556 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001557
nharper46833c32019-05-15 21:33:05 -07001558 std::unique_ptr<QuicPacket> ConstructDataPacket(uint64_t number,
1559 bool has_stop_waiting,
1560 EncryptionLevel level) {
1561 QuicPacketHeader header = ConstructPacketHeader(number, level);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001562 QuicFrames frames;
1563 frames.push_back(QuicFrame(frame1_));
1564 if (has_stop_waiting) {
1565 frames.push_back(QuicFrame(stop_waiting_));
1566 }
1567 return ConstructPacket(header, frames);
1568 }
1569
wub8a5dafa2020-05-13 12:30:17 -07001570 std::unique_ptr<SerializedPacket> ConstructProbingPacket() {
fkastenholz305e1732019-06-18 05:01:22 -07001571 if (VersionHasIetfQuicFrames(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001572 QuicPathFrameBuffer payload = {
1573 {0xde, 0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xfe}};
1574 return QuicPacketCreatorPeer::
1575 SerializePathChallengeConnectivityProbingPacket(&peer_creator_,
1576 &payload);
1577 }
1578 return QuicPacketCreatorPeer::SerializeConnectivityProbingPacket(
1579 &peer_creator_);
1580 }
1581
1582 std::unique_ptr<QuicPacket> ConstructClosePacket(uint64_t number) {
1583 QuicPacketHeader header;
1584 // Set connection_id to peer's in memory representation as this connection
1585 // close packet is created by peer_framer.
dschinazi5e1a7b22019-07-31 12:23:21 -07001586 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
QUICHE team2252b702019-05-14 23:55:14 -04001587 header.source_connection_id = connection_id_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001588 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
fayangd4291e42019-05-30 10:31:21 -07001589 if (!VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04001590 header.source_connection_id_included = CONNECTION_ID_PRESENT;
1591 }
1592 } else {
1593 header.destination_connection_id = connection_id_;
fayangd4291e42019-05-30 10:31:21 -07001594 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04001595 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1596 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001597 }
1598
QUICHE team2252b702019-05-14 23:55:14 -04001599 header.packet_number = QuicPacketNumber(number);
1600
fkastenholz0d6554a2019-08-05 12:20:35 -07001601 QuicErrorCode kQuicErrorCode = QUIC_PEER_GOING_AWAY;
fkastenholz591814c2019-09-06 12:11:46 -07001602 QuicConnectionCloseFrame qccf(peer_framer_.transport_version(),
1603 kQuicErrorCode, "",
1604 /*transport_close_frame_type=*/0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001605 QuicFrames frames;
1606 frames.push_back(QuicFrame(&qccf));
1607 return ConstructPacket(header, frames);
1608 }
1609
1610 QuicTime::Delta DefaultRetransmissionTime() {
1611 return QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
1612 }
1613
1614 QuicTime::Delta DefaultDelayedAckTime() {
1615 return QuicTime::Delta::FromMilliseconds(kDefaultDelayedAckTimeMs);
1616 }
1617
1618 const QuicStopWaitingFrame InitStopWaitingFrame(uint64_t least_unacked) {
1619 QuicStopWaitingFrame frame;
1620 frame.least_unacked = QuicPacketNumber(least_unacked);
1621 return frame;
1622 }
1623
1624 // Construct a ack_frame that acks all packet numbers between 1 and
1625 // |largest_acked|, except |missing|.
1626 // REQUIRES: 1 <= |missing| < |largest_acked|
1627 QuicAckFrame ConstructAckFrame(uint64_t largest_acked, uint64_t missing) {
1628 return ConstructAckFrame(QuicPacketNumber(largest_acked),
1629 QuicPacketNumber(missing));
1630 }
1631
1632 QuicAckFrame ConstructAckFrame(QuicPacketNumber largest_acked,
1633 QuicPacketNumber missing) {
1634 if (missing == QuicPacketNumber(1)) {
1635 return InitAckFrame({{missing + 1, largest_acked + 1}});
1636 }
1637 return InitAckFrame(
1638 {{QuicPacketNumber(1), missing}, {missing + 1, largest_acked + 1}});
1639 }
1640
1641 // Undo nacking a packet within the frame.
1642 void AckPacket(QuicPacketNumber arrived, QuicAckFrame* frame) {
1643 EXPECT_FALSE(frame->packets.Contains(arrived));
1644 frame->packets.Add(arrived);
1645 }
1646
1647 void TriggerConnectionClose() {
1648 // Send an erroneous packet to close the connection.
fkastenholz5d880a92019-06-21 09:01:56 -07001649 EXPECT_CALL(visitor_,
1650 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
1651 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
1652
QUICHE teamcd098022019-03-22 18:49:55 -07001653 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1654 // Triggers a connection by receiving ACK of unsent packet.
1655 QuicAckFrame frame = InitAckFrame(10000);
1656 ProcessAckPacket(1, &frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001657 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1658 nullptr);
fkastenholz5d880a92019-06-21 09:01:56 -07001659 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08001660 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
1661 IsError(QUIC_INVALID_ACK_DATA));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001662 }
1663
1664 void BlockOnNextWrite() {
1665 writer_->BlockOnNextWrite();
1666 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
1667 }
1668
1669 void SimulateNextPacketTooLarge() { writer_->SimulateNextPacketTooLarge(); }
1670
1671 void AlwaysGetPacketTooLarge() { writer_->AlwaysGetPacketTooLarge(); }
1672
1673 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
1674 writer_->SetWritePauseTimeDelta(delta);
1675 }
1676
1677 void CongestionBlockWrites() {
1678 EXPECT_CALL(*send_algorithm_, CanSend(_))
1679 .WillRepeatedly(testing::Return(false));
1680 }
1681
1682 void CongestionUnblockWrites() {
1683 EXPECT_CALL(*send_algorithm_, CanSend(_))
1684 .WillRepeatedly(testing::Return(true));
1685 }
1686
1687 void set_perspective(Perspective perspective) {
1688 connection_.set_perspective(perspective);
1689 if (perspective == Perspective::IS_SERVER) {
1690 connection_.set_can_truncate_connection_ids(true);
wub256b2d62019-11-25 08:46:55 -08001691 QuicConnectionPeer::SetNegotiatedVersion(&connection_);
wubbea386e2020-01-27 09:04:51 -08001692 connection_.OnSuccessfulVersionNegotiation();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001693 }
1694 QuicFramerPeer::SetPerspective(&peer_framer_,
nharper4eba09b2019-06-26 20:17:25 -07001695 QuicUtils::InvertPerspective(perspective));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001696 }
1697
1698 void set_packets_between_probes_base(
1699 const QuicPacketCount packets_between_probes_base) {
wub173916e2019-11-27 14:36:24 -08001700 QuicConnectionPeer::ReInitializeMtuDiscoverer(
1701 &connection_, packets_between_probes_base,
1702 QuicPacketNumber(packets_between_probes_base));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001703 }
1704
1705 bool IsDefaultTestConfiguration() {
1706 TestParams p = GetParam();
1707 return p.ack_response == AckResponse::kImmediate &&
1708 p.version == AllSupportedVersions()[0] && p.no_stop_waiting;
1709 }
1710
fkastenholz5d880a92019-06-21 09:01:56 -07001711 void TestConnectionCloseQuicErrorCode(QuicErrorCode expected_code) {
1712 // Not strictly needed for this test, but is commonly done.
1713 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1714 nullptr);
1715 const std::vector<QuicConnectionCloseFrame>& connection_close_frames =
1716 writer_->connection_close_frames();
1717 ASSERT_EQ(1u, connection_close_frames.size());
bnc77e77b82020-04-05 10:36:49 -07001718
dschinazi39e5e552020-05-06 13:55:24 -07001719 EXPECT_THAT(connection_close_frames[0].quic_error_code,
1720 IsError(expected_code));
bnc77e77b82020-04-05 10:36:49 -07001721
fkastenholz0d6554a2019-08-05 12:20:35 -07001722 if (!VersionHasIetfQuicFrames(version().transport_version)) {
dschinazi39e5e552020-05-06 13:55:24 -07001723 EXPECT_THAT(connection_close_frames[0].wire_error_code,
1724 IsError(expected_code));
fkastenholz0d6554a2019-08-05 12:20:35 -07001725 EXPECT_EQ(GOOGLE_QUIC_CONNECTION_CLOSE,
1726 connection_close_frames[0].close_type);
1727 return;
1728 }
1729
1730 QuicErrorCodeToIetfMapping mapping =
1731 QuicErrorCodeToTransportErrorCode(expected_code);
1732
bnc0054cc62020-04-09 18:22:57 -07001733 if (mapping.is_transport_close) {
fkastenholz0d6554a2019-08-05 12:20:35 -07001734 // This Google QUIC Error Code maps to a transport close,
1735 EXPECT_EQ(IETF_QUIC_TRANSPORT_CONNECTION_CLOSE,
1736 connection_close_frames[0].close_type);
fkastenholz0d6554a2019-08-05 12:20:35 -07001737 } else {
1738 // This maps to an application close.
fkastenholz0d6554a2019-08-05 12:20:35 -07001739 EXPECT_EQ(IETF_QUIC_APPLICATION_CONNECTION_CLOSE,
1740 connection_close_frames[0].close_type);
fkastenholz0d6554a2019-08-05 12:20:35 -07001741 }
bnc0054cc62020-04-09 18:22:57 -07001742 EXPECT_EQ(mapping.error_code, connection_close_frames[0].wire_error_code);
fkastenholz5d880a92019-06-21 09:01:56 -07001743 }
1744
wub031d47c2019-11-21 08:04:07 -08001745 void MtuDiscoveryTestInit() {
1746 set_perspective(Perspective::IS_SERVER);
wub031d47c2019-11-21 08:04:07 -08001747 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
fayang6a258412020-05-28 08:57:12 -07001748 if (version().SupportsAntiAmplificationLimit()) {
1749 QuicConnectionPeer::SetAddressValidated(&connection_);
1750 }
wub031d47c2019-11-21 08:04:07 -08001751 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1752 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
1753 // QuicFramer::GetMaxPlaintextSize uses the smallest max plaintext size
1754 // across all encrypters. The initial encrypter used with IETF QUIC has a
1755 // 16-byte overhead, while the NullEncrypter used throughout this test has a
1756 // 12-byte overhead. This test tests behavior that relies on computing the
1757 // packet size correctly, so by unsetting the initial encrypter, we avoid
1758 // having a mismatch between the overheads for the encrypters used. In
1759 // non-test scenarios all encrypters used for a given connection have the
1760 // same overhead, either 12 bytes for ones using Google QUIC crypto, or 16
1761 // bytes for ones using TLS.
1762 connection_.SetEncrypter(ENCRYPTION_INITIAL, nullptr);
wubecb643f2020-03-19 08:58:46 -07001763 // Prevent packets from being coalesced.
1764 EXPECT_CALL(visitor_, GetHandshakeState())
1765 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
wub031d47c2019-11-21 08:04:07 -08001766 EXPECT_TRUE(connection_.connected());
1767 }
1768
dschinazi1c6e5922020-06-19 10:35:03 -07001769 void PathProbeTestInit(Perspective perspective) {
1770 set_perspective(perspective);
1771 EXPECT_EQ(connection_.perspective(), perspective);
1772 if (perspective == Perspective::IS_SERVER) {
1773 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1774 }
1775 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1776 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
1777 }
1778
dschinazi39e5e552020-05-06 13:55:24 -07001779 void TestClientRetryHandling(bool invalid_retry_tag,
dschinazie7c38a52020-05-29 15:25:45 -07001780 bool missing_original_id_in_config,
1781 bool wrong_original_id_in_config,
1782 bool missing_retry_id_in_config,
1783 bool wrong_retry_id_in_config);
dschinazi39e5e552020-05-06 13:55:24 -07001784
QUICHE teama6ef0a62019-03-07 20:34:33 -05001785 QuicConnectionId connection_id_;
1786 QuicFramer framer_;
1787
1788 MockSendAlgorithm* send_algorithm_;
1789 std::unique_ptr<MockLossAlgorithm> loss_algorithm_;
1790 MockClock clock_;
1791 MockRandom random_generator_;
1792 SimpleBufferAllocator buffer_allocator_;
1793 std::unique_ptr<TestConnectionHelper> helper_;
1794 std::unique_ptr<TestAlarmFactory> alarm_factory_;
1795 QuicFramer peer_framer_;
1796 QuicPacketCreator peer_creator_;
1797 std::unique_ptr<TestPacketWriter> writer_;
1798 TestConnection connection_;
1799 QuicPacketCreator* creator_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001800 QuicSentPacketManager* manager_;
1801 StrictMock<MockQuicConnectionVisitor> visitor_;
1802
1803 QuicStreamFrame frame1_;
1804 QuicStreamFrame frame2_;
nharper46833c32019-05-15 21:33:05 -07001805 QuicCryptoFrame crypto_frame_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001806 QuicAckFrame ack_;
1807 QuicStopWaitingFrame stop_waiting_;
1808 QuicPacketNumberLength packet_number_length_;
1809 QuicConnectionIdIncluded connection_id_included_;
1810
1811 SimpleSessionNotifier notifier_;
fkastenholz5d880a92019-06-21 09:01:56 -07001812
1813 QuicConnectionCloseFrame saved_connection_close_frame_;
1814 int connection_close_frame_count_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001815};
1816
1817// Run all end to end tests with all supported versions.
dschinazi39e5e552020-05-06 13:55:24 -07001818INSTANTIATE_TEST_SUITE_P(QuicConnectionTests,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001819 QuicConnectionTest,
dschinazi142051a2019-09-18 18:17:29 -07001820 ::testing::ValuesIn(GetTestParams()),
1821 ::testing::PrintToStringParamName());
QUICHE teama6ef0a62019-03-07 20:34:33 -05001822
fkastenholz0d6554a2019-08-05 12:20:35 -07001823// These two tests ensure that the QuicErrorCode mapping works correctly.
1824// Both tests expect to see a Google QUIC close if not running IETF QUIC.
1825// If running IETF QUIC, the first will generate a transport connection
1826// close, the second an application connection close.
1827// The connection close codes for the two tests are manually chosen;
1828// they are expected to always map to transport- and application-
dschinazi39e5e552020-05-06 13:55:24 -07001829// closes, respectively. If that changes, new codes should be chosen.
fkastenholz0d6554a2019-08-05 12:20:35 -07001830TEST_P(QuicConnectionTest, CloseErrorCodeTestTransport) {
1831 EXPECT_TRUE(connection_.connected());
1832 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
1833 connection_.CloseConnection(
1834 IETF_QUIC_PROTOCOL_VIOLATION, "Should be transport close",
1835 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1836 EXPECT_FALSE(connection_.connected());
1837 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
1838}
1839
1840// Test that the IETF QUIC Error code mapping function works
1841// properly for application connection close codes.
1842TEST_P(QuicConnectionTest, CloseErrorCodeTestApplication) {
1843 EXPECT_TRUE(connection_.connected());
1844 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
1845 connection_.CloseConnection(
1846 QUIC_HEADERS_STREAM_DATA_DECOMPRESS_FAILURE,
1847 "Should be application close",
1848 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1849 EXPECT_FALSE(connection_.connected());
1850 TestConnectionCloseQuicErrorCode(QUIC_HEADERS_STREAM_DATA_DECOMPRESS_FAILURE);
1851}
1852
QUICHE teama6ef0a62019-03-07 20:34:33 -05001853TEST_P(QuicConnectionTest, SelfAddressChangeAtClient) {
1854 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1855
1856 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
1857 EXPECT_TRUE(connection_.connected());
1858
nharper46833c32019-05-15 21:33:05 -07001859 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07001860 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1861 } else {
nharper46833c32019-05-15 21:33:05 -07001862 EXPECT_CALL(visitor_, OnStreamFrame(_));
1863 }
wub8a5dafa2020-05-13 12:30:17 -07001864 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
1865 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001866 // Cause change in self_address.
1867 QuicIpAddress host;
1868 host.FromString("1.1.1.1");
1869 QuicSocketAddress self_address(host, 123);
nharper46833c32019-05-15 21:33:05 -07001870 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1871 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1872 } else {
1873 EXPECT_CALL(visitor_, OnStreamFrame(_));
1874 }
wub8a5dafa2020-05-13 12:30:17 -07001875 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address,
1876 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001877 EXPECT_TRUE(connection_.connected());
1878}
1879
1880TEST_P(QuicConnectionTest, SelfAddressChangeAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001881 set_perspective(Perspective::IS_SERVER);
1882 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1883
1884 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1885 EXPECT_TRUE(connection_.connected());
1886
nharper46833c32019-05-15 21:33:05 -07001887 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07001888 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1889 } else {
nharper46833c32019-05-15 21:33:05 -07001890 EXPECT_CALL(visitor_, OnStreamFrame(_));
1891 }
wub8a5dafa2020-05-13 12:30:17 -07001892 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
1893 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001894 // Cause change in self_address.
1895 QuicIpAddress host;
1896 host.FromString("1.1.1.1");
1897 QuicSocketAddress self_address(host, 123);
1898 EXPECT_CALL(visitor_, AllowSelfAddressChange()).WillOnce(Return(false));
fkastenholz5d880a92019-06-21 09:01:56 -07001899 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
wub8a5dafa2020-05-13 12:30:17 -07001900 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address,
1901 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001902 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07001903 TestConnectionCloseQuicErrorCode(QUIC_ERROR_MIGRATING_ADDRESS);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001904}
1905
1906TEST_P(QuicConnectionTest, AllowSelfAddressChangeToMappedIpv4AddressAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001907 set_perspective(Perspective::IS_SERVER);
1908 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1909
1910 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1911 EXPECT_TRUE(connection_.connected());
1912
nharper46833c32019-05-15 21:33:05 -07001913 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07001914 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(3);
1915 } else {
nharper46833c32019-05-15 21:33:05 -07001916 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(3);
1917 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001918 QuicIpAddress host;
1919 host.FromString("1.1.1.1");
1920 QuicSocketAddress self_address1(host, 443);
wub8a5dafa2020-05-13 12:30:17 -07001921 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address1,
1922 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001923 // Cause self_address change to mapped Ipv4 address.
1924 QuicIpAddress host2;
dmcardlecf0bfcf2019-12-13 08:08:21 -08001925 host2.FromString(quiche::QuicheStrCat(
1926 "::ffff:", connection_.self_address().host().ToString()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001927 QuicSocketAddress self_address2(host2, connection_.self_address().port());
wub8a5dafa2020-05-13 12:30:17 -07001928 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address2,
1929 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001930 EXPECT_TRUE(connection_.connected());
1931 // self_address change back to Ipv4 address.
wub8a5dafa2020-05-13 12:30:17 -07001932 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address1,
1933 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001934 EXPECT_TRUE(connection_.connected());
1935}
1936
1937TEST_P(QuicConnectionTest, ClientAddressChangeAndPacketReordered) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001938 set_perspective(Perspective::IS_SERVER);
1939 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1940
1941 // Clear direct_peer_address.
1942 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1943 // Clear effective_peer_address, it is the same as direct_peer_address for
1944 // this test.
1945 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1946 QuicSocketAddress());
1947
nharper46833c32019-05-15 21:33:05 -07001948 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07001949 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1950 } else {
nharper46833c32019-05-15 21:33:05 -07001951 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1952 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001953 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001954 const QuicSocketAddress kNewPeerAddress =
1955 QuicSocketAddress(QuicIpAddress::Loopback6(),
1956 /*port=*/23456);
wub8a5dafa2020-05-13 12:30:17 -07001957 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
1958 kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001959 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1960 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1961
1962 // Decrease packet number to simulate out-of-order packets.
1963 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 4);
1964 // This is an old packet, do not migrate.
1965 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
wub8a5dafa2020-05-13 12:30:17 -07001966 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
1967 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001968 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1969 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1970}
1971
1972TEST_P(QuicConnectionTest, PeerAddressChangeAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001973 set_perspective(Perspective::IS_SERVER);
1974 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1975 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1976
1977 // Clear direct_peer_address.
1978 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1979 // Clear effective_peer_address, it is the same as direct_peer_address for
1980 // this test.
1981 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1982 QuicSocketAddress());
1983 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1984
nharper46833c32019-05-15 21:33:05 -07001985 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07001986 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1987 } else {
nharper46833c32019-05-15 21:33:05 -07001988 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1989 }
wub8a5dafa2020-05-13 12:30:17 -07001990 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
1991 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001992 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1993 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1994
1995 // Process another packet with a different peer address on server side will
1996 // start connection migration.
1997 const QuicSocketAddress kNewPeerAddress =
1998 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
1999 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
wub8a5dafa2020-05-13 12:30:17 -07002000 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2001 kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002002 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2003 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2004}
2005
2006TEST_P(QuicConnectionTest, EffectivePeerAddressChangeAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002007 set_perspective(Perspective::IS_SERVER);
2008 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2009 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
fayang6a258412020-05-28 08:57:12 -07002010 if (version().SupportsAntiAmplificationLimit()) {
2011 QuicConnectionPeer::SetAddressValidated(&connection_);
2012 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002013
2014 // Clear direct_peer_address.
2015 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2016 // Clear effective_peer_address, it is different from direct_peer_address for
2017 // this test.
2018 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2019 QuicSocketAddress());
2020 const QuicSocketAddress kEffectivePeerAddress =
2021 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/43210);
2022 connection_.ReturnEffectivePeerAddressForNextPacket(kEffectivePeerAddress);
2023
nharper46833c32019-05-15 21:33:05 -07002024 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07002025 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2026 } else {
nharper46833c32019-05-15 21:33:05 -07002027 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2028 }
wub8a5dafa2020-05-13 12:30:17 -07002029 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2030 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002031 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2032 EXPECT_EQ(kEffectivePeerAddress, connection_.effective_peer_address());
2033
2034 // Process another packet with the same direct peer address and different
2035 // effective peer address on server side will start connection migration.
2036 const QuicSocketAddress kNewEffectivePeerAddress =
2037 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/54321);
2038 connection_.ReturnEffectivePeerAddressForNextPacket(kNewEffectivePeerAddress);
2039 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
wub8a5dafa2020-05-13 12:30:17 -07002040 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2041 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002042 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2043 EXPECT_EQ(kNewEffectivePeerAddress, connection_.effective_peer_address());
2044
2045 // Process another packet with a different direct peer address and the same
2046 // effective peer address on server side will not start connection migration.
2047 const QuicSocketAddress kNewPeerAddress =
2048 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2049 connection_.ReturnEffectivePeerAddressForNextPacket(kNewEffectivePeerAddress);
2050 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2051 // ack_frame is used to complete the migration started by the last packet, we
2052 // need to make sure a new migration does not start after the previous one is
2053 // completed.
2054 QuicAckFrame ack_frame = InitAckFrame(1);
2055 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
2056 ProcessFramePacketWithAddresses(QuicFrame(&ack_frame), kSelfAddress,
2057 kNewPeerAddress);
2058 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2059 EXPECT_EQ(kNewEffectivePeerAddress, connection_.effective_peer_address());
2060
2061 // Process another packet with different direct peer address and different
2062 // effective peer address on server side will start connection migration.
2063 const QuicSocketAddress kNewerEffectivePeerAddress =
2064 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/65432);
2065 const QuicSocketAddress kFinalPeerAddress =
2066 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/34567);
2067 connection_.ReturnEffectivePeerAddressForNextPacket(
2068 kNewerEffectivePeerAddress);
2069 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
wub8a5dafa2020-05-13 12:30:17 -07002070 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2071 kFinalPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002072 EXPECT_EQ(kFinalPeerAddress, connection_.peer_address());
2073 EXPECT_EQ(kNewerEffectivePeerAddress, connection_.effective_peer_address());
2074 EXPECT_EQ(PORT_CHANGE, connection_.active_effective_peer_migration_type());
2075
2076 // While the previous migration is ongoing, process another packet with the
2077 // same direct peer address and different effective peer address on server
2078 // side will start a new connection migration.
2079 const QuicSocketAddress kNewestEffectivePeerAddress =
2080 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/65430);
2081 connection_.ReturnEffectivePeerAddressForNextPacket(
2082 kNewestEffectivePeerAddress);
2083 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
2084 EXPECT_CALL(*send_algorithm_, OnConnectionMigration()).Times(1);
wub8a5dafa2020-05-13 12:30:17 -07002085 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2086 kFinalPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002087 EXPECT_EQ(kFinalPeerAddress, connection_.peer_address());
2088 EXPECT_EQ(kNewestEffectivePeerAddress, connection_.effective_peer_address());
2089 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
2090 connection_.active_effective_peer_migration_type());
2091}
2092
zhongyif06ca342020-02-24 14:11:13 -08002093TEST_P(QuicConnectionTest, ReceivePathProbeWithNoAddressChangeAtServer) {
dschinazi1c6e5922020-06-19 10:35:03 -07002094 PathProbeTestInit(Perspective::IS_SERVER);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002095
2096 // Clear direct_peer_address.
2097 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2098 // Clear effective_peer_address, it is the same as direct_peer_address for
2099 // this test.
2100 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2101 QuicSocketAddress());
2102 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2103
nharper46833c32019-05-15 21:33:05 -07002104 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07002105 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2106 } else {
nharper46833c32019-05-15 21:33:05 -07002107 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2108 }
wub8a5dafa2020-05-13 12:30:17 -07002109 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2110 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002111 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2112 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2113
2114 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyi83161e42019-08-19 09:06:25 -07002115 EXPECT_CALL(visitor_, OnPacketReceived(_, _, false)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002116
2117 // Process a padded PING or PATH CHALLENGE packet with no peer address change
2118 // on server side will be ignored.
wub8a5dafa2020-05-13 12:30:17 -07002119 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
zhongyif06ca342020-02-24 14:11:13 -08002120
QUICHE teama6ef0a62019-03-07 20:34:33 -05002121 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2122 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2123 probing_packet->encrypted_length),
2124 clock_.Now()));
2125
2126 uint64_t num_probing_received =
2127 connection_.GetStats().num_connectivity_probing_received;
2128 ProcessReceivedPacket(kSelfAddress, kPeerAddress, *received);
2129
2130 EXPECT_EQ(num_probing_received,
2131 connection_.GetStats().num_connectivity_probing_received);
2132 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2133 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2134}
2135
wub54bd5bf2020-05-13 13:02:16 -07002136// Regression test for b/150161358.
2137TEST_P(QuicConnectionTest, BufferedMtuPacketTooBig) {
wub54bd5bf2020-05-13 13:02:16 -07002138 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
2139 writer_->SetWriteBlocked();
2140
2141 // Send a MTU packet while blocked. It should be buffered.
2142 connection_.SendMtuDiscoveryPacket(kMaxOutgoingPacketSize);
2143 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2144 EXPECT_TRUE(writer_->IsWriteBlocked());
2145
2146 writer_->AlwaysGetPacketTooLarge();
2147 writer_->SetWritable();
2148 connection_.OnCanWrite();
2149}
2150
QUICHE teama6ef0a62019-03-07 20:34:33 -05002151TEST_P(QuicConnectionTest, WriteOutOfOrderQueuedPackets) {
2152 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
fayangc31c9952019-06-05 13:54:48 -07002153 if (!IsDefaultTestConfiguration()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002154 return;
2155 }
2156
2157 set_perspective(Perspective::IS_CLIENT);
2158
2159 BlockOnNextWrite();
2160
2161 QuicStreamId stream_id = 2;
2162 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
2163
2164 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2165
2166 writer_->SetWritable();
2167 connection_.SendConnectivityProbingPacket(writer_.get(),
2168 connection_.peer_address());
fayange62e63c2019-12-04 07:16:25 -08002169 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
2170 connection_.OnCanWrite();
QUICHE teama6ef0a62019-03-07 20:34:33 -05002171}
2172
2173TEST_P(QuicConnectionTest, DiscardQueuedPacketsAfterConnectionClose) {
2174 // Regression test for b/74073386.
2175 {
2176 InSequence seq;
rch39c88ab2019-10-16 19:24:40 -07002177 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2178 .Times(AtLeast(1));
2179 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002180 }
2181
2182 set_perspective(Perspective::IS_CLIENT);
2183
2184 writer_->SimulateNextPacketTooLarge();
2185
2186 // This packet write should fail, which should cause the connection to close
2187 // after sending a connection close packet, then the failed packet should be
2188 // queued.
2189 connection_.SendStreamDataWithString(/*id=*/2, "foo", 0, NO_FIN);
2190
2191 EXPECT_FALSE(connection_.connected());
fayange62e63c2019-12-04 07:16:25 -08002192 // No need to buffer packets.
2193 EXPECT_EQ(0u, connection_.NumQueuedPackets());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002194
2195 EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
2196 connection_.OnCanWrite();
fayang0f0c4e62019-07-16 08:55:54 -07002197 EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002198}
2199
zhongyif06ca342020-02-24 14:11:13 -08002200// Receive a path probe request at the server side, i.e.,
2201// in non-IETF version: receive a padded PING packet with a peer addess change;
2202// in IETF version: receive a packet contains PATH CHALLENGE with peer address
2203// change.
2204TEST_P(QuicConnectionTest, ReceivePathProbingAtServer) {
dschinazi1c6e5922020-06-19 10:35:03 -07002205 PathProbeTestInit(Perspective::IS_SERVER);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002206
2207 // Clear direct_peer_address.
2208 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2209 // Clear effective_peer_address, it is the same as direct_peer_address for
2210 // this test.
2211 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2212 QuicSocketAddress());
2213 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2214
nharper46833c32019-05-15 21:33:05 -07002215 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07002216 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2217 } else {
nharper46833c32019-05-15 21:33:05 -07002218 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2219 }
wub8a5dafa2020-05-13 12:30:17 -07002220 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2221 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002222 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2223 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2224
2225 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyif06ca342020-02-24 14:11:13 -08002226 if (!GetParam().version.HasIetfQuicFrames()) {
2227 EXPECT_CALL(visitor_,
2228 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2229 .Times(1);
2230 } else {
2231 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2232 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002233 // Process a padded PING packet from a new peer address on server side
2234 // is effectively receiving a connectivity probing.
2235 const QuicSocketAddress kNewPeerAddress =
2236 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2237
wub8a5dafa2020-05-13 12:30:17 -07002238 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
QUICHE teama6ef0a62019-03-07 20:34:33 -05002239 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2240 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2241 probing_packet->encrypted_length),
2242 clock_.Now()));
2243
2244 uint64_t num_probing_received =
2245 connection_.GetStats().num_connectivity_probing_received;
2246 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2247
2248 EXPECT_EQ(num_probing_received + 1,
2249 connection_.GetStats().num_connectivity_probing_received);
2250 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2251 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2252
2253 // Process another packet with the old peer address on server side will not
2254 // start peer migration.
2255 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
wub8a5dafa2020-05-13 12:30:17 -07002256 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2257 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002258 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2259 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2260}
2261
zhongyif06ca342020-02-24 14:11:13 -08002262// Receive a padded PING packet with a port change on server side.
2263TEST_P(QuicConnectionTest, ReceivePaddedPingWithPortChangeAtServer) {
2264 set_perspective(Perspective::IS_SERVER);
2265 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2266 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2267
2268 // Clear direct_peer_address.
2269 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2270 // Clear effective_peer_address, it is the same as direct_peer_address for
2271 // this test.
2272 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2273 QuicSocketAddress());
2274 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2275
zhongyif06ca342020-02-24 14:11:13 -08002276 if (GetParam().version.UsesCryptoFrames()) {
zhongyif06ca342020-02-24 14:11:13 -08002277 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2278 } else {
zhongyif06ca342020-02-24 14:11:13 -08002279 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2280 }
wub8a5dafa2020-05-13 12:30:17 -07002281 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2282 kPeerAddress);
zhongyif06ca342020-02-24 14:11:13 -08002283 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2284 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2285
2286 if (GetParam().version.HasIetfQuicFrames()) {
2287 // In IETF version, a padded PING packet with port change is not taken as
2288 // connectivity probe.
2289 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2290 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2291 } else {
2292 // In non-IETF version, process a padded PING packet from a new peer
2293 // address on server side is effectively receiving a connectivity probing.
2294 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2295 EXPECT_CALL(visitor_,
2296 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2297 .Times(1);
2298 }
2299 const QuicSocketAddress kNewPeerAddress =
2300 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2301
2302 QuicFrames frames;
2303 // Write a PING frame, which has no data payload.
2304 QuicPingFrame ping_frame;
2305 frames.push_back(QuicFrame(ping_frame));
2306
2307 // Add padding to the rest of the packet.
2308 QuicPaddingFrame padding_frame;
2309 frames.push_back(QuicFrame(padding_frame));
2310
2311 uint64_t num_probing_received =
2312 connection_.GetStats().num_connectivity_probing_received;
2313
2314 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress);
2315
2316 if (GetParam().version.HasIetfQuicFrames()) {
2317 // Padded PING with port changen is not considered as connectivity probe but
2318 // a PORT CHANGE.
2319 EXPECT_EQ(num_probing_received,
2320 connection_.GetStats().num_connectivity_probing_received);
2321 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2322 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2323 } else {
2324 EXPECT_EQ(num_probing_received + 1,
2325 connection_.GetStats().num_connectivity_probing_received);
2326 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2327 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2328 }
2329
2330 // Process another packet with the old peer address on server side.
2331 if (GetParam().version.HasIetfQuicFrames()) {
2332 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2333 } else {
2334 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2335 }
wub8a5dafa2020-05-13 12:30:17 -07002336 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2337 kPeerAddress);
zhongyif06ca342020-02-24 14:11:13 -08002338 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2339 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2340}
2341
2342TEST_P(QuicConnectionTest, ReceiveReorderedPathProbingAtServer) {
dschinazi1c6e5922020-06-19 10:35:03 -07002343 PathProbeTestInit(Perspective::IS_SERVER);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002344
2345 // Clear direct_peer_address.
2346 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2347 // Clear effective_peer_address, it is the same as direct_peer_address for
2348 // this test.
2349 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2350 QuicSocketAddress());
2351 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2352
nharper46833c32019-05-15 21:33:05 -07002353 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07002354 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2355 } else {
nharper46833c32019-05-15 21:33:05 -07002356 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2357 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002358 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
wub8a5dafa2020-05-13 12:30:17 -07002359 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2360 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002361 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2362 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2363
2364 // Decrease packet number to simulate out-of-order packets.
2365 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 4);
2366
2367 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyif06ca342020-02-24 14:11:13 -08002368 if (!GetParam().version.HasIetfQuicFrames()) {
2369 EXPECT_CALL(visitor_,
2370 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2371 .Times(1);
2372 } else {
2373 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2374 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002375
2376 // Process a padded PING packet from a new peer address on server side
2377 // is effectively receiving a connectivity probing, even if a newer packet has
2378 // been received before this one.
2379 const QuicSocketAddress kNewPeerAddress =
2380 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2381
wub8a5dafa2020-05-13 12:30:17 -07002382 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
QUICHE teama6ef0a62019-03-07 20:34:33 -05002383 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2384 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2385 probing_packet->encrypted_length),
2386 clock_.Now()));
2387
2388 uint64_t num_probing_received =
2389 connection_.GetStats().num_connectivity_probing_received;
2390 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2391
2392 EXPECT_EQ(num_probing_received + 1,
2393 connection_.GetStats().num_connectivity_probing_received);
2394 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2395 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2396}
2397
2398TEST_P(QuicConnectionTest, MigrateAfterProbingAtServer) {
dschinazi1c6e5922020-06-19 10:35:03 -07002399 PathProbeTestInit(Perspective::IS_SERVER);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002400
2401 // Clear direct_peer_address.
2402 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2403 // Clear effective_peer_address, it is the same as direct_peer_address for
2404 // this test.
2405 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2406 QuicSocketAddress());
2407 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2408
nharper46833c32019-05-15 21:33:05 -07002409 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07002410 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2411 } else {
nharper46833c32019-05-15 21:33:05 -07002412 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2413 }
wub8a5dafa2020-05-13 12:30:17 -07002414 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2415 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002416 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2417 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2418
2419 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyif06ca342020-02-24 14:11:13 -08002420 if (!GetParam().version.HasIetfQuicFrames()) {
2421 EXPECT_CALL(visitor_,
2422 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2423 .Times(1);
2424 } else {
2425 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2426 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002427
2428 // Process a padded PING packet from a new peer address on server side
2429 // is effectively receiving a connectivity probing.
2430 const QuicSocketAddress kNewPeerAddress =
2431 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2432
wub8a5dafa2020-05-13 12:30:17 -07002433 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
QUICHE teama6ef0a62019-03-07 20:34:33 -05002434 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2435 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2436 probing_packet->encrypted_length),
2437 clock_.Now()));
2438 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2439 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2440 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2441
2442 // Process another non-probing packet with the new peer address on server
2443 // side will start peer migration.
2444 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2445
wub8a5dafa2020-05-13 12:30:17 -07002446 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2447 kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002448 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2449 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2450}
2451
2452TEST_P(QuicConnectionTest, ReceivePaddedPingAtClient) {
2453 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
dschinazi1c6e5922020-06-19 10:35:03 -07002454 PathProbeTestInit(Perspective::IS_CLIENT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002455
2456 // Clear direct_peer_address.
2457 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2458 // Clear effective_peer_address, it is the same as direct_peer_address for
2459 // this test.
2460 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2461 QuicSocketAddress());
2462 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2463
nharper46833c32019-05-15 21:33:05 -07002464 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07002465 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2466 } else {
nharper46833c32019-05-15 21:33:05 -07002467 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2468 }
wub8a5dafa2020-05-13 12:30:17 -07002469 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2470 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002471 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2472 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2473
2474 // Client takes all padded PING packet as speculative connectivity
2475 // probing packet, and reports to visitor.
2476 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyi83161e42019-08-19 09:06:25 -07002477 EXPECT_CALL(visitor_, OnPacketReceived(_, _, false)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002478
wub8a5dafa2020-05-13 12:30:17 -07002479 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
QUICHE teama6ef0a62019-03-07 20:34:33 -05002480 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2481 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2482 probing_packet->encrypted_length),
2483 clock_.Now()));
2484 uint64_t num_probing_received =
2485 connection_.GetStats().num_connectivity_probing_received;
2486 ProcessReceivedPacket(kSelfAddress, kPeerAddress, *received);
2487
2488 EXPECT_EQ(num_probing_received,
2489 connection_.GetStats().num_connectivity_probing_received);
2490 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2491 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2492}
2493
zhongyif06ca342020-02-24 14:11:13 -08002494TEST_P(QuicConnectionTest, ReceiveConnectivityProbingResponseAtClient) {
2495 // TODO(b/150095484): add test coverage for IETF to verify that client takes
2496 // PATH RESPONSE with peer address change as correct validation on the new
2497 // path.
2498 if (GetParam().version.HasIetfQuicFrames()) {
2499 return;
2500 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002501 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
dschinazi1c6e5922020-06-19 10:35:03 -07002502 PathProbeTestInit(Perspective::IS_CLIENT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002503
2504 // Clear direct_peer_address.
2505 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2506 // Clear effective_peer_address, it is the same as direct_peer_address for
2507 // this test.
2508 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2509 QuicSocketAddress());
2510 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2511
nharper46833c32019-05-15 21:33:05 -07002512 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07002513 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2514 } else {
nharper46833c32019-05-15 21:33:05 -07002515 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2516 }
wub8a5dafa2020-05-13 12:30:17 -07002517 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2518 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002519 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2520 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2521
2522 // Process a padded PING packet with a different self address on client side
2523 // is effectively receiving a connectivity probing.
2524 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyif06ca342020-02-24 14:11:13 -08002525 if (!GetParam().version.HasIetfQuicFrames()) {
2526 EXPECT_CALL(visitor_,
2527 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2528 .Times(1);
2529 } else {
2530 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2531 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002532
2533 const QuicSocketAddress kNewSelfAddress =
2534 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2535
wub8a5dafa2020-05-13 12:30:17 -07002536 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
QUICHE teama6ef0a62019-03-07 20:34:33 -05002537 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2538 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2539 probing_packet->encrypted_length),
2540 clock_.Now()));
2541 uint64_t num_probing_received =
2542 connection_.GetStats().num_connectivity_probing_received;
2543 ProcessReceivedPacket(kNewSelfAddress, kPeerAddress, *received);
2544
2545 EXPECT_EQ(num_probing_received + 1,
2546 connection_.GetStats().num_connectivity_probing_received);
2547 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2548 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2549}
2550
2551TEST_P(QuicConnectionTest, PeerAddressChangeAtClient) {
2552 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2553 set_perspective(Perspective::IS_CLIENT);
2554 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2555
2556 // Clear direct_peer_address.
2557 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2558 // Clear effective_peer_address, it is the same as direct_peer_address for
2559 // this test.
2560 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2561 QuicSocketAddress());
2562 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2563
nharper46833c32019-05-15 21:33:05 -07002564 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07002565 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2566 } else {
nharper46833c32019-05-15 21:33:05 -07002567 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2568 }
wub8a5dafa2020-05-13 12:30:17 -07002569 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2570 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002571 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2572 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2573
2574 // Process another packet with a different peer address on client side will
2575 // only update peer address.
2576 const QuicSocketAddress kNewPeerAddress =
2577 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2578 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
wub8a5dafa2020-05-13 12:30:17 -07002579 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2580 kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002581 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2582 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2583}
2584
2585TEST_P(QuicConnectionTest, MaxPacketSize) {
2586 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2587 EXPECT_EQ(1350u, connection_.max_packet_length());
2588}
2589
dschinazi4ad1f462020-01-16 11:56:52 -08002590TEST_P(QuicConnectionTest, PeerLowersMaxPacketSize) {
2591 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2592
2593 // SetFromConfig is always called after construction from InitializeSession.
2594 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
2595 constexpr uint32_t kTestMaxPacketSize = 1233u;
2596 QuicConfig config;
2597 QuicConfigPeer::SetReceivedMaxPacketSize(&config, kTestMaxPacketSize);
2598 connection_.SetFromConfig(config);
2599
2600 EXPECT_EQ(kTestMaxPacketSize, connection_.max_packet_length());
2601}
2602
vasilvvebc5d0c2020-01-16 15:19:21 -08002603TEST_P(QuicConnectionTest, PeerCannotRaiseMaxPacketSize) {
2604 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2605
2606 // SetFromConfig is always called after construction from InitializeSession.
2607 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
2608 constexpr uint32_t kTestMaxPacketSize = 1450u;
2609 QuicConfig config;
2610 QuicConfigPeer::SetReceivedMaxPacketSize(&config, kTestMaxPacketSize);
2611 connection_.SetFromConfig(config);
2612
2613 EXPECT_EQ(kDefaultMaxPacketSize, connection_.max_packet_length());
2614}
2615
QUICHE teama6ef0a62019-03-07 20:34:33 -05002616TEST_P(QuicConnectionTest, SmallerServerMaxPacketSize) {
2617 TestConnection connection(TestConnectionId(), kPeerAddress, helper_.get(),
2618 alarm_factory_.get(), writer_.get(),
2619 Perspective::IS_SERVER, version());
2620 EXPECT_EQ(Perspective::IS_SERVER, connection.perspective());
2621 EXPECT_EQ(1000u, connection.max_packet_length());
2622}
2623
2624TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSize) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002625 set_perspective(Perspective::IS_SERVER);
2626 connection_.SetMaxPacketLength(1000);
2627
2628 QuicPacketHeader header;
2629 header.destination_connection_id = connection_id_;
2630 header.version_flag = true;
nharper21af28e2019-06-17 15:54:34 -07002631 header.packet_number = QuicPacketNumber(12);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002632
2633 if (QuicVersionHasLongHeaderLengths(
2634 peer_framer_.version().transport_version)) {
2635 header.long_packet_type = INITIAL;
2636 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
2637 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
2638 }
2639
2640 QuicFrames frames;
2641 QuicPaddingFrame padding;
nharper46833c32019-05-15 21:33:05 -07002642 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2643 frames.push_back(QuicFrame(&crypto_frame_));
2644 } else {
2645 frames.push_back(QuicFrame(frame1_));
2646 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002647 frames.push_back(QuicFrame(padding));
2648 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
dschinazi66dea072019-04-09 11:41:06 -07002649 char buffer[kMaxOutgoingPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07002650 size_t encrypted_length =
2651 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12),
dschinazi66dea072019-04-09 11:41:06 -07002652 *packet, buffer, kMaxOutgoingPacketSize);
2653 EXPECT_EQ(kMaxOutgoingPacketSize, encrypted_length);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002654
2655 framer_.set_version(version());
nharper46833c32019-05-15 21:33:05 -07002656 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2657 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
2658 } else {
2659 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2660 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002661 connection_.ProcessUdpPacket(
2662 kSelfAddress, kPeerAddress,
2663 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
2664
dschinazi66dea072019-04-09 11:41:06 -07002665 EXPECT_EQ(kMaxOutgoingPacketSize, connection_.max_packet_length());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002666}
2667
2668TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSizeWhileWriterLimited) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002669 const QuicByteCount lower_max_packet_size = 1240;
2670 writer_->set_max_packet_size(lower_max_packet_size);
2671 set_perspective(Perspective::IS_SERVER);
2672 connection_.SetMaxPacketLength(1000);
2673 EXPECT_EQ(1000u, connection_.max_packet_length());
2674
2675 QuicPacketHeader header;
2676 header.destination_connection_id = connection_id_;
2677 header.version_flag = true;
nharper21af28e2019-06-17 15:54:34 -07002678 header.packet_number = QuicPacketNumber(12);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002679
2680 if (QuicVersionHasLongHeaderLengths(
2681 peer_framer_.version().transport_version)) {
2682 header.long_packet_type = INITIAL;
2683 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
2684 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
2685 }
2686
2687 QuicFrames frames;
2688 QuicPaddingFrame padding;
nharper46833c32019-05-15 21:33:05 -07002689 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2690 frames.push_back(QuicFrame(&crypto_frame_));
2691 } else {
2692 frames.push_back(QuicFrame(frame1_));
2693 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002694 frames.push_back(QuicFrame(padding));
2695 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
dschinazi66dea072019-04-09 11:41:06 -07002696 char buffer[kMaxOutgoingPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07002697 size_t encrypted_length =
2698 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12),
dschinazi66dea072019-04-09 11:41:06 -07002699 *packet, buffer, kMaxOutgoingPacketSize);
2700 EXPECT_EQ(kMaxOutgoingPacketSize, encrypted_length);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002701
2702 framer_.set_version(version());
nharper46833c32019-05-15 21:33:05 -07002703 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2704 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
2705 } else {
2706 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2707 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002708 connection_.ProcessUdpPacket(
2709 kSelfAddress, kPeerAddress,
2710 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
2711
2712 // Here, the limit imposed by the writer is lower than the size of the packet
2713 // received, so the writer max packet size is used.
2714 EXPECT_EQ(lower_max_packet_size, connection_.max_packet_length());
2715}
2716
2717TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriter) {
2718 const QuicByteCount lower_max_packet_size = 1240;
2719 writer_->set_max_packet_size(lower_max_packet_size);
2720
2721 static_assert(lower_max_packet_size < kDefaultMaxPacketSize,
2722 "Default maximum packet size is too low");
2723 connection_.SetMaxPacketLength(kDefaultMaxPacketSize);
2724
2725 EXPECT_EQ(lower_max_packet_size, connection_.max_packet_length());
2726}
2727
2728TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriterForNewConnection) {
2729 const QuicConnectionId connection_id = TestConnectionId(17);
2730 const QuicByteCount lower_max_packet_size = 1240;
2731 writer_->set_max_packet_size(lower_max_packet_size);
2732 TestConnection connection(connection_id, kPeerAddress, helper_.get(),
2733 alarm_factory_.get(), writer_.get(),
2734 Perspective::IS_CLIENT, version());
2735 EXPECT_EQ(Perspective::IS_CLIENT, connection.perspective());
2736 EXPECT_EQ(lower_max_packet_size, connection.max_packet_length());
2737}
2738
2739TEST_P(QuicConnectionTest, PacketsInOrder) {
2740 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2741
2742 ProcessPacket(1);
fayangc31c9952019-06-05 13:54:48 -07002743 EXPECT_EQ(QuicPacketNumber(1u), LargestAcked(connection_.ack_frame()));
2744 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002745
2746 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07002747 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(connection_.ack_frame()));
2748 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002749
2750 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002751 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
2752 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002753}
2754
2755TEST_P(QuicConnectionTest, PacketsOutOfOrder) {
2756 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2757
2758 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002759 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002760 EXPECT_TRUE(IsMissing(2));
2761 EXPECT_TRUE(IsMissing(1));
2762
2763 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07002764 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002765 EXPECT_FALSE(IsMissing(2));
2766 EXPECT_TRUE(IsMissing(1));
2767
2768 ProcessPacket(1);
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_FALSE(IsMissing(1));
2772}
2773
2774TEST_P(QuicConnectionTest, DuplicatePacket) {
2775 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2776
2777 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002778 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002779 EXPECT_TRUE(IsMissing(2));
2780 EXPECT_TRUE(IsMissing(1));
2781
2782 // Send packet 3 again, but do not set the expectation that
2783 // the visitor OnStreamFrame() will be called.
2784 ProcessDataPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002785 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002786 EXPECT_TRUE(IsMissing(2));
2787 EXPECT_TRUE(IsMissing(1));
2788}
2789
2790TEST_P(QuicConnectionTest, PacketsOutOfOrderWithAdditionsAndLeastAwaiting) {
QUICHE teamcd098022019-03-22 18:49:55 -07002791 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2792 return;
2793 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002794 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2795
2796 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002797 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002798 EXPECT_TRUE(IsMissing(2));
2799 EXPECT_TRUE(IsMissing(1));
2800
2801 ProcessPacket(2);
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(1));
2804
2805 ProcessPacket(5);
fayangc31c9952019-06-05 13:54:48 -07002806 EXPECT_EQ(QuicPacketNumber(5u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002807 EXPECT_TRUE(IsMissing(1));
2808 EXPECT_TRUE(IsMissing(4));
2809
2810 // Pretend at this point the client has gotten acks for 2 and 3 and 1 is a
2811 // packet the peer will not retransmit. It indicates this by sending 'least
2812 // awaiting' is 4. The connection should then realize 1 will not be
2813 // retransmitted, and will remove it from the missing list.
2814 QuicAckFrame frame = InitAckFrame(1);
2815 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
2816 ProcessAckPacket(6, &frame);
2817
2818 // Force an ack to be sent.
2819 SendAckPacketToPeer();
2820 EXPECT_TRUE(IsMissing(4));
2821}
2822
QUICHE teama6ef0a62019-03-07 20:34:33 -05002823TEST_P(QuicConnectionTest, RejectUnencryptedStreamData) {
2824 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
2825 if (!IsDefaultTestConfiguration()) {
2826 return;
2827 }
2828
2829 // Process an unencrypted packet from the non-crypto stream.
2830 frame1_.stream_id = 3;
2831 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fkastenholz5d880a92019-06-21 09:01:56 -07002832 EXPECT_CALL(visitor_,
2833 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
nharper2c9f02a2019-05-08 10:25:50 -07002834 EXPECT_QUIC_PEER_BUG(ProcessDataPacketAtLevel(1, false, ENCRYPTION_INITIAL),
2835 "");
fkastenholz5d880a92019-06-21 09:01:56 -07002836 TestConnectionCloseQuicErrorCode(QUIC_UNENCRYPTED_STREAM_DATA);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002837}
2838
2839TEST_P(QuicConnectionTest, OutOfOrderReceiptCausesAckSend) {
2840 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2841
2842 ProcessPacket(3);
fayang6dba4902019-06-17 10:04:23 -07002843 // Should not cause an ack.
2844 EXPECT_EQ(0u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002845
2846 ProcessPacket(2);
fayang6dba4902019-06-17 10:04:23 -07002847 // Should ack immediately, since this fills the last hole.
2848 EXPECT_EQ(1u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002849
2850 ProcessPacket(1);
2851 // Should ack immediately, since this fills the last hole.
fayang6dba4902019-06-17 10:04:23 -07002852 EXPECT_EQ(2u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002853
2854 ProcessPacket(4);
2855 // Should not cause an ack.
fayang6dba4902019-06-17 10:04:23 -07002856 EXPECT_EQ(2u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002857}
2858
2859TEST_P(QuicConnectionTest, OutOfOrderAckReceiptCausesNoAck) {
2860 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2861
2862 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
2863 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
2864 EXPECT_EQ(2u, writer_->packets_write_attempts());
2865
2866 QuicAckFrame ack1 = InitAckFrame(1);
2867 QuicAckFrame ack2 = InitAckFrame(2);
2868 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
fayang2f2915d2020-01-24 06:47:15 -08002869 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2870 EXPECT_CALL(visitor_, OnOneRttPacketAcknowledged()).Times(1);
2871 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002872 ProcessAckPacket(2, &ack2);
2873 // Should ack immediately since we have missing packets.
2874 EXPECT_EQ(2u, writer_->packets_write_attempts());
2875
fayang2f2915d2020-01-24 06:47:15 -08002876 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2877 EXPECT_CALL(visitor_, OnOneRttPacketAcknowledged()).Times(0);
2878 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002879 ProcessAckPacket(1, &ack1);
2880 // Should not ack an ack filling a missing packet.
2881 EXPECT_EQ(2u, writer_->packets_write_attempts());
2882}
2883
2884TEST_P(QuicConnectionTest, AckReceiptCausesAckSend) {
2885 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2886 QuicPacketNumber original, second;
2887
2888 QuicByteCount packet_size =
2889 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &original); // 1st packet.
2890 SendStreamDataToPeer(3, "bar", 3, NO_FIN, &second); // 2nd packet.
2891
2892 QuicAckFrame frame = InitAckFrame({{second, second + 1}});
2893 // First nack triggers early retransmit.
2894 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07002895 lost_packets.push_back(LostPacket(original, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002896 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07002897 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
2898 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002899 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2900 QuicPacketNumber retransmission;
2901 // Packet 1 is short header for IETF QUIC because the encryption level
2902 // switched to ENCRYPTION_FORWARD_SECURE in SendStreamDataToPeer.
fayangd4291e42019-05-30 10:31:21 -07002903 EXPECT_CALL(*send_algorithm_,
2904 OnPacketSent(_, _, _,
2905 VersionHasIetfInvariantHeader(
2906 GetParam().version.transport_version)
2907 ? packet_size
2908 : packet_size - kQuicVersionSize,
2909 _))
QUICHE teama6ef0a62019-03-07 20:34:33 -05002910 .WillOnce(SaveArg<2>(&retransmission));
2911
2912 ProcessAckPacket(&frame);
2913
2914 QuicAckFrame frame2 = ConstructAckFrame(retransmission, original);
2915 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2916 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
2917 ProcessAckPacket(&frame2);
2918
2919 // Now if the peer sends an ack which still reports the retransmitted packet
2920 // as missing, that will bundle an ack with data after two acks in a row
2921 // indicate the high water mark needs to be raised.
2922 EXPECT_CALL(*send_algorithm_,
2923 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA));
2924 connection_.SendStreamDataWithString(3, "foo", 6, NO_FIN);
2925 // No ack sent.
nharper55fa6132019-05-07 19:37:21 -07002926 size_t padding_frame_count = writer_->padding_frames().size();
2927 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002928 EXPECT_EQ(1u, writer_->stream_frames().size());
2929
2930 // No more packet loss for the rest of the test.
2931 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
2932 .Times(AnyNumber());
2933 ProcessAckPacket(&frame2);
2934 EXPECT_CALL(*send_algorithm_,
2935 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA));
fayang03916692019-05-22 17:57:18 -07002936 connection_.SendStreamDataWithString(3, "foofoofoo", 9, NO_FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002937 // Ack bundled.
2938 if (GetParam().no_stop_waiting) {
fayang8a27b0f2019-11-04 11:27:40 -08002939 // Do not ACK acks.
2940 EXPECT_EQ(1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002941 } else {
2942 EXPECT_EQ(3u, writer_->frame_count());
2943 }
2944 EXPECT_EQ(1u, writer_->stream_frames().size());
fayang8a27b0f2019-11-04 11:27:40 -08002945 if (GetParam().no_stop_waiting) {
fayang03916692019-05-22 17:57:18 -07002946 EXPECT_TRUE(writer_->ack_frames().empty());
2947 } else {
2948 EXPECT_FALSE(writer_->ack_frames().empty());
2949 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002950
2951 // But an ack with no missing packets will not send an ack.
2952 AckPacket(original, &frame2);
2953 ProcessAckPacket(&frame2);
2954 ProcessAckPacket(&frame2);
2955}
2956
2957TEST_P(QuicConnectionTest, AckSentEveryNthPacket) {
2958 connection_.set_ack_frequency_before_ack_decimation(3);
2959
2960 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2961 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(39);
2962
2963 // Expect 13 acks, every 3rd packet.
2964 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(13);
2965 // Receives packets 1 - 39.
2966 for (size_t i = 1; i <= 39; ++i) {
2967 ProcessDataPacket(i);
2968 }
2969}
2970
2971TEST_P(QuicConnectionTest, AckDecimationReducesAcks) {
2972 const size_t kMinRttMs = 40;
2973 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
2974 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
2975 QuicTime::Delta::Zero(), QuicTime::Zero());
2976 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
2977
2978 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
2979
2980 // Start ack decimation from 10th packet.
2981 connection_.set_min_received_before_ack_decimation(10);
2982
2983 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2984 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(30);
2985
2986 // Expect 6 acks: 5 acks between packets 1-10, and ack at 20.
2987 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(6);
2988 // Receives packets 1 - 29.
2989 for (size_t i = 1; i <= 29; ++i) {
2990 ProcessDataPacket(i);
2991 }
2992
2993 // We now receive the 30th packet, and so we send an ack.
2994 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2995 ProcessDataPacket(30);
2996}
2997
2998TEST_P(QuicConnectionTest, AckNeedsRetransmittableFrames) {
ianswett68cf0042019-05-09 08:37:58 -07002999 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003000 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3001 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(99);
3002
3003 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(19);
3004 // Receives packets 1 - 39.
3005 for (size_t i = 1; i <= 39; ++i) {
3006 ProcessDataPacket(i);
3007 }
3008 // Receiving Packet 40 causes 20th ack to send. Session is informed and adds
3009 // WINDOW_UPDATE.
3010 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
3011 .WillOnce(Invoke([this]() {
3012 connection_.SendControlFrame(
3013 QuicFrame(new QuicWindowUpdateFrame(1, 0, 0)));
3014 }));
3015 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3016 EXPECT_EQ(0u, writer_->window_update_frames().size());
3017 ProcessDataPacket(40);
3018 EXPECT_EQ(1u, writer_->window_update_frames().size());
3019
3020 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(9);
3021 // Receives packets 41 - 59.
3022 for (size_t i = 41; i <= 59; ++i) {
3023 ProcessDataPacket(i);
3024 }
3025 // Send a packet containing stream frame.
QUICHE team8c1daa22019-03-13 08:33:41 -07003026 SendStreamDataToPeer(
nharper46833c32019-05-15 21:33:05 -07003027 QuicUtils::GetFirstBidirectionalStreamId(
3028 connection_.version().transport_version, Perspective::IS_CLIENT),
QUICHE team8c1daa22019-03-13 08:33:41 -07003029 "bar", 0, NO_FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003030
3031 // Session will not be informed until receiving another 20 packets.
3032 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(19);
3033 for (size_t i = 60; i <= 98; ++i) {
3034 ProcessDataPacket(i);
3035 EXPECT_EQ(0u, writer_->window_update_frames().size());
3036 }
3037 // Session does not add a retransmittable frame.
3038 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
3039 .WillOnce(Invoke([this]() {
3040 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
3041 }));
3042 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3043 EXPECT_EQ(0u, writer_->ping_frames().size());
3044 ProcessDataPacket(99);
3045 EXPECT_EQ(0u, writer_->window_update_frames().size());
3046 // A ping frame will be added.
3047 EXPECT_EQ(1u, writer_->ping_frames().size());
3048}
3049
ianswett6083a102020-02-09 12:04:04 -08003050TEST_P(QuicConnectionTest, AckNeedsRetransmittableFramesAfterPto) {
ianswett6083a102020-02-09 12:04:04 -08003051 // Disable TLP so the RTO fires immediately.
3052 connection_.SetMaxTailLossProbes(0);
3053 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3054 QuicConfig config;
3055 QuicTagVector connection_options;
3056 connection_options.push_back(kEACK);
3057 config.SetConnectionOptionsToSend(connection_options);
3058 connection_.SetFromConfig(config);
3059
3060 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3061 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3062 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(10);
3063
3064 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(4);
3065 // Receive packets 1 - 9.
3066 for (size_t i = 1; i <= 9; ++i) {
3067 ProcessDataPacket(i);
3068 }
3069
3070 // Send a ping and fire the retransmission alarm.
3071 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3072 SendPing();
3073 QuicTime retransmission_time =
3074 connection_.GetRetransmissionAlarm()->deadline();
3075 clock_.AdvanceTime(retransmission_time - clock_.Now());
3076 connection_.GetRetransmissionAlarm()->Fire();
3077 ASSERT_TRUE(manager_->GetConsecutiveRtoCount() > 0 ||
3078 manager_->GetConsecutivePtoCount() > 0);
3079
3080 // Process a packet, which requests a retransmittable frame be bundled
3081 // with the ACK.
3082 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
3083 .WillOnce(Invoke([this]() {
3084 connection_.SendControlFrame(
3085 QuicFrame(new QuicWindowUpdateFrame(1, 0, 0)));
3086 }));
3087 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3088 ProcessDataPacket(11);
3089 EXPECT_EQ(1u, writer_->window_update_frames().size());
3090}
3091
QUICHE teama6ef0a62019-03-07 20:34:33 -05003092TEST_P(QuicConnectionTest, LeastUnackedLower) {
fayangc31c9952019-06-05 13:54:48 -07003093 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003094 return;
3095 }
3096 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3097
3098 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
3099 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
3100 SendStreamDataToPeer(1, "eep", 6, NO_FIN, nullptr);
3101
3102 // Start out saying the least unacked is 2.
3103 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
3104 ProcessStopWaitingPacket(InitStopWaitingFrame(2));
3105
3106 // Change it to 1, but lower the packet number to fake out-of-order packets.
3107 // This should be fine.
3108 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 1);
3109 // The scheduler will not process out of order acks, but all packet processing
3110 // causes the connection to try to write.
3111 if (!GetParam().no_stop_waiting) {
3112 EXPECT_CALL(visitor_, OnCanWrite());
3113 }
3114 ProcessStopWaitingPacket(InitStopWaitingFrame(1));
3115
3116 // Now claim it's one, but set the ordering so it was sent "after" the first
3117 // one. This should cause a connection error.
3118 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 7);
3119 if (!GetParam().no_stop_waiting) {
rch39c88ab2019-10-16 19:24:40 -07003120 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3121 .Times(AtLeast(1));
fkastenholz5d880a92019-06-21 09:01:56 -07003122 EXPECT_CALL(visitor_,
rch39c88ab2019-10-16 19:24:40 -07003123 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
3124 .Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003125 }
3126 ProcessStopWaitingPacket(InitStopWaitingFrame(1));
fkastenholz5d880a92019-06-21 09:01:56 -07003127 if (!GetParam().no_stop_waiting) {
3128 TestConnectionCloseQuicErrorCode(QUIC_INVALID_STOP_WAITING_DATA);
3129 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003130}
3131
3132TEST_P(QuicConnectionTest, TooManySentPackets) {
3133 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3134
3135 QuicPacketCount max_tracked_packets = 50;
3136 QuicConnectionPeer::SetMaxTrackedPackets(&connection_, max_tracked_packets);
3137
3138 const int num_packets = max_tracked_packets + 5;
3139
3140 for (int i = 0; i < num_packets; ++i) {
3141 SendStreamDataToPeer(1, "foo", 3 * i, NO_FIN, nullptr);
3142 }
3143
3144 // Ack packet 1, which leaves more than the limit outstanding.
3145 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3146 EXPECT_CALL(visitor_,
fkastenholz5d880a92019-06-21 09:01:56 -07003147 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003148
3149 // Nack the first packet and ack the rest, leaving a huge gap.
3150 QuicAckFrame frame1 = ConstructAckFrame(num_packets, 1);
3151 ProcessAckPacket(&frame1);
fkastenholz5d880a92019-06-21 09:01:56 -07003152 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003153}
3154
3155TEST_P(QuicConnectionTest, LargestObservedLower) {
3156 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3157
3158 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
3159 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
3160 SendStreamDataToPeer(1, "eep", 6, NO_FIN, nullptr);
3161 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3162
3163 // Start out saying the largest observed is 2.
3164 QuicAckFrame frame1 = InitAckFrame(1);
3165 QuicAckFrame frame2 = InitAckFrame(2);
3166 ProcessAckPacket(&frame2);
3167
fayang745c93a2019-06-21 13:43:04 -07003168 EXPECT_CALL(visitor_, OnCanWrite());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003169 ProcessAckPacket(&frame1);
3170}
3171
3172TEST_P(QuicConnectionTest, AckUnsentData) {
3173 // Ack a packet which has not been sent.
fkastenholz5d880a92019-06-21 09:01:56 -07003174 EXPECT_CALL(visitor_,
3175 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003176 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
rch39c88ab2019-10-16 19:24:40 -07003177 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003178 QuicAckFrame frame = InitAckFrame(1);
3179 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
3180 ProcessAckPacket(&frame);
fkastenholz5d880a92019-06-21 09:01:56 -07003181 TestConnectionCloseQuicErrorCode(QUIC_INVALID_ACK_DATA);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003182}
3183
3184TEST_P(QuicConnectionTest, BasicSending) {
QUICHE teamcd098022019-03-22 18:49:55 -07003185 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3186 return;
3187 }
fayang643c7dd2020-05-18 07:11:27 -07003188 const QuicConnectionStats& stats = connection_.GetStats();
3189 EXPECT_FALSE(stats.first_decrypted_packet.IsInitialized());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003190 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3191 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3192 ProcessDataPacket(1);
fayang643c7dd2020-05-18 07:11:27 -07003193 EXPECT_EQ(QuicPacketNumber(1), stats.first_decrypted_packet);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003194 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
3195 QuicPacketNumber last_packet;
3196 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
3197 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
3198 SendAckPacketToPeer(); // Packet 2
3199
3200 if (GetParam().no_stop_waiting) {
3201 // Expect no stop waiting frame is sent.
3202 EXPECT_FALSE(least_unacked().IsInitialized());
3203 } else {
3204 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
3205 }
3206
3207 SendAckPacketToPeer(); // Packet 3
3208 if (GetParam().no_stop_waiting) {
3209 // Expect no stop waiting frame is sent.
3210 EXPECT_FALSE(least_unacked().IsInitialized());
3211 } else {
3212 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
3213 }
3214
3215 SendStreamDataToPeer(1, "bar", 3, NO_FIN, &last_packet); // Packet 4
3216 EXPECT_EQ(QuicPacketNumber(4u), last_packet);
3217 SendAckPacketToPeer(); // Packet 5
3218 if (GetParam().no_stop_waiting) {
3219 // Expect no stop waiting frame is sent.
3220 EXPECT_FALSE(least_unacked().IsInitialized());
3221 } else {
3222 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
3223 }
3224
3225 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3226
3227 // Peer acks up to packet 3.
3228 QuicAckFrame frame = InitAckFrame(3);
3229 ProcessAckPacket(&frame);
3230 SendAckPacketToPeer(); // Packet 6
3231
3232 // As soon as we've acked one, we skip ack packets 2 and 3 and note lack of
3233 // ack for 4.
3234 if (GetParam().no_stop_waiting) {
3235 // Expect no stop waiting frame is sent.
3236 EXPECT_FALSE(least_unacked().IsInitialized());
3237 } else {
3238 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
3239 }
3240
3241 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3242
3243 // Peer acks up to packet 4, the last packet.
3244 QuicAckFrame frame2 = InitAckFrame(6);
3245 ProcessAckPacket(&frame2); // Acks don't instigate acks.
3246
3247 // Verify that we did not send an ack.
3248 EXPECT_EQ(QuicPacketNumber(6u), writer_->header().packet_number);
3249
3250 // So the last ack has not changed.
3251 if (GetParam().no_stop_waiting) {
3252 // Expect no stop waiting frame is sent.
3253 EXPECT_FALSE(least_unacked().IsInitialized());
3254 } else {
3255 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
3256 }
3257
3258 // If we force an ack, we shouldn't change our retransmit state.
3259 SendAckPacketToPeer(); // Packet 7
3260 if (GetParam().no_stop_waiting) {
3261 // Expect no stop waiting frame is sent.
3262 EXPECT_FALSE(least_unacked().IsInitialized());
3263 } else {
3264 EXPECT_EQ(QuicPacketNumber(7u), least_unacked());
3265 }
3266
3267 // But if we send more data it should.
3268 SendStreamDataToPeer(1, "eep", 6, NO_FIN, &last_packet); // Packet 8
3269 EXPECT_EQ(QuicPacketNumber(8u), last_packet);
3270 SendAckPacketToPeer(); // Packet 9
3271 if (GetParam().no_stop_waiting) {
3272 // Expect no stop waiting frame is sent.
3273 EXPECT_FALSE(least_unacked().IsInitialized());
3274 } else {
3275 EXPECT_EQ(QuicPacketNumber(7u), least_unacked());
3276 }
fayang643c7dd2020-05-18 07:11:27 -07003277 EXPECT_EQ(QuicPacketNumber(1), stats.first_decrypted_packet);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003278}
3279
3280// QuicConnection should record the packet sent-time prior to sending the
3281// packet.
3282TEST_P(QuicConnectionTest, RecordSentTimeBeforePacketSent) {
3283 // We're using a MockClock for the tests, so we have complete control over the
3284 // time.
3285 // Our recorded timestamp for the last packet sent time will be passed in to
3286 // the send_algorithm. Make sure that it is set to the correct value.
3287 QuicTime actual_recorded_send_time = QuicTime::Zero();
3288 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3289 .WillOnce(SaveArg<0>(&actual_recorded_send_time));
3290
3291 // First send without any pause and check the result.
3292 QuicTime expected_recorded_send_time = clock_.Now();
3293 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3294 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
3295 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
3296 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
3297
3298 // Now pause during the write, and check the results.
3299 actual_recorded_send_time = QuicTime::Zero();
3300 const QuicTime::Delta write_pause_time_delta =
3301 QuicTime::Delta::FromMilliseconds(5000);
3302 SetWritePauseTimeDelta(write_pause_time_delta);
3303 expected_recorded_send_time = clock_.Now();
3304
3305 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3306 .WillOnce(SaveArg<0>(&actual_recorded_send_time));
3307 connection_.SendStreamDataWithString(2, "baz", 0, NO_FIN);
3308 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
3309 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
3310 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
3311}
3312
3313TEST_P(QuicConnectionTest, FramePacking) {
3314 // Send two stream frames in 1 packet by queueing them.
3315 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3316 {
fayanga4b37b22019-06-18 13:37:47 -07003317 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003318 connection_.SendStreamData3();
3319 connection_.SendStreamData5();
3320 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3321 }
3322 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3323 EXPECT_FALSE(connection_.HasQueuedData());
3324
3325 // Parse the last packet and ensure it's an ack and two stream frames from
3326 // two different streams.
3327 if (GetParam().no_stop_waiting) {
3328 EXPECT_EQ(2u, writer_->frame_count());
3329 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
3330 } else {
3331 EXPECT_EQ(2u, writer_->frame_count());
3332 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
3333 }
3334
3335 EXPECT_TRUE(writer_->ack_frames().empty());
3336
3337 ASSERT_EQ(2u, writer_->stream_frames().size());
3338 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3339 writer_->stream_frames()[0]->stream_id);
3340 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3341 writer_->stream_frames()[1]->stream_id);
3342}
3343
3344TEST_P(QuicConnectionTest, FramePackingNonCryptoThenCrypto) {
3345 // Send two stream frames (one non-crypto, then one crypto) in 2 packets by
3346 // queueing them.
3347 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3348 {
3349 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
fayanga4b37b22019-06-18 13:37:47 -07003350 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003351 connection_.SendStreamData3();
fayang58f71072019-11-05 08:47:02 -08003352 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003353 connection_.SendCryptoStreamData();
fayang58f71072019-11-05 08:47:02 -08003354 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003355 }
3356 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3357 EXPECT_FALSE(connection_.HasQueuedData());
3358
3359 // Parse the last packet and ensure it's the crypto stream frame.
3360 EXPECT_EQ(2u, writer_->frame_count());
3361 ASSERT_EQ(1u, writer_->padding_frames().size());
QUICHE teamea740082019-03-11 17:58:43 -07003362 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003363 ASSERT_EQ(1u, writer_->stream_frames().size());
3364 EXPECT_EQ(QuicUtils::GetCryptoStreamId(connection_.transport_version()),
3365 writer_->stream_frames()[0]->stream_id);
3366 } else {
3367 EXPECT_EQ(1u, writer_->crypto_frames().size());
3368 }
3369}
3370
3371TEST_P(QuicConnectionTest, FramePackingCryptoThenNonCrypto) {
3372 // Send two stream frames (one crypto, then one non-crypto) in 2 packets by
3373 // queueing them.
3374 {
3375 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3376 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
fayanga4b37b22019-06-18 13:37:47 -07003377 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003378 connection_.SendCryptoStreamData();
3379 connection_.SendStreamData3();
3380 }
3381 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3382 EXPECT_FALSE(connection_.HasQueuedData());
3383
3384 // Parse the last packet and ensure it's the stream frame from stream 3.
nharper55fa6132019-05-07 19:37:21 -07003385 size_t padding_frame_count = writer_->padding_frames().size();
3386 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003387 ASSERT_EQ(1u, writer_->stream_frames().size());
3388 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3389 writer_->stream_frames()[0]->stream_id);
3390}
3391
3392TEST_P(QuicConnectionTest, FramePackingAckResponse) {
3393 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3394 // Process a data packet to queue up a pending ack.
fayang3451f6e2019-06-11 08:18:12 -07003395 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3396 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
3397 } else {
3398 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3399 }
3400 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
3401
QUICHE teama6ef0a62019-03-07 20:34:33 -05003402 QuicPacketNumber last_packet;
nharper46833c32019-05-15 21:33:05 -07003403 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3404 connection_.SendCryptoDataWithString("foo", 0);
3405 } else {
3406 SendStreamDataToPeer(
3407 QuicUtils::GetCryptoStreamId(connection_.transport_version()), "foo", 0,
3408 NO_FIN, &last_packet);
3409 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003410 // Verify ack is bundled with outging packet.
3411 EXPECT_FALSE(writer_->ack_frames().empty());
3412
3413 EXPECT_CALL(visitor_, OnCanWrite())
3414 .WillOnce(DoAll(IgnoreResult(InvokeWithoutArgs(
3415 &connection_, &TestConnection::SendStreamData3)),
3416 IgnoreResult(InvokeWithoutArgs(
3417 &connection_, &TestConnection::SendStreamData5))));
3418
3419 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3420
3421 // Process a data packet to cause the visitor's OnCanWrite to be invoked.
3422 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
QUICHE team8c1daa22019-03-13 08:33:41 -07003423 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07003424 std::make_unique<TaggingEncrypter>(0x01));
zhongyi546cc452019-04-12 15:27:49 -07003425 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07003426 std::make_unique<StrictTaggingDecrypter>(0x01));
nharper2c9f02a2019-05-08 10:25:50 -07003427 ProcessDataPacket(2);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003428
3429 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3430 EXPECT_FALSE(connection_.HasQueuedData());
3431
3432 // Parse the last packet and ensure it's an ack and two stream frames from
3433 // two different streams.
3434 if (GetParam().no_stop_waiting) {
3435 EXPECT_EQ(3u, writer_->frame_count());
3436 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
3437 } else {
3438 EXPECT_EQ(4u, writer_->frame_count());
3439 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3440 }
3441 EXPECT_FALSE(writer_->ack_frames().empty());
3442 ASSERT_EQ(2u, writer_->stream_frames().size());
3443 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3444 writer_->stream_frames()[0]->stream_id);
3445 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3446 writer_->stream_frames()[1]->stream_id);
3447}
3448
3449TEST_P(QuicConnectionTest, FramePackingSendv) {
nharper46833c32019-05-15 21:33:05 -07003450 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003451 // Send data in 1 packet by writing multiple blocks in a single iovector
3452 // using writev.
3453 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3454
3455 char data[] = "ABCDEF";
3456 struct iovec iov[2];
3457 iov[0].iov_base = data;
3458 iov[0].iov_len = 4;
3459 iov[1].iov_base = data + 4;
3460 iov[1].iov_len = 2;
nharper46833c32019-05-15 21:33:05 -07003461 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
3462 connection_.transport_version(), Perspective::IS_CLIENT);
3463 connection_.SaveAndSendStreamData(stream_id, iov, 2, 6, 0, NO_FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003464
3465 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3466 EXPECT_FALSE(connection_.HasQueuedData());
3467
3468 // Parse the last packet and ensure multiple iovector blocks have
3469 // been packed into a single stream frame from one stream.
nharper46833c32019-05-15 21:33:05 -07003470 EXPECT_EQ(1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003471 EXPECT_EQ(1u, writer_->stream_frames().size());
nharper46833c32019-05-15 21:33:05 -07003472 EXPECT_EQ(0u, writer_->padding_frames().size());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003473 QuicStreamFrame* frame = writer_->stream_frames()[0].get();
nharper46833c32019-05-15 21:33:05 -07003474 EXPECT_EQ(stream_id, frame->stream_id);
dmcardlecf0bfcf2019-12-13 08:08:21 -08003475 EXPECT_EQ("ABCDEF",
3476 quiche::QuicheStringPiece(frame->data_buffer, frame->data_length));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003477}
3478
3479TEST_P(QuicConnectionTest, FramePackingSendvQueued) {
nharper46833c32019-05-15 21:33:05 -07003480 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003481 // Try to send two stream frames in 1 packet by using writev.
3482 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3483
3484 BlockOnNextWrite();
3485 char data[] = "ABCDEF";
3486 struct iovec iov[2];
3487 iov[0].iov_base = data;
3488 iov[0].iov_len = 4;
3489 iov[1].iov_base = data + 4;
3490 iov[1].iov_len = 2;
nharper46833c32019-05-15 21:33:05 -07003491 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
3492 connection_.transport_version(), Perspective::IS_CLIENT);
3493 connection_.SaveAndSendStreamData(stream_id, iov, 2, 6, 0, NO_FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003494
3495 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3496 EXPECT_TRUE(connection_.HasQueuedData());
3497
3498 // Unblock the writes and actually send.
3499 writer_->SetWritable();
3500 connection_.OnCanWrite();
3501 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3502
3503 // Parse the last packet and ensure it's one stream frame from one stream.
nharper46833c32019-05-15 21:33:05 -07003504 EXPECT_EQ(1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003505 EXPECT_EQ(1u, writer_->stream_frames().size());
nharper46833c32019-05-15 21:33:05 -07003506 EXPECT_EQ(0u, writer_->padding_frames().size());
3507 EXPECT_EQ(stream_id, writer_->stream_frames()[0]->stream_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003508}
3509
3510TEST_P(QuicConnectionTest, SendingZeroBytes) {
3511 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3512 // Send a zero byte write with a fin using writev.
3513 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
nharper46833c32019-05-15 21:33:05 -07003514 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
3515 connection_.transport_version(), Perspective::IS_CLIENT);
3516 connection_.SaveAndSendStreamData(stream_id, nullptr, 0, 0, 0, FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003517
3518 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3519 EXPECT_FALSE(connection_.HasQueuedData());
3520
nharper55fa6132019-05-07 19:37:21 -07003521 // Padding frames are added by v99 to ensure a minimum packet size.
3522 size_t extra_padding_frames = 0;
3523 if (GetParam().version.HasHeaderProtection()) {
3524 extra_padding_frames = 1;
3525 }
3526
QUICHE teama6ef0a62019-03-07 20:34:33 -05003527 // Parse the last packet and ensure it's one stream frame from one stream.
nharper55fa6132019-05-07 19:37:21 -07003528 EXPECT_EQ(1u + extra_padding_frames, writer_->frame_count());
3529 EXPECT_EQ(extra_padding_frames, writer_->padding_frames().size());
3530 ASSERT_EQ(1u, writer_->stream_frames().size());
nharper46833c32019-05-15 21:33:05 -07003531 EXPECT_EQ(stream_id, writer_->stream_frames()[0]->stream_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003532 EXPECT_TRUE(writer_->stream_frames()[0]->fin);
3533}
3534
3535TEST_P(QuicConnectionTest, LargeSendWithPendingAck) {
3536 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
fayang15042962020-07-01 12:14:29 -07003537 EXPECT_CALL(visitor_, GetHandshakeState())
3538 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003539 // Set the ack alarm by processing a ping frame.
3540 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3541
3542 // Processs a PING frame.
3543 ProcessFramePacket(QuicFrame(QuicPingFrame()));
3544 // Ensure that this has caused the ACK alarm to be set.
fayang9adfb532020-06-04 06:58:45 -07003545 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003546
3547 // Send data and ensure the ack is bundled.
3548 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(8);
3549 size_t len = 10000;
3550 std::unique_ptr<char[]> data_array(new char[len]);
3551 memset(data_array.get(), '?', len);
3552 struct iovec iov;
3553 iov.iov_base = data_array.get();
3554 iov.iov_len = len;
3555 QuicConsumedData consumed = connection_.SaveAndSendStreamData(
dschinazi552accc2019-06-17 17:07:34 -07003556 GetNthClientInitiatedStreamId(0, connection_.transport_version()), &iov,
3557 1, len, 0, FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003558 EXPECT_EQ(len, consumed.bytes_consumed);
3559 EXPECT_TRUE(consumed.fin_consumed);
3560 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3561 EXPECT_FALSE(connection_.HasQueuedData());
3562
3563 // Parse the last packet and ensure it's one stream frame with a fin.
3564 EXPECT_EQ(1u, writer_->frame_count());
nharper55fa6132019-05-07 19:37:21 -07003565 ASSERT_EQ(1u, writer_->stream_frames().size());
dschinazi552accc2019-06-17 17:07:34 -07003566 EXPECT_EQ(GetNthClientInitiatedStreamId(0, connection_.transport_version()),
QUICHE teama6ef0a62019-03-07 20:34:33 -05003567 writer_->stream_frames()[0]->stream_id);
3568 EXPECT_TRUE(writer_->stream_frames()[0]->fin);
3569 // Ensure the ack alarm was cancelled when the ack was sent.
fayang9adfb532020-06-04 06:58:45 -07003570 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003571}
3572
3573TEST_P(QuicConnectionTest, OnCanWrite) {
3574 // Visitor's OnCanWrite will send data, but will have more pending writes.
3575 EXPECT_CALL(visitor_, OnCanWrite())
3576 .WillOnce(DoAll(IgnoreResult(InvokeWithoutArgs(
3577 &connection_, &TestConnection::SendStreamData3)),
3578 IgnoreResult(InvokeWithoutArgs(
3579 &connection_, &TestConnection::SendStreamData5))));
3580 {
3581 InSequence seq;
3582 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillOnce(Return(true));
3583 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
3584 .WillRepeatedly(Return(false));
3585 }
3586
3587 EXPECT_CALL(*send_algorithm_, CanSend(_))
3588 .WillRepeatedly(testing::Return(true));
3589
3590 connection_.OnCanWrite();
3591
3592 // Parse the last packet and ensure it's the two stream frames from
3593 // two different streams.
3594 EXPECT_EQ(2u, writer_->frame_count());
3595 EXPECT_EQ(2u, writer_->stream_frames().size());
3596 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3597 writer_->stream_frames()[0]->stream_id);
3598 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3599 writer_->stream_frames()[1]->stream_id);
3600}
3601
3602TEST_P(QuicConnectionTest, RetransmitOnNack) {
3603 QuicPacketNumber last_packet;
3604 QuicByteCount second_packet_size;
3605 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet); // Packet 1
3606 second_packet_size =
3607 SendStreamDataToPeer(3, "foos", 3, NO_FIN, &last_packet); // Packet 2
3608 SendStreamDataToPeer(3, "fooos", 7, NO_FIN, &last_packet); // Packet 3
3609
3610 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3611
3612 // Don't lose a packet on an ack, and nothing is retransmitted.
3613 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3614 QuicAckFrame ack_one = InitAckFrame(1);
3615 ProcessAckPacket(&ack_one);
3616
3617 // Lose a packet and ensure it triggers retransmission.
3618 QuicAckFrame nack_two = ConstructAckFrame(3, 2);
3619 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003620 lost_packets.push_back(
3621 LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003622 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07003623 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
3624 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003625 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3626 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3627 EXPECT_FALSE(QuicPacketCreatorPeer::SendVersionInPacket(creator_));
3628 ProcessAckPacket(&nack_two);
3629}
3630
3631TEST_P(QuicConnectionTest, DoNotSendQueuedPacketForResetStream) {
3632 // Block the connection to queue the packet.
3633 BlockOnNextWrite();
3634
3635 QuicStreamId stream_id = 2;
3636 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
3637
3638 // Now that there is a queued packet, reset the stream.
3639 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
3640
3641 // Unblock the connection and verify that only the RST_STREAM is sent.
3642 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3643 writer_->SetWritable();
3644 connection_.OnCanWrite();
nharper55fa6132019-05-07 19:37:21 -07003645 size_t padding_frame_count = writer_->padding_frames().size();
3646 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003647 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3648}
3649
3650TEST_P(QuicConnectionTest, SendQueuedPacketForQuicRstStreamNoError) {
3651 // Block the connection to queue the packet.
3652 BlockOnNextWrite();
3653
3654 QuicStreamId stream_id = 2;
fayange62e63c2019-12-04 07:16:25 -08003655 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003656 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
3657
3658 // Now that there is a queued packet, reset the stream.
3659 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 3);
3660
3661 // Unblock the connection and verify that the RST_STREAM is sent and the data
3662 // packet is sent.
fayange62e63c2019-12-04 07:16:25 -08003663 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003664 writer_->SetWritable();
3665 connection_.OnCanWrite();
nharper55fa6132019-05-07 19:37:21 -07003666 size_t padding_frame_count = writer_->padding_frames().size();
3667 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003668 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3669}
3670
3671TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnNack) {
3672 QuicStreamId stream_id = 2;
3673 QuicPacketNumber last_packet;
3674 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3675 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3676 SendStreamDataToPeer(stream_id, "fooos", 7, NO_FIN, &last_packet);
3677
3678 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3679 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 12);
3680
3681 // Lose a packet and ensure it does not trigger retransmission.
3682 QuicAckFrame nack_two = ConstructAckFrame(last_packet, last_packet - 1);
3683 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3684 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3685 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3686 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3687 ProcessAckPacket(&nack_two);
3688}
3689
3690TEST_P(QuicConnectionTest, RetransmitForQuicRstStreamNoErrorOnNack) {
3691 QuicStreamId stream_id = 2;
3692 QuicPacketNumber last_packet;
3693 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3694 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3695 SendStreamDataToPeer(stream_id, "fooos", 7, NO_FIN, &last_packet);
3696
3697 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3698 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 12);
3699
3700 // Lose a packet, ensure it triggers retransmission.
3701 QuicAckFrame nack_two = ConstructAckFrame(last_packet, last_packet - 1);
3702 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3703 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003704 lost_packets.push_back(LostPacket(last_packet - 1, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003705 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07003706 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
3707 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003708 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3709 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
3710 ProcessAckPacket(&nack_two);
3711}
3712
3713TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnRTO) {
3714 QuicStreamId stream_id = 2;
3715 QuicPacketNumber last_packet;
3716 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3717
3718 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3719 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
3720
3721 // Fire the RTO and verify that the RST_STREAM is resent, not stream data.
3722 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3723 clock_.AdvanceTime(DefaultRetransmissionTime());
3724 connection_.GetRetransmissionAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07003725 size_t padding_frame_count = writer_->padding_frames().size();
3726 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003727 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3728 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
3729}
3730
3731// Ensure that if the only data in flight is non-retransmittable, the
3732// retransmission alarm is not set.
3733TEST_P(QuicConnectionTest, CancelRetransmissionAlarmAfterResetStream) {
3734 QuicStreamId stream_id = 2;
3735 QuicPacketNumber last_data_packet;
3736 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
3737
3738 // Cancel the stream.
3739 const QuicPacketNumber rst_packet = last_data_packet + 1;
3740 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, rst_packet, _, _)).Times(1);
3741 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
3742
3743 // Ack the RST_STREAM frame (since it's retransmittable), but not the data
3744 // packet, which is no longer retransmittable since the stream was cancelled.
3745 QuicAckFrame nack_stream_data =
3746 ConstructAckFrame(rst_packet, last_data_packet);
3747 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3748 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3749 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3750 ProcessAckPacket(&nack_stream_data);
3751
3752 // Ensure that the data is still in flight, but the retransmission alarm is no
3753 // longer set.
ianswett9f459cb2019-04-21 06:39:59 -07003754 EXPECT_GT(manager_->GetBytesInFlight(), 0u);
fayangcff885a2019-10-22 07:39:04 -07003755 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003756}
3757
3758TEST_P(QuicConnectionTest, RetransmitForQuicRstStreamNoErrorOnRTO) {
3759 connection_.SetMaxTailLossProbes(0);
3760
3761 QuicStreamId stream_id = 2;
3762 QuicPacketNumber last_packet;
3763 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3764
3765 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3766 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 3);
3767
3768 // Fire the RTO and verify that the RST_STREAM is resent, the stream data
3769 // is sent.
fayang1c2d1ab2020-03-11 12:08:41 -07003770 const size_t num_retransmissions =
3771 connection_.SupportsMultiplePacketNumberSpaces() ? 1 : 2;
3772 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3773 .Times(AtLeast(num_retransmissions));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003774 clock_.AdvanceTime(DefaultRetransmissionTime());
3775 connection_.GetRetransmissionAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07003776 size_t padding_frame_count = writer_->padding_frames().size();
3777 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
fayang1c2d1ab2020-03-11 12:08:41 -07003778 if (num_retransmissions == 2) {
3779 ASSERT_EQ(1u, writer_->rst_stream_frames().size());
3780 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
3781 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003782}
3783
3784TEST_P(QuicConnectionTest, DoNotSendPendingRetransmissionForResetStream) {
3785 QuicStreamId stream_id = 2;
3786 QuicPacketNumber last_packet;
3787 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3788 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3789 BlockOnNextWrite();
3790 connection_.SendStreamDataWithString(stream_id, "fooos", 7, NO_FIN);
3791
3792 // Lose a packet which will trigger a pending retransmission.
3793 QuicAckFrame ack = ConstructAckFrame(last_packet, last_packet - 1);
3794 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3795 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3796 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3797 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3798 ProcessAckPacket(&ack);
3799
3800 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 12);
3801
3802 // Unblock the connection and verify that the RST_STREAM is sent but not the
3803 // second data packet nor a retransmit.
3804 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3805 writer_->SetWritable();
3806 connection_.OnCanWrite();
nharper55fa6132019-05-07 19:37:21 -07003807 size_t padding_frame_count = writer_->padding_frames().size();
3808 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
zhongyi546cc452019-04-12 15:27:49 -07003809 ASSERT_EQ(1u, writer_->rst_stream_frames().size());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003810 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
3811}
3812
3813TEST_P(QuicConnectionTest, SendPendingRetransmissionForQuicRstStreamNoError) {
3814 QuicStreamId stream_id = 2;
3815 QuicPacketNumber last_packet;
3816 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3817 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3818 BlockOnNextWrite();
3819 connection_.SendStreamDataWithString(stream_id, "fooos", 7, NO_FIN);
3820
3821 // Lose a packet which will trigger a pending retransmission.
3822 QuicAckFrame ack = ConstructAckFrame(last_packet, last_packet - 1);
3823 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3824 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003825 lost_packets.push_back(LostPacket(last_packet - 1, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003826 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07003827 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
3828 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003829 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3830 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3831 ProcessAckPacket(&ack);
3832
3833 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 12);
3834
3835 // Unblock the connection and verify that the RST_STREAM is sent and the
3836 // second data packet or a retransmit is sent.
3837 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(2));
3838 writer_->SetWritable();
3839 connection_.OnCanWrite();
3840 // The RST_STREAM_FRAME is sent after queued packets and pending
3841 // retransmission.
3842 connection_.SendControlFrame(QuicFrame(
3843 new QuicRstStreamFrame(1, stream_id, QUIC_STREAM_NO_ERROR, 14)));
nharper55fa6132019-05-07 19:37:21 -07003844 size_t padding_frame_count = writer_->padding_frames().size();
3845 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003846 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3847}
3848
3849TEST_P(QuicConnectionTest, RetransmitAckedPacket) {
3850 QuicPacketNumber last_packet;
3851 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
3852 SendStreamDataToPeer(1, "foos", 3, NO_FIN, &last_packet); // Packet 2
3853 SendStreamDataToPeer(1, "fooos", 7, NO_FIN, &last_packet); // Packet 3
3854
3855 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3856
3857 // Instigate a loss with an ack.
3858 QuicAckFrame nack_two = ConstructAckFrame(3, 2);
3859 // The first nack should trigger a fast retransmission, but we'll be
3860 // write blocked, so the packet will be queued.
3861 BlockOnNextWrite();
3862
3863 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003864 lost_packets.push_back(
3865 LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003866 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07003867 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
3868 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003869 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
fayange62e63c2019-12-04 07:16:25 -08003870 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _))
3871 .Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003872 ProcessAckPacket(&nack_two);
3873 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3874
3875 // Now, ack the previous transmission.
3876 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3877 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(false, _, _, _, _));
3878 QuicAckFrame ack_all = InitAckFrame(3);
3879 ProcessAckPacket(&ack_all);
3880
fayange62e63c2019-12-04 07:16:25 -08003881 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _))
3882 .Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003883
3884 writer_->SetWritable();
3885 connection_.OnCanWrite();
3886
3887 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3888 // We do not store retransmittable frames of this retransmission.
3889 EXPECT_FALSE(QuicConnectionPeer::HasRetransmittableFrames(&connection_, 4));
3890}
3891
3892TEST_P(QuicConnectionTest, RetransmitNackedLargestObserved) {
3893 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3894 QuicPacketNumber original, second;
3895
3896 QuicByteCount packet_size =
3897 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &original); // 1st packet.
3898 SendStreamDataToPeer(3, "bar", 3, NO_FIN, &second); // 2nd packet.
3899
3900 QuicAckFrame frame = InitAckFrame({{second, second + 1}});
3901 // The first nack should retransmit the largest observed packet.
3902 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003903 lost_packets.push_back(LostPacket(original, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003904 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07003905 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
3906 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003907 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3908 // Packet 1 is short header for IETF QUIC because the encryption level
3909 // switched to ENCRYPTION_FORWARD_SECURE in SendStreamDataToPeer.
fayangd4291e42019-05-30 10:31:21 -07003910 EXPECT_CALL(*send_algorithm_,
3911 OnPacketSent(_, _, _,
3912 VersionHasIetfInvariantHeader(
3913 GetParam().version.transport_version)
3914 ? packet_size
3915 : packet_size - kQuicVersionSize,
3916 _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003917 ProcessAckPacket(&frame);
3918}
3919
3920TEST_P(QuicConnectionTest, QueueAfterTwoRTOs) {
fayangcff885a2019-10-22 07:39:04 -07003921 if (connection_.PtoEnabled()) {
fayang5f135052019-08-22 17:59:40 -07003922 return;
3923 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003924 connection_.SetMaxTailLossProbes(0);
3925
3926 for (int i = 0; i < 10; ++i) {
3927 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3928 connection_.SendStreamDataWithString(3, "foo", i * 3, NO_FIN);
3929 }
3930
3931 // Block the writer and ensure they're queued.
3932 BlockOnNextWrite();
3933 clock_.AdvanceTime(DefaultRetransmissionTime());
fayange62e63c2019-12-04 07:16:25 -08003934 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003935 connection_.GetRetransmissionAlarm()->Fire();
3936 EXPECT_TRUE(connection_.HasQueuedData());
3937
3938 // Unblock the writer.
3939 writer_->SetWritable();
3940 clock_.AdvanceTime(QuicTime::Delta::FromMicroseconds(
3941 2 * DefaultRetransmissionTime().ToMicroseconds()));
fayange62e63c2019-12-04 07:16:25 -08003942 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003943 connection_.GetRetransmissionAlarm()->Fire();
3944 connection_.OnCanWrite();
3945}
3946
3947TEST_P(QuicConnectionTest, WriteBlockedBufferedThenSent) {
3948 BlockOnNextWrite();
3949 writer_->set_is_write_blocked_data_buffered(true);
3950 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3951 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3952 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3953
3954 writer_->SetWritable();
3955 connection_.OnCanWrite();
3956 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3957}
3958
3959TEST_P(QuicConnectionTest, WriteBlockedThenSent) {
3960 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3961 BlockOnNextWrite();
fayange62e63c2019-12-04 07:16:25 -08003962 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003963 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
fayange62e63c2019-12-04 07:16:25 -08003964 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003965 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3966
3967 // The second packet should also be queued, in order to ensure packets are
3968 // never sent out of order.
3969 writer_->SetWritable();
fayange62e63c2019-12-04 07:16:25 -08003970 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003971 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3972 EXPECT_EQ(2u, connection_.NumQueuedPackets());
3973
3974 // Now both are sent in order when we unblock.
fayange62e63c2019-12-04 07:16:25 -08003975 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003976 connection_.OnCanWrite();
3977 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
fayang2ce66082019-10-02 06:29:04 -07003978 EXPECT_EQ(0u, connection_.NumQueuedPackets());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003979}
3980
3981TEST_P(QuicConnectionTest, RetransmitWriteBlockedAckedOriginalThenSent) {
3982 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3983 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
3984 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3985
3986 BlockOnNextWrite();
3987 writer_->set_is_write_blocked_data_buffered(true);
3988 // Simulate the retransmission alarm firing.
3989 clock_.AdvanceTime(DefaultRetransmissionTime());
3990 connection_.GetRetransmissionAlarm()->Fire();
3991
3992 // Ack the sent packet before the callback returns, which happens in
3993 // rare circumstances with write blocked sockets.
3994 QuicAckFrame ack = InitAckFrame(1);
3995 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3996 ProcessAckPacket(&ack);
3997
3998 writer_->SetWritable();
3999 connection_.OnCanWrite();
fayangcff885a2019-10-22 07:39:04 -07004000 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
fayang5d011982020-05-13 14:14:38 -07004001 uint64_t retransmission = connection_.SupportsMultiplePacketNumberSpaces() &&
4002 !GetQuicReloadableFlag(quic_default_on_pto)
4003 ? 3
4004 : 2;
fayang1c2d1ab2020-03-11 12:08:41 -07004005 EXPECT_FALSE(QuicConnectionPeer::HasRetransmittableFrames(&connection_,
4006 retransmission));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004007}
4008
4009TEST_P(QuicConnectionTest, AlarmsWhenWriteBlocked) {
4010 // Block the connection.
4011 BlockOnNextWrite();
4012 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
4013 EXPECT_EQ(1u, writer_->packets_write_attempts());
4014 EXPECT_TRUE(writer_->IsWriteBlocked());
4015
4016 // Set the send alarm. Fire the alarm and ensure it doesn't attempt to write.
4017 connection_.GetSendAlarm()->Set(clock_.ApproximateNow());
4018 connection_.GetSendAlarm()->Fire();
4019 EXPECT_TRUE(writer_->IsWriteBlocked());
4020 EXPECT_EQ(1u, writer_->packets_write_attempts());
4021}
4022
4023TEST_P(QuicConnectionTest, NoSendAlarmAfterProcessPacketWhenWriteBlocked) {
4024 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4025
4026 // Block the connection.
4027 BlockOnNextWrite();
4028 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
4029 EXPECT_TRUE(writer_->IsWriteBlocked());
4030 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4031 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4032
4033 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4034 // Process packet number 1. Can not call ProcessPacket or ProcessDataPacket
4035 // here, because they will fire the alarm after QuicConnection::ProcessPacket
4036 // is returned.
4037 const uint64_t received_packet_num = 1;
4038 const bool has_stop_waiting = false;
nharperc6b99512019-09-19 11:13:48 -07004039 const EncryptionLevel level = ENCRYPTION_FORWARD_SECURE;
4040 std::unique_ptr<QuicPacket> packet(
4041 ConstructDataPacket(received_packet_num, has_stop_waiting, level));
dschinazi66dea072019-04-09 11:41:06 -07004042 char buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05004043 size_t encrypted_length =
4044 peer_framer_.EncryptPayload(level, QuicPacketNumber(received_packet_num),
dschinazi66dea072019-04-09 11:41:06 -07004045 *packet, buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004046 connection_.ProcessUdpPacket(
4047 kSelfAddress, kPeerAddress,
4048 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
4049
4050 EXPECT_TRUE(writer_->IsWriteBlocked());
4051 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4052}
4053
4054TEST_P(QuicConnectionTest, AddToWriteBlockedListIfWriterBlockedWhenProcessing) {
4055 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4056 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
4057
4058 // Simulate the case where a shared writer gets blocked by another connection.
4059 writer_->SetWriteBlocked();
4060
4061 // Process an ACK, make sure the connection calls visitor_->OnWriteBlocked().
4062 QuicAckFrame ack1 = InitAckFrame(1);
4063 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
4064 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
4065 ProcessAckPacket(1, &ack1);
4066}
4067
4068TEST_P(QuicConnectionTest, DoNotAddToWriteBlockedListAfterDisconnect) {
4069 writer_->SetBatchMode(true);
4070 EXPECT_TRUE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07004071 // Have to explicitly grab the OnConnectionClosed frame and check
4072 // its parameters because this is a silent connection close and the
4073 // frame is not also transmitted to the peer.
4074 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
4075 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004076
4077 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
4078
4079 {
fayanga4b37b22019-06-18 13:37:47 -07004080 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004081 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
4082 ConnectionCloseBehavior::SILENT_CLOSE);
4083
4084 EXPECT_FALSE(connection_.connected());
4085 writer_->SetWriteBlocked();
4086 }
fkastenholz5d880a92019-06-21 09:01:56 -07004087 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08004088 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
4089 IsError(QUIC_PEER_GOING_AWAY));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004090}
4091
4092TEST_P(QuicConnectionTest, AddToWriteBlockedListIfBlockedOnFlushPackets) {
4093 writer_->SetBatchMode(true);
4094 writer_->BlockOnNextFlush();
4095
4096 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
4097 {
fayanga4b37b22019-06-18 13:37:47 -07004098 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004099 // flusher's destructor will call connection_.FlushPackets, which should add
4100 // the connection to the write blocked list.
4101 }
4102}
4103
4104TEST_P(QuicConnectionTest, NoLimitPacketsPerNack) {
4105 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4106 int offset = 0;
4107 // Send packets 1 to 15.
4108 for (int i = 0; i < 15; ++i) {
4109 SendStreamDataToPeer(1, "foo", offset, NO_FIN, nullptr);
4110 offset += 3;
4111 }
4112
4113 // Ack 15, nack 1-14.
4114
4115 QuicAckFrame nack =
4116 InitAckFrame({{QuicPacketNumber(15), QuicPacketNumber(16)}});
4117
4118 // 14 packets have been NACK'd and lost.
4119 LostPacketVector lost_packets;
4120 for (int i = 1; i < 15; ++i) {
dschinazi66dea072019-04-09 11:41:06 -07004121 lost_packets.push_back(
4122 LostPacket(QuicPacketNumber(i), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004123 }
4124 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07004125 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
4126 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004127 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
fayangcff885a2019-10-22 07:39:04 -07004128 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004129 ProcessAckPacket(&nack);
4130}
4131
4132// Test sending multiple acks from the connection to the session.
4133TEST_P(QuicConnectionTest, MultipleAcks) {
QUICHE teamcd098022019-03-22 18:49:55 -07004134 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4135 return;
4136 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004137 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4138 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4139 ProcessDataPacket(1);
4140 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
4141 QuicPacketNumber last_packet;
4142 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
4143 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4144 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet); // Packet 2
4145 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
4146 SendAckPacketToPeer(); // Packet 3
4147 SendStreamDataToPeer(5, "foo", 0, NO_FIN, &last_packet); // Packet 4
4148 EXPECT_EQ(QuicPacketNumber(4u), last_packet);
4149 SendStreamDataToPeer(1, "foo", 3, NO_FIN, &last_packet); // Packet 5
4150 EXPECT_EQ(QuicPacketNumber(5u), last_packet);
4151 SendStreamDataToPeer(3, "foo", 3, NO_FIN, &last_packet); // Packet 6
4152 EXPECT_EQ(QuicPacketNumber(6u), last_packet);
4153
4154 // Client will ack packets 1, 2, [!3], 4, 5.
4155 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4156 QuicAckFrame frame1 = ConstructAckFrame(5, 3);
4157 ProcessAckPacket(&frame1);
4158
4159 // Now the client implicitly acks 3, and explicitly acks 6.
4160 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4161 QuicAckFrame frame2 = InitAckFrame(6);
4162 ProcessAckPacket(&frame2);
4163}
4164
4165TEST_P(QuicConnectionTest, DontLatchUnackedPacket) {
QUICHE teamcd098022019-03-22 18:49:55 -07004166 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4167 return;
4168 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004169 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4170 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4171 ProcessDataPacket(1);
4172 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
4173 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr); // Packet 1;
4174 // From now on, we send acks, so the send algorithm won't mark them pending.
4175 SendAckPacketToPeer(); // Packet 2
4176
4177 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4178 QuicAckFrame frame = InitAckFrame(1);
4179 ProcessAckPacket(&frame);
4180
4181 // Verify that our internal state has least-unacked as 2, because we're still
4182 // waiting for a potential ack for 2.
4183
4184 EXPECT_EQ(QuicPacketNumber(2u), stop_waiting()->least_unacked);
4185
4186 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4187 frame = InitAckFrame(2);
4188 ProcessAckPacket(&frame);
4189 EXPECT_EQ(QuicPacketNumber(3u), stop_waiting()->least_unacked);
4190
4191 // When we send an ack, we make sure our least-unacked makes sense. In this
4192 // case since we're not waiting on an ack for 2 and all packets are acked, we
4193 // set it to 3.
4194 SendAckPacketToPeer(); // Packet 3
4195 // Least_unacked remains at 3 until another ack is received.
4196 EXPECT_EQ(QuicPacketNumber(3u), stop_waiting()->least_unacked);
4197 if (GetParam().no_stop_waiting) {
4198 // Expect no stop waiting frame is sent.
4199 EXPECT_FALSE(least_unacked().IsInitialized());
4200 } else {
4201 // Check that the outgoing ack had its packet number as least_unacked.
4202 EXPECT_EQ(QuicPacketNumber(3u), least_unacked());
4203 }
4204
4205 // Ack the ack, which updates the rtt and raises the least unacked.
4206 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4207 frame = InitAckFrame(3);
4208 ProcessAckPacket(&frame);
4209
4210 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr); // Packet 4
4211 EXPECT_EQ(QuicPacketNumber(4u), stop_waiting()->least_unacked);
4212 SendAckPacketToPeer(); // Packet 5
4213 if (GetParam().no_stop_waiting) {
4214 // Expect no stop waiting frame is sent.
4215 EXPECT_FALSE(least_unacked().IsInitialized());
4216 } else {
4217 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
4218 }
4219
4220 // Send two data packets at the end, and ensure if the last one is acked,
4221 // the least unacked is raised above the ack packets.
4222 SendStreamDataToPeer(1, "bar", 6, NO_FIN, nullptr); // Packet 6
4223 SendStreamDataToPeer(1, "bar", 9, NO_FIN, nullptr); // Packet 7
4224
4225 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4226 frame = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(5)},
4227 {QuicPacketNumber(7), QuicPacketNumber(8)}});
4228 ProcessAckPacket(&frame);
4229
4230 EXPECT_EQ(QuicPacketNumber(6u), stop_waiting()->least_unacked);
4231}
4232
4233TEST_P(QuicConnectionTest, TLP) {
fayang5d011982020-05-13 14:14:38 -07004234 if (connection_.PtoEnabled()) {
4235 return;
4236 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004237 connection_.SetMaxTailLossProbes(1);
4238
4239 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
4240 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4241 QuicTime retransmission_time =
4242 connection_.GetRetransmissionAlarm()->deadline();
4243 EXPECT_NE(QuicTime::Zero(), retransmission_time);
4244
4245 EXPECT_EQ(QuicPacketNumber(1u), writer_->header().packet_number);
4246 // Simulate the retransmission alarm firing and sending a tlp,
4247 // so send algorithm's OnRetransmissionTimeout is not called.
4248 clock_.AdvanceTime(retransmission_time - clock_.Now());
fayang1c2d1ab2020-03-11 12:08:41 -07004249 const QuicPacketNumber retransmission(
4250 connection_.SupportsMultiplePacketNumberSpaces() ? 3 : 2);
4251 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, retransmission, _, _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004252 connection_.GetRetransmissionAlarm()->Fire();
fayang1c2d1ab2020-03-11 12:08:41 -07004253 EXPECT_EQ(retransmission, writer_->header().packet_number);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004254 // We do not raise the high water mark yet.
4255 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4256}
4257
zhongyifbb25772019-04-10 16:54:08 -07004258TEST_P(QuicConnectionTest, TailLossProbeDelayForStreamDataInTLPR) {
fayangcff885a2019-10-22 07:39:04 -07004259 if (connection_.PtoEnabled()) {
zhongyi1b2f7832019-06-14 13:31:34 -07004260 return;
4261 }
4262
zhongyifbb25772019-04-10 16:54:08 -07004263 // Set TLPR from QuicConfig.
4264 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4265 QuicConfig config;
4266 QuicTagVector options;
4267 options.push_back(kTLPR);
4268 config.SetConnectionOptionsToSend(options);
4269 connection_.SetFromConfig(config);
4270 connection_.SetMaxTailLossProbes(1);
4271
4272 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
4273 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4274
4275 QuicTime retransmission_time =
4276 connection_.GetRetransmissionAlarm()->deadline();
4277 EXPECT_NE(QuicTime::Zero(), retransmission_time);
4278 QuicTime::Delta expected_tlp_delay =
4279 0.5 * manager_->GetRttStats()->SmoothedOrInitialRtt();
4280 EXPECT_EQ(expected_tlp_delay, retransmission_time - clock_.Now());
4281
4282 EXPECT_EQ(QuicPacketNumber(1u), writer_->header().packet_number);
4283 // Simulate firing of the retransmission alarm and retransmit the packet.
4284 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
4285 clock_.AdvanceTime(retransmission_time - clock_.Now());
4286 connection_.GetRetransmissionAlarm()->Fire();
4287 EXPECT_EQ(QuicPacketNumber(2u), writer_->header().packet_number);
4288
4289 // We do not raise the high water mark yet.
4290 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4291}
4292
4293TEST_P(QuicConnectionTest, TailLossProbeDelayForNonStreamDataInTLPR) {
fayangcff885a2019-10-22 07:39:04 -07004294 if (connection_.PtoEnabled()) {
zhongyi1b2f7832019-06-14 13:31:34 -07004295 return;
4296 }
4297
zhongyifbb25772019-04-10 16:54:08 -07004298 // Set TLPR from QuicConfig.
4299 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4300 QuicConfig config;
4301 QuicTagVector options;
4302 options.push_back(kTLPR);
4303 config.SetConnectionOptionsToSend(options);
dschinazif7c6a912020-05-05 11:39:53 -07004304 QuicConfigPeer::SetNegotiated(&config, true);
dschinazie7c38a52020-05-29 15:25:45 -07004305 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
4306 QuicConfigPeer::SetReceivedOriginalConnectionId(
4307 &config, connection_.connection_id());
4308 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
4309 &config, connection_.connection_id());
4310 }
zhongyifbb25772019-04-10 16:54:08 -07004311 connection_.SetFromConfig(config);
4312 connection_.SetMaxTailLossProbes(1);
4313
4314 // Sets retransmittable on wire.
4315 const QuicTime::Delta retransmittable_on_wire_timeout =
4316 QuicTime::Delta::FromMilliseconds(50);
zhongyi79ace162019-10-21 15:57:09 -07004317 connection_.set_initial_retransmittable_on_wire_timeout(
zhongyifbb25772019-04-10 16:54:08 -07004318 retransmittable_on_wire_timeout);
4319
4320 EXPECT_TRUE(connection_.connected());
4321 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4322 .WillRepeatedly(Return(true));
fayangb59c6f12020-03-23 15:06:14 -07004323 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
zhongyifbb25772019-04-10 16:54:08 -07004324 EXPECT_FALSE(connection_.IsPathDegrading());
4325 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4326
4327 const char data[] = "data";
4328 size_t data_size = strlen(data);
4329 QuicStreamOffset offset = 0;
4330
4331 // Send a data packet.
4332 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
4333 offset += data_size;
4334
4335 // Path degrading alarm should be set when there is a retransmittable packet
4336 // on the wire.
fayangb59c6f12020-03-23 15:06:14 -07004337 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
zhongyifbb25772019-04-10 16:54:08 -07004338
4339 // Verify the path degrading delay.
4340 // First TLP with stream data.
4341 QuicTime::Delta srtt = manager_->GetRttStats()->SmoothedOrInitialRtt();
4342 QuicTime::Delta expected_delay = 0.5 * srtt;
4343 // Add 1st RTO.
4344 QuicTime::Delta retransmission_delay =
4345 QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
4346 expected_delay = expected_delay + retransmission_delay;
4347 // Add 2nd RTO.
4348 expected_delay = expected_delay + retransmission_delay * 2;
4349 EXPECT_EQ(expected_delay,
4350 QuicConnectionPeer::GetSentPacketManager(&connection_)
4351 ->GetPathDegradingDelay());
4352 ASSERT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
4353
4354 // The ping alarm is set for the ping timeout, not the shorter
4355 // retransmittable_on_wire_timeout.
4356 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004357 EXPECT_EQ(connection_.ping_timeout(),
zhongyifbb25772019-04-10 16:54:08 -07004358 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
4359
4360 // Receive an ACK for the data packet.
4361 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4362 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4363 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4364 QuicAckFrame frame =
4365 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
4366 ProcessAckPacket(&frame);
4367
4368 // Path degrading alarm should be cancelled as there is no more
4369 // reretransmittable packets on the wire.
fayangb59c6f12020-03-23 15:06:14 -07004370 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
zhongyifbb25772019-04-10 16:54:08 -07004371 // The ping alarm should be set to the retransmittable_on_wire_timeout.
4372 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4373 EXPECT_EQ(retransmittable_on_wire_timeout,
4374 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
4375
4376 // Simulate firing of the retransmittable on wire and send a PING.
4377 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
4378 clock_.AdvanceTime(retransmittable_on_wire_timeout);
4379 connection_.GetPingAlarm()->Fire();
4380
4381 // The retransmission alarm and the path degrading alarm should be set as
4382 // there is a retransmittable packet (PING) on the wire,
4383 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
fayangb59c6f12020-03-23 15:06:14 -07004384 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
zhongyifbb25772019-04-10 16:54:08 -07004385
4386 // Verify the retransmission delay.
4387 QuicTime::Delta min_rto_timeout =
4388 QuicTime::Delta::FromMilliseconds(kMinRetransmissionTimeMs);
4389 srtt = manager_->GetRttStats()->SmoothedOrInitialRtt();
zhongyi9fa2be32019-09-10 12:39:01 -07004390
4391 // First TLP without unacked stream data will no longer use TLPR.
4392 expected_delay = std::max(2 * srtt, 1.5 * srtt + 0.5 * min_rto_timeout);
zhongyifbb25772019-04-10 16:54:08 -07004393 EXPECT_EQ(expected_delay,
4394 connection_.GetRetransmissionAlarm()->deadline() - clock_.Now());
4395
zhongyi1b2f7832019-06-14 13:31:34 -07004396 // Verify the path degrading delay = TLP delay + 1st RTO + 2nd RTO.
zhongyifbb25772019-04-10 16:54:08 -07004397 // Add 1st RTO.
4398 retransmission_delay =
4399 std::max(manager_->GetRttStats()->smoothed_rtt() +
4400 4 * manager_->GetRttStats()->mean_deviation(),
4401 min_rto_timeout);
4402 expected_delay = expected_delay + retransmission_delay;
4403 // Add 2nd RTO.
4404 expected_delay = expected_delay + retransmission_delay * 2;
4405 EXPECT_EQ(expected_delay,
4406 QuicConnectionPeer::GetSentPacketManager(&connection_)
4407 ->GetPathDegradingDelay());
4408
4409 // The ping alarm is set for the ping timeout, not the shorter
4410 // retransmittable_on_wire_timeout.
4411 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004412 EXPECT_EQ(connection_.ping_timeout(),
zhongyifbb25772019-04-10 16:54:08 -07004413 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
zhongyi1b2f7832019-06-14 13:31:34 -07004414
4415 // Advance a small period of time: 5ms. And receive a retransmitted ACK.
4416 // This will update the retransmission alarm, verify the retransmission delay
4417 // is correct.
4418 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4419 QuicAckFrame ack = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
4420 ProcessAckPacket(&ack);
4421
4422 // Verify the retransmission delay.
zhongyi9fa2be32019-09-10 12:39:01 -07004423 // First TLP without unacked stream data will no longer use TLPR.
4424 expected_delay = std::max(2 * srtt, 1.5 * srtt + 0.5 * min_rto_timeout);
zhongyi1b2f7832019-06-14 13:31:34 -07004425 expected_delay = expected_delay - QuicTime::Delta::FromMilliseconds(5);
4426 EXPECT_EQ(expected_delay,
4427 connection_.GetRetransmissionAlarm()->deadline() - clock_.Now());
zhongyifbb25772019-04-10 16:54:08 -07004428}
4429
QUICHE teama6ef0a62019-03-07 20:34:33 -05004430TEST_P(QuicConnectionTest, RTO) {
fayang5f135052019-08-22 17:59:40 -07004431 if (connection_.PtoEnabled()) {
4432 return;
4433 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004434 connection_.SetMaxTailLossProbes(0);
4435
4436 QuicTime default_retransmission_time =
4437 clock_.ApproximateNow() + DefaultRetransmissionTime();
4438 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
4439 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4440
4441 EXPECT_EQ(QuicPacketNumber(1u), writer_->header().packet_number);
4442 EXPECT_EQ(default_retransmission_time,
4443 connection_.GetRetransmissionAlarm()->deadline());
4444 // Simulate the retransmission alarm firing.
4445 clock_.AdvanceTime(DefaultRetransmissionTime());
4446 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
4447 connection_.GetRetransmissionAlarm()->Fire();
4448 EXPECT_EQ(QuicPacketNumber(2u), writer_->header().packet_number);
4449 // We do not raise the high water mark yet.
4450 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4451}
4452
fayanga29eb242019-07-16 12:25:38 -07004453// Regression test of b/133771183.
4454TEST_P(QuicConnectionTest, RtoWithNoDataToRetransmit) {
fayangcff885a2019-10-22 07:39:04 -07004455 if (connection_.PtoEnabled()) {
fayanga29eb242019-07-16 12:25:38 -07004456 return;
4457 }
4458 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4459 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4460 connection_.SetMaxTailLossProbes(0);
4461
4462 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
4463 // Connection is cwnd limited.
4464 CongestionBlockWrites();
4465 // Stream gets reset.
4466 SendRstStream(3, QUIC_ERROR_PROCESSING_STREAM, 3);
4467 // Simulate the retransmission alarm firing.
4468 clock_.AdvanceTime(DefaultRetransmissionTime());
4469 // RTO fires, but there is no packet to be RTOed.
fayange861aee2019-10-16 13:40:39 -07004470 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
fayanga29eb242019-07-16 12:25:38 -07004471 connection_.GetRetransmissionAlarm()->Fire();
fayange861aee2019-10-16 13:40:39 -07004472 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
fayanga29eb242019-07-16 12:25:38 -07004473
4474 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(40);
4475 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(20);
fayange861aee2019-10-16 13:40:39 -07004476 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(false));
4477 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(1);
fayanga29eb242019-07-16 12:25:38 -07004478 // Receives packets 1 - 40.
4479 for (size_t i = 1; i <= 40; ++i) {
4480 ProcessDataPacket(i);
4481 }
4482}
4483
QUICHE teama6ef0a62019-03-07 20:34:33 -05004484TEST_P(QuicConnectionTest, SendHandshakeMessages) {
4485 use_tagging_decrypter();
4486 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
4487 // the end of the packet. We can test this to check which encrypter was used.
QUICHE team6987b4a2019-03-15 16:23:04 -07004488 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07004489 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004490
4491 // Attempt to send a handshake message and have the socket block.
4492 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
4493 BlockOnNextWrite();
nharper46833c32019-05-15 21:33:05 -07004494 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004495 // The packet should be serialized, but not queued.
4496 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4497
4498 // Switch to the new encrypter.
4499 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004500 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004501 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4502
4503 // Now become writeable and flush the packets.
4504 writer_->SetWritable();
4505 EXPECT_CALL(visitor_, OnCanWrite());
4506 connection_.OnCanWrite();
4507 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4508
4509 // Verify that the handshake packet went out at the null encryption.
4510 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
4511}
4512
4513TEST_P(QuicConnectionTest,
4514 DropRetransmitsForNullEncryptedPacketAfterForwardSecure) {
4515 use_tagging_decrypter();
QUICHE team6987b4a2019-03-15 16:23:04 -07004516 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07004517 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004518 connection_.SendCryptoStreamData();
4519
4520 // Simulate the retransmission alarm firing and the socket blocking.
4521 BlockOnNextWrite();
4522 clock_.AdvanceTime(DefaultRetransmissionTime());
fayange62e63c2019-12-04 07:16:25 -08004523 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004524 connection_.GetRetransmissionAlarm()->Fire();
fayang2ce66082019-10-02 06:29:04 -07004525 EXPECT_EQ(1u, connection_.NumQueuedPackets());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004526
4527 // Go forward secure.
4528 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07004529 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004530 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4531 notifier_.NeuterUnencryptedData();
4532 connection_.NeuterUnencryptedPackets();
fayang2ce66082019-10-02 06:29:04 -07004533 connection_.OnHandshakeComplete();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004534
4535 EXPECT_EQ(QuicTime::Zero(), connection_.GetRetransmissionAlarm()->deadline());
4536 // Unblock the socket and ensure that no packets are sent.
4537 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4538 writer_->SetWritable();
4539 connection_.OnCanWrite();
4540}
4541
4542TEST_P(QuicConnectionTest, RetransmitPacketsWithInitialEncryption) {
renjietang37d4ae12020-06-18 11:18:31 -07004543 SetQuicReloadableFlag(quic_do_not_retransmit_immediately_on_zero_rtt_reject,
4544 true);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004545 use_tagging_decrypter();
QUICHE team6987b4a2019-03-15 16:23:04 -07004546 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07004547 std::make_unique<TaggingEncrypter>(0x01));
QUICHE team6987b4a2019-03-15 16:23:04 -07004548 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004549
nharper46833c32019-05-15 21:33:05 -07004550 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004551
4552 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004553 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004554 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4555
4556 SendStreamDataToPeer(2, "bar", 0, NO_FIN, nullptr);
renjietang37d4ae12020-06-18 11:18:31 -07004557 EXPECT_FALSE(notifier_.HasLostStreamData());
renjietangc0080082020-05-26 18:35:19 -07004558 connection_.RetransmitZeroRttPackets();
renjietang37d4ae12020-06-18 11:18:31 -07004559 EXPECT_TRUE(notifier_.HasLostStreamData());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004560}
4561
4562TEST_P(QuicConnectionTest, BufferNonDecryptablePackets) {
QUICHE teamcd098022019-03-22 18:49:55 -07004563 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4564 return;
4565 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004566 // SetFromConfig is always called after construction from InitializeSession.
4567 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4568 QuicConfig config;
4569 connection_.SetFromConfig(config);
4570 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4571 use_tagging_decrypter();
4572
4573 const uint8_t tag = 0x07;
4574 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004575 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004576
4577 // Process an encrypted packet which can not yet be decrypted which should
4578 // result in the packet being buffered.
4579 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4580
4581 // Transition to the new encryption state and process another encrypted packet
4582 // which should result in the original packet being processed.
zhongyi546cc452019-04-12 15:27:49 -07004583 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004584 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004585 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4586 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004587 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004588 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(2);
4589 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4590
4591 // Finally, process a third packet and note that we do not reprocess the
4592 // buffered packet.
4593 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4594 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4595}
4596
4597TEST_P(QuicConnectionTest, TestRetransmitOrder) {
fayang5f135052019-08-22 17:59:40 -07004598 if (connection_.PtoEnabled()) {
4599 return;
4600 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004601 connection_.SetMaxTailLossProbes(0);
4602
4603 QuicByteCount first_packet_size;
4604 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4605 .WillOnce(SaveArg<3>(&first_packet_size));
4606
4607 connection_.SendStreamDataWithString(3, "first_packet", 0, NO_FIN);
4608 QuicByteCount second_packet_size;
4609 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4610 .WillOnce(SaveArg<3>(&second_packet_size));
4611 connection_.SendStreamDataWithString(3, "second_packet", 12, NO_FIN);
4612 EXPECT_NE(first_packet_size, second_packet_size);
4613 // Advance the clock by huge time to make sure packets will be retransmitted.
4614 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
4615 {
4616 InSequence s;
4617 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, first_packet_size, _));
4618 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, second_packet_size, _));
4619 }
4620 connection_.GetRetransmissionAlarm()->Fire();
4621
4622 // Advance again and expect the packets to be sent again in the same order.
4623 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(20));
4624 {
4625 InSequence s;
4626 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, first_packet_size, _));
4627 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, second_packet_size, _));
4628 }
4629 connection_.GetRetransmissionAlarm()->Fire();
4630}
4631
4632TEST_P(QuicConnectionTest, Buffer100NonDecryptablePacketsThenKeyChange) {
QUICHE teamcd098022019-03-22 18:49:55 -07004633 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4634 return;
4635 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004636 // SetFromConfig is always called after construction from InitializeSession.
4637 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4638 QuicConfig config;
4639 config.set_max_undecryptable_packets(100);
4640 connection_.SetFromConfig(config);
4641 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4642 use_tagging_decrypter();
4643
4644 const uint8_t tag = 0x07;
4645 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004646 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004647
4648 // Process an encrypted packet which can not yet be decrypted which should
4649 // result in the packet being buffered.
4650 for (uint64_t i = 1; i <= 100; ++i) {
4651 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4652 }
4653
4654 // Transition to the new encryption state and process another encrypted packet
4655 // which should result in the original packets being processed.
4656 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
zhongyi546cc452019-04-12 15:27:49 -07004657 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004658 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004659 EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
4660 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4661 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004662 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004663
4664 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(100);
4665 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
4666
4667 // Finally, process a third packet and note that we do not reprocess the
4668 // buffered packet.
4669 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4670 ProcessDataPacketAtLevel(102, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4671}
4672
4673TEST_P(QuicConnectionTest, SetRTOAfterWritingToSocket) {
4674 BlockOnNextWrite();
fayange62e63c2019-12-04 07:16:25 -08004675 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004676 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
fayange62e63c2019-12-04 07:16:25 -08004677 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004678
4679 // Test that RTO is started once we write to the socket.
4680 writer_->SetWritable();
fayange62e63c2019-12-04 07:16:25 -08004681 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004682 connection_.OnCanWrite();
4683 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4684}
4685
4686TEST_P(QuicConnectionTest, DelayRTOWithAckReceipt) {
fayang5f135052019-08-22 17:59:40 -07004687 if (connection_.PtoEnabled()) {
4688 return;
4689 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004690 connection_.SetMaxTailLossProbes(0);
4691
4692 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4693 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
4694 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
4695 connection_.SendStreamDataWithString(3, "bar", 0, NO_FIN);
4696 QuicAlarm* retransmission_alarm = connection_.GetRetransmissionAlarm();
4697 EXPECT_TRUE(retransmission_alarm->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004698 EXPECT_EQ(DefaultRetransmissionTime(),
4699 retransmission_alarm->deadline() - clock_.Now());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004700
4701 // Advance the time right before the RTO, then receive an ack for the first
4702 // packet to delay the RTO.
4703 clock_.AdvanceTime(DefaultRetransmissionTime());
4704 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4705 QuicAckFrame ack = InitAckFrame(1);
4706 ProcessAckPacket(&ack);
4707 // Now we have an RTT sample of DefaultRetransmissionTime(500ms),
4708 // so the RTO has increased to 2 * SRTT.
4709 EXPECT_TRUE(retransmission_alarm->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004710 EXPECT_EQ(retransmission_alarm->deadline() - clock_.Now(),
4711 2 * DefaultRetransmissionTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004712
4713 // Move forward past the original RTO and ensure the RTO is still pending.
4714 clock_.AdvanceTime(2 * DefaultRetransmissionTime());
4715
4716 // Ensure the second packet gets retransmitted when it finally fires.
4717 EXPECT_TRUE(retransmission_alarm->IsSet());
4718 EXPECT_EQ(retransmission_alarm->deadline(), clock_.ApproximateNow());
4719 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4720 // Manually cancel the alarm to simulate a real test.
4721 connection_.GetRetransmissionAlarm()->Fire();
4722
4723 // The new retransmitted packet number should set the RTO to a larger value
4724 // than previously.
4725 EXPECT_TRUE(retransmission_alarm->IsSet());
4726 QuicTime next_rto_time = retransmission_alarm->deadline();
4727 QuicTime expected_rto_time =
4728 connection_.sent_packet_manager().GetRetransmissionTime();
4729 EXPECT_EQ(next_rto_time, expected_rto_time);
4730}
4731
4732TEST_P(QuicConnectionTest, TestQueued) {
4733 connection_.SetMaxTailLossProbes(0);
4734
4735 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4736 BlockOnNextWrite();
4737 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4738 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4739
4740 // Unblock the writes and actually send.
4741 writer_->SetWritable();
4742 connection_.OnCanWrite();
4743 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4744}
4745
4746TEST_P(QuicConnectionTest, InitialTimeout) {
4747 EXPECT_TRUE(connection_.connected());
4748 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4749 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4750
4751 // SetFromConfig sets the initial timeouts before negotiation.
4752 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4753 QuicConfig config;
4754 connection_.SetFromConfig(config);
4755 // Subtract a second from the idle timeout on the client side.
4756 QuicTime default_timeout =
4757 clock_.ApproximateNow() +
4758 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4759 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
4760
fkastenholz5d880a92019-06-21 09:01:56 -07004761 EXPECT_CALL(visitor_,
4762 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004763 // Simulate the timeout alarm firing.
4764 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1));
4765 connection_.GetTimeoutAlarm()->Fire();
4766
4767 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4768 EXPECT_FALSE(connection_.connected());
4769
fayang9adfb532020-06-04 06:58:45 -07004770 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004771 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4772 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4773 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4774 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
renjietang11e4a3d2019-05-03 11:27:26 -07004775 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07004776 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004777}
4778
4779TEST_P(QuicConnectionTest, IdleTimeoutAfterFirstSentPacket) {
4780 EXPECT_TRUE(connection_.connected());
4781 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4782 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4783
4784 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4785 QuicConfig config;
4786 connection_.SetFromConfig(config);
4787 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4788 QuicTime initial_ddl =
4789 clock_.ApproximateNow() +
4790 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4791 EXPECT_EQ(initial_ddl, connection_.GetTimeoutAlarm()->deadline());
4792 EXPECT_TRUE(connection_.connected());
4793
4794 // Advance the time and send the first packet to the peer.
fayangb9c88442020-03-26 07:03:57 -07004795 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004796 QuicPacketNumber last_packet;
4797 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4798 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4799 // This will be the updated deadline for the connection to idle time out.
4800 QuicTime new_ddl = clock_.ApproximateNow() +
4801 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4802
4803 // Simulate the timeout alarm firing, the connection should not be closed as
4804 // a new packet has been sent.
fkastenholz5d880a92019-06-21 09:01:56 -07004805 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004806 QuicTime::Delta delay = initial_ddl - clock_.ApproximateNow();
4807 clock_.AdvanceTime(delay);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004808 // Verify the timeout alarm deadline is updated.
4809 EXPECT_TRUE(connection_.connected());
4810 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4811 EXPECT_EQ(new_ddl, connection_.GetTimeoutAlarm()->deadline());
4812
4813 // Simulate the timeout alarm firing again, the connection now should be
4814 // closed.
fkastenholz5d880a92019-06-21 09:01:56 -07004815 EXPECT_CALL(visitor_,
4816 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004817 clock_.AdvanceTime(new_ddl - clock_.ApproximateNow());
4818 connection_.GetTimeoutAlarm()->Fire();
4819 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4820 EXPECT_FALSE(connection_.connected());
4821
fayang9adfb532020-06-04 06:58:45 -07004822 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004823 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4824 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4825 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4826 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07004827 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004828}
4829
4830TEST_P(QuicConnectionTest, IdleTimeoutAfterSendTwoPackets) {
4831 EXPECT_TRUE(connection_.connected());
4832 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4833 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4834
4835 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4836 QuicConfig config;
4837 connection_.SetFromConfig(config);
4838 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4839 QuicTime initial_ddl =
4840 clock_.ApproximateNow() +
4841 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4842 EXPECT_EQ(initial_ddl, connection_.GetTimeoutAlarm()->deadline());
4843 EXPECT_TRUE(connection_.connected());
4844
4845 // Immediately send the first packet, this is a rare case but test code will
4846 // hit this issue often as MockClock used for tests doesn't move with code
4847 // execution until manually adjusted.
4848 QuicPacketNumber last_packet;
4849 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4850 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4851
4852 // Advance the time and send the second packet to the peer.
4853 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
4854 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4855 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
4856
zhongyic1cab062019-06-19 12:02:24 -07004857 // Simulate the timeout alarm firing, the connection will be closed.
fkastenholz5d880a92019-06-21 09:01:56 -07004858 EXPECT_CALL(visitor_,
4859 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
zhongyic1cab062019-06-19 12:02:24 -07004860 clock_.AdvanceTime(initial_ddl - clock_.ApproximateNow());
4861 connection_.GetTimeoutAlarm()->Fire();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004862
4863 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4864 EXPECT_FALSE(connection_.connected());
4865
fayang9adfb532020-06-04 06:58:45 -07004866 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004867 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4868 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4869 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4870 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07004871 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004872}
4873
4874TEST_P(QuicConnectionTest, HandshakeTimeout) {
4875 // Use a shorter handshake timeout than idle timeout for this test.
4876 const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(5);
4877 connection_.SetNetworkTimeouts(timeout, timeout);
4878 EXPECT_TRUE(connection_.connected());
4879 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4880
4881 QuicTime handshake_timeout =
4882 clock_.ApproximateNow() + timeout - QuicTime::Delta::FromSeconds(1);
4883 EXPECT_EQ(handshake_timeout, connection_.GetTimeoutAlarm()->deadline());
4884 EXPECT_TRUE(connection_.connected());
4885
4886 // Send and ack new data 3 seconds later to lengthen the idle timeout.
4887 SendStreamDataToPeer(
dschinazi552accc2019-06-17 17:07:34 -07004888 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
4889 "GET /", 0, FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004890 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(3));
4891 QuicAckFrame frame = InitAckFrame(1);
4892 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4893 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4894 ProcessAckPacket(&frame);
4895
QUICHE teama6ef0a62019-03-07 20:34:33 -05004896 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4897 EXPECT_TRUE(connection_.connected());
4898
4899 clock_.AdvanceTime(timeout - QuicTime::Delta::FromSeconds(2));
4900
fkastenholz5d880a92019-06-21 09:01:56 -07004901 EXPECT_CALL(visitor_,
4902 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004903 // Simulate the timeout alarm firing.
4904 connection_.GetTimeoutAlarm()->Fire();
4905
4906 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4907 EXPECT_FALSE(connection_.connected());
4908
fayang9adfb532020-06-04 06:58:45 -07004909 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004910 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4911 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4912 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07004913 TestConnectionCloseQuicErrorCode(QUIC_HANDSHAKE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004914}
4915
4916TEST_P(QuicConnectionTest, PingAfterSend) {
QUICHE teamcd098022019-03-22 18:49:55 -07004917 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4918 return;
4919 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004920 EXPECT_TRUE(connection_.connected());
4921 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4922 .WillRepeatedly(Return(true));
4923 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4924
4925 // Advance to 5ms, and send a packet to the peer, which will set
4926 // the ping alarm.
4927 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4928 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4929 SendStreamDataToPeer(
dschinazi552accc2019-06-17 17:07:34 -07004930 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
4931 "GET /", 0, FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004932 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004933 EXPECT_EQ(QuicTime::Delta::FromSeconds(15),
4934 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004935
4936 // Now recevie an ACK of the previous packet, which will move the
4937 // ping alarm forward.
4938 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4939 QuicAckFrame frame = InitAckFrame(1);
4940 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4941 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4942 ProcessAckPacket(&frame);
4943 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4944 // The ping timer is set slightly less than 15 seconds in the future, because
4945 // of the 1s ping timer alarm granularity.
zhongyieef848f2019-10-18 07:09:37 -07004946 EXPECT_EQ(
4947 QuicTime::Delta::FromSeconds(15) - QuicTime::Delta::FromMilliseconds(5),
4948 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004949
4950 writer_->Reset();
4951 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15));
zhongyifbb25772019-04-10 16:54:08 -07004952 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004953 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07004954 size_t padding_frame_count = writer_->padding_frames().size();
4955 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004956 ASSERT_EQ(1u, writer_->ping_frames().size());
4957 writer_->Reset();
4958
4959 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4960 .WillRepeatedly(Return(false));
4961 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4962 SendAckPacketToPeer();
4963
4964 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4965}
4966
4967TEST_P(QuicConnectionTest, ReducedPingTimeout) {
QUICHE teamcd098022019-03-22 18:49:55 -07004968 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4969 return;
4970 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004971 EXPECT_TRUE(connection_.connected());
4972 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4973 .WillRepeatedly(Return(true));
4974 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4975
4976 // Use a reduced ping timeout for this connection.
4977 connection_.set_ping_timeout(QuicTime::Delta::FromSeconds(10));
4978
4979 // Advance to 5ms, and send a packet to the peer, which will set
4980 // the ping alarm.
4981 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4982 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4983 SendStreamDataToPeer(
dschinazi552accc2019-06-17 17:07:34 -07004984 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
4985 "GET /", 0, FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004986 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004987 EXPECT_EQ(QuicTime::Delta::FromSeconds(10),
4988 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004989
4990 // Now recevie an ACK of the previous packet, which will move the
4991 // ping alarm forward.
4992 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4993 QuicAckFrame frame = InitAckFrame(1);
4994 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4995 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4996 ProcessAckPacket(&frame);
4997 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4998 // The ping timer is set slightly less than 10 seconds in the future, because
4999 // of the 1s ping timer alarm granularity.
zhongyieef848f2019-10-18 07:09:37 -07005000 EXPECT_EQ(
5001 QuicTime::Delta::FromSeconds(10) - QuicTime::Delta::FromMilliseconds(5),
5002 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005003
5004 writer_->Reset();
5005 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
5006 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
5007 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
5008 }));
5009 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07005010 size_t padding_frame_count = writer_->padding_frames().size();
5011 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005012 ASSERT_EQ(1u, writer_->ping_frames().size());
5013 writer_->Reset();
5014
5015 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
5016 .WillRepeatedly(Return(false));
5017 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
5018 SendAckPacketToPeer();
5019
5020 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
5021}
5022
5023// Tests whether sending an MTU discovery packet to peer successfully causes the
5024// maximum packet size to increase.
5025TEST_P(QuicConnectionTest, SendMtuDiscoveryPacket) {
wub031d47c2019-11-21 08:04:07 -08005026 MtuDiscoveryTestInit();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005027
5028 // Send an MTU probe.
5029 const size_t new_mtu = kDefaultMaxPacketSize + 100;
5030 QuicByteCount mtu_probe_size;
5031 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5032 .WillOnce(SaveArg<3>(&mtu_probe_size));
5033 connection_.SendMtuDiscoveryPacket(new_mtu);
5034 EXPECT_EQ(new_mtu, mtu_probe_size);
5035 EXPECT_EQ(QuicPacketNumber(1u), creator_->packet_number());
5036
5037 // Send more than MTU worth of data. No acknowledgement was received so far,
5038 // so the MTU should be at its old value.
vasilvvc48c8712019-03-11 13:38:16 -07005039 const std::string data(kDefaultMaxPacketSize + 1, '.');
QUICHE teama6ef0a62019-03-07 20:34:33 -05005040 QuicByteCount size_before_mtu_change;
5041 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5042 .Times(2)
5043 .WillOnce(SaveArg<3>(&size_before_mtu_change))
5044 .WillOnce(Return());
5045 connection_.SendStreamDataWithString(3, data, 0, FIN);
5046 EXPECT_EQ(QuicPacketNumber(3u), creator_->packet_number());
5047 EXPECT_EQ(kDefaultMaxPacketSize, size_before_mtu_change);
5048
5049 // Acknowledge all packets so far.
5050 QuicAckFrame probe_ack = InitAckFrame(3);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005051 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5052 ProcessAckPacket(&probe_ack);
5053 EXPECT_EQ(new_mtu, connection_.max_packet_length());
5054
5055 // Send the same data again. Check that it fits into a single packet now.
5056 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
5057 connection_.SendStreamDataWithString(3, data, 0, FIN);
5058 EXPECT_EQ(QuicPacketNumber(4u), creator_->packet_number());
5059}
5060
wubb442b862020-01-31 08:16:21 -08005061// Verifies that when a MTU probe packet is sent and buffered in a batch writer,
5062// the writer is flushed immediately.
5063TEST_P(QuicConnectionTest, BatchWriterFlushedAfterMtuDiscoveryPacket) {
5064 writer_->SetBatchMode(true);
5065 MtuDiscoveryTestInit();
5066
5067 // Send an MTU probe.
5068 const size_t target_mtu = kDefaultMaxPacketSize + 100;
5069 QuicByteCount mtu_probe_size;
5070 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5071 .WillOnce(SaveArg<3>(&mtu_probe_size));
5072 const uint32_t prior_flush_attempts = writer_->flush_attempts();
5073 connection_.SendMtuDiscoveryPacket(target_mtu);
5074 EXPECT_EQ(target_mtu, mtu_probe_size);
wub18f47342020-03-16 15:56:03 -07005075 EXPECT_EQ(writer_->flush_attempts(), prior_flush_attempts + 1);
wubb442b862020-01-31 08:16:21 -08005076}
5077
QUICHE teama6ef0a62019-03-07 20:34:33 -05005078// Tests whether MTU discovery does not happen when it is not explicitly enabled
5079// by the connection options.
5080TEST_P(QuicConnectionTest, MtuDiscoveryDisabled) {
wub031d47c2019-11-21 08:04:07 -08005081 MtuDiscoveryTestInit();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005082
5083 const QuicPacketCount packets_between_probes_base = 10;
5084 set_packets_between_probes_base(packets_between_probes_base);
5085
5086 const QuicPacketCount number_of_packets = packets_between_probes_base * 2;
5087 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
5088 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5089 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5090 EXPECT_EQ(0u, connection_.mtu_probe_count());
5091 }
5092}
5093
wubf76cf2a2019-10-11 18:49:07 -07005094// Tests whether MTU discovery works when all probes are acknowledged on the
QUICHE teama6ef0a62019-03-07 20:34:33 -05005095// first try.
5096TEST_P(QuicConnectionTest, MtuDiscoveryEnabled) {
wub031d47c2019-11-21 08:04:07 -08005097 MtuDiscoveryTestInit();
nharperc6b99512019-09-19 11:13:48 -07005098
QUICHE teama6ef0a62019-03-07 20:34:33 -05005099 const QuicPacketCount packets_between_probes_base = 5;
5100 set_packets_between_probes_base(packets_between_probes_base);
5101
wubf76cf2a2019-10-11 18:49:07 -07005102 connection_.EnablePathMtuDiscovery(send_algorithm_);
5103
QUICHE teama6ef0a62019-03-07 20:34:33 -05005104 // Send enough packets so that the next one triggers path MTU discovery.
5105 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5106 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5107 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5108 }
5109
5110 // Trigger the probe.
5111 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5112 nullptr);
5113 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5114 QuicByteCount probe_size;
5115 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5116 .WillOnce(SaveArg<3>(&probe_size));
5117 connection_.GetMtuDiscoveryAlarm()->Fire();
wub173916e2019-11-27 14:36:24 -08005118
5119 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(),
5120 kMtuDiscoveryTargetPacketSizeHigh));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005121
5122 const QuicPacketNumber probe_packet_number =
5123 FirstSendingPacketNumber() + packets_between_probes_base;
5124 ASSERT_EQ(probe_packet_number, creator_->packet_number());
5125
5126 // Acknowledge all packets sent so far.
5127 QuicAckFrame probe_ack = InitAckFrame(probe_packet_number);
wubf76cf2a2019-10-11 18:49:07 -07005128 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5129 .Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005130 ProcessAckPacket(&probe_ack);
wubf76cf2a2019-10-11 18:49:07 -07005131 EXPECT_EQ(probe_size, connection_.max_packet_length());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005132 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5133
wubf76cf2a2019-10-11 18:49:07 -07005134 EXPECT_EQ(1u, connection_.mtu_probe_count());
5135
wubf76cf2a2019-10-11 18:49:07 -07005136 QuicStreamOffset stream_offset = packets_between_probes_base;
wubecb643f2020-03-19 08:58:46 -07005137 QuicByteCount last_probe_size = 0;
wubf76cf2a2019-10-11 18:49:07 -07005138 for (size_t num_probes = 1; num_probes < kMtuDiscoveryAttempts;
5139 ++num_probes) {
5140 // Send just enough packets without triggering the next probe.
5141 for (QuicPacketCount i = 0;
5142 i < (packets_between_probes_base << num_probes) - 1; ++i) {
5143 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5144 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5145 }
5146
5147 // Trigger the next probe.
5148 SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
5149 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5150 QuicByteCount new_probe_size;
5151 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5152 .WillOnce(SaveArg<3>(&new_probe_size));
5153 connection_.GetMtuDiscoveryAlarm()->Fire();
5154 EXPECT_THAT(new_probe_size,
5155 InRange(probe_size, kMtuDiscoveryTargetPacketSizeHigh));
5156 EXPECT_EQ(num_probes + 1, connection_.mtu_probe_count());
5157
5158 // Acknowledge all packets sent so far.
5159 QuicAckFrame probe_ack = InitAckFrame(creator_->packet_number());
5160 ProcessAckPacket(&probe_ack);
5161 EXPECT_EQ(new_probe_size, connection_.max_packet_length());
5162 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5163
wubecb643f2020-03-19 08:58:46 -07005164 last_probe_size = probe_size;
wubf76cf2a2019-10-11 18:49:07 -07005165 probe_size = new_probe_size;
5166 }
5167
5168 // The last probe size should be equal to the target.
5169 EXPECT_EQ(probe_size, kMtuDiscoveryTargetPacketSizeHigh);
wubecb643f2020-03-19 08:58:46 -07005170
wubae6581a2020-05-04 12:13:05 -07005171 writer_->SetShouldWriteFail();
wubecb643f2020-03-19 08:58:46 -07005172
wubae6581a2020-05-04 12:13:05 -07005173 // Ignore PACKET_WRITE_ERROR once.
5174 SendStreamDataToPeer(3, "(", stream_offset++, NO_FIN, nullptr);
5175 EXPECT_EQ(last_probe_size, connection_.max_packet_length());
5176 EXPECT_TRUE(connection_.connected());
wubecb643f2020-03-19 08:58:46 -07005177
wubae6581a2020-05-04 12:13:05 -07005178 // Close connection on another PACKET_WRITE_ERROR.
5179 EXPECT_CALL(visitor_, OnConnectionClosed(_, _))
5180 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
5181 SendStreamDataToPeer(3, ")", stream_offset++, NO_FIN, nullptr);
5182 EXPECT_EQ(last_probe_size, connection_.max_packet_length());
5183 EXPECT_FALSE(connection_.connected());
5184 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
5185 IsError(QUIC_PACKET_WRITE_ERROR));
wubf76cf2a2019-10-11 18:49:07 -07005186}
5187
wub748e20b2020-03-20 14:33:59 -07005188// After a successful MTU probe, one and only one write error should be ignored
5189// if it happened in QuicConnection::FlushPacket.
5190TEST_P(QuicConnectionTest,
5191 MtuDiscoveryIgnoreOneWriteErrorInFlushAfterSuccessfulProbes) {
5192 MtuDiscoveryTestInit();
5193 writer_->SetBatchMode(true);
5194
5195 const QuicPacketCount packets_between_probes_base = 5;
5196 set_packets_between_probes_base(packets_between_probes_base);
5197
5198 connection_.EnablePathMtuDiscovery(send_algorithm_);
5199
5200 const QuicByteCount original_max_packet_length =
5201 connection_.max_packet_length();
5202 // Send enough packets so that the next one triggers path MTU discovery.
5203 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5204 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5205 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5206 }
5207
5208 // Trigger the probe.
5209 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5210 nullptr);
5211 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5212 QuicByteCount probe_size;
5213 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5214 .WillOnce(SaveArg<3>(&probe_size));
5215 connection_.GetMtuDiscoveryAlarm()->Fire();
5216
5217 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(),
5218 kMtuDiscoveryTargetPacketSizeHigh));
5219
5220 const QuicPacketNumber probe_packet_number =
5221 FirstSendingPacketNumber() + packets_between_probes_base;
5222 ASSERT_EQ(probe_packet_number, creator_->packet_number());
5223
5224 // Acknowledge all packets sent so far.
5225 QuicAckFrame probe_ack = InitAckFrame(probe_packet_number);
5226 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5227 .Times(AnyNumber());
5228 ProcessAckPacket(&probe_ack);
5229 EXPECT_EQ(probe_size, connection_.max_packet_length());
5230 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5231
5232 EXPECT_EQ(1u, connection_.mtu_probe_count());
5233
wubae6581a2020-05-04 12:13:05 -07005234 writer_->SetShouldWriteFail();
wub748e20b2020-03-20 14:33:59 -07005235
wubae6581a2020-05-04 12:13:05 -07005236 // Ignore PACKET_WRITE_ERROR once.
5237 {
5238 QuicConnection::ScopedPacketFlusher flusher(&connection_);
5239 // flusher's destructor will call connection_.FlushPackets, which should
5240 // get a WRITE_STATUS_ERROR from the writer and ignore it.
wub748e20b2020-03-20 14:33:59 -07005241 }
wubae6581a2020-05-04 12:13:05 -07005242 EXPECT_EQ(original_max_packet_length, connection_.max_packet_length());
5243 EXPECT_TRUE(connection_.connected());
5244
5245 // Close connection on another PACKET_WRITE_ERROR.
5246 EXPECT_CALL(visitor_, OnConnectionClosed(_, _))
5247 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
5248 {
5249 QuicConnection::ScopedPacketFlusher flusher(&connection_);
5250 // flusher's destructor will call connection_.FlushPackets, which should
5251 // get a WRITE_STATUS_ERROR from the writer and ignore it.
5252 }
5253 EXPECT_EQ(original_max_packet_length, connection_.max_packet_length());
5254 EXPECT_FALSE(connection_.connected());
5255 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
5256 IsError(QUIC_PACKET_WRITE_ERROR));
wub748e20b2020-03-20 14:33:59 -07005257}
5258
wubf76cf2a2019-10-11 18:49:07 -07005259// Simulate the case where the first attempt to send a probe is write blocked,
5260// and after unblock, the second attempt returns a MSG_TOO_BIG error.
5261TEST_P(QuicConnectionTest, MtuDiscoveryWriteBlocked) {
wub031d47c2019-11-21 08:04:07 -08005262 MtuDiscoveryTestInit();
wubf76cf2a2019-10-11 18:49:07 -07005263
5264 const QuicPacketCount packets_between_probes_base = 5;
5265 set_packets_between_probes_base(packets_between_probes_base);
5266
5267 connection_.EnablePathMtuDiscovery(send_algorithm_);
5268
5269 // Send enough packets so that the next one triggers path MTU discovery.
5270 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5271 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005272 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5273 }
5274
wubf76cf2a2019-10-11 18:49:07 -07005275 QuicByteCount original_max_packet_length = connection_.max_packet_length();
5276
5277 // Trigger the probe.
5278 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5279 nullptr);
5280 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
fayange62e63c2019-12-04 07:16:25 -08005281 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
wubf76cf2a2019-10-11 18:49:07 -07005282 BlockOnNextWrite();
5283 EXPECT_EQ(0u, connection_.NumQueuedPackets());
5284 connection_.GetMtuDiscoveryAlarm()->Fire();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005285 EXPECT_EQ(1u, connection_.mtu_probe_count());
wubf76cf2a2019-10-11 18:49:07 -07005286 EXPECT_EQ(1u, connection_.NumQueuedPackets());
5287 ASSERT_TRUE(connection_.connected());
5288
5289 writer_->SetWritable();
5290 SimulateNextPacketTooLarge();
5291 connection_.OnCanWrite();
5292 EXPECT_EQ(0u, connection_.NumQueuedPackets());
5293 EXPECT_EQ(original_max_packet_length, connection_.max_packet_length());
5294 EXPECT_TRUE(connection_.connected());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005295}
5296
5297// Tests whether MTU discovery works correctly when the probes never get
5298// acknowledged.
5299TEST_P(QuicConnectionTest, MtuDiscoveryFailed) {
wub031d47c2019-11-21 08:04:07 -08005300 MtuDiscoveryTestInit();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005301
QUICHE teama6ef0a62019-03-07 20:34:33 -05005302 // Lower the number of probes between packets in order to make the test go
5303 // much faster.
5304 const QuicPacketCount packets_between_probes_base = 5;
5305 set_packets_between_probes_base(packets_between_probes_base);
5306
wubf76cf2a2019-10-11 18:49:07 -07005307 connection_.EnablePathMtuDiscovery(send_algorithm_);
5308
5309 const QuicTime::Delta rtt = QuicTime::Delta::FromMilliseconds(100);
5310
5311 EXPECT_EQ(packets_between_probes_base,
5312 QuicConnectionPeer::GetPacketsBetweenMtuProbes(&connection_));
5313
QUICHE teama6ef0a62019-03-07 20:34:33 -05005314 // This tests sends more packets than strictly necessary to make sure that if
5315 // the connection was to send more discovery packets than needed, those would
5316 // get caught as well.
5317 const QuicPacketCount number_of_packets =
5318 packets_between_probes_base * (1 << (kMtuDiscoveryAttempts + 1));
5319 std::vector<QuicPacketNumber> mtu_discovery_packets;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005320 // Called on many acks.
5321 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5322 .Times(AnyNumber());
5323 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
5324 SendStreamDataToPeer(3, "!", i, NO_FIN, nullptr);
5325 clock_.AdvanceTime(rtt);
5326
5327 // Receive an ACK, which marks all data packets as received, and all MTU
5328 // discovery packets as missing.
5329
5330 QuicAckFrame ack;
5331
5332 if (!mtu_discovery_packets.empty()) {
5333 QuicPacketNumber min_packet = *min_element(mtu_discovery_packets.begin(),
5334 mtu_discovery_packets.end());
5335 QuicPacketNumber max_packet = *max_element(mtu_discovery_packets.begin(),
5336 mtu_discovery_packets.end());
5337 ack.packets.AddRange(QuicPacketNumber(1), min_packet);
5338 ack.packets.AddRange(QuicPacketNumber(max_packet + 1),
5339 creator_->packet_number() + 1);
5340 ack.largest_acked = creator_->packet_number();
5341
5342 } else {
5343 ack.packets.AddRange(QuicPacketNumber(1), creator_->packet_number() + 1);
5344 ack.largest_acked = creator_->packet_number();
5345 }
5346
5347 ProcessAckPacket(&ack);
5348
5349 // Trigger MTU probe if it would be scheduled now.
5350 if (!connection_.GetMtuDiscoveryAlarm()->IsSet()) {
5351 continue;
5352 }
5353
5354 // Fire the alarm. The alarm should cause a packet to be sent.
5355 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5356 connection_.GetMtuDiscoveryAlarm()->Fire();
5357 // Record the packet number of the MTU discovery packet in order to
5358 // mark it as NACK'd.
5359 mtu_discovery_packets.push_back(creator_->packet_number());
5360 }
5361
5362 // Ensure the number of packets between probes grows exponentially by checking
5363 // it against the closed-form expression for the packet number.
5364 ASSERT_EQ(kMtuDiscoveryAttempts, mtu_discovery_packets.size());
5365 for (uint64_t i = 0; i < kMtuDiscoveryAttempts; i++) {
5366 // 2^0 + 2^1 + 2^2 + ... + 2^n = 2^(n + 1) - 1
5367 const QuicPacketCount packets_between_probes =
5368 packets_between_probes_base * ((1 << (i + 1)) - 1);
5369 EXPECT_EQ(QuicPacketNumber(packets_between_probes + (i + 1)),
5370 mtu_discovery_packets[i]);
5371 }
5372
5373 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5374 EXPECT_EQ(kDefaultMaxPacketSize, connection_.max_packet_length());
5375 EXPECT_EQ(kMtuDiscoveryAttempts, connection_.mtu_probe_count());
5376}
5377
wubf76cf2a2019-10-11 18:49:07 -07005378// Probe 3 times, the first one succeeds, then fails, then succeeds again.
5379TEST_P(QuicConnectionTest, MtuDiscoverySecondProbeFailed) {
wub031d47c2019-11-21 08:04:07 -08005380 MtuDiscoveryTestInit();
wubf76cf2a2019-10-11 18:49:07 -07005381
5382 const QuicPacketCount packets_between_probes_base = 5;
5383 set_packets_between_probes_base(packets_between_probes_base);
5384
5385 connection_.EnablePathMtuDiscovery(send_algorithm_);
5386
5387 // Send enough packets so that the next one triggers path MTU discovery.
5388 QuicStreamOffset stream_offset = 0;
5389 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5390 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5391 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5392 }
5393
5394 // Trigger the probe.
5395 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5396 nullptr);
5397 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5398 QuicByteCount probe_size;
5399 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5400 .WillOnce(SaveArg<3>(&probe_size));
5401 connection_.GetMtuDiscoveryAlarm()->Fire();
5402 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(),
5403 kMtuDiscoveryTargetPacketSizeHigh));
5404
5405 const QuicPacketNumber probe_packet_number =
5406 FirstSendingPacketNumber() + packets_between_probes_base;
5407 ASSERT_EQ(probe_packet_number, creator_->packet_number());
5408
5409 // Acknowledge all packets sent so far.
5410 QuicAckFrame first_ack = InitAckFrame(probe_packet_number);
wubf76cf2a2019-10-11 18:49:07 -07005411 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5412 .Times(AnyNumber());
5413 ProcessAckPacket(&first_ack);
5414 EXPECT_EQ(probe_size, connection_.max_packet_length());
5415 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5416
5417 EXPECT_EQ(1u, connection_.mtu_probe_count());
5418
5419 // Send just enough packets without triggering the second probe.
5420 for (QuicPacketCount i = 0; i < (packets_between_probes_base << 1) - 1; ++i) {
5421 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5422 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5423 }
5424
5425 // Trigger the second probe.
5426 SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
5427 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5428 QuicByteCount second_probe_size;
5429 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5430 .WillOnce(SaveArg<3>(&second_probe_size));
5431 connection_.GetMtuDiscoveryAlarm()->Fire();
5432 EXPECT_THAT(second_probe_size,
5433 InRange(probe_size, kMtuDiscoveryTargetPacketSizeHigh));
5434 EXPECT_EQ(2u, connection_.mtu_probe_count());
5435
5436 // Acknowledge all packets sent so far, except the second probe.
5437 QuicPacketNumber second_probe_packet_number = creator_->packet_number();
5438 QuicAckFrame second_ack = InitAckFrame(second_probe_packet_number - 1);
5439 ProcessAckPacket(&first_ack);
5440 EXPECT_EQ(probe_size, connection_.max_packet_length());
5441
5442 // Send just enough packets without triggering the third probe.
5443 for (QuicPacketCount i = 0; i < (packets_between_probes_base << 2) - 1; ++i) {
5444 SendStreamDataToPeer(3, "@", stream_offset++, NO_FIN, nullptr);
5445 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5446 }
5447
5448 // Trigger the third probe.
5449 SendStreamDataToPeer(3, "#", stream_offset++, NO_FIN, nullptr);
5450 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5451 QuicByteCount third_probe_size;
5452 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5453 .WillOnce(SaveArg<3>(&third_probe_size));
5454 connection_.GetMtuDiscoveryAlarm()->Fire();
5455 EXPECT_THAT(third_probe_size, InRange(probe_size, second_probe_size));
5456 EXPECT_EQ(3u, connection_.mtu_probe_count());
5457
5458 // Acknowledge all packets sent so far, except the second probe.
5459 QuicAckFrame third_ack =
5460 ConstructAckFrame(creator_->packet_number(), second_probe_packet_number);
5461 ProcessAckPacket(&third_ack);
5462 EXPECT_EQ(third_probe_size, connection_.max_packet_length());
5463}
5464
QUICHE teama6ef0a62019-03-07 20:34:33 -05005465// Tests whether MTU discovery works when the writer has a limit on how large a
5466// packet can be.
5467TEST_P(QuicConnectionTest, MtuDiscoveryWriterLimited) {
wub031d47c2019-11-21 08:04:07 -08005468 MtuDiscoveryTestInit();
nharperc6b99512019-09-19 11:13:48 -07005469
QUICHE teama6ef0a62019-03-07 20:34:33 -05005470 const QuicByteCount mtu_limit = kMtuDiscoveryTargetPacketSizeHigh - 1;
5471 writer_->set_max_packet_size(mtu_limit);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005472
5473 const QuicPacketCount packets_between_probes_base = 5;
5474 set_packets_between_probes_base(packets_between_probes_base);
5475
wubf76cf2a2019-10-11 18:49:07 -07005476 connection_.EnablePathMtuDiscovery(send_algorithm_);
5477
QUICHE teama6ef0a62019-03-07 20:34:33 -05005478 // Send enough packets so that the next one triggers path MTU discovery.
5479 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5480 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5481 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5482 }
5483
5484 // Trigger the probe.
5485 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5486 nullptr);
5487 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5488 QuicByteCount probe_size;
5489 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5490 .WillOnce(SaveArg<3>(&probe_size));
5491 connection_.GetMtuDiscoveryAlarm()->Fire();
wub173916e2019-11-27 14:36:24 -08005492
5493 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(), mtu_limit));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005494
5495 const QuicPacketNumber probe_sequence_number =
5496 FirstSendingPacketNumber() + packets_between_probes_base;
5497 ASSERT_EQ(probe_sequence_number, creator_->packet_number());
5498
5499 // Acknowledge all packets sent so far.
5500 QuicAckFrame probe_ack = InitAckFrame(probe_sequence_number);
wubf76cf2a2019-10-11 18:49:07 -07005501 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5502 .Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005503 ProcessAckPacket(&probe_ack);
wubf76cf2a2019-10-11 18:49:07 -07005504 EXPECT_EQ(probe_size, connection_.max_packet_length());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005505 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5506
wubf76cf2a2019-10-11 18:49:07 -07005507 EXPECT_EQ(1u, connection_.mtu_probe_count());
5508
wubf76cf2a2019-10-11 18:49:07 -07005509 QuicStreamOffset stream_offset = packets_between_probes_base;
5510 for (size_t num_probes = 1; num_probes < kMtuDiscoveryAttempts;
5511 ++num_probes) {
5512 // Send just enough packets without triggering the next probe.
5513 for (QuicPacketCount i = 0;
5514 i < (packets_between_probes_base << num_probes) - 1; ++i) {
5515 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5516 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5517 }
5518
5519 // Trigger the next probe.
5520 SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
5521 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5522 QuicByteCount new_probe_size;
5523 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5524 .WillOnce(SaveArg<3>(&new_probe_size));
5525 connection_.GetMtuDiscoveryAlarm()->Fire();
5526 EXPECT_THAT(new_probe_size, InRange(probe_size, mtu_limit));
5527 EXPECT_EQ(num_probes + 1, connection_.mtu_probe_count());
5528
5529 // Acknowledge all packets sent so far.
5530 QuicAckFrame probe_ack = InitAckFrame(creator_->packet_number());
5531 ProcessAckPacket(&probe_ack);
5532 EXPECT_EQ(new_probe_size, connection_.max_packet_length());
5533 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5534
5535 probe_size = new_probe_size;
5536 }
5537
5538 // The last probe size should be equal to the target.
5539 EXPECT_EQ(probe_size, mtu_limit);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005540}
5541
5542// Tests whether MTU discovery works when the writer returns an error despite
5543// advertising higher packet length.
5544TEST_P(QuicConnectionTest, MtuDiscoveryWriterFailed) {
wub031d47c2019-11-21 08:04:07 -08005545 MtuDiscoveryTestInit();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005546
5547 const QuicByteCount mtu_limit = kMtuDiscoveryTargetPacketSizeHigh - 1;
5548 const QuicByteCount initial_mtu = connection_.max_packet_length();
5549 EXPECT_LT(initial_mtu, mtu_limit);
5550 writer_->set_max_packet_size(mtu_limit);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005551
5552 const QuicPacketCount packets_between_probes_base = 5;
5553 set_packets_between_probes_base(packets_between_probes_base);
5554
wubf76cf2a2019-10-11 18:49:07 -07005555 connection_.EnablePathMtuDiscovery(send_algorithm_);
5556
QUICHE teama6ef0a62019-03-07 20:34:33 -05005557 // Send enough packets so that the next one triggers path MTU discovery.
5558 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5559 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5560 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5561 }
5562
5563 // Trigger the probe.
5564 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5565 nullptr);
5566 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5567 writer_->SimulateNextPacketTooLarge();
5568 connection_.GetMtuDiscoveryAlarm()->Fire();
5569 ASSERT_TRUE(connection_.connected());
5570
5571 // Send more data.
5572 QuicPacketNumber probe_number = creator_->packet_number();
5573 QuicPacketCount extra_packets = packets_between_probes_base * 3;
5574 for (QuicPacketCount i = 0; i < extra_packets; i++) {
5575 connection_.EnsureWritableAndSendStreamData5();
5576 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5577 }
5578
5579 // Acknowledge all packets sent so far, except for the lost probe.
5580 QuicAckFrame probe_ack =
5581 ConstructAckFrame(creator_->packet_number(), probe_number);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005582 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5583 ProcessAckPacket(&probe_ack);
5584 EXPECT_EQ(initial_mtu, connection_.max_packet_length());
5585
5586 // Send more packets, and ensure that none of them sets the alarm.
5587 for (QuicPacketCount i = 0; i < 4 * packets_between_probes_base; i++) {
5588 connection_.EnsureWritableAndSendStreamData5();
5589 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5590 }
5591
5592 EXPECT_EQ(initial_mtu, connection_.max_packet_length());
5593 EXPECT_EQ(1u, connection_.mtu_probe_count());
5594}
5595
5596TEST_P(QuicConnectionTest, NoMtuDiscoveryAfterConnectionClosed) {
wub031d47c2019-11-21 08:04:07 -08005597 MtuDiscoveryTestInit();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005598
QUICHE teama6ef0a62019-03-07 20:34:33 -05005599 const QuicPacketCount packets_between_probes_base = 10;
5600 set_packets_between_probes_base(packets_between_probes_base);
5601
wubf76cf2a2019-10-11 18:49:07 -07005602 connection_.EnablePathMtuDiscovery(send_algorithm_);
5603
QUICHE teama6ef0a62019-03-07 20:34:33 -05005604 // Send enough packets so that the next one triggers path MTU discovery.
5605 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5606 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5607 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5608 }
5609
5610 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5611 nullptr);
5612 EXPECT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5613
fkastenholz5d880a92019-06-21 09:01:56 -07005614 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005615 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
5616 ConnectionCloseBehavior::SILENT_CLOSE);
5617 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5618}
5619
dschinazi9a6194e2020-04-30 16:21:09 -07005620TEST_P(QuicConnectionTest, TimeoutAfterSendDuringHandshake) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005621 EXPECT_TRUE(connection_.connected());
5622 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5623 QuicConfig config;
5624 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005625
5626 const QuicTime::Delta initial_idle_timeout =
5627 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5628 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5629 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
5630
5631 // When we send a packet, the timeout will change to 5ms +
5632 // kInitialIdleTimeoutSecs.
5633 clock_.AdvanceTime(five_ms);
5634 SendStreamDataToPeer(
5635 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5636 0, FIN, nullptr);
fayang3a58dc42020-06-29 11:27:14 -07005637 EXPECT_EQ(default_timeout + five_ms,
5638 connection_.GetTimeoutAlarm()->deadline());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005639
5640 // Now send more data. This will not move the timeout because
5641 // no data has been received since the previous write.
5642 clock_.AdvanceTime(five_ms);
5643 SendStreamDataToPeer(
5644 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5645 3, FIN, nullptr);
fayang3a58dc42020-06-29 11:27:14 -07005646 EXPECT_EQ(default_timeout + five_ms,
5647 connection_.GetTimeoutAlarm()->deadline());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005648
5649 // The original alarm will fire. We should not time out because we had a
5650 // network event at t=5ms. The alarm will reregister.
5651 clock_.AdvanceTime(initial_idle_timeout - five_ms - five_ms);
5652 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005653 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5654 EXPECT_TRUE(connection_.connected());
5655 EXPECT_EQ(default_timeout + five_ms,
5656 connection_.GetTimeoutAlarm()->deadline());
5657
5658 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07005659 EXPECT_CALL(visitor_,
5660 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07005661 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005662 clock_.AdvanceTime(five_ms);
5663 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5664 connection_.GetTimeoutAlarm()->Fire();
5665 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5666 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005667 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005668}
5669
5670TEST_P(QuicConnectionTest, TimeoutAfterRetransmission) {
fayang5f135052019-08-22 17:59:40 -07005671 if (connection_.PtoEnabled()) {
5672 return;
5673 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005674 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5675 EXPECT_TRUE(connection_.connected());
5676 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5677 QuicConfig config;
5678 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005679
5680 const QuicTime start_time = clock_.Now();
5681 const QuicTime::Delta initial_idle_timeout =
5682 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5683 QuicTime default_timeout = clock_.Now() + initial_idle_timeout;
5684
5685 connection_.SetMaxTailLossProbes(0);
5686 const QuicTime default_retransmission_time =
5687 start_time + DefaultRetransmissionTime();
5688
5689 ASSERT_LT(default_retransmission_time, default_timeout);
5690
5691 // When we send a packet, the timeout will change to 5 ms +
5692 // kInitialIdleTimeoutSecs (but it will not reschedule the alarm).
5693 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5694 const QuicTime send_time = start_time + five_ms;
5695 clock_.AdvanceTime(five_ms);
5696 ASSERT_EQ(send_time, clock_.Now());
5697 SendStreamDataToPeer(
5698 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5699 0, FIN, nullptr);
fayang3a58dc42020-06-29 11:27:14 -07005700 EXPECT_EQ(default_timeout + five_ms,
5701 connection_.GetTimeoutAlarm()->deadline());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005702
5703 // Move forward 5 ms and receive a packet, which will move the timeout
5704 // forward 5 ms more (but will not reschedule the alarm).
5705 const QuicTime receive_time = send_time + five_ms;
5706 clock_.AdvanceTime(receive_time - clock_.Now());
5707 ASSERT_EQ(receive_time, clock_.Now());
5708 ProcessPacket(1);
5709
5710 // Now move forward to the retransmission time and retransmit the
5711 // packet, which should move the timeout forward again (but will not
5712 // reschedule the alarm).
5713 EXPECT_EQ(default_retransmission_time + five_ms,
5714 connection_.GetRetransmissionAlarm()->deadline());
5715 // Simulate the retransmission alarm firing.
5716 const QuicTime rto_time = send_time + DefaultRetransmissionTime();
5717 const QuicTime final_timeout = rto_time + initial_idle_timeout;
5718 clock_.AdvanceTime(rto_time - clock_.Now());
5719 ASSERT_EQ(rto_time, clock_.Now());
5720 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _));
5721 connection_.GetRetransmissionAlarm()->Fire();
5722
5723 // Advance to the original timeout and fire the alarm. The connection should
5724 // timeout, and the alarm should be registered based on the time of the
5725 // retransmission.
5726 clock_.AdvanceTime(default_timeout - clock_.Now());
5727 ASSERT_EQ(default_timeout.ToDebuggingValue(),
5728 clock_.Now().ToDebuggingValue());
5729 EXPECT_EQ(default_timeout, clock_.Now());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005730 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5731 EXPECT_TRUE(connection_.connected());
5732 ASSERT_EQ(final_timeout.ToDebuggingValue(),
5733 connection_.GetTimeoutAlarm()->deadline().ToDebuggingValue());
5734
5735 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07005736 EXPECT_CALL(visitor_,
5737 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07005738 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005739 clock_.AdvanceTime(final_timeout - clock_.Now());
5740 EXPECT_EQ(connection_.GetTimeoutAlarm()->deadline(), clock_.Now());
5741 EXPECT_EQ(final_timeout, clock_.Now());
5742 connection_.GetTimeoutAlarm()->Fire();
5743 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5744 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005745 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005746}
5747
dschinazi9a6194e2020-04-30 16:21:09 -07005748TEST_P(QuicConnectionTest, TimeoutAfterSendAfterHandshake) {
5749 // When the idle timeout fires, verify that by default we do not send any
5750 // connection close packets.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005751 EXPECT_TRUE(connection_.connected());
5752 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5753 QuicConfig config;
5754
5755 // Create a handshake message that also enables silent close.
5756 CryptoHandshakeMessage msg;
vasilvvc48c8712019-03-11 13:38:16 -07005757 std::string error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005758 QuicConfig client_config;
5759 client_config.SetInitialStreamFlowControlWindowToSend(
5760 kInitialStreamFlowControlWindowForTest);
5761 client_config.SetInitialSessionFlowControlWindowToSend(
5762 kInitialSessionFlowControlWindowForTest);
5763 client_config.SetIdleNetworkTimeout(
dschinazi027366e2020-05-01 14:31:19 -07005764 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs));
fkastenholzd3a1de92019-05-15 07:00:07 -07005765 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005766 const QuicErrorCode error =
5767 config.ProcessPeerHello(msg, CLIENT, &error_details);
bncf54082a2019-11-27 10:19:47 -08005768 EXPECT_THAT(error, IsQuicNoError());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005769
dschinazie7c38a52020-05-29 15:25:45 -07005770 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
5771 QuicConfigPeer::SetReceivedOriginalConnectionId(
5772 &config, connection_.connection_id());
5773 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
5774 &config, connection_.connection_id());
5775 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005776 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005777
5778 const QuicTime::Delta default_idle_timeout =
dschinazi027366e2020-05-01 14:31:19 -07005779 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs - 1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005780 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5781 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5782
5783 // When we send a packet, the timeout will change to 5ms +
5784 // kInitialIdleTimeoutSecs.
5785 clock_.AdvanceTime(five_ms);
5786 SendStreamDataToPeer(
5787 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5788 0, FIN, nullptr);
fayang3a58dc42020-06-29 11:27:14 -07005789 EXPECT_EQ(default_timeout + five_ms,
5790 connection_.GetTimeoutAlarm()->deadline());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005791
5792 // Now send more data. This will not move the timeout because
5793 // no data has been received since the previous write.
5794 clock_.AdvanceTime(five_ms);
5795 SendStreamDataToPeer(
5796 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5797 3, FIN, nullptr);
fayang3a58dc42020-06-29 11:27:14 -07005798 EXPECT_EQ(default_timeout + five_ms,
5799 connection_.GetTimeoutAlarm()->deadline());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005800
5801 // The original alarm will fire. We should not time out because we had a
5802 // network event at t=5ms. The alarm will reregister.
5803 clock_.AdvanceTime(default_idle_timeout - five_ms - five_ms);
5804 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005805 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5806 EXPECT_TRUE(connection_.connected());
5807 EXPECT_EQ(default_timeout + five_ms,
5808 connection_.GetTimeoutAlarm()->deadline());
5809
5810 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07005811 // This results in a SILENT_CLOSE, so the writer will not be invoked
5812 // and will not save the frame. Grab the frame from OnConnectionClosed
5813 // directly.
5814 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
5815 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
5816
QUICHE teama6ef0a62019-03-07 20:34:33 -05005817 clock_.AdvanceTime(five_ms);
5818 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5819 connection_.GetTimeoutAlarm()->Fire();
5820 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5821 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005822 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08005823 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
5824 IsError(QUIC_NETWORK_IDLE_TIMEOUT));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005825}
5826
5827TEST_P(QuicConnectionTest, TimeoutAfterSendSilentCloseAndTLP) {
fayang5f135052019-08-22 17:59:40 -07005828 if (connection_.PtoEnabled()) {
5829 return;
5830 }
dschinazi9a6194e2020-04-30 16:21:09 -07005831 // Same test as above, but sending TLPs causes a connection close to be sent.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005832 EXPECT_TRUE(connection_.connected());
5833 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5834 QuicConfig config;
5835
5836 // Create a handshake message that also enables silent close.
5837 CryptoHandshakeMessage msg;
vasilvvc48c8712019-03-11 13:38:16 -07005838 std::string error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005839 QuicConfig client_config;
5840 client_config.SetInitialStreamFlowControlWindowToSend(
5841 kInitialStreamFlowControlWindowForTest);
5842 client_config.SetInitialSessionFlowControlWindowToSend(
5843 kInitialSessionFlowControlWindowForTest);
5844 client_config.SetIdleNetworkTimeout(
dschinazi027366e2020-05-01 14:31:19 -07005845 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs));
fkastenholzd3a1de92019-05-15 07:00:07 -07005846 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005847 const QuicErrorCode error =
5848 config.ProcessPeerHello(msg, CLIENT, &error_details);
bncf54082a2019-11-27 10:19:47 -08005849 EXPECT_THAT(error, IsQuicNoError());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005850
5851 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005852
5853 const QuicTime::Delta default_idle_timeout =
dschinazi027366e2020-05-01 14:31:19 -07005854 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs - 1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005855 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5856 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5857
5858 // When we send a packet, the timeout will change to 5ms +
5859 // kInitialIdleTimeoutSecs.
5860 clock_.AdvanceTime(five_ms);
5861 SendStreamDataToPeer(
5862 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5863 0, FIN, nullptr);
fayang3a58dc42020-06-29 11:27:14 -07005864 EXPECT_EQ(default_timeout + five_ms,
5865 connection_.GetTimeoutAlarm()->deadline());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005866
5867 // Retransmit the packet via tail loss probe.
5868 clock_.AdvanceTime(connection_.GetRetransmissionAlarm()->deadline() -
5869 clock_.Now());
5870 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _));
5871 connection_.GetRetransmissionAlarm()->Fire();
5872
5873 // This time, we should time out and send a connection close due to the TLP.
fkastenholz5d880a92019-06-21 09:01:56 -07005874 EXPECT_CALL(visitor_,
5875 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07005876 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005877 clock_.AdvanceTime(connection_.GetTimeoutAlarm()->deadline() -
5878 clock_.ApproximateNow() + five_ms);
5879 connection_.GetTimeoutAlarm()->Fire();
5880 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5881 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005882 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005883}
5884
5885TEST_P(QuicConnectionTest, TimeoutAfterSendSilentCloseWithOpenStreams) {
dschinazi9a6194e2020-04-30 16:21:09 -07005886 // Same test as above, but having open streams causes a connection close
5887 // to be sent.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005888 EXPECT_TRUE(connection_.connected());
5889 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5890 QuicConfig config;
5891
5892 // Create a handshake message that also enables silent close.
5893 CryptoHandshakeMessage msg;
vasilvvc48c8712019-03-11 13:38:16 -07005894 std::string error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005895 QuicConfig client_config;
5896 client_config.SetInitialStreamFlowControlWindowToSend(
5897 kInitialStreamFlowControlWindowForTest);
5898 client_config.SetInitialSessionFlowControlWindowToSend(
5899 kInitialSessionFlowControlWindowForTest);
5900 client_config.SetIdleNetworkTimeout(
dschinazi027366e2020-05-01 14:31:19 -07005901 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs));
fkastenholzd3a1de92019-05-15 07:00:07 -07005902 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005903 const QuicErrorCode error =
5904 config.ProcessPeerHello(msg, CLIENT, &error_details);
bncf54082a2019-11-27 10:19:47 -08005905 EXPECT_THAT(error, IsQuicNoError());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005906
dschinazie7c38a52020-05-29 15:25:45 -07005907 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
5908 QuicConfigPeer::SetReceivedOriginalConnectionId(
5909 &config, connection_.connection_id());
5910 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
5911 &config, connection_.connection_id());
5912 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005913 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005914
5915 const QuicTime::Delta default_idle_timeout =
dschinazi027366e2020-05-01 14:31:19 -07005916 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs - 1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005917 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5918 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5919
5920 // When we send a packet, the timeout will change to 5ms +
5921 // kInitialIdleTimeoutSecs.
5922 clock_.AdvanceTime(five_ms);
5923 SendStreamDataToPeer(
5924 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5925 0, FIN, nullptr);
fayang3a58dc42020-06-29 11:27:14 -07005926 EXPECT_EQ(default_timeout + five_ms,
5927 connection_.GetTimeoutAlarm()->deadline());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005928
5929 // Indicate streams are still open.
5930 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
5931 .WillRepeatedly(Return(true));
5932
5933 // This time, we should time out and send a connection close due to the TLP.
fkastenholz5d880a92019-06-21 09:01:56 -07005934 EXPECT_CALL(visitor_,
5935 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07005936 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005937 clock_.AdvanceTime(connection_.GetTimeoutAlarm()->deadline() -
5938 clock_.ApproximateNow() + five_ms);
5939 connection_.GetTimeoutAlarm()->Fire();
5940 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5941 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005942 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005943}
5944
5945TEST_P(QuicConnectionTest, TimeoutAfterReceive) {
5946 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5947 EXPECT_TRUE(connection_.connected());
5948 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5949 QuicConfig config;
5950 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005951
5952 const QuicTime::Delta initial_idle_timeout =
5953 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5954 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5955 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
5956
5957 connection_.SendStreamDataWithString(
5958 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5959 0, NO_FIN);
5960 connection_.SendStreamDataWithString(
5961 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5962 3, NO_FIN);
5963
5964 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5965 clock_.AdvanceTime(five_ms);
5966
5967 // When we receive a packet, the timeout will change to 5ms +
5968 // kInitialIdleTimeoutSecs.
5969 QuicAckFrame ack = InitAckFrame(2);
5970 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5971 ProcessAckPacket(&ack);
5972
5973 // The original alarm will fire. We should not time out because we had a
5974 // network event at t=5ms. The alarm will reregister.
5975 clock_.AdvanceTime(initial_idle_timeout - five_ms);
5976 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005977 EXPECT_TRUE(connection_.connected());
5978 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5979 EXPECT_EQ(default_timeout + five_ms,
5980 connection_.GetTimeoutAlarm()->deadline());
5981
5982 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07005983 EXPECT_CALL(visitor_,
5984 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07005985 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005986 clock_.AdvanceTime(five_ms);
5987 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5988 connection_.GetTimeoutAlarm()->Fire();
5989 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5990 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005991 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005992}
5993
5994TEST_P(QuicConnectionTest, TimeoutAfterReceiveNotSendWhenUnacked) {
5995 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5996 EXPECT_TRUE(connection_.connected());
5997 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5998 QuicConfig config;
5999 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006000
6001 const QuicTime::Delta initial_idle_timeout =
6002 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
6003 connection_.SetNetworkTimeouts(
6004 QuicTime::Delta::Infinite(),
6005 initial_idle_timeout + QuicTime::Delta::FromSeconds(1));
6006 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
6007 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
6008
6009 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
6010 connection_.SendStreamDataWithString(
6011 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6012 0, NO_FIN);
6013 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
6014 connection_.SendStreamDataWithString(
6015 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6016 3, NO_FIN);
6017
6018 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
6019
6020 clock_.AdvanceTime(five_ms);
6021
6022 // When we receive a packet, the timeout will change to 5ms +
6023 // kInitialIdleTimeoutSecs.
6024 QuicAckFrame ack = InitAckFrame(2);
6025 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
6026 ProcessAckPacket(&ack);
6027
6028 // The original alarm will fire. We should not time out because we had a
6029 // network event at t=5ms. The alarm will reregister.
6030 clock_.AdvanceTime(initial_idle_timeout - five_ms);
6031 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006032 EXPECT_TRUE(connection_.connected());
6033 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
6034 EXPECT_EQ(default_timeout + five_ms,
6035 connection_.GetTimeoutAlarm()->deadline());
6036
6037 // Now, send packets while advancing the time and verify that the connection
6038 // eventually times out.
fkastenholz5d880a92019-06-21 09:01:56 -07006039 EXPECT_CALL(visitor_,
6040 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006041 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
6042 for (int i = 0; i < 100 && connection_.connected(); ++i) {
6043 QUIC_LOG(INFO) << "sending data packet";
6044 connection_.SendStreamDataWithString(
6045 GetNthClientInitiatedStreamId(1, connection_.transport_version()),
6046 "foo", 0, NO_FIN);
6047 connection_.GetTimeoutAlarm()->Fire();
6048 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
6049 }
6050 EXPECT_FALSE(connection_.connected());
6051 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07006052 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006053}
6054
6055TEST_P(QuicConnectionTest, TimeoutAfter5ClientRTOs) {
fayang5f135052019-08-22 17:59:40 -07006056 if (connection_.PtoEnabled()) {
6057 return;
6058 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006059 connection_.SetMaxTailLossProbes(2);
6060 EXPECT_TRUE(connection_.connected());
6061 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6062 QuicConfig config;
6063 QuicTagVector connection_options;
6064 connection_options.push_back(k5RTO);
6065 config.SetConnectionOptionsToSend(connection_options);
dschinazif7c6a912020-05-05 11:39:53 -07006066 QuicConfigPeer::SetNegotiated(&config, true);
fayang656cbb52020-06-09 13:29:35 -07006067 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangf78b6932020-06-08 08:36:45 -07006068 EXPECT_CALL(visitor_, GetHandshakeState())
6069 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
6070 }
dschinazie7c38a52020-05-29 15:25:45 -07006071 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
6072 QuicConfigPeer::SetReceivedOriginalConnectionId(
6073 &config, connection_.connection_id());
6074 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
6075 &config, connection_.connection_id());
6076 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006077 connection_.SetFromConfig(config);
6078
6079 // Send stream data.
6080 SendStreamDataToPeer(
6081 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6082 0, FIN, nullptr);
6083
6084 // Fire the retransmission alarm 6 times, twice for TLP and 4 times for RTO.
6085 for (int i = 0; i < 6; ++i) {
6086 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
6087 connection_.GetRetransmissionAlarm()->Fire();
6088 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
6089 EXPECT_TRUE(connection_.connected());
6090 }
fayang2205d952020-05-12 13:45:56 -07006091 EXPECT_CALL(visitor_, OnPathDegrading());
6092 connection_.PathDegradingTimeout();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006093
6094 EXPECT_EQ(2u, connection_.sent_packet_manager().GetConsecutiveTlpCount());
6095 EXPECT_EQ(4u, connection_.sent_packet_manager().GetConsecutiveRtoCount());
6096 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07006097 EXPECT_CALL(visitor_,
6098 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07006099 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
fayang2205d952020-05-12 13:45:56 -07006100 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
6101 connection_.GetBlackholeDetectorAlarm()->Fire();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006102 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
6103 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07006104 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006105}
6106
6107TEST_P(QuicConnectionTest, SendScheduler) {
6108 // Test that if we send a packet without delay, it is not queued.
6109 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
QUICHE team8c1daa22019-03-13 08:33:41 -07006110 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07006111 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006112 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
6113 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
QUICHE team6987b4a2019-03-15 16:23:04 -07006114 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05006115 HAS_RETRANSMITTABLE_DATA, false, false);
6116 EXPECT_EQ(0u, connection_.NumQueuedPackets());
6117}
6118
6119TEST_P(QuicConnectionTest, FailToSendFirstPacket) {
6120 // Test that the connection does not crash when it fails to send the first
6121 // packet at which point self_address_ might be uninitialized.
6122 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
fkastenholz5d880a92019-06-21 09:01:56 -07006123 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
QUICHE team8c1daa22019-03-13 08:33:41 -07006124 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07006125 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006126 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
6127 writer_->SetShouldWriteFail();
QUICHE team6987b4a2019-03-15 16:23:04 -07006128 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05006129 HAS_RETRANSMITTABLE_DATA, false, false);
6130}
6131
6132TEST_P(QuicConnectionTest, SendSchedulerEAGAIN) {
6133 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
QUICHE team8c1daa22019-03-13 08:33:41 -07006134 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07006135 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006136 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
6137 BlockOnNextWrite();
6138 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _))
6139 .Times(0);
QUICHE team6987b4a2019-03-15 16:23:04 -07006140 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05006141 HAS_RETRANSMITTABLE_DATA, false, false);
6142 EXPECT_EQ(1u, connection_.NumQueuedPackets());
6143}
6144
6145TEST_P(QuicConnectionTest, TestQueueLimitsOnSendStreamData) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006146 // Queue the first packet.
ianswett3085da82019-04-04 07:24:24 -07006147 size_t payload_length = connection_.max_packet_length();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006148 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(testing::Return(false));
vasilvvc48c8712019-03-11 13:38:16 -07006149 const std::string payload(payload_length, 'a');
ianswett3085da82019-04-04 07:24:24 -07006150 QuicStreamId first_bidi_stream_id(QuicUtils::GetFirstBidirectionalStreamId(
6151 connection_.version().transport_version, Perspective::IS_CLIENT));
6152 EXPECT_EQ(0u, connection_
6153 .SendStreamDataWithString(first_bidi_stream_id, payload, 0,
6154 NO_FIN)
QUICHE teama6ef0a62019-03-07 20:34:33 -05006155 .bytes_consumed);
6156 EXPECT_EQ(0u, connection_.NumQueuedPackets());
6157}
6158
ianswett3085da82019-04-04 07:24:24 -07006159TEST_P(QuicConnectionTest, SendingThreePackets) {
ianswett3085da82019-04-04 07:24:24 -07006160 // Make the payload twice the size of the packet, so 3 packets are written.
6161 size_t total_payload_length = 2 * connection_.max_packet_length();
vasilvvc48c8712019-03-11 13:38:16 -07006162 const std::string payload(total_payload_length, 'a');
ianswett3085da82019-04-04 07:24:24 -07006163 QuicStreamId first_bidi_stream_id(QuicUtils::GetFirstBidirectionalStreamId(
6164 connection_.version().transport_version, Perspective::IS_CLIENT));
6165 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
6166 EXPECT_EQ(payload.size(), connection_
6167 .SendStreamDataWithString(first_bidi_stream_id,
6168 payload, 0, NO_FIN)
6169 .bytes_consumed);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006170}
6171
6172TEST_P(QuicConnectionTest, LoopThroughSendingPacketsWithTruncation) {
6173 set_perspective(Perspective::IS_SERVER);
fayangd4291e42019-05-30 10:31:21 -07006174 if (!VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006175 // For IETF QUIC, encryption level will be switched to FORWARD_SECURE in
6176 // SendStreamDataWithString.
6177 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
6178 }
6179 // Set up a larger payload than will fit in one packet.
vasilvvc48c8712019-03-11 13:38:16 -07006180 const std::string payload(connection_.max_packet_length(), 'a');
QUICHE teama6ef0a62019-03-07 20:34:33 -05006181 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
6182
6183 // Now send some packets with no truncation.
6184 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
6185 EXPECT_EQ(payload.size(),
6186 connection_.SendStreamDataWithString(3, payload, 0, NO_FIN)
6187 .bytes_consumed);
6188 // Track the size of the second packet here. The overhead will be the largest
6189 // we see in this test, due to the non-truncated connection id.
6190 size_t non_truncated_packet_size = writer_->last_packet_size();
6191
6192 // Change to a 0 byte connection id.
6193 QuicConfig config;
6194 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
6195 connection_.SetFromConfig(config);
6196 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
6197 EXPECT_EQ(payload.size(),
6198 connection_.SendStreamDataWithString(3, payload, 1350, NO_FIN)
6199 .bytes_consumed);
fayangd4291e42019-05-30 10:31:21 -07006200 if (VersionHasIetfInvariantHeader(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006201 // Short header packets sent from server omit connection ID already, and
6202 // stream offset size increases from 0 to 2.
6203 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() - 2);
6204 } else {
6205 // Just like above, we save 8 bytes on payload, and 8 on truncation. -2
6206 // because stream offset size is 2 instead of 0.
6207 EXPECT_EQ(non_truncated_packet_size,
6208 writer_->last_packet_size() + 8 * 2 - 2);
6209 }
6210}
6211
6212TEST_P(QuicConnectionTest, SendDelayedAck) {
6213 QuicTime ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6214 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006215 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006216 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006217 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006218 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006219 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006220 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006221 // Process a packet from the non-crypto stream.
6222 frame1_.stream_id = 3;
6223
6224 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006225 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006226 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6227 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6228
6229 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006230 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006231 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6232 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07006233 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006234 connection_.GetAckAlarm()->Fire();
6235 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006236 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006237 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006238 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006239 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6240 } else {
nharper55fa6132019-05-07 19:37:21 -07006241 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006242 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6243 }
6244 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006245 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006246}
6247
6248TEST_P(QuicConnectionTest, SendDelayedAfterQuiescence) {
6249 QuicConnectionPeer::SetFastAckAfterQuiescence(&connection_, true);
6250
6251 // The beginning of the connection counts as quiescence.
ianswett8f90e512019-12-18 10:50:27 -08006252 QuicTime ack_time = clock_.ApproximateNow() + kAlarmGranularity;
QUICHE teama6ef0a62019-03-07 20:34:33 -05006253 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006254 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006255 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006256 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006257 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006258 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006259 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006260 // Process a packet from the non-crypto stream.
6261 frame1_.stream_id = 3;
6262
6263 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006264 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006265 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6266 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6267
6268 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006269 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006270 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6271 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07006272 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006273 connection_.GetAckAlarm()->Fire();
6274 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006275 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006276 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006277 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006278 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6279 } else {
nharper55fa6132019-05-07 19:37:21 -07006280 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006281 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6282 }
6283 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006284 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006285
6286 // Process another packet immedately after sending the ack and expect the
6287 // ack alarm to be set delayed ack time in the future.
6288 ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6289 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6290 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6291
6292 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006293 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006294 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6295 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07006296 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006297 connection_.GetAckAlarm()->Fire();
6298 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006299 padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006300 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006301 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006302 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6303 } else {
nharper55fa6132019-05-07 19:37:21 -07006304 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006305 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6306 }
6307 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006308 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006309
ianswett8f90e512019-12-18 10:50:27 -08006310 // Wait 1 second and ensure the ack alarm is set to 1ms in the future.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006311 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
6312 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
6313 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6314 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6315
6316 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006317 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006318 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6319}
6320
6321TEST_P(QuicConnectionTest, SendDelayedAckDecimation) {
6322 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6323 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION);
6324
6325 const size_t kMinRttMs = 40;
6326 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6327 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6328 QuicTime::Delta::Zero(), QuicTime::Zero());
6329 // The ack time should be based on min_rtt/4, since it's less than the
6330 // default delayed ack time.
6331 QuicTime ack_time = clock_.ApproximateNow() +
6332 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6333 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006334 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006335 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006336 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006337 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006338 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006339 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006340 // Process a packet from the non-crypto stream.
6341 frame1_.stream_id = 3;
6342
6343 // Process all the initial packets in order so there aren't missing packets.
6344 uint64_t kFirstDecimatedPacket = 101;
6345 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6346 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6347 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6348 }
fayang9adfb532020-06-04 06:58:45 -07006349 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006350 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006351 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006352 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6353 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6354 ENCRYPTION_ZERO_RTT);
6355
6356 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006357 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006358 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6359
6360 // The 10th received packet causes an ack to be sent.
6361 for (int i = 0; i < 9; ++i) {
fayang9adfb532020-06-04 06:58:45 -07006362 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006363 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6364 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6365 ENCRYPTION_ZERO_RTT);
6366 }
6367 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07006368 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006369 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07006370 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006371 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6372 } else {
nharperc32d8ab2019-10-09 11:09:06 -07006373 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006374 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6375 }
6376 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006377 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006378}
6379
6380TEST_P(QuicConnectionTest, SendDelayedAckAckDecimationAfterQuiescence) {
6381 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6382 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION);
6383 QuicConnectionPeer::SetFastAckAfterQuiescence(&connection_, true);
6384
6385 const size_t kMinRttMs = 40;
6386 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6387 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6388 QuicTime::Delta::Zero(), QuicTime::Zero());
6389
6390 // The beginning of the connection counts as quiescence.
6391 QuicTime ack_time =
6392 clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
6393 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006394 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006395 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006396 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006397 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006398 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006399 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006400 // Process a packet from the non-crypto stream.
6401 frame1_.stream_id = 3;
6402
6403 // 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(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6407
6408 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006409 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006410 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6411 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07006412 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006413 connection_.GetAckAlarm()->Fire();
6414 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006415 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006416 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006417 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006418 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6419 } else {
nharper55fa6132019-05-07 19:37:21 -07006420 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006421 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6422 }
6423 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006424 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006425
6426 // Process another packet immedately after sending the ack and expect the
6427 // ack alarm to be set delayed ack time in the future.
6428 ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6429 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6430 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6431
6432 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006433 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006434 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6435 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07006436 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006437 connection_.GetAckAlarm()->Fire();
6438 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006439 padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006440 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006441 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006442 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6443 } else {
nharper55fa6132019-05-07 19:37:21 -07006444 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006445 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6446 }
6447 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006448 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006449
6450 // Wait 1 second and enesure the ack alarm is set to 1ms in the future.
6451 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
6452 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
6453 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6454 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6455
6456 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006457 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006458 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6459
6460 // Process enough packets to get into ack decimation behavior.
6461 // The ack time should be based on min_rtt/4, since it's less than the
6462 // default delayed ack time.
6463 ack_time = clock_.ApproximateNow() +
6464 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6465 uint64_t kFirstDecimatedPacket = 101;
6466 for (unsigned int i = 0; i < kFirstDecimatedPacket - 4; ++i) {
6467 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6468 ProcessDataPacketAtLevel(4 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6469 }
fayang9adfb532020-06-04 06:58:45 -07006470 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006471 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006472 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006473 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6474 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6475 ENCRYPTION_ZERO_RTT);
6476
6477 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006478 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006479 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6480
6481 // The 10th received packet causes an ack to be sent.
6482 for (int i = 0; i < 9; ++i) {
fayang9adfb532020-06-04 06:58:45 -07006483 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006484 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6485 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6486 ENCRYPTION_ZERO_RTT);
6487 }
6488 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07006489 padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006490 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07006491 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006492 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6493 } else {
nharperc32d8ab2019-10-09 11:09:06 -07006494 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006495 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6496 }
6497 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006498 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006499
6500 // Wait 1 second and enesure the ack alarm is set to 1ms in the future.
6501 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
6502 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
6503 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6504 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 10, !kHasStopWaiting,
6505 ENCRYPTION_ZERO_RTT);
6506
6507 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006508 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006509 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6510}
6511
6512TEST_P(QuicConnectionTest, SendDelayedAckDecimationUnlimitedAggregation) {
6513 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6514 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6515 QuicConfig config;
6516 QuicTagVector connection_options;
6517 connection_options.push_back(kACKD);
6518 // No limit on the number of packets received before sending an ack.
6519 connection_options.push_back(kAKDU);
6520 config.SetConnectionOptionsToSend(connection_options);
6521 connection_.SetFromConfig(config);
6522
6523 const size_t kMinRttMs = 40;
6524 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6525 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6526 QuicTime::Delta::Zero(), QuicTime::Zero());
6527 // The ack time should be based on min_rtt/4, since it's less than the
6528 // default delayed ack time.
6529 QuicTime ack_time = clock_.ApproximateNow() +
6530 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6531 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006532 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006533 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006534 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006535 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006536 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006537 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006538 // Process a packet from the non-crypto stream.
6539 frame1_.stream_id = 3;
6540
6541 // Process all the initial packets in order so there aren't missing packets.
6542 uint64_t kFirstDecimatedPacket = 101;
6543 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6544 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6545 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6546 }
fayang9adfb532020-06-04 06:58:45 -07006547 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006548 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006549 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006550 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6551 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6552 ENCRYPTION_ZERO_RTT);
6553
6554 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006555 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006556 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6557
6558 // 18 packets will not cause an ack to be sent. 19 will because when
6559 // stop waiting frames are in use, we ack every 20 packets no matter what.
6560 for (int i = 0; i < 18; ++i) {
fayang9adfb532020-06-04 06:58:45 -07006561 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006562 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6563 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6564 ENCRYPTION_ZERO_RTT);
6565 }
6566 // The delayed ack timer should still be set to the expected deadline.
fayang9adfb532020-06-04 06:58:45 -07006567 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006568 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6569}
6570
6571TEST_P(QuicConnectionTest, SendDelayedAckDecimationEighthRtt) {
6572 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6573 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION);
6574 QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
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/8, since it's less than the
6581 // default delayed ack time.
6582 QuicTime ack_time = clock_.ApproximateNow() +
6583 QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
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 // The 10th received packet causes an ack to be sent.
6612 for (int i = 0; i < 9; ++i) {
fayang9adfb532020-06-04 06:58:45 -07006613 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006614 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6615 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6616 ENCRYPTION_ZERO_RTT);
6617 }
6618 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07006619 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006620 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07006621 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006622 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6623 } else {
nharperc32d8ab2019-10-09 11:09:06 -07006624 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006625 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6626 }
6627 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006628 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006629}
6630
6631TEST_P(QuicConnectionTest, SendDelayedAckDecimationWithReordering) {
6632 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6633 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6634
6635 const size_t kMinRttMs = 40;
6636 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6637 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6638 QuicTime::Delta::Zero(), QuicTime::Zero());
6639 // The ack time should be based on min_rtt/4, since it's less than the
6640 // default delayed ack time.
6641 QuicTime ack_time = clock_.ApproximateNow() +
6642 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6643 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006644 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006645 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006646 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006647 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006648 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006649 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006650 // Process a packet from the non-crypto stream.
6651 frame1_.stream_id = 3;
6652
6653 // Process all the initial packets in order so there aren't missing packets.
6654 uint64_t kFirstDecimatedPacket = 101;
6655 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6656 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6657 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6658 }
fayang9adfb532020-06-04 06:58:45 -07006659 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006660
6661 // Receive one packet out of order and then the rest in order.
6662 // The loop leaves a one packet gap between acks sent to simulate some loss.
6663 for (int j = 0; j < 3; ++j) {
6664 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6665 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6666 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 9 + (j * 11),
6667 !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6668 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
fayang9adfb532020-06-04 06:58:45 -07006669 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006670 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6671
6672 // The 10th received packet causes an ack to be sent.
6673 writer_->Reset();
6674 for (int i = 0; i < 9; ++i) {
fayang9adfb532020-06-04 06:58:45 -07006675 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006676 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6677 // The ACK shouldn't be sent until the 10th packet is processed.
6678 EXPECT_TRUE(writer_->ack_frames().empty());
6679 ProcessDataPacketAtLevel(kFirstDecimatedPacket + i + (j * 11),
6680 !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6681 }
6682 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07006683 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006684 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07006685 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006686 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6687 } else {
nharperc32d8ab2019-10-09 11:09:06 -07006688 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006689 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6690 }
6691 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006692 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006693 }
6694}
6695
6696TEST_P(QuicConnectionTest, SendDelayedAckDecimationWithLargeReordering) {
6697 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6698 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6699
6700 const size_t kMinRttMs = 40;
6701 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6702 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6703 QuicTime::Delta::Zero(), QuicTime::Zero());
6704 // The ack time should be based on min_rtt/4, since it's less than the
6705 // default delayed ack time.
6706 QuicTime ack_time = clock_.ApproximateNow() +
6707 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6708 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006709 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006710 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006711 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006712 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006713 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006714 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006715 // Process a packet from the non-crypto stream.
6716 frame1_.stream_id = 3;
6717
6718 // Process all the initial packets in order so there aren't missing packets.
6719 uint64_t kFirstDecimatedPacket = 101;
6720 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6721 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6722 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6723 }
fayang9adfb532020-06-04 06:58:45 -07006724 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006725 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006726 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006727 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6728 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6729 ENCRYPTION_ZERO_RTT);
6730
6731 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006732 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006733 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6734
6735 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6736 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6737 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 19, !kHasStopWaiting,
6738 ENCRYPTION_ZERO_RTT);
6739 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
fayang9adfb532020-06-04 06:58:45 -07006740 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006741 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6742
6743 // The 10th received packet causes an ack to be sent.
6744 for (int i = 0; i < 8; ++i) {
fayang9adfb532020-06-04 06:58:45 -07006745 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006746 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6747 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6748 ENCRYPTION_ZERO_RTT);
6749 }
6750 // Check that ack is sent and that delayed ack alarm is reset.
6751 if (GetParam().no_stop_waiting) {
fayang58f71072019-11-05 08:47:02 -08006752 EXPECT_EQ(writer_->padding_frames().size() + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006753 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6754 } else {
6755 EXPECT_EQ(2u, writer_->frame_count());
6756 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6757 }
6758 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006759 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006760
6761 // The next packet received in order will cause an immediate ack,
6762 // because it fills a hole.
fayang9adfb532020-06-04 06:58:45 -07006763 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006764 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6765 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 10, !kHasStopWaiting,
6766 ENCRYPTION_ZERO_RTT);
6767 // Check that ack is sent and that delayed ack alarm is reset.
6768 if (GetParam().no_stop_waiting) {
fayang58f71072019-11-05 08:47:02 -08006769 EXPECT_EQ(writer_->padding_frames().size() + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006770 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6771 } else {
6772 EXPECT_EQ(2u, writer_->frame_count());
6773 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6774 }
6775 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006776 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006777}
6778
6779TEST_P(QuicConnectionTest, SendDelayedAckDecimationWithReorderingEighthRtt) {
6780 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6781 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6782 QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
6783
6784 const size_t kMinRttMs = 40;
6785 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6786 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6787 QuicTime::Delta::Zero(), QuicTime::Zero());
6788 // The ack time should be based on min_rtt/8, since it's less than the
6789 // default delayed ack time.
6790 QuicTime ack_time = clock_.ApproximateNow() +
6791 QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
6792 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006793 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006794 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006795 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006796 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006797 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006798 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006799 // Process a packet from the non-crypto stream.
6800 frame1_.stream_id = 3;
6801
6802 // Process all the initial packets in order so there aren't missing packets.
6803 uint64_t kFirstDecimatedPacket = 101;
6804 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6805 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6806 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6807 }
fayang9adfb532020-06-04 06:58:45 -07006808 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006809 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006810 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006811 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6812 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6813 ENCRYPTION_ZERO_RTT);
6814
6815 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006816 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006817 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6818
6819 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6820 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6821 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 9, !kHasStopWaiting,
6822 ENCRYPTION_ZERO_RTT);
6823 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
fayang9adfb532020-06-04 06:58:45 -07006824 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006825 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6826
6827 // The 10th received packet causes an ack to be sent.
6828 for (int i = 0; i < 8; ++i) {
fayang9adfb532020-06-04 06:58:45 -07006829 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006830 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6831 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6832 ENCRYPTION_ZERO_RTT);
6833 }
6834 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07006835 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006836 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07006837 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006838 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6839 } else {
nharperc32d8ab2019-10-09 11:09:06 -07006840 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006841 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6842 }
6843 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006844 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006845}
6846
6847TEST_P(QuicConnectionTest,
6848 SendDelayedAckDecimationWithLargeReorderingEighthRtt) {
6849 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6850 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6851 QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
6852
6853 const size_t kMinRttMs = 40;
6854 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6855 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6856 QuicTime::Delta::Zero(), QuicTime::Zero());
6857 // The ack time should be based on min_rtt/8, since it's less than the
6858 // default delayed ack time.
6859 QuicTime ack_time = clock_.ApproximateNow() +
6860 QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
6861 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006862 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006863 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006864 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006865 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006866 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006867 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006868 // Process a packet from the non-crypto stream.
6869 frame1_.stream_id = 3;
6870
6871 // Process all the initial packets in order so there aren't missing packets.
6872 uint64_t kFirstDecimatedPacket = 101;
6873 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6874 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6875 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6876 }
fayang9adfb532020-06-04 06:58:45 -07006877 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006878 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006879 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006880 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6881 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6882 ENCRYPTION_ZERO_RTT);
6883
6884 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006885 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006886 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6887
6888 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6889 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6890 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 19, !kHasStopWaiting,
6891 ENCRYPTION_ZERO_RTT);
6892 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
fayang9adfb532020-06-04 06:58:45 -07006893 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006894 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6895
6896 // The 10th received packet causes an ack to be sent.
6897 for (int i = 0; i < 8; ++i) {
fayang9adfb532020-06-04 06:58:45 -07006898 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006899 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6900 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6901 ENCRYPTION_ZERO_RTT);
6902 }
6903 // Check that ack is sent and that delayed ack alarm is reset.
6904 if (GetParam().no_stop_waiting) {
fayang58f71072019-11-05 08:47:02 -08006905 EXPECT_EQ(writer_->padding_frames().size() + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006906 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6907 } else {
6908 EXPECT_EQ(2u, writer_->frame_count());
6909 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6910 }
6911 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006912 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006913
6914 // The next packet received in order will cause an immediate ack,
6915 // because it fills a hole.
fayang9adfb532020-06-04 06:58:45 -07006916 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006917 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6918 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 10, !kHasStopWaiting,
6919 ENCRYPTION_ZERO_RTT);
6920 // Check that ack is sent and that delayed ack alarm is reset.
6921 if (GetParam().no_stop_waiting) {
fayang58f71072019-11-05 08:47:02 -08006922 EXPECT_EQ(writer_->padding_frames().size() + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006923 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6924 } else {
6925 EXPECT_EQ(2u, writer_->frame_count());
6926 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6927 }
6928 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006929 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006930}
6931
6932TEST_P(QuicConnectionTest, SendDelayedAckOnHandshakeConfirmed) {
6933 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6934 ProcessPacket(1);
6935 // Check that ack is sent and that delayed ack alarm is set.
fayang9adfb532020-06-04 06:58:45 -07006936 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006937 QuicTime ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6938 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6939
6940 // Completing the handshake as the server does nothing.
6941 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_SERVER);
6942 connection_.OnHandshakeComplete();
fayang9adfb532020-06-04 06:58:45 -07006943 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006944 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6945
6946 // Complete the handshake as the client decreases the delayed ack time to 0ms.
6947 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_CLIENT);
6948 connection_.OnHandshakeComplete();
fayang9adfb532020-06-04 06:58:45 -07006949 EXPECT_TRUE(connection_.HasPendingAcks());
fayangb296fb82020-02-11 08:14:28 -08006950 if (connection_.SupportsMultiplePacketNumberSpaces()) {
6951 EXPECT_EQ(clock_.ApproximateNow() + DefaultDelayedAckTime(),
6952 connection_.GetAckAlarm()->deadline());
6953 } else {
6954 EXPECT_EQ(clock_.ApproximateNow(), connection_.GetAckAlarm()->deadline());
6955 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006956}
6957
6958TEST_P(QuicConnectionTest, SendDelayedAckOnSecondPacket) {
6959 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6960 ProcessPacket(1);
6961 ProcessPacket(2);
6962 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006963 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006964 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006965 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006966 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6967 } else {
nharper55fa6132019-05-07 19:37:21 -07006968 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006969 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6970 }
6971 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006972 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006973}
6974
6975TEST_P(QuicConnectionTest, NoAckOnOldNacks) {
6976 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang6dba4902019-06-17 10:04:23 -07006977 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006978 ProcessPacket(2);
6979 size_t frames_per_ack = GetParam().no_stop_waiting ? 1 : 2;
QUICHE teama6ef0a62019-03-07 20:34:33 -05006980
6981 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
6982 ProcessPacket(3);
nharper55fa6132019-05-07 19:37:21 -07006983 size_t padding_frame_count = writer_->padding_frames().size();
6984 EXPECT_EQ(padding_frame_count + frames_per_ack, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006985 EXPECT_FALSE(writer_->ack_frames().empty());
6986 writer_->Reset();
6987
fayang6dba4902019-06-17 10:04:23 -07006988 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006989 ProcessPacket(4);
fayang6dba4902019-06-17 10:04:23 -07006990 EXPECT_EQ(0u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006991
6992 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
6993 ProcessPacket(5);
nharper55fa6132019-05-07 19:37:21 -07006994 padding_frame_count = writer_->padding_frames().size();
6995 EXPECT_EQ(padding_frame_count + frames_per_ack, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006996 EXPECT_FALSE(writer_->ack_frames().empty());
6997 writer_->Reset();
6998
6999 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
7000 // Now only set the timer on the 6th packet, instead of sending another ack.
7001 ProcessPacket(6);
nharper55fa6132019-05-07 19:37:21 -07007002 padding_frame_count = writer_->padding_frames().size();
7003 EXPECT_EQ(padding_frame_count, writer_->frame_count());
fayang9adfb532020-06-04 06:58:45 -07007004 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007005}
7006
7007TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingPacket) {
7008 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
QUICHE team8c1daa22019-03-13 08:33:41 -07007009 EXPECT_CALL(visitor_, OnStreamFrame(_));
7010 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07007011 std::make_unique<TaggingEncrypter>(0x01));
zhongyi546cc452019-04-12 15:27:49 -07007012 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07007013 std::make_unique<StrictTaggingDecrypter>(0x01));
nharper2c9f02a2019-05-08 10:25:50 -07007014 ProcessDataPacket(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007015 connection_.SendStreamDataWithString(
7016 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
7017 0, NO_FIN);
7018 // Check that ack is bundled with outgoing data and that delayed ack
7019 // alarm is reset.
7020 if (GetParam().no_stop_waiting) {
7021 EXPECT_EQ(2u, writer_->frame_count());
7022 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
7023 } else {
7024 EXPECT_EQ(3u, writer_->frame_count());
7025 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
7026 }
7027 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07007028 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007029}
7030
7031TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingCryptoPacket) {
7032 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayangc31c9952019-06-05 13:54:48 -07007033 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
7034 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
7035 } else {
7036 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7037 }
7038 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
nharper46833c32019-05-15 21:33:05 -07007039 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007040 // Check that ack is bundled with outgoing crypto data.
7041 if (GetParam().no_stop_waiting) {
7042 EXPECT_EQ(3u, writer_->frame_count());
7043 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
7044 } else {
7045 EXPECT_EQ(4u, writer_->frame_count());
7046 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
7047 }
fayang9adfb532020-06-04 06:58:45 -07007048 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007049}
7050
7051TEST_P(QuicConnectionTest, BlockAndBufferOnFirstCHLOPacketOfTwo) {
7052 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7053 ProcessPacket(1);
7054 BlockOnNextWrite();
7055 writer_->set_is_write_blocked_data_buffered(true);
fayang6a258412020-05-28 08:57:12 -07007056 if (GetQuicReloadableFlag(quic_move_amplification_limit) &&
7057 QuicVersionUsesCryptoFrames(connection_.transport_version())) {
7058 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7059 } else {
7060 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
7061 }
nharper46833c32019-05-15 21:33:05 -07007062 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007063 EXPECT_TRUE(writer_->IsWriteBlocked());
7064 EXPECT_FALSE(connection_.HasQueuedData());
nharper46833c32019-05-15 21:33:05 -07007065 connection_.SendCryptoDataWithString("bar", 3);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007066 EXPECT_TRUE(writer_->IsWriteBlocked());
fayang6a258412020-05-28 08:57:12 -07007067 if (GetQuicReloadableFlag(quic_move_amplification_limit) &&
7068 QuicVersionUsesCryptoFrames(connection_.transport_version())) {
7069 // CRYPTO frames are not flushed when writer is blocked.
7070 EXPECT_FALSE(connection_.HasQueuedData());
7071 } else {
7072 EXPECT_TRUE(connection_.HasQueuedData());
7073 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007074}
7075
7076TEST_P(QuicConnectionTest, BundleAckForSecondCHLO) {
7077 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07007078 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007079 EXPECT_CALL(visitor_, OnCanWrite())
7080 .WillOnce(IgnoreResult(InvokeWithoutArgs(
7081 &connection_, &TestConnection::SendCryptoStreamData)));
7082 // Process a packet from the crypto stream, which is frame1_'s default.
7083 // Receiving the CHLO as packet 2 first will cause the connection to
7084 // immediately send an ack, due to the packet gap.
fayangc31c9952019-06-05 13:54:48 -07007085 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
7086 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
7087 } else {
7088 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7089 }
7090 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007091 // Check that ack is sent and that delayed ack alarm is reset.
7092 if (GetParam().no_stop_waiting) {
7093 EXPECT_EQ(3u, writer_->frame_count());
7094 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
7095 } else {
7096 EXPECT_EQ(4u, writer_->frame_count());
7097 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
7098 }
QUICHE teamea740082019-03-11 17:58:43 -07007099 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007100 EXPECT_EQ(1u, writer_->stream_frames().size());
7101 } else {
7102 EXPECT_EQ(1u, writer_->crypto_frames().size());
7103 }
7104 EXPECT_EQ(1u, writer_->padding_frames().size());
7105 ASSERT_FALSE(writer_->ack_frames().empty());
7106 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(writer_->ack_frames().front()));
fayang9adfb532020-06-04 06:58:45 -07007107 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007108}
7109
7110TEST_P(QuicConnectionTest, BundleAckForSecondCHLOTwoPacketReject) {
7111 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07007112 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007113
7114 // Process two packets from the crypto stream, which is frame1_'s default,
7115 // simulating a 2 packet reject.
7116 {
fayangc31c9952019-06-05 13:54:48 -07007117 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
7118 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
7119 } else {
7120 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7121 }
7122 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007123 // Send the new CHLO when the REJ is processed.
fayangc31c9952019-06-05 13:54:48 -07007124 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
7125 EXPECT_CALL(visitor_, OnCryptoFrame(_))
7126 .WillOnce(IgnoreResult(InvokeWithoutArgs(
7127 &connection_, &TestConnection::SendCryptoStreamData)));
7128 } else {
7129 EXPECT_CALL(visitor_, OnStreamFrame(_))
7130 .WillOnce(IgnoreResult(InvokeWithoutArgs(
7131 &connection_, &TestConnection::SendCryptoStreamData)));
7132 }
7133 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007134 }
7135 // Check that ack is sent and that delayed ack alarm is reset.
7136 if (GetParam().no_stop_waiting) {
7137 EXPECT_EQ(3u, writer_->frame_count());
7138 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
7139 } else {
7140 EXPECT_EQ(4u, writer_->frame_count());
7141 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
7142 }
QUICHE teamea740082019-03-11 17:58:43 -07007143 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007144 EXPECT_EQ(1u, writer_->stream_frames().size());
7145 } else {
7146 EXPECT_EQ(1u, writer_->crypto_frames().size());
7147 }
7148 EXPECT_EQ(1u, writer_->padding_frames().size());
7149 ASSERT_FALSE(writer_->ack_frames().empty());
7150 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(writer_->ack_frames().front()));
fayang9adfb532020-06-04 06:58:45 -07007151 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007152}
7153
7154TEST_P(QuicConnectionTest, BundleAckWithDataOnIncomingAck) {
7155 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7156 connection_.SendStreamDataWithString(
7157 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
7158 0, NO_FIN);
7159 connection_.SendStreamDataWithString(
7160 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
7161 3, NO_FIN);
7162 // Ack the second packet, which will retransmit the first packet.
7163 QuicAckFrame ack = ConstructAckFrame(2, 1);
7164 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07007165 lost_packets.push_back(
7166 LostPacket(QuicPacketNumber(1), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007167 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07007168 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
7169 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007170 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7171 ProcessAckPacket(&ack);
nharper55fa6132019-05-07 19:37:21 -07007172 size_t padding_frame_count = writer_->padding_frames().size();
7173 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007174 EXPECT_EQ(1u, writer_->stream_frames().size());
7175 writer_->Reset();
7176
7177 // Now ack the retransmission, which will both raise the high water mark
7178 // and see if there is more data to send.
7179 ack = ConstructAckFrame(3, 1);
7180 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
7181 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7182 ProcessAckPacket(&ack);
7183
7184 // Check that no packet is sent and the ack alarm isn't set.
7185 EXPECT_EQ(0u, writer_->frame_count());
fayang9adfb532020-06-04 06:58:45 -07007186 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007187 writer_->Reset();
7188
7189 // Send the same ack, but send both data and an ack together.
7190 ack = ConstructAckFrame(3, 1);
7191 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
7192 EXPECT_CALL(visitor_, OnCanWrite())
7193 .WillOnce(IgnoreResult(InvokeWithoutArgs(
7194 &connection_, &TestConnection::EnsureWritableAndSendStreamData5)));
7195 ProcessAckPacket(&ack);
7196
7197 // Check that ack is bundled with outgoing data and the delayed ack
7198 // alarm is reset.
7199 if (GetParam().no_stop_waiting) {
fayang8a27b0f2019-11-04 11:27:40 -08007200 // Do not ACK acks.
7201 EXPECT_EQ(1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007202 } else {
7203 EXPECT_EQ(3u, writer_->frame_count());
7204 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
7205 }
fayang8a27b0f2019-11-04 11:27:40 -08007206 if (GetParam().no_stop_waiting) {
fayang03916692019-05-22 17:57:18 -07007207 EXPECT_TRUE(writer_->ack_frames().empty());
7208 } else {
7209 EXPECT_FALSE(writer_->ack_frames().empty());
7210 EXPECT_EQ(QuicPacketNumber(3u),
7211 LargestAcked(writer_->ack_frames().front()));
7212 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007213 EXPECT_EQ(1u, writer_->stream_frames().size());
fayang9adfb532020-06-04 06:58:45 -07007214 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007215}
7216
7217TEST_P(QuicConnectionTest, NoAckSentForClose) {
7218 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7219 ProcessPacket(1);
fkastenholz5d880a92019-06-21 09:01:56 -07007220 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
7221 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007222 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
7223 ProcessClosePacket(2);
fkastenholz5d880a92019-06-21 09:01:56 -07007224 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007225 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7226 IsError(QUIC_PEER_GOING_AWAY));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007227}
7228
7229TEST_P(QuicConnectionTest, SendWhenDisconnected) {
7230 EXPECT_TRUE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07007231 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7232 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007233 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
7234 ConnectionCloseBehavior::SILENT_CLOSE);
7235 EXPECT_FALSE(connection_.connected());
ianswettfc16a2b2020-05-18 16:05:49 -07007236 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
fayang15042962020-07-01 12:14:29 -07007237 if (GetQuicReloadableFlag(quic_determine_serialized_packet_fate_early)) {
7238 EXPECT_EQ(DISCARD, connection_.GetSerializedPacketFate(
7239 /*is_mtu_discovery=*/false, ENCRYPTION_INITIAL));
7240 return;
7241 }
QUICHE team8c1daa22019-03-13 08:33:41 -07007242 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07007243 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007244 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
7245 .Times(0);
QUICHE team6987b4a2019-03-15 16:23:04 -07007246 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05007247 HAS_RETRANSMITTABLE_DATA, false, false);
fkastenholz5d880a92019-06-21 09:01:56 -07007248 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007249 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7250 IsError(QUIC_PEER_GOING_AWAY));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007251}
7252
7253TEST_P(QuicConnectionTest, SendConnectivityProbingWhenDisconnected) {
7254 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
fayangc31c9952019-06-05 13:54:48 -07007255 if (!IsDefaultTestConfiguration()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007256 return;
7257 }
7258
7259 EXPECT_TRUE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07007260 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7261 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007262 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
7263 ConnectionCloseBehavior::SILENT_CLOSE);
7264 EXPECT_FALSE(connection_.connected());
ianswettfc16a2b2020-05-18 16:05:49 -07007265 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007266
7267 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
7268 .Times(0);
7269
7270 EXPECT_QUIC_BUG(connection_.SendConnectivityProbingPacket(
7271 writer_.get(), connection_.peer_address()),
7272 "Not sending connectivity probing packet as connection is "
7273 "disconnected.");
fkastenholz5d880a92019-06-21 09:01:56 -07007274 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007275 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7276 IsError(QUIC_PEER_GOING_AWAY));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007277}
7278
7279TEST_P(QuicConnectionTest, WriteBlockedAfterClientSendsConnectivityProbe) {
dschinazi1c6e5922020-06-19 10:35:03 -07007280 PathProbeTestInit(Perspective::IS_CLIENT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007281 TestPacketWriter probing_writer(version(), &clock_);
7282 // Block next write so that sending connectivity probe will encounter a
7283 // blocked write when send a connectivity probe to the peer.
7284 probing_writer.BlockOnNextWrite();
7285 // Connection will not be marked as write blocked as connectivity probe only
7286 // affects the probing_writer which is not the default.
7287 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
7288
7289 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
7290 .Times(1);
7291 connection_.SendConnectivityProbingPacket(&probing_writer,
7292 connection_.peer_address());
7293}
7294
7295TEST_P(QuicConnectionTest, WriterBlockedAfterServerSendsConnectivityProbe) {
dschinazi1c6e5922020-06-19 10:35:03 -07007296 PathProbeTestInit(Perspective::IS_SERVER);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007297
7298 // Block next write so that sending connectivity probe will encounter a
7299 // blocked write when send a connectivity probe to the peer.
7300 writer_->BlockOnNextWrite();
7301 // Connection will be marked as write blocked as server uses the default
7302 // writer to send connectivity probes.
7303 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
7304
7305 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
7306 .Times(1);
7307 connection_.SendConnectivityProbingPacket(writer_.get(),
7308 connection_.peer_address());
7309}
7310
7311TEST_P(QuicConnectionTest, WriterErrorWhenClientSendsConnectivityProbe) {
dschinazi1c6e5922020-06-19 10:35:03 -07007312 PathProbeTestInit(Perspective::IS_CLIENT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007313 TestPacketWriter probing_writer(version(), &clock_);
7314 probing_writer.SetShouldWriteFail();
7315
7316 // Connection should not be closed if a connectivity probe is failed to be
7317 // sent.
fkastenholz5d880a92019-06-21 09:01:56 -07007318 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007319
7320 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
7321 .Times(0);
7322 connection_.SendConnectivityProbingPacket(&probing_writer,
7323 connection_.peer_address());
7324}
7325
7326TEST_P(QuicConnectionTest, WriterErrorWhenServerSendsConnectivityProbe) {
dschinazi1c6e5922020-06-19 10:35:03 -07007327 PathProbeTestInit(Perspective::IS_SERVER);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007328
7329 writer_->SetShouldWriteFail();
7330 // Connection should not be closed if a connectivity probe is failed to be
7331 // sent.
fkastenholz5d880a92019-06-21 09:01:56 -07007332 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007333
7334 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
7335 .Times(0);
7336 connection_.SendConnectivityProbingPacket(writer_.get(),
7337 connection_.peer_address());
7338}
7339
7340TEST_P(QuicConnectionTest, PublicReset) {
fayangc31c9952019-06-05 13:54:48 -07007341 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007342 return;
7343 }
7344 QuicPublicResetPacket header;
7345 // Public reset packet in only built by server.
7346 header.connection_id = connection_id_;
7347 std::unique_ptr<QuicEncryptedPacket> packet(
7348 framer_.BuildPublicResetPacket(header));
7349 std::unique_ptr<QuicReceivedPacket> received(
7350 ConstructReceivedPacket(*packet, QuicTime::Zero()));
fkastenholz5d880a92019-06-21 09:01:56 -07007351 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
7352 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007353 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
fkastenholz5d880a92019-06-21 09:01:56 -07007354 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007355 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7356 IsError(QUIC_PUBLIC_RESET));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007357}
7358
7359TEST_P(QuicConnectionTest, IetfStatelessReset) {
fayangc31c9952019-06-05 13:54:48 -07007360 if (!VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007361 return;
7362 }
7363 const QuicUint128 kTestStatelessResetToken = 1010101;
7364 QuicConfig config;
7365 QuicConfigPeer::SetReceivedStatelessResetToken(&config,
7366 kTestStatelessResetToken);
7367 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7368 connection_.SetFromConfig(config);
7369 std::unique_ptr<QuicEncryptedPacket> packet(
7370 QuicFramer::BuildIetfStatelessResetPacket(connection_id_,
7371 kTestStatelessResetToken));
7372 std::unique_ptr<QuicReceivedPacket> received(
7373 ConstructReceivedPacket(*packet, QuicTime::Zero()));
renjietang7f483b52020-05-20 14:30:47 -07007374 EXPECT_CALL(visitor_, ValidateStatelessReset(_, _)).WillOnce(Return(true));
fkastenholz5d880a92019-06-21 09:01:56 -07007375 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
7376 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007377 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
fkastenholz5d880a92019-06-21 09:01:56 -07007378 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007379 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7380 IsError(QUIC_PUBLIC_RESET));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007381}
7382
7383TEST_P(QuicConnectionTest, GoAway) {
fkastenholz305e1732019-06-18 05:01:22 -07007384 if (VersionHasIetfQuicFrames(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007385 // GoAway is not available in version 99.
7386 return;
7387 }
7388
7389 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7390
wub8a5dafa2020-05-13 12:30:17 -07007391 QuicGoAwayFrame* goaway = new QuicGoAwayFrame();
7392 goaway->last_good_stream_id = 1;
7393 goaway->error_code = QUIC_PEER_GOING_AWAY;
7394 goaway->reason_phrase = "Going away.";
QUICHE teama6ef0a62019-03-07 20:34:33 -05007395 EXPECT_CALL(visitor_, OnGoAway(_));
wub8a5dafa2020-05-13 12:30:17 -07007396 ProcessGoAwayPacket(goaway);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007397}
7398
7399TEST_P(QuicConnectionTest, WindowUpdate) {
7400 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7401
wub8a5dafa2020-05-13 12:30:17 -07007402 QuicWindowUpdateFrame* window_update = new QuicWindowUpdateFrame();
7403 window_update->stream_id = 3;
7404 window_update->max_data = 1234;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007405 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
wub8a5dafa2020-05-13 12:30:17 -07007406 ProcessFramePacket(QuicFrame(window_update));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007407}
7408
7409TEST_P(QuicConnectionTest, Blocked) {
7410 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7411
wub8a5dafa2020-05-13 12:30:17 -07007412 QuicBlockedFrame* blocked = new QuicBlockedFrame();
7413 blocked->stream_id = 3;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007414 EXPECT_CALL(visitor_, OnBlockedFrame(_));
wub8a5dafa2020-05-13 12:30:17 -07007415 ProcessFramePacket(QuicFrame(blocked));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007416 EXPECT_EQ(1u, connection_.GetStats().blocked_frames_received);
7417 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7418}
7419
7420TEST_P(QuicConnectionTest, ZeroBytePacket) {
7421 // Don't close the connection for zero byte packets.
fkastenholz5d880a92019-06-21 09:01:56 -07007422 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007423 QuicReceivedPacket encrypted(nullptr, 0, QuicTime::Zero());
7424 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, encrypted);
7425}
7426
7427TEST_P(QuicConnectionTest, MissingPacketsBeforeLeastUnacked) {
fayangd4291e42019-05-30 10:31:21 -07007428 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007429 return;
7430 }
7431 // Set the packet number of the ack packet to be least unacked (4).
7432 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 3);
7433 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7434 ProcessStopWaitingPacket(InitStopWaitingFrame(4));
fayangc31c9952019-06-05 13:54:48 -07007435 EXPECT_FALSE(connection_.ack_frame().packets.Empty());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007436}
7437
QUICHE teama6ef0a62019-03-07 20:34:33 -05007438TEST_P(QuicConnectionTest, ClientHandlesVersionNegotiation) {
dschinazi48ac9192019-07-31 00:07:26 -07007439 // All supported versions except the one the connection supports.
7440 ParsedQuicVersionVector versions;
7441 for (auto version : AllSupportedVersions()) {
7442 if (version != connection_.version()) {
7443 versions.push_back(version);
7444 }
7445 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007446
7447 // Send a version negotiation packet.
7448 std::unique_ptr<QuicEncryptedPacket> encrypted(
dschinazib417d602019-05-29 13:08:45 -07007449 QuicFramer::BuildVersionNegotiationPacket(
7450 connection_id_, EmptyQuicConnectionId(),
fayangd4291e42019-05-30 10:31:21 -07007451 VersionHasIetfInvariantHeader(connection_.transport_version()),
dschinazi48ac9192019-07-31 00:07:26 -07007452 connection_.version().HasLengthPrefixedConnectionIds(), versions));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007453 std::unique_ptr<QuicReceivedPacket> received(
7454 ConstructReceivedPacket(*encrypted, QuicTime::Zero()));
fkastenholz5d880a92019-06-21 09:01:56 -07007455 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7456 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
fayang95cef072019-10-10 12:44:14 -07007457 // Verify no connection close packet gets sent.
7458 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007459 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
fayang9ed391a2019-06-20 11:16:59 -07007460 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07007461 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007462 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7463 IsError(QUIC_INVALID_VERSION));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007464}
7465
7466TEST_P(QuicConnectionTest, BadVersionNegotiation) {
7467 // Send a version negotiation packet with the version the client started with.
7468 // It should be rejected.
fkastenholz5d880a92019-06-21 09:01:56 -07007469 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7470 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007471 std::unique_ptr<QuicEncryptedPacket> encrypted(
dschinazib417d602019-05-29 13:08:45 -07007472 QuicFramer::BuildVersionNegotiationPacket(
7473 connection_id_, EmptyQuicConnectionId(),
fayangd4291e42019-05-30 10:31:21 -07007474 VersionHasIetfInvariantHeader(connection_.transport_version()),
dschinazi48ac9192019-07-31 00:07:26 -07007475 connection_.version().HasLengthPrefixedConnectionIds(),
QUICHE teama6ef0a62019-03-07 20:34:33 -05007476 AllSupportedVersions()));
7477 std::unique_ptr<QuicReceivedPacket> received(
7478 ConstructReceivedPacket(*encrypted, QuicTime::Zero()));
7479 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
fkastenholz5d880a92019-06-21 09:01:56 -07007480 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007481 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7482 IsError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007483}
7484
7485TEST_P(QuicConnectionTest, CheckSendStats) {
fayang5f135052019-08-22 17:59:40 -07007486 if (connection_.PtoEnabled()) {
7487 return;
7488 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007489 connection_.SetMaxTailLossProbes(0);
7490
7491 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7492 connection_.SendStreamDataWithString(3, "first", 0, NO_FIN);
7493 size_t first_packet_size = writer_->last_packet_size();
7494
7495 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7496 connection_.SendStreamDataWithString(5, "second", 0, NO_FIN);
7497 size_t second_packet_size = writer_->last_packet_size();
7498
7499 // 2 retransmissions due to rto, 1 due to explicit nack.
7500 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
7501 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
7502
7503 // Retransmit due to RTO.
7504 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
7505 connection_.GetRetransmissionAlarm()->Fire();
7506
7507 // Retransmit due to explicit nacks.
7508 QuicAckFrame nack_three =
7509 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)},
7510 {QuicPacketNumber(4), QuicPacketNumber(5)}});
7511
7512 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07007513 lost_packets.push_back(
7514 LostPacket(QuicPacketNumber(1), kMaxOutgoingPacketSize));
7515 lost_packets.push_back(
7516 LostPacket(QuicPacketNumber(3), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007517 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07007518 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
7519 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007520 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007521 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7522 ProcessAckPacket(&nack_three);
7523
7524 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
7525 .WillOnce(Return(QuicBandwidth::Zero()));
7526
7527 const QuicConnectionStats& stats = connection_.GetStats();
7528 // For IETF QUIC, version is not included as the encryption level switches to
7529 // FORWARD_SECURE in SendStreamDataWithString.
7530 size_t save_on_version =
fayangd4291e42019-05-30 10:31:21 -07007531 VersionHasIetfInvariantHeader(GetParam().version.transport_version)
7532 ? 0
7533 : kQuicVersionSize;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007534 EXPECT_EQ(3 * first_packet_size + 2 * second_packet_size - save_on_version,
7535 stats.bytes_sent);
7536 EXPECT_EQ(5u, stats.packets_sent);
7537 EXPECT_EQ(2 * first_packet_size + second_packet_size - save_on_version,
7538 stats.bytes_retransmitted);
7539 EXPECT_EQ(3u, stats.packets_retransmitted);
7540 EXPECT_EQ(1u, stats.rto_count);
7541 EXPECT_EQ(kDefaultMaxPacketSize, stats.max_packet_size);
7542}
7543
7544TEST_P(QuicConnectionTest, ProcessFramesIfPacketClosedConnection) {
7545 // Construct a packet with stream frame and connection close frame.
7546 QuicPacketHeader header;
dschinazi5e1a7b22019-07-31 12:23:21 -07007547 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
QUICHE team2252b702019-05-14 23:55:14 -04007548 header.source_connection_id = connection_id_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007549 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
fayangd4291e42019-05-30 10:31:21 -07007550 if (!VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04007551 header.source_connection_id_included = CONNECTION_ID_PRESENT;
7552 }
7553 } else {
7554 header.destination_connection_id = connection_id_;
fayangd4291e42019-05-30 10:31:21 -07007555 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04007556 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
7557 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007558 }
7559 header.packet_number = QuicPacketNumber(1);
7560 header.version_flag = false;
7561
fkastenholz488a4622019-08-26 06:24:46 -07007562 QuicErrorCode kQuicErrorCode = QUIC_PEER_GOING_AWAY;
7563 // This QuicConnectionCloseFrame will default to being for a Google QUIC
7564 // close. If doing IETF QUIC then set fields appropriately for CC/T or CC/A,
7565 // depending on the mapping.
fkastenholz591814c2019-09-06 12:11:46 -07007566 QuicConnectionCloseFrame qccf(peer_framer_.transport_version(),
7567 kQuicErrorCode, "",
7568 /*transport_close_frame_type=*/0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007569 QuicFrames frames;
7570 frames.push_back(QuicFrame(frame1_));
7571 frames.push_back(QuicFrame(&qccf));
7572 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
7573 EXPECT_TRUE(nullptr != packet);
dschinazi66dea072019-04-09 11:41:06 -07007574 char buffer[kMaxOutgoingPacketSize];
nharperc6b99512019-09-19 11:13:48 -07007575 size_t encrypted_length = peer_framer_.EncryptPayload(
7576 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
7577 kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007578
fkastenholz5d880a92019-06-21 09:01:56 -07007579 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
7580 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007581 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7582 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7583
7584 connection_.ProcessUdpPacket(
7585 kSelfAddress, kPeerAddress,
7586 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
fkastenholz5d880a92019-06-21 09:01:56 -07007587 EXPECT_EQ(1, connection_close_frame_count_);
bnc77e77b82020-04-05 10:36:49 -07007588 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
bncf54082a2019-11-27 10:19:47 -08007589 IsError(QUIC_PEER_GOING_AWAY));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007590}
7591
7592TEST_P(QuicConnectionTest, SelectMutualVersion) {
7593 connection_.SetSupportedVersions(AllSupportedVersions());
7594 // Set the connection to speak the lowest quic version.
7595 connection_.set_version(QuicVersionMin());
7596 EXPECT_EQ(QuicVersionMin(), connection_.version());
7597
7598 // Pass in available versions which includes a higher mutually supported
7599 // version. The higher mutually supported version should be selected.
7600 ParsedQuicVersionVector supported_versions = AllSupportedVersions();
7601 EXPECT_TRUE(connection_.SelectMutualVersion(supported_versions));
7602 EXPECT_EQ(QuicVersionMax(), connection_.version());
7603
7604 // Expect that the lowest version is selected.
7605 // Ensure the lowest supported version is less than the max, unless they're
7606 // the same.
7607 ParsedQuicVersionVector lowest_version_vector;
7608 lowest_version_vector.push_back(QuicVersionMin());
7609 EXPECT_TRUE(connection_.SelectMutualVersion(lowest_version_vector));
7610 EXPECT_EQ(QuicVersionMin(), connection_.version());
7611
7612 // Shouldn't be able to find a mutually supported version.
7613 ParsedQuicVersionVector unsupported_version;
7614 unsupported_version.push_back(UnsupportedQuicVersion());
7615 EXPECT_FALSE(connection_.SelectMutualVersion(unsupported_version));
7616}
7617
7618TEST_P(QuicConnectionTest, ConnectionCloseWhenWritable) {
7619 EXPECT_FALSE(writer_->IsWriteBlocked());
7620
7621 // Send a packet.
7622 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7623 EXPECT_EQ(0u, connection_.NumQueuedPackets());
7624 EXPECT_EQ(1u, writer_->packets_write_attempts());
7625
7626 TriggerConnectionClose();
rch39c88ab2019-10-16 19:24:40 -07007627 EXPECT_LE(2u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007628}
7629
7630TEST_P(QuicConnectionTest, ConnectionCloseGettingWriteBlocked) {
7631 BlockOnNextWrite();
7632 TriggerConnectionClose();
7633 EXPECT_EQ(1u, writer_->packets_write_attempts());
7634 EXPECT_TRUE(writer_->IsWriteBlocked());
7635}
7636
7637TEST_P(QuicConnectionTest, ConnectionCloseWhenWriteBlocked) {
7638 BlockOnNextWrite();
7639 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7640 EXPECT_EQ(1u, connection_.NumQueuedPackets());
7641 EXPECT_EQ(1u, writer_->packets_write_attempts());
7642 EXPECT_TRUE(writer_->IsWriteBlocked());
7643 TriggerConnectionClose();
7644 EXPECT_EQ(1u, writer_->packets_write_attempts());
7645}
7646
7647TEST_P(QuicConnectionTest, OnPacketSentDebugVisitor) {
dschinazi1c6e5922020-06-19 10:35:03 -07007648 PathProbeTestInit(Perspective::IS_CLIENT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007649 MockQuicConnectionDebugVisitor debug_visitor;
7650 connection_.set_debug_visitor(&debug_visitor);
7651
fayangcff885a2019-10-22 07:39:04 -07007652 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007653 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7654
fayangcff885a2019-10-22 07:39:04 -07007655 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007656 connection_.SendConnectivityProbingPacket(writer_.get(),
7657 connection_.peer_address());
7658}
7659
7660TEST_P(QuicConnectionTest, OnPacketHeaderDebugVisitor) {
7661 QuicPacketHeader header;
7662 header.packet_number = QuicPacketNumber(1);
fayangd4291e42019-05-30 10:31:21 -07007663 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007664 header.form = IETF_QUIC_LONG_HEADER_PACKET;
7665 }
7666
7667 MockQuicConnectionDebugVisitor debug_visitor;
7668 connection_.set_debug_visitor(&debug_visitor);
7669 EXPECT_CALL(debug_visitor, OnPacketHeader(Ref(header))).Times(1);
7670 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(1);
7671 EXPECT_CALL(debug_visitor, OnSuccessfulVersionNegotiation(_)).Times(1);
7672 connection_.OnPacketHeader(header);
7673}
7674
7675TEST_P(QuicConnectionTest, Pacing) {
7676 TestConnection server(connection_id_, kSelfAddress, helper_.get(),
7677 alarm_factory_.get(), writer_.get(),
7678 Perspective::IS_SERVER, version());
7679 TestConnection client(connection_id_, kPeerAddress, helper_.get(),
7680 alarm_factory_.get(), writer_.get(),
7681 Perspective::IS_CLIENT, version());
7682 EXPECT_FALSE(QuicSentPacketManagerPeer::UsingPacing(
7683 static_cast<const QuicSentPacketManager*>(
7684 &client.sent_packet_manager())));
7685 EXPECT_FALSE(QuicSentPacketManagerPeer::UsingPacing(
7686 static_cast<const QuicSentPacketManager*>(
7687 &server.sent_packet_manager())));
7688}
7689
7690TEST_P(QuicConnectionTest, WindowUpdateInstigateAcks) {
7691 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7692
7693 // Send a WINDOW_UPDATE frame.
wub8a5dafa2020-05-13 12:30:17 -07007694 QuicWindowUpdateFrame* window_update = new QuicWindowUpdateFrame();
7695 window_update->stream_id = 3;
7696 window_update->max_data = 1234;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007697 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
wub8a5dafa2020-05-13 12:30:17 -07007698 ProcessFramePacket(QuicFrame(window_update));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007699
7700 // Ensure that this has caused the ACK alarm to be set.
fayang9adfb532020-06-04 06:58:45 -07007701 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007702}
7703
7704TEST_P(QuicConnectionTest, BlockedFrameInstigateAcks) {
7705 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7706
7707 // Send a BLOCKED frame.
wub8a5dafa2020-05-13 12:30:17 -07007708 QuicBlockedFrame* blocked = new QuicBlockedFrame();
7709 blocked->stream_id = 3;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007710 EXPECT_CALL(visitor_, OnBlockedFrame(_));
wub8a5dafa2020-05-13 12:30:17 -07007711 ProcessFramePacket(QuicFrame(blocked));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007712
7713 // Ensure that this has caused the ACK alarm to be set.
fayang9adfb532020-06-04 06:58:45 -07007714 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007715}
7716
7717TEST_P(QuicConnectionTest, ReevaluateTimeUntilSendOnAck) {
7718 // Enable pacing.
7719 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7720 QuicConfig config;
7721 connection_.SetFromConfig(config);
7722
7723 // Send two packets. One packet is not sufficient because if it gets acked,
7724 // there will be no packets in flight after that and the pacer will always
7725 // allow the next packet in that situation.
7726 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7727 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
7728 connection_.SendStreamDataWithString(
7729 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
7730 0, NO_FIN);
7731 connection_.SendStreamDataWithString(
7732 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "bar",
7733 3, NO_FIN);
7734 connection_.OnCanWrite();
7735
7736 // Schedule the next packet for a few milliseconds in future.
7737 QuicSentPacketManagerPeer::DisablePacerBursts(manager_);
7738 QuicTime scheduled_pacing_time =
7739 clock_.Now() + QuicTime::Delta::FromMilliseconds(5);
7740 QuicSentPacketManagerPeer::SetNextPacedPacketTime(manager_,
7741 scheduled_pacing_time);
7742
7743 // Send a packet and have it be blocked by congestion control.
7744 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(false));
7745 connection_.SendStreamDataWithString(
7746 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "baz",
7747 6, NO_FIN);
7748 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
7749
7750 // Process an ack and the send alarm will be set to the new 5ms delay.
7751 QuicAckFrame ack = InitAckFrame(1);
7752 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
7753 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7754 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
7755 ProcessAckPacket(&ack);
nharper55fa6132019-05-07 19:37:21 -07007756 size_t padding_frame_count = writer_->padding_frames().size();
7757 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007758 EXPECT_EQ(1u, writer_->stream_frames().size());
7759 EXPECT_TRUE(connection_.GetSendAlarm()->IsSet());
7760 EXPECT_EQ(scheduled_pacing_time, connection_.GetSendAlarm()->deadline());
7761 writer_->Reset();
7762}
7763
7764TEST_P(QuicConnectionTest, SendAcksImmediately) {
QUICHE teamcd098022019-03-22 18:49:55 -07007765 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7766 return;
7767 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007768 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7769 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7770 ProcessDataPacket(1);
7771 CongestionBlockWrites();
7772 SendAckPacketToPeer();
7773}
7774
7775TEST_P(QuicConnectionTest, SendPingImmediately) {
7776 MockQuicConnectionDebugVisitor debug_visitor;
7777 connection_.set_debug_visitor(&debug_visitor);
7778
7779 CongestionBlockWrites();
fayang93cc53a2019-08-22 12:47:30 -07007780 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007781 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
fayangcff885a2019-10-22 07:39:04 -07007782 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007783 EXPECT_CALL(debug_visitor, OnPingSent()).Times(1);
7784 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
7785 EXPECT_FALSE(connection_.HasQueuedData());
7786}
7787
7788TEST_P(QuicConnectionTest, SendBlockedImmediately) {
7789 MockQuicConnectionDebugVisitor debug_visitor;
7790 connection_.set_debug_visitor(&debug_visitor);
7791
fayang93cc53a2019-08-22 12:47:30 -07007792 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007793 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
fayangcff885a2019-10-22 07:39:04 -07007794 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007795 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7796 connection_.SendControlFrame(QuicFrame(new QuicBlockedFrame(1, 3)));
7797 EXPECT_EQ(1u, connection_.GetStats().blocked_frames_sent);
7798 EXPECT_FALSE(connection_.HasQueuedData());
7799}
7800
fayang93cc53a2019-08-22 12:47:30 -07007801TEST_P(QuicConnectionTest, FailedToSendBlockedFrames) {
7802 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
7803 return;
7804 }
7805 MockQuicConnectionDebugVisitor debug_visitor;
7806 connection_.set_debug_visitor(&debug_visitor);
7807 QuicBlockedFrame blocked(1, 3);
7808
7809 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
fayangcff885a2019-10-22 07:39:04 -07007810 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(0);
fayang93cc53a2019-08-22 12:47:30 -07007811 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7812 connection_.SendControlFrame(QuicFrame(&blocked));
7813 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7814 EXPECT_FALSE(connection_.HasQueuedData());
7815}
7816
QUICHE teama6ef0a62019-03-07 20:34:33 -05007817TEST_P(QuicConnectionTest, SendingUnencryptedStreamDataFails) {
7818 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
7819 if (!IsDefaultTestConfiguration()) {
7820 return;
7821 }
7822
fkastenholz5d880a92019-06-21 09:01:56 -07007823 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7824 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007825 struct iovec iov;
7826 MakeIOVector("", &iov);
7827 EXPECT_QUIC_BUG(connection_.SaveAndSendStreamData(3, &iov, 1, 0, 0, FIN),
fayang49523232019-05-03 06:28:22 -07007828 "Cannot send stream data with level: ENCRYPTION_INITIAL");
QUICHE teama6ef0a62019-03-07 20:34:33 -05007829 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07007830 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007831 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7832 IsError(QUIC_ATTEMPT_TO_SEND_UNENCRYPTED_STREAM_DATA));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007833}
7834
7835TEST_P(QuicConnectionTest, SetRetransmissionAlarmForCryptoPacket) {
7836 EXPECT_TRUE(connection_.connected());
7837 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
7838
7839 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7840 connection_.SendCryptoStreamData();
7841
7842 // Verify retransmission timer is correctly set after crypto packet has been
7843 // sent.
7844 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
7845 QuicTime retransmission_time =
7846 QuicConnectionPeer::GetSentPacketManager(&connection_)
7847 ->GetRetransmissionTime();
7848 EXPECT_NE(retransmission_time, clock_.ApproximateNow());
7849 EXPECT_EQ(retransmission_time,
7850 connection_.GetRetransmissionAlarm()->deadline());
7851
7852 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7853 connection_.GetRetransmissionAlarm()->Fire();
7854}
7855
vasilvv693d5b02019-04-09 21:58:56 -07007856// Includes regression test for b/69979024.
zhongyi3ae832d2020-06-15 13:03:31 -07007857TEST_P(QuicConnectionTest, PathDegradingDetectionForNonCryptoPackets) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007858 EXPECT_TRUE(connection_.connected());
fayangb59c6f12020-03-23 15:06:14 -07007859 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007860 EXPECT_FALSE(connection_.IsPathDegrading());
7861
7862 const char data[] = "data";
7863 size_t data_size = strlen(data);
7864 QuicStreamOffset offset = 0;
7865
7866 for (int i = 0; i < 2; ++i) {
7867 // Send a packet. Now there's a retransmittable packet on the wire, so the
zhongyi3ae832d2020-06-15 13:03:31 -07007868 // path degrading detection should be set.
QUICHE teama6ef0a62019-03-07 20:34:33 -05007869 connection_.SendStreamDataWithString(
7870 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
7871 offset, NO_FIN);
7872 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07007873 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
zhongyi3ae832d2020-06-15 13:03:31 -07007874 // Check the deadline of the path degrading detection.
QUICHE teama6ef0a62019-03-07 20:34:33 -05007875 QuicTime::Delta delay =
7876 QuicConnectionPeer::GetSentPacketManager(&connection_)
7877 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07007878 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7879 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007880
zhongyi3ae832d2020-06-15 13:03:31 -07007881 // Send a second packet. The path degrading detection's deadline should
7882 // remain the same.
vasilvv693d5b02019-04-09 21:58:56 -07007883 // Regression test for b/69979024.
QUICHE teama6ef0a62019-03-07 20:34:33 -05007884 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
fayang2205d952020-05-12 13:45:56 -07007885 QuicTime prev_deadline =
7886 connection_.GetBlackholeDetectorAlarm()->deadline();
QUICHE teama6ef0a62019-03-07 20:34:33 -05007887 connection_.SendStreamDataWithString(
7888 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
7889 offset, NO_FIN);
7890 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07007891 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
fayang2205d952020-05-12 13:45:56 -07007892 EXPECT_EQ(prev_deadline,
7893 connection_.GetBlackholeDetectorAlarm()->deadline());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007894
7895 // Now receive an ACK of the first packet. This should advance the path
zhongyi3ae832d2020-06-15 13:03:31 -07007896 // degrading detection's deadline since forward progress has been made.
QUICHE teama6ef0a62019-03-07 20:34:33 -05007897 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7898 if (i == 0) {
7899 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7900 }
7901 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7902 QuicAckFrame frame = InitAckFrame(
7903 {{QuicPacketNumber(1u + 2u * i), QuicPacketNumber(2u + 2u * i)}});
7904 ProcessAckPacket(&frame);
fayangb59c6f12020-03-23 15:06:14 -07007905 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
zhongyi3ae832d2020-06-15 13:03:31 -07007906 // Check the deadline of the path degrading detection.
QUICHE teama6ef0a62019-03-07 20:34:33 -05007907 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7908 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07007909 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7910 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007911
7912 if (i == 0) {
7913 // Now receive an ACK of the second packet. Since there are no more
7914 // retransmittable packets on the wire, this should cancel the path
zhongyi3ae832d2020-06-15 13:03:31 -07007915 // degrading detection.
QUICHE teama6ef0a62019-03-07 20:34:33 -05007916 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7917 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7918 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
7919 ProcessAckPacket(&frame);
fayangb59c6f12020-03-23 15:06:14 -07007920 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007921 } else {
7922 // Advance time to the path degrading alarm's deadline and simulate
7923 // firing the alarm.
7924 clock_.AdvanceTime(delay);
7925 EXPECT_CALL(visitor_, OnPathDegrading());
fayangb59c6f12020-03-23 15:06:14 -07007926 connection_.PathDegradingTimeout();
7927 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007928 }
7929 }
7930 EXPECT_TRUE(connection_.IsPathDegrading());
7931}
7932
7933TEST_P(QuicConnectionTest, RetransmittableOnWireSetsPingAlarm) {
7934 const QuicTime::Delta retransmittable_on_wire_timeout =
7935 QuicTime::Delta::FromMilliseconds(50);
zhongyi79ace162019-10-21 15:57:09 -07007936 connection_.set_initial_retransmittable_on_wire_timeout(
QUICHE teama6ef0a62019-03-07 20:34:33 -05007937 retransmittable_on_wire_timeout);
7938
7939 EXPECT_TRUE(connection_.connected());
7940 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7941 .WillRepeatedly(Return(true));
7942
fayangb59c6f12020-03-23 15:06:14 -07007943 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007944 EXPECT_FALSE(connection_.IsPathDegrading());
7945 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
7946
7947 const char data[] = "data";
7948 size_t data_size = strlen(data);
7949 QuicStreamOffset offset = 0;
7950
7951 // Send a packet.
7952 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7953 offset += data_size;
7954 // Now there's a retransmittable packet on the wire, so the path degrading
7955 // alarm should be set.
7956 // The retransmittable-on-wire alarm should not be set.
fayangb59c6f12020-03-23 15:06:14 -07007957 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007958 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7959 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07007960 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7961 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007962 ASSERT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
7963 // The ping alarm is set for the ping timeout, not the shorter
7964 // retransmittable_on_wire_timeout.
7965 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7966 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
zhongyieef848f2019-10-18 07:09:37 -07007967 EXPECT_EQ(ping_delay,
7968 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007969
7970 // Now receive an ACK of the packet.
7971 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7972 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7973 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7974 QuicAckFrame frame =
7975 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7976 ProcessAckPacket(&frame);
7977 // No more retransmittable packets on the wire, so the path degrading alarm
7978 // should be cancelled, and the ping alarm should be set to the
7979 // retransmittable_on_wire_timeout.
fayangb59c6f12020-03-23 15:06:14 -07007980 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007981 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07007982 EXPECT_EQ(retransmittable_on_wire_timeout,
7983 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007984
7985 // Simulate firing the ping alarm and sending a PING.
7986 clock_.AdvanceTime(retransmittable_on_wire_timeout);
7987 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
7988 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
7989 }));
7990 connection_.GetPingAlarm()->Fire();
7991
7992 // Now there's a retransmittable packet (PING) on the wire, so the path
7993 // degrading alarm should be set.
fayangb59c6f12020-03-23 15:06:14 -07007994 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007995 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7996 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07007997 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7998 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007999}
8000
8001// This test verifies that the connection marks path as degrading and does not
8002// spin timer to detect path degrading when a new packet is sent on the
8003// degraded path.
zhongyi3ae832d2020-06-15 13:03:31 -07008004TEST_P(QuicConnectionTest, NoPathDegradingDetectionIfPathIsDegrading) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008005 EXPECT_TRUE(connection_.connected());
fayangb59c6f12020-03-23 15:06:14 -07008006 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008007 EXPECT_FALSE(connection_.IsPathDegrading());
8008
8009 const char data[] = "data";
8010 size_t data_size = strlen(data);
8011 QuicStreamOffset offset = 0;
8012
8013 // Send the first packet. Now there's a retransmittable packet on the wire, so
8014 // the path degrading alarm should be set.
8015 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8016 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07008017 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
zhongyi3ae832d2020-06-15 13:03:31 -07008018 // Check the deadline of the path degrading detection.
QUICHE teama6ef0a62019-03-07 20:34:33 -05008019 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
8020 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07008021 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
8022 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008023
zhongyi3ae832d2020-06-15 13:03:31 -07008024 // Send a second packet. The path degrading detection's deadline should remain
QUICHE teama6ef0a62019-03-07 20:34:33 -05008025 // the same.
8026 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
fayang2205d952020-05-12 13:45:56 -07008027 QuicTime prev_deadline = connection_.GetBlackholeDetectorAlarm()->deadline();
QUICHE teama6ef0a62019-03-07 20:34:33 -05008028 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8029 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07008030 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
fayang2205d952020-05-12 13:45:56 -07008031 EXPECT_EQ(prev_deadline, connection_.GetBlackholeDetectorAlarm()->deadline());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008032
8033 // Now receive an ACK of the first packet. This should advance the path
zhongyi3ae832d2020-06-15 13:03:31 -07008034 // degrading detection's deadline since forward progress has been made.
QUICHE teama6ef0a62019-03-07 20:34:33 -05008035 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8036 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8037 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8038 QuicAckFrame frame =
8039 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
8040 ProcessAckPacket(&frame);
fayangb59c6f12020-03-23 15:06:14 -07008041 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008042 // Check the deadline of the path degrading alarm.
8043 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
zhongyi3ae832d2020-06-15 13:03:31 -07008048 // Advance time to the path degrading detection's deadline and simulate
8049 // firing the path degrading detection. This path will be considered as
QUICHE teama6ef0a62019-03-07 20:34:33 -05008050 // degrading.
8051 clock_.AdvanceTime(delay);
8052 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
fayangb59c6f12020-03-23 15:06:14 -07008053 connection_.PathDegradingTimeout();
8054 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008055 EXPECT_TRUE(connection_.IsPathDegrading());
8056
8057 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
fayangb59c6f12020-03-23 15:06:14 -07008058 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
zhongyi3ae832d2020-06-15 13:03:31 -07008059 // Send a third packet. The path degrading detection is no longer set but path
QUICHE teama6ef0a62019-03-07 20:34:33 -05008060 // should still be marked as degrading.
8061 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8062 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07008063 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008064 EXPECT_TRUE(connection_.IsPathDegrading());
8065}
8066
8067// This test verifies that the connection unmarks path as degrarding and spins
8068// the timer to detect future path degrading when forward progress is made
8069// after path has been marked degrading.
8070TEST_P(QuicConnectionTest, UnmarkPathDegradingOnForwardProgress) {
8071 EXPECT_TRUE(connection_.connected());
fayangb59c6f12020-03-23 15:06:14 -07008072 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008073 EXPECT_FALSE(connection_.IsPathDegrading());
8074
8075 const char data[] = "data";
8076 size_t data_size = strlen(data);
8077 QuicStreamOffset offset = 0;
8078
8079 // Send the first packet. Now there's a retransmittable packet on the wire, so
8080 // the path degrading alarm should be set.
8081 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8082 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07008083 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008084 // Check the deadline of the path degrading alarm.
8085 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
8086 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07008087 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
8088 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008089
8090 // Send a second packet. The path degrading alarm's deadline should remain
8091 // the same.
8092 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
fayang2205d952020-05-12 13:45:56 -07008093 QuicTime prev_deadline = connection_.GetBlackholeDetectorAlarm()->deadline();
QUICHE teama6ef0a62019-03-07 20:34:33 -05008094 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8095 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07008096 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
fayang2205d952020-05-12 13:45:56 -07008097 EXPECT_EQ(prev_deadline, connection_.GetBlackholeDetectorAlarm()->deadline());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008098
8099 // Now receive an ACK of the first packet. This should advance the path
8100 // degrading alarm's deadline since forward progress has been made.
8101 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8102 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8103 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8104 QuicAckFrame frame =
8105 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
8106 ProcessAckPacket(&frame);
fayangb59c6f12020-03-23 15:06:14 -07008107 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008108 // Check the deadline of the path degrading alarm.
8109 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
8110 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07008111 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
8112 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008113
8114 // Advance time to the path degrading alarm's deadline and simulate
8115 // firing the alarm.
8116 clock_.AdvanceTime(delay);
8117 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
fayangb59c6f12020-03-23 15:06:14 -07008118 connection_.PathDegradingTimeout();
8119 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008120 EXPECT_TRUE(connection_.IsPathDegrading());
8121
8122 // Send a third packet. The path degrading alarm is no longer set but path
8123 // should still be marked as degrading.
8124 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
fayangb59c6f12020-03-23 15:06:14 -07008125 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008126 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8127 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07008128 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008129 EXPECT_TRUE(connection_.IsPathDegrading());
8130
8131 // Now receive an ACK of the second packet. This should unmark the path as
8132 // degrading. And will set a timer to detect new path degrading.
8133 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8134 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
zhongyief1d6752020-06-11 16:19:28 -07008135 EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading()).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008136 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8137 ProcessAckPacket(&frame);
8138 EXPECT_FALSE(connection_.IsPathDegrading());
fayangb59c6f12020-03-23 15:06:14 -07008139 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008140}
8141
8142TEST_P(QuicConnectionTest, NoPathDegradingOnServer) {
QUICHE teamcd098022019-03-22 18:49:55 -07008143 if (connection_.SupportsMultiplePacketNumberSpaces()) {
8144 return;
8145 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008146 set_perspective(Perspective::IS_SERVER);
8147 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
8148
8149 EXPECT_FALSE(connection_.IsPathDegrading());
fayangb59c6f12020-03-23 15:06:14 -07008150 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008151
8152 // Send data.
8153 const char data[] = "data";
8154 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
8155 EXPECT_FALSE(connection_.IsPathDegrading());
fayangb59c6f12020-03-23 15:06:14 -07008156 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008157
8158 // Ack data.
8159 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
QUICHE teama6ef0a62019-03-07 20:34:33 -05008160 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8161 QuicAckFrame frame =
8162 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
8163 ProcessAckPacket(&frame);
8164 EXPECT_FALSE(connection_.IsPathDegrading());
fayangb59c6f12020-03-23 15:06:14 -07008165 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008166}
8167
8168TEST_P(QuicConnectionTest, NoPathDegradingAfterSendingAck) {
QUICHE teamcd098022019-03-22 18:49:55 -07008169 if (connection_.SupportsMultiplePacketNumberSpaces()) {
8170 return;
8171 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008172 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8173 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
8174 ProcessDataPacket(1);
8175 SendAckPacketToPeer();
8176 EXPECT_FALSE(connection_.sent_packet_manager().unacked_packets().empty());
8177 EXPECT_FALSE(connection_.sent_packet_manager().HasInFlightPackets());
8178 EXPECT_FALSE(connection_.IsPathDegrading());
fayangb59c6f12020-03-23 15:06:14 -07008179 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008180}
8181
8182TEST_P(QuicConnectionTest, MultipleCallsToCloseConnection) {
8183 // Verifies that multiple calls to CloseConnection do not
8184 // result in multiple attempts to close the connection - it will be marked as
8185 // disconnected after the first call.
fkastenholz5d880a92019-06-21 09:01:56 -07008186 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008187 connection_.CloseConnection(QUIC_NO_ERROR, "no reason",
8188 ConnectionCloseBehavior::SILENT_CLOSE);
8189 connection_.CloseConnection(QUIC_NO_ERROR, "no reason",
8190 ConnectionCloseBehavior::SILENT_CLOSE);
8191}
8192
8193TEST_P(QuicConnectionTest, ServerReceivesChloOnNonCryptoStream) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008194 set_perspective(Perspective::IS_SERVER);
8195 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
8196
8197 CryptoHandshakeMessage message;
8198 CryptoFramer framer;
8199 message.set_tag(kCHLO);
QUICHE team3fe6a8b2019-03-14 09:10:38 -07008200 std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008201 frame1_.stream_id = 10;
8202 frame1_.data_buffer = data->data();
8203 frame1_.data_length = data->length();
8204
fkastenholz5d880a92019-06-21 09:01:56 -07008205 EXPECT_CALL(visitor_,
8206 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05008207 ForceProcessFramePacket(QuicFrame(frame1_));
fkastenholz5d880a92019-06-21 09:01:56 -07008208 TestConnectionCloseQuicErrorCode(QUIC_MAYBE_CORRUPTED_MEMORY);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008209}
8210
8211TEST_P(QuicConnectionTest, ClientReceivesRejOnNonCryptoStream) {
8212 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8213
8214 CryptoHandshakeMessage message;
8215 CryptoFramer framer;
8216 message.set_tag(kREJ);
QUICHE team3fe6a8b2019-03-14 09:10:38 -07008217 std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008218 frame1_.stream_id = 10;
8219 frame1_.data_buffer = data->data();
8220 frame1_.data_length = data->length();
8221
fkastenholz5d880a92019-06-21 09:01:56 -07008222 EXPECT_CALL(visitor_,
8223 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05008224 ForceProcessFramePacket(QuicFrame(frame1_));
fkastenholz5d880a92019-06-21 09:01:56 -07008225 TestConnectionCloseQuicErrorCode(QUIC_MAYBE_CORRUPTED_MEMORY);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008226}
8227
8228TEST_P(QuicConnectionTest, CloseConnectionOnPacketTooLarge) {
8229 SimulateNextPacketTooLarge();
8230 // A connection close packet is sent
fkastenholz5d880a92019-06-21 09:01:56 -07008231 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
QUICHE teama6ef0a62019-03-07 20:34:33 -05008232 .Times(1);
8233 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
fkastenholz5d880a92019-06-21 09:01:56 -07008234 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008235}
8236
8237TEST_P(QuicConnectionTest, AlwaysGetPacketTooLarge) {
8238 // Test even we always get packet too large, we do not infinitely try to send
8239 // close packet.
8240 AlwaysGetPacketTooLarge();
fkastenholz5d880a92019-06-21 09:01:56 -07008241 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
QUICHE teama6ef0a62019-03-07 20:34:33 -05008242 .Times(1);
8243 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
fkastenholz5d880a92019-06-21 09:01:56 -07008244 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008245}
8246
nharperef468962019-07-02 14:15:38 -07008247TEST_P(QuicConnectionTest, CloseConnectionOnQueuedWriteError) {
nharperef468962019-07-02 14:15:38 -07008248 // Regression test for crbug.com/979507.
8249 //
8250 // If we get a write error when writing queued packets, we should attempt to
8251 // send a connection close packet, but if sending that fails, it shouldn't get
8252 // queued.
8253
8254 // Queue a packet to write.
8255 BlockOnNextWrite();
8256 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
8257 EXPECT_EQ(1u, connection_.NumQueuedPackets());
8258
8259 // Configure writer to always fail.
8260 AlwaysGetPacketTooLarge();
8261
8262 // Expect that we attempt to close the connection exactly once.
8263 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
8264 .Times(1);
8265
8266 // Unblock the writes and actually send.
8267 writer_->SetWritable();
8268 connection_.OnCanWrite();
8269 EXPECT_EQ(0u, connection_.NumQueuedPackets());
8270
8271 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
8272}
8273
QUICHE teama6ef0a62019-03-07 20:34:33 -05008274// Verify that if connection has no outstanding data, it notifies the send
8275// algorithm after the write.
8276TEST_P(QuicConnectionTest, SendDataAndBecomeApplicationLimited) {
8277 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
8278 {
8279 InSequence seq;
8280 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
8281 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
8282 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
8283 .WillRepeatedly(Return(false));
8284 }
8285
8286 connection_.SendStreamData3();
8287}
8288
8289// Verify that the connection does not become app-limited if there is
8290// outstanding data to send after the write.
8291TEST_P(QuicConnectionTest, NotBecomeApplicationLimitedIfMoreDataAvailable) {
8292 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
8293 {
8294 InSequence seq;
8295 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
8296 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
8297 }
8298
8299 connection_.SendStreamData3();
8300}
8301
8302// Verify that the connection does not become app-limited after blocked write
8303// even if there is outstanding data to send after the write.
8304TEST_P(QuicConnectionTest, NotBecomeApplicationLimitedDueToWriteBlock) {
8305 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
8306 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
8307 BlockOnNextWrite();
8308
fayange62e63c2019-12-04 07:16:25 -08008309 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008310 connection_.SendStreamData3();
8311
8312 // Now unblock the writer, become congestion control blocked,
8313 // and ensure we become app-limited after writing.
8314 writer_->SetWritable();
8315 CongestionBlockWrites();
8316 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(false));
fayange62e63c2019-12-04 07:16:25 -08008317 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
fayang2ce66082019-10-02 06:29:04 -07008318 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008319 connection_.OnCanWrite();
8320}
8321
8322// Test the mode in which the link is filled up with probing retransmissions if
8323// the connection becomes application-limited.
8324TEST_P(QuicConnectionTest, SendDataWhenApplicationLimited) {
8325 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8326 EXPECT_CALL(*send_algorithm_, ShouldSendProbingPacket())
8327 .WillRepeatedly(Return(true));
8328 {
8329 InSequence seq;
8330 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
8331 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
8332 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
8333 .WillRepeatedly(Return(false));
8334 }
QUICHE teamb8343252019-04-29 13:58:01 -07008335 EXPECT_CALL(visitor_, SendProbingData()).WillRepeatedly([this] {
8336 return connection_.sent_packet_manager().MaybeRetransmitOldestPacket(
8337 PROBING_RETRANSMISSION);
8338 });
QUICHE teama6ef0a62019-03-07 20:34:33 -05008339 // Fix congestion window to be 20,000 bytes.
8340 EXPECT_CALL(*send_algorithm_, CanSend(Ge(20000u)))
8341 .WillRepeatedly(Return(false));
8342 EXPECT_CALL(*send_algorithm_, CanSend(Lt(20000u)))
8343 .WillRepeatedly(Return(true));
8344
8345 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
8346 ASSERT_EQ(0u, connection_.GetStats().packets_sent);
8347 connection_.set_fill_up_link_during_probing(true);
fayangedf9ad52020-03-05 13:49:18 -08008348 EXPECT_CALL(visitor_, GetHandshakeState())
fayang15042962020-07-01 12:14:29 -07008349 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
QUICHE teama6ef0a62019-03-07 20:34:33 -05008350 connection_.OnHandshakeComplete();
8351 connection_.SendStreamData3();
8352
8353 // We expect a lot of packets from a 20 kbyte window.
8354 EXPECT_GT(connection_.GetStats().packets_sent, 10u);
8355 // Ensure that the packets are padded.
8356 QuicByteCount average_packet_size =
8357 connection_.GetStats().bytes_sent / connection_.GetStats().packets_sent;
8358 EXPECT_GT(average_packet_size, 1000u);
8359
8360 // Acknowledge all packets sent, except for the last one.
8361 QuicAckFrame ack = InitAckFrame(
8362 connection_.sent_packet_manager().GetLargestSentPacket() - 1);
8363 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
8364 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8365
8366 // Ensure that since we no longer have retransmittable bytes in flight, this
8367 // will not cause any responses to be sent.
8368 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8369 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
8370 ProcessAckPacket(&ack);
8371}
8372
rchd672c6d2019-11-27 15:30:54 -08008373TEST_P(QuicConnectionTest, DoNotForceSendingAckOnPacketTooLarge) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008374 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8375 // Send an ack by simulating delayed ack alarm firing.
8376 ProcessPacket(1);
fayang9adfb532020-06-04 06:58:45 -07008377 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008378 connection_.GetAckAlarm()->Fire();
8379 // Simulate data packet causes write error.
fkastenholz5d880a92019-06-21 09:01:56 -07008380 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05008381 SimulateNextPacketTooLarge();
8382 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
rchd672c6d2019-11-27 15:30:54 -08008383 EXPECT_EQ(1u, writer_->connection_close_frames().size());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008384 // Ack frame is not bundled in connection close packet.
8385 EXPECT_TRUE(writer_->ack_frames().empty());
rchd672c6d2019-11-27 15:30:54 -08008386 if (writer_->padding_frames().empty()) {
8387 EXPECT_EQ(1u, writer_->frame_count());
8388 } else {
8389 EXPECT_EQ(2u, writer_->frame_count());
8390 }
8391
fkastenholz5d880a92019-06-21 09:01:56 -07008392 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008393}
8394
rchd672c6d2019-11-27 15:30:54 -08008395TEST_P(QuicConnectionTest, CloseConnectionAllLevels) {
fayangc303bfd2020-02-11 09:19:54 -08008396 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8397 return;
8398 }
rchd672c6d2019-11-27 15:30:54 -08008399
8400 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
8401 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
8402 connection_.CloseConnection(
8403 kQuicErrorCode, "Some random error message",
8404 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
8405
8406 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
8407
8408 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
8409 EXPECT_EQ(1u, writer_->connection_close_frames().size());
8410
8411 if (!connection_.version().CanSendCoalescedPackets()) {
8412 // Each connection close packet should be sent in distinct UDP packets.
8413 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
8414 writer_->connection_close_packets());
8415 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
8416 writer_->packets_write_attempts());
8417 return;
8418 }
8419
8420 // A single UDP packet should be sent with multiple connection close packets
8421 // coalesced together.
8422 EXPECT_EQ(1u, writer_->packets_write_attempts());
8423
8424 // Only the first packet has been processed yet.
8425 EXPECT_EQ(1u, writer_->connection_close_packets());
8426
8427 // ProcessPacket resets the visitor and frees the coalesced packet.
8428 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
8429 auto packet = writer_->coalesced_packet()->Clone();
8430 writer_->framer()->ProcessPacket(*packet);
8431 EXPECT_EQ(1u, writer_->connection_close_packets());
8432 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
8433}
8434
8435TEST_P(QuicConnectionTest, CloseConnectionOneLevel) {
fayangc303bfd2020-02-11 09:19:54 -08008436 if (connection_.SupportsMultiplePacketNumberSpaces()) {
8437 return;
8438 }
rchd672c6d2019-11-27 15:30:54 -08008439
8440 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
8441 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
8442 connection_.CloseConnection(
8443 kQuicErrorCode, "Some random error message",
8444 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
8445
8446 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
8447
8448 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
8449 EXPECT_EQ(1u, writer_->connection_close_frames().size());
8450 EXPECT_EQ(1u, writer_->connection_close_packets());
8451 EXPECT_EQ(1u, writer_->packets_write_attempts());
8452 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
8453}
8454
fayang9abdfec2020-02-13 12:34:58 -08008455TEST_P(QuicConnectionTest, DoNotPadServerInitialConnectionClose) {
8456 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8457 return;
8458 }
8459 set_perspective(Perspective::IS_SERVER);
8460
8461 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
8462 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
8463 connection_.CloseConnection(
8464 kQuicErrorCode, "Some random error message",
8465 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
8466
8467 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
8468
8469 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
8470 EXPECT_EQ(1u, writer_->connection_close_frames().size());
8471 EXPECT_TRUE(writer_->padding_frames().empty());
8472 EXPECT_EQ(ENCRYPTION_INITIAL, writer_->framer()->last_decrypted_level());
8473}
8474
QUICHE teama6ef0a62019-03-07 20:34:33 -05008475// Regression test for b/63620844.
8476TEST_P(QuicConnectionTest, FailedToWriteHandshakePacket) {
8477 SimulateNextPacketTooLarge();
fkastenholz5d880a92019-06-21 09:01:56 -07008478 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
QUICHE teama6ef0a62019-03-07 20:34:33 -05008479 .Times(1);
fkastenholz5d880a92019-06-21 09:01:56 -07008480
QUICHE teama6ef0a62019-03-07 20:34:33 -05008481 connection_.SendCryptoStreamData();
fkastenholz5d880a92019-06-21 09:01:56 -07008482 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008483}
8484
8485TEST_P(QuicConnectionTest, MaxPacingRate) {
8486 EXPECT_EQ(0, connection_.MaxPacingRate().ToBytesPerSecond());
8487 connection_.SetMaxPacingRate(QuicBandwidth::FromBytesPerSecond(100));
8488 EXPECT_EQ(100, connection_.MaxPacingRate().ToBytesPerSecond());
8489}
8490
8491TEST_P(QuicConnectionTest, ClientAlwaysSendConnectionId) {
8492 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
8493 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8494 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
8495 EXPECT_EQ(CONNECTION_ID_PRESENT,
8496 writer_->last_packet_header().destination_connection_id_included);
8497
8498 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8499 QuicConfig config;
8500 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
8501 connection_.SetFromConfig(config);
8502
8503 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8504 connection_.SendStreamDataWithString(3, "bar", 3, NO_FIN);
8505 // Verify connection id is still sent in the packet.
8506 EXPECT_EQ(CONNECTION_ID_PRESENT,
8507 writer_->last_packet_header().destination_connection_id_included);
8508}
8509
8510TEST_P(QuicConnectionTest, SendProbingRetransmissions) {
8511 MockQuicConnectionDebugVisitor debug_visitor;
8512 connection_.set_debug_visitor(&debug_visitor);
8513
8514 const QuicStreamId stream_id = 2;
8515 QuicPacketNumber last_packet;
8516 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
8517 SendStreamDataToPeer(stream_id, "bar", 3, NO_FIN, &last_packet);
8518 SendStreamDataToPeer(stream_id, "test", 6, NO_FIN, &last_packet);
8519
8520 const QuicByteCount old_bytes_in_flight =
8521 connection_.sent_packet_manager().GetBytesInFlight();
8522
8523 // Allow 9 probing retransmissions to be sent.
8524 {
8525 InSequence seq;
8526 EXPECT_CALL(*send_algorithm_, CanSend(_))
8527 .Times(9 * 2)
8528 .WillRepeatedly(Return(true));
8529 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(Return(false));
8530 }
8531 // Expect them retransmitted in cyclic order (foo, bar, test, foo, bar...).
8532 QuicPacketCount sent_count = 0;
fayangcff885a2019-10-22 07:39:04 -07008533 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _))
QUICHE teama6ef0a62019-03-07 20:34:33 -05008534 .WillRepeatedly(Invoke([this, &sent_count](const SerializedPacket&,
QUICHE teama6ef0a62019-03-07 20:34:33 -05008535 TransmissionType, QuicTime) {
8536 ASSERT_EQ(1u, writer_->stream_frames().size());
fayang58f71072019-11-05 08:47:02 -08008537 if (connection_.version().CanSendCoalescedPackets()) {
8538 // There is a delay of sending coalesced packet, so (6, 0, 3, 6,
8539 // 0...).
8540 EXPECT_EQ(3 * ((sent_count + 2) % 3),
8541 writer_->stream_frames()[0]->offset);
8542 } else {
8543 // Identify the frames by stream offset (0, 3, 6, 0, 3...).
8544 EXPECT_EQ(3 * (sent_count % 3), writer_->stream_frames()[0]->offset);
8545 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008546 sent_count++;
8547 }));
8548 EXPECT_CALL(*send_algorithm_, ShouldSendProbingPacket())
8549 .WillRepeatedly(Return(true));
QUICHE teamb8343252019-04-29 13:58:01 -07008550 EXPECT_CALL(visitor_, SendProbingData()).WillRepeatedly([this] {
8551 return connection_.sent_packet_manager().MaybeRetransmitOldestPacket(
8552 PROBING_RETRANSMISSION);
8553 });
QUICHE teama6ef0a62019-03-07 20:34:33 -05008554
8555 connection_.SendProbingRetransmissions();
8556
8557 // Ensure that the in-flight has increased.
8558 const QuicByteCount new_bytes_in_flight =
8559 connection_.sent_packet_manager().GetBytesInFlight();
8560 EXPECT_GT(new_bytes_in_flight, old_bytes_in_flight);
8561}
8562
8563// Ensure that SendProbingRetransmissions() does not retransmit anything when
8564// there are no outstanding packets.
8565TEST_P(QuicConnectionTest,
8566 SendProbingRetransmissionsFailsWhenNothingToRetransmit) {
8567 ASSERT_TRUE(connection_.sent_packet_manager().unacked_packets().empty());
8568
8569 MockQuicConnectionDebugVisitor debug_visitor;
8570 connection_.set_debug_visitor(&debug_visitor);
fayangcff885a2019-10-22 07:39:04 -07008571 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008572 EXPECT_CALL(*send_algorithm_, ShouldSendProbingPacket())
8573 .WillRepeatedly(Return(true));
QUICHE teamb8343252019-04-29 13:58:01 -07008574 EXPECT_CALL(visitor_, SendProbingData()).WillRepeatedly([this] {
8575 return connection_.sent_packet_manager().MaybeRetransmitOldestPacket(
8576 PROBING_RETRANSMISSION);
8577 });
QUICHE teama6ef0a62019-03-07 20:34:33 -05008578
8579 connection_.SendProbingRetransmissions();
8580}
8581
8582TEST_P(QuicConnectionTest, PingAfterLastRetransmittablePacketAcked) {
8583 const QuicTime::Delta retransmittable_on_wire_timeout =
8584 QuicTime::Delta::FromMilliseconds(50);
zhongyi79ace162019-10-21 15:57:09 -07008585 connection_.set_initial_retransmittable_on_wire_timeout(
QUICHE teama6ef0a62019-03-07 20:34:33 -05008586 retransmittable_on_wire_timeout);
8587
8588 EXPECT_TRUE(connection_.connected());
8589 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8590 .WillRepeatedly(Return(true));
8591
8592 const char data[] = "data";
8593 size_t data_size = strlen(data);
8594 QuicStreamOffset offset = 0;
8595
8596 // Advance 5ms, send a retransmittable packet to the peer.
8597 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8598 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8599 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8600 offset += data_size;
8601 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8602 // The ping alarm is set for the ping timeout, not the shorter
8603 // retransmittable_on_wire_timeout.
8604 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8605 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
zhongyieef848f2019-10-18 07:09:37 -07008606 EXPECT_EQ(ping_delay,
8607 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008608
8609 // Advance 5ms, send a second retransmittable packet to the peer.
8610 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8611 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8612 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8613 offset += data_size;
8614 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8615
8616 // Now receive an ACK of the first packet. This should not set the
8617 // retransmittable-on-wire alarm since packet 2 is still on the wire.
8618 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8619 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8620 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8621 QuicAckFrame frame =
8622 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8623 ProcessAckPacket(&frame);
8624 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8625 // The ping alarm is set for the ping timeout, not the shorter
8626 // retransmittable_on_wire_timeout.
8627 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8628 // The ping alarm has a 1 second granularity, and the clock has been advanced
8629 // 10ms since it was originally set.
zhongyieef848f2019-10-18 07:09:37 -07008630 EXPECT_EQ(ping_delay - QuicTime::Delta::FromMilliseconds(10),
8631 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008632
8633 // Now receive an ACK of the second packet. This should set the
8634 // retransmittable-on-wire alarm now that no retransmittable packets are on
8635 // the wire.
8636 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8637 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8638 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8639 ProcessAckPacket(&frame);
8640 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07008641 EXPECT_EQ(retransmittable_on_wire_timeout,
8642 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008643
8644 // Now receive a duplicate ACK of the second packet. This should not update
8645 // the ping alarm.
8646 QuicTime prev_deadline = connection_.GetPingAlarm()->deadline();
8647 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8648 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8649 ProcessAckPacket(&frame);
8650 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8651 EXPECT_EQ(prev_deadline, connection_.GetPingAlarm()->deadline());
8652
8653 // Now receive a non-ACK packet. This should not update the ping alarm.
8654 prev_deadline = connection_.GetPingAlarm()->deadline();
8655 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8656 ProcessPacket(4);
8657 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8658 EXPECT_EQ(prev_deadline, connection_.GetPingAlarm()->deadline());
8659
8660 // Simulate the alarm firing and check that a PING is sent.
8661 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8662 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
8663 }));
8664 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07008665 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05008666 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07008667 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008668 } else {
nharper55fa6132019-05-07 19:37:21 -07008669 EXPECT_EQ(padding_frame_count + 3u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008670 }
8671 ASSERT_EQ(1u, writer_->ping_frames().size());
8672}
8673
8674TEST_P(QuicConnectionTest, NoPingIfRetransmittablePacketSent) {
8675 const QuicTime::Delta retransmittable_on_wire_timeout =
8676 QuicTime::Delta::FromMilliseconds(50);
zhongyi79ace162019-10-21 15:57:09 -07008677 connection_.set_initial_retransmittable_on_wire_timeout(
QUICHE teama6ef0a62019-03-07 20:34:33 -05008678 retransmittable_on_wire_timeout);
8679
8680 EXPECT_TRUE(connection_.connected());
8681 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8682 .WillRepeatedly(Return(true));
8683
8684 const char data[] = "data";
8685 size_t data_size = strlen(data);
8686 QuicStreamOffset offset = 0;
8687
8688 // Advance 5ms, send a retransmittable packet to the peer.
8689 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8690 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8691 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8692 offset += data_size;
8693 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8694 // The ping alarm is set for the ping timeout, not the shorter
8695 // retransmittable_on_wire_timeout.
8696 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8697 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
zhongyieef848f2019-10-18 07:09:37 -07008698 EXPECT_EQ(ping_delay,
8699 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008700
8701 // Now receive an ACK of the first packet. This should set the
8702 // retransmittable-on-wire alarm now that no retransmittable packets are on
8703 // the wire.
8704 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8705 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8706 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8707 QuicAckFrame frame =
8708 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8709 ProcessAckPacket(&frame);
8710 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07008711 EXPECT_EQ(retransmittable_on_wire_timeout,
8712 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008713
8714 // Before the alarm fires, send another retransmittable packet. This should
8715 // cancel the retransmittable-on-wire alarm since now there's a
8716 // retransmittable packet on the wire.
8717 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8718 offset += data_size;
8719 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8720
8721 // Now receive an ACK of the second packet. This should set the
8722 // retransmittable-on-wire alarm now that no retransmittable packets are on
8723 // the wire.
8724 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8725 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8726 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8727 ProcessAckPacket(&frame);
8728 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07008729 EXPECT_EQ(retransmittable_on_wire_timeout,
8730 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008731
8732 // Simulate the alarm firing and check that a PING is sent.
8733 writer_->Reset();
8734 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8735 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
8736 }));
8737 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07008738 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05008739 if (GetParam().no_stop_waiting) {
fayang8a27b0f2019-11-04 11:27:40 -08008740 // Do not ACK acks.
8741 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008742 } else {
nharper55fa6132019-05-07 19:37:21 -07008743 EXPECT_EQ(padding_frame_count + 3u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008744 }
8745 ASSERT_EQ(1u, writer_->ping_frames().size());
8746}
8747
zhongyi79ace162019-10-21 15:57:09 -07008748// When there is no stream data received but are open streams, send the
8749// first few consecutive pings with aggressive retransmittable-on-wire
8750// timeout. Exponentially back off the retransmittable-on-wire ping timeout
8751// afterwards until it exceeds the default ping timeout.
8752TEST_P(QuicConnectionTest, BackOffRetransmittableOnWireTimeout) {
8753 int max_aggressive_retransmittable_on_wire_ping_count = 5;
8754 SetQuicFlag(FLAGS_quic_max_aggressive_retransmittable_on_wire_ping_count,
8755 max_aggressive_retransmittable_on_wire_ping_count);
8756 const QuicTime::Delta initial_retransmittable_on_wire_timeout =
8757 QuicTime::Delta::FromMilliseconds(200);
8758 connection_.set_initial_retransmittable_on_wire_timeout(
8759 initial_retransmittable_on_wire_timeout);
8760
8761 EXPECT_TRUE(connection_.connected());
8762 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8763 .WillRepeatedly(Return(true));
8764
8765 const char data[] = "data";
8766 // Advance 5ms, send a retransmittable data packet to the peer.
8767 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8768 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8769 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
8770 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8771 // The ping alarm is set for the ping timeout, not the shorter
8772 // retransmittable_on_wire_timeout.
8773 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8774 EXPECT_EQ(connection_.ping_timeout(),
8775 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8776
8777 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
8778 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
8779 .Times(AnyNumber());
8780
8781 // Verify that the first few consecutive retransmittable on wire pings are
8782 // sent with aggressive timeout.
8783 for (int i = 0; i <= max_aggressive_retransmittable_on_wire_ping_count; i++) {
8784 // Receive an ACK of the previous packet. This should set the ping alarm
8785 // with the initial retransmittable-on-wire timeout.
8786 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8787 QuicPacketNumber ack_num = creator_->packet_number();
8788 QuicAckFrame frame = InitAckFrame(
8789 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8790 ProcessAckPacket(&frame);
8791 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8792 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8793 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8794 // Simulate the alarm firing and check that a PING is sent.
8795 writer_->Reset();
8796 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8797 SendPing();
8798 }));
8799 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8800 connection_.GetPingAlarm()->Fire();
8801 }
8802
8803 QuicTime::Delta retransmittable_on_wire_timeout =
8804 initial_retransmittable_on_wire_timeout;
8805
8806 // Verify subsequent pings are sent with timeout that is exponentially backed
8807 // off.
8808 while (retransmittable_on_wire_timeout * 2 < connection_.ping_timeout()) {
8809 // Receive an ACK for the previous PING. This should set the
8810 // ping alarm with backed off retransmittable-on-wire timeout.
8811 retransmittable_on_wire_timeout = retransmittable_on_wire_timeout * 2;
8812 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8813 QuicPacketNumber ack_num = creator_->packet_number();
8814 QuicAckFrame frame = InitAckFrame(
8815 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8816 ProcessAckPacket(&frame);
8817 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8818 EXPECT_EQ(retransmittable_on_wire_timeout,
8819 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8820
8821 // Simulate the alarm firing and check that a PING is sent.
8822 writer_->Reset();
8823 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8824 SendPing();
8825 }));
8826 clock_.AdvanceTime(retransmittable_on_wire_timeout);
8827 connection_.GetPingAlarm()->Fire();
8828 }
8829
8830 // The ping alarm is set with default ping timeout.
8831 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8832 EXPECT_EQ(connection_.ping_timeout(),
8833 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8834
8835 // Receive an ACK for the previous PING. The ping alarm is set with an
8836 // earlier deadline.
8837 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8838 QuicPacketNumber ack_num = creator_->packet_number();
8839 QuicAckFrame frame = InitAckFrame(
8840 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8841 ProcessAckPacket(&frame);
8842 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8843 EXPECT_EQ(connection_.ping_timeout() - QuicTime::Delta::FromMilliseconds(5),
8844 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8845}
8846
8847// This test verify that the count of consecutive aggressive pings is reset
8848// when new data is received. And it also verifies the connection resets
8849// the exponential back-off of the retransmittable-on-wire ping timeout
8850// after receiving new stream data.
8851TEST_P(QuicConnectionTest, ResetBackOffRetransmitableOnWireTimeout) {
8852 int max_aggressive_retransmittable_on_wire_ping_count = 3;
8853 SetQuicFlag(FLAGS_quic_max_aggressive_retransmittable_on_wire_ping_count, 3);
8854 const QuicTime::Delta initial_retransmittable_on_wire_timeout =
8855 QuicTime::Delta::FromMilliseconds(200);
8856 connection_.set_initial_retransmittable_on_wire_timeout(
8857 initial_retransmittable_on_wire_timeout);
8858
8859 EXPECT_TRUE(connection_.connected());
8860 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8861 .WillRepeatedly(Return(true));
8862 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
8863 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
8864 .Times(AnyNumber());
8865
8866 const char data[] = "data";
8867 // Advance 5ms, send a retransmittable data packet to the peer.
8868 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8869 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8870 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
8871 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8872 // The ping alarm is set for the ping timeout, not the shorter
8873 // retransmittable_on_wire_timeout.
8874 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8875 EXPECT_EQ(connection_.ping_timeout(),
8876 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8877
8878 // Receive an ACK of the first packet. This should set the ping alarm with
8879 // initial retransmittable-on-wire timeout since there is no retransmittable
8880 // packet on the wire.
8881 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8882 QuicAckFrame frame =
8883 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8884 ProcessAckPacket(&frame);
8885 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8886 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8887 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8888
8889 // Simulate the alarm firing and check that a PING is sent.
8890 writer_->Reset();
8891 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
8892 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8893 connection_.GetPingAlarm()->Fire();
8894
8895 // Receive an ACK for the previous PING. Ping alarm will be set with
8896 // aggressive timeout.
8897 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8898 QuicPacketNumber ack_num = creator_->packet_number();
8899 frame = InitAckFrame(
8900 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8901 ProcessAckPacket(&frame);
8902 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8903 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8904 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8905
8906 // Process a data packet.
8907 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
8908 ProcessDataPacket(peer_creator_.packet_number() + 1);
8909 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_,
8910 peer_creator_.packet_number() + 1);
8911 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8912 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8913
8914 // Verify the count of consecutive aggressive pings is reset.
8915 for (int i = 0; i < max_aggressive_retransmittable_on_wire_ping_count; i++) {
8916 // Receive an ACK of the previous packet. This should set the ping alarm
8917 // with the initial retransmittable-on-wire timeout.
8918 QuicPacketNumber ack_num = creator_->packet_number();
8919 QuicAckFrame frame = InitAckFrame(
8920 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8921 ProcessAckPacket(&frame);
8922 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8923 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8924 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8925 // Simulate the alarm firing and check that a PING is sent.
8926 writer_->Reset();
8927 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8928 SendPing();
8929 }));
8930 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8931 connection_.GetPingAlarm()->Fire();
8932 // Advance 5ms to receive next packet.
8933 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8934 }
8935
8936 // Receive another ACK for the previous PING. This should set the
8937 // ping alarm with backed off retransmittable-on-wire timeout.
8938 ack_num = creator_->packet_number();
8939 frame = InitAckFrame(
8940 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8941 ProcessAckPacket(&frame);
8942 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8943 EXPECT_EQ(initial_retransmittable_on_wire_timeout * 2,
8944 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8945
8946 writer_->Reset();
8947 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
8948 clock_.AdvanceTime(2 * initial_retransmittable_on_wire_timeout);
8949 connection_.GetPingAlarm()->Fire();
8950
8951 // Process another data packet and a new ACK packet. The ping alarm is set
8952 // with aggressive ping timeout again.
8953 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
8954 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8955 ProcessDataPacket(peer_creator_.packet_number() + 1);
8956 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_,
8957 peer_creator_.packet_number() + 1);
8958 ack_num = creator_->packet_number();
8959 frame = InitAckFrame(
8960 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8961 ProcessAckPacket(&frame);
8962 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8963 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8964 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8965}
8966
QUICHE teama6ef0a62019-03-07 20:34:33 -05008967TEST_P(QuicConnectionTest, ValidStatelessResetToken) {
8968 const QuicUint128 kTestToken = 1010101;
8969 const QuicUint128 kWrongTestToken = 1010100;
8970 QuicConfig config;
8971 // No token has been received.
8972 EXPECT_FALSE(connection_.IsValidStatelessResetToken(kTestToken));
8973
8974 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(2);
8975 // Token is different from received token.
8976 QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestToken);
8977 connection_.SetFromConfig(config);
8978 EXPECT_FALSE(connection_.IsValidStatelessResetToken(kWrongTestToken));
8979
8980 QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestToken);
8981 connection_.SetFromConfig(config);
8982 EXPECT_TRUE(connection_.IsValidStatelessResetToken(kTestToken));
8983}
8984
8985TEST_P(QuicConnectionTest, WriteBlockedWithInvalidAck) {
8986 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayange62e63c2019-12-04 07:16:25 -08008987 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008988 BlockOnNextWrite();
fayange62e63c2019-12-04 07:16:25 -08008989 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008990 connection_.SendStreamDataWithString(5, "foo", 0, FIN);
8991 // This causes connection to be closed because packet 1 has not been sent yet.
8992 QuicAckFrame frame = InitAckFrame(1);
fayange62e63c2019-12-04 07:16:25 -08008993 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05008994 ProcessAckPacket(1, &frame);
fayange62e63c2019-12-04 07:16:25 -08008995 EXPECT_EQ(0, connection_close_frame_count_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008996}
8997
8998TEST_P(QuicConnectionTest, SendMessage) {
fayangc31c9952019-06-05 13:54:48 -07008999 if (!VersionSupportsMessageFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05009000 return;
9001 }
dschinazied459c02020-05-07 16:12:23 -07009002 if (connection_.version().UsesTls()) {
9003 QuicConfig config;
9004 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
9005 &config, kMaxAcceptedDatagramFrameSize);
9006 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9007 connection_.SetFromConfig(config);
9008 }
ianswettb239f862019-04-05 09:15:06 -07009009 std::string message(connection_.GetCurrentLargestMessagePayload() * 2, 'a');
dmcardlecf0bfcf2019-12-13 08:08:21 -08009010 quiche::QuicheStringPiece message_data(message);
QUICHE teama6ef0a62019-03-07 20:34:33 -05009011 QuicMemSliceStorage storage(nullptr, 0, nullptr, 0);
9012 {
fayanga4b37b22019-06-18 13:37:47 -07009013 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05009014 connection_.SendStreamData3();
9015 // Send a message which cannot fit into current open packet, and 2 packets
9016 // get sent, one contains stream frame, and the other only contains the
9017 // message frame.
9018 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
QUICHE team350e9e62019-11-19 13:16:24 -08009019 EXPECT_EQ(MESSAGE_STATUS_SUCCESS,
9020 connection_.SendMessage(
9021 1,
9022 MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(),
dmcardlecf0bfcf2019-12-13 08:08:21 -08009023 quiche::QuicheStringPiece(
QUICHE team350e9e62019-11-19 13:16:24 -08009024 message_data.data(),
9025 connection_.GetCurrentLargestMessagePayload()),
9026 &storage),
9027 false));
QUICHE teama6ef0a62019-03-07 20:34:33 -05009028 }
9029 // Fail to send a message if connection is congestion control blocked.
9030 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(Return(false));
QUICHE team350e9e62019-11-19 13:16:24 -08009031 EXPECT_EQ(MESSAGE_STATUS_BLOCKED,
9032 connection_.SendMessage(
9033 2,
9034 MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(),
9035 "message", &storage),
9036 false));
QUICHE teama6ef0a62019-03-07 20:34:33 -05009037
9038 // Always fail to send a message which cannot fit into one packet.
9039 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE team350e9e62019-11-19 13:16:24 -08009040 EXPECT_EQ(MESSAGE_STATUS_TOO_LARGE,
9041 connection_.SendMessage(
9042 3,
9043 MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(),
dmcardlecf0bfcf2019-12-13 08:08:21 -08009044 quiche::QuicheStringPiece(
QUICHE team350e9e62019-11-19 13:16:24 -08009045 message_data.data(),
9046 connection_.GetCurrentLargestMessagePayload() + 1),
9047 &storage),
9048 false));
QUICHE teama6ef0a62019-03-07 20:34:33 -05009049}
9050
dschinazied459c02020-05-07 16:12:23 -07009051TEST_P(QuicConnectionTest, GetCurrentLargestMessagePayload) {
9052 if (!connection_.version().SupportsMessageFrames()) {
9053 return;
9054 }
9055 // Force use of this encrypter to simplify test expectations by making sure
9056 // that the encryption overhead is constant across versions.
9057 connection_.SetEncrypter(ENCRYPTION_INITIAL,
9058 std::make_unique<TaggingEncrypter>(0x00));
9059 QuicPacketLength expected_largest_payload = 1319;
9060 if (connection_.version().SendsVariableLengthPacketNumberInLongHeader()) {
9061 expected_largest_payload += 3;
9062 }
9063 if (connection_.version().HasLongHeaderLengths()) {
9064 expected_largest_payload -= 2;
9065 }
9066 if (connection_.version().HasLengthPrefixedConnectionIds()) {
9067 expected_largest_payload -= 1;
9068 }
9069 if (connection_.version().UsesTls()) {
9070 // QUIC+TLS disallows DATAGRAM/MESSAGE frames before the handshake.
9071 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), 0);
9072 QuicConfig config;
9073 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
9074 &config, kMaxAcceptedDatagramFrameSize);
9075 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9076 connection_.SetFromConfig(config);
9077 // Verify the value post-handshake.
9078 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(),
9079 expected_largest_payload);
9080 } else {
9081 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(),
9082 expected_largest_payload);
9083 }
9084}
9085
9086TEST_P(QuicConnectionTest, GetGuaranteedLargestMessagePayload) {
9087 if (!connection_.version().SupportsMessageFrames()) {
9088 return;
9089 }
9090 // Force use of this encrypter to simplify test expectations by making sure
9091 // that the encryption overhead is constant across versions.
9092 connection_.SetEncrypter(ENCRYPTION_INITIAL,
9093 std::make_unique<TaggingEncrypter>(0x00));
9094 QuicPacketLength expected_largest_payload = 1319;
9095 if (connection_.version().HasLongHeaderLengths()) {
9096 expected_largest_payload -= 2;
9097 }
9098 if (connection_.version().HasLengthPrefixedConnectionIds()) {
9099 expected_largest_payload -= 1;
9100 }
9101 if (connection_.version().UsesTls()) {
9102 // QUIC+TLS disallows DATAGRAM/MESSAGE frames before the handshake.
9103 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(), 0);
9104 QuicConfig config;
9105 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
9106 &config, kMaxAcceptedDatagramFrameSize);
9107 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9108 connection_.SetFromConfig(config);
9109 // Verify the value post-handshake.
9110 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(),
9111 expected_largest_payload);
9112 } else {
9113 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(),
9114 expected_largest_payload);
9115 }
9116}
9117
9118TEST_P(QuicConnectionTest, LimitedLargestMessagePayload) {
9119 if (!connection_.version().SupportsMessageFrames() ||
9120 !connection_.version().UsesTls()) {
9121 return;
9122 }
9123 constexpr QuicPacketLength kFrameSizeLimit = 1000;
9124 constexpr QuicPacketLength kPayloadSizeLimit =
9125 kFrameSizeLimit - kQuicFrameTypeSize;
9126 // QUIC+TLS disallows DATAGRAM/MESSAGE frames before the handshake.
9127 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), 0);
9128 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(), 0);
9129 QuicConfig config;
9130 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(&config, kFrameSizeLimit);
9131 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9132 connection_.SetFromConfig(config);
9133 // Verify the value post-handshake.
9134 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), kPayloadSizeLimit);
9135 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(),
9136 kPayloadSizeLimit);
9137}
9138
QUICHE teama6ef0a62019-03-07 20:34:33 -05009139// Test to check that the path challenge/path response logic works
9140// correctly. This test is only for version-99
9141TEST_P(QuicConnectionTest, PathChallengeResponse) {
fkastenholz305e1732019-06-18 05:01:22 -07009142 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05009143 return;
9144 }
9145 // First check if we can probe from server to client and back
9146 set_perspective(Perspective::IS_SERVER);
9147 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
9148
9149 // Create and send the probe request (PATH_CHALLENGE frame).
9150 // SendConnectivityProbingPacket ends up calling
9151 // TestPacketWriter::WritePacket() which in turns receives and parses the
9152 // packet by calling framer_.ProcessPacket() -- which in turn calls
9153 // SimpleQuicFramer::OnPathChallengeFrame(). SimpleQuicFramer saves
9154 // the packet in writer_->path_challenge_frames()
9155 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9156 connection_.SendConnectivityProbingPacket(writer_.get(),
9157 connection_.peer_address());
9158 // Save the random contents of the challenge for later comparison to the
9159 // response.
nharper55fa6132019-05-07 19:37:21 -07009160 ASSERT_GE(writer_->path_challenge_frames().size(), 1u);
QUICHE teama6ef0a62019-03-07 20:34:33 -05009161 QuicPathFrameBuffer challenge_data =
9162 writer_->path_challenge_frames().front().data_buffer;
9163
9164 // Normally, QuicConnection::OnPathChallengeFrame and OnPaddingFrame would be
9165 // called and it will perform actions to ensure that the rest of the protocol
9166 // is performed (specifically, call UpdatePacketContent to say that this is a
9167 // path challenge so that when QuicConnection::OnPacketComplete is called
9168 // (again, out of the framer), the response is generated). Simulate those
9169 // calls so that the right internal state is set up for generating
9170 // the response.
9171 EXPECT_TRUE(connection_.OnPathChallengeFrame(
9172 writer_->path_challenge_frames().front()));
9173 EXPECT_TRUE(connection_.OnPaddingFrame(writer_->padding_frames().front()));
9174 // Cause the response to be created and sent. Result is that the response
9175 // should be stashed in writer's path_response_frames.
9176 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9177 connection_.SendConnectivityProbingResponsePacket(connection_.peer_address());
9178
9179 // The final check is to ensure that the random data in the response matches
9180 // the random data from the challenge.
9181 EXPECT_EQ(0, memcmp(&challenge_data,
9182 &(writer_->path_response_frames().front().data_buffer),
9183 sizeof(challenge_data)));
9184}
9185
zhongyi2da16be2020-06-17 11:05:23 -07009186TEST_P(QuicConnectionTest,
9187 RestartPathDegradingDetectionAfterMigrationWithProbe) {
9188 // TODO(b/150095484): add test coverage for IETF to verify that client takes
9189 // PATH RESPONSE with peer address change as correct validation on the new
9190 // path.
9191 if (GetParam().version.HasIetfQuicFrames()) {
9192 return;
9193 }
9194 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
dschinazi1c6e5922020-06-19 10:35:03 -07009195 PathProbeTestInit(Perspective::IS_CLIENT);
zhongyi2da16be2020-06-17 11:05:23 -07009196
9197 // Clear direct_peer_address and effective_peer_address.
9198 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
9199 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
9200 QuicSocketAddress());
9201 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
9202
9203 EXPECT_TRUE(connection_.connected());
9204 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
9205 .WillRepeatedly(Return(true));
9206 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
9207 EXPECT_FALSE(connection_.IsPathDegrading());
9208 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
9209
9210 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9211 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9212 } else {
9213 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
9214 }
9215 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
9216 kPeerAddress);
9217 EXPECT_EQ(kPeerAddress, connection_.peer_address());
9218 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
9219
9220 // Send data and verify the path degrading detection is set.
9221 const char data[] = "data";
9222 size_t data_size = strlen(data);
9223 QuicStreamOffset offset = 0;
9224 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
9225 offset += data_size;
9226
9227 // Verify the path degrading detection is in progress.
9228 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
9229 EXPECT_FALSE(connection_.IsPathDegrading());
9230 QuicTime ddl = connection_.GetBlackholeDetectorAlarm()->deadline();
9231
9232 // Simulate the firing of path degrading.
9233 clock_.AdvanceTime(ddl - clock_.ApproximateNow());
9234 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
9235 connection_.PathDegradingTimeout();
9236 EXPECT_TRUE(connection_.IsPathDegrading());
9237 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
9238
9239 // Simulate path degrading handling by sending a probe on an alternet path.
9240 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
9241 TestPacketWriter probing_writer(version(), &clock_);
9242 connection_.SendConnectivityProbingPacket(&probing_writer,
9243 connection_.peer_address());
9244 // Verify that path degrading detection is not reset.
9245 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
9246
9247 // Simulate successful path degrading handling by receiving probe response.
9248 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
9249
9250 if (!GetParam().version.HasIetfQuicFrames()) {
9251 EXPECT_CALL(visitor_,
9252 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
9253 .Times(1);
9254 } else {
9255 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
9256 }
9257 const QuicSocketAddress kNewSelfAddress =
9258 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
9259
9260 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
9261 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
9262 QuicEncryptedPacket(probing_packet->encrypted_buffer,
9263 probing_packet->encrypted_length),
9264 clock_.Now()));
9265 uint64_t num_probing_received =
9266 connection_.GetStats().num_connectivity_probing_received;
9267 ProcessReceivedPacket(kNewSelfAddress, kPeerAddress, *received);
9268
9269 EXPECT_EQ(num_probing_received + 1,
9270 connection_.GetStats().num_connectivity_probing_received);
9271 EXPECT_EQ(kPeerAddress, connection_.peer_address());
9272 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
9273 EXPECT_TRUE(connection_.IsPathDegrading());
9274
9275 // Verify new path degrading detection is activated.
9276 EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading()).Times(1);
9277 connection_.OnSuccessfulMigrationAfterProbing();
9278 EXPECT_FALSE(connection_.IsPathDegrading());
9279 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
9280}
9281
QUICHE teama6ef0a62019-03-07 20:34:33 -05009282// Regression test for b/110259444
9283TEST_P(QuicConnectionTest, DoNotScheduleSpuriousAckAlarm) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05009284 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9285 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
9286 writer_->SetWriteBlocked();
9287
9288 ProcessPacket(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05009289 // Verify ack alarm is set.
fayang9adfb532020-06-04 06:58:45 -07009290 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05009291 // Fire the ack alarm, verify no packet is sent because the writer is blocked.
9292 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9293 connection_.GetAckAlarm()->Fire();
9294
9295 writer_->SetWritable();
9296 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9297 ProcessPacket(2);
9298 // Verify ack alarm is not set.
fayang9adfb532020-06-04 06:58:45 -07009299 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05009300}
9301
9302TEST_P(QuicConnectionTest, DisablePacingOffloadConnectionOptions) {
9303 EXPECT_FALSE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
9304 writer_->set_supports_release_time(true);
9305 QuicConfig config;
9306 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9307 connection_.SetFromConfig(config);
9308 EXPECT_TRUE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
9309
9310 QuicTagVector connection_options;
9311 connection_options.push_back(kNPCO);
9312 config.SetConnectionOptionsToSend(connection_options);
9313 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9314 connection_.SetFromConfig(config);
9315 // Verify pacing offload is disabled.
9316 EXPECT_FALSE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
9317}
9318
9319// Regression test for b/110259444
9320// Get a path response without having issued a path challenge...
9321TEST_P(QuicConnectionTest, OrphanPathResponse) {
9322 QuicPathFrameBuffer data = {{0, 1, 2, 3, 4, 5, 6, 7}};
9323
9324 QuicPathResponseFrame frame(99, data);
9325 EXPECT_TRUE(connection_.OnPathResponseFrame(frame));
9326 // If PATH_RESPONSE was accepted (payload matches the payload saved
9327 // in QuicConnection::transmitted_connectivity_probe_payload_) then
9328 // current_packet_content_ would be set to FIRST_FRAME_IS_PING.
9329 // Since this PATH_RESPONSE does not match, current_packet_content_
9330 // must not be FIRST_FRAME_IS_PING.
9331 EXPECT_NE(QuicConnection::FIRST_FRAME_IS_PING,
9332 QuicConnectionPeer::GetCurrentPacketContent(&connection_));
9333}
9334
9335// Regression test for b/120791670
9336TEST_P(QuicConnectionTest, StopProcessingGQuicPacketInIetfQuicConnection) {
9337 // This test mimics a problematic scenario where an IETF QUIC connection
9338 // receives a Google QUIC packet and continue processing it using Google QUIC
9339 // wire format.
fayangd4291e42019-05-30 10:31:21 -07009340 if (!VersionHasIetfInvariantHeader(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05009341 return;
9342 }
9343 set_perspective(Perspective::IS_SERVER);
nharper46833c32019-05-15 21:33:05 -07009344 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07009345 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
9346 } else {
nharper46833c32019-05-15 21:33:05 -07009347 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
9348 }
wub8a5dafa2020-05-13 12:30:17 -07009349 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
9350 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05009351
9352 // Let connection process a Google QUIC packet.
9353 peer_framer_.set_version_for_tests(
9354 ParsedQuicVersion(PROTOCOL_QUIC_CRYPTO, QUIC_VERSION_43));
QUICHE team8c1daa22019-03-13 08:33:41 -07009355 std::unique_ptr<QuicPacket> packet(
QUICHE team6987b4a2019-03-15 16:23:04 -07009356 ConstructDataPacket(2, !kHasStopWaiting, ENCRYPTION_INITIAL));
dschinazi66dea072019-04-09 11:41:06 -07009357 char buffer[kMaxOutgoingPacketSize];
9358 size_t encrypted_length =
9359 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(2),
9360 *packet, buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05009361 // Make sure no stream frame is processed.
9362 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(0);
9363 connection_.ProcessUdpPacket(
9364 kSelfAddress, kPeerAddress,
9365 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
9366
9367 EXPECT_EQ(2u, connection_.GetStats().packets_received);
9368 EXPECT_EQ(1u, connection_.GetStats().packets_processed);
9369}
9370
9371TEST_P(QuicConnectionTest, AcceptPacketNumberZero) {
fkastenholz305e1732019-06-18 05:01:22 -07009372 if (!VersionHasIetfQuicFrames(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05009373 return;
9374 }
9375 // Set first_sending_packet_number to be 0 to allow successfully processing
9376 // acks which ack packet number 0.
9377 QuicFramerPeer::SetFirstSendingPacketNumber(writer_->framer()->framer(), 0);
9378 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9379
9380 ProcessPacket(0);
fayangc31c9952019-06-05 13:54:48 -07009381 EXPECT_EQ(QuicPacketNumber(0), LargestAcked(connection_.ack_frame()));
9382 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05009383
9384 ProcessPacket(1);
fayangc31c9952019-06-05 13:54:48 -07009385 EXPECT_EQ(QuicPacketNumber(1), LargestAcked(connection_.ack_frame()));
9386 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05009387
9388 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07009389 EXPECT_EQ(QuicPacketNumber(2), LargestAcked(connection_.ack_frame()));
9390 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05009391}
9392
QUICHE teamcd098022019-03-22 18:49:55 -07009393TEST_P(QuicConnectionTest, MultiplePacketNumberSpacesBasicSending) {
9394 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
9395 return;
9396 }
9397 use_tagging_decrypter();
9398 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07009399 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teamcd098022019-03-22 18:49:55 -07009400
9401 connection_.SendCryptoStreamData();
9402 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9403 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
9404 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
9405 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9406 QuicAckFrame frame1 = InitAckFrame(1);
9407 // Received ACK for packet 1.
9408 ProcessFramePacketAtLevel(30, QuicFrame(&frame1), ENCRYPTION_INITIAL);
9409
9410 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(4);
9411 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
9412 NO_FIN);
9413 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 4,
9414 NO_FIN);
9415 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
9416 8, NO_FIN);
9417 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
9418 12, FIN);
9419 // Received ACK for packets 2, 4, 5.
9420 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
9421 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
9422 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9423 QuicAckFrame frame2 =
9424 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)},
9425 {QuicPacketNumber(4), QuicPacketNumber(6)}});
9426 // Make sure although the same packet number is used, but they are in
9427 // different packet number spaces.
9428 ProcessFramePacketAtLevel(30, QuicFrame(&frame2), ENCRYPTION_FORWARD_SECURE);
9429}
9430
9431TEST_P(QuicConnectionTest, PeerAcksPacketsInWrongPacketNumberSpace) {
9432 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
9433 return;
9434 }
9435 use_tagging_decrypter();
9436 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07009437 std::make_unique<TaggingEncrypter>(0x01));
rch39c88ab2019-10-16 19:24:40 -07009438 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
9439 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teamcd098022019-03-22 18:49:55 -07009440
9441 connection_.SendCryptoStreamData();
9442 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9443 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
9444 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
9445 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9446 QuicAckFrame frame1 = InitAckFrame(1);
9447 // Received ACK for packet 1.
9448 ProcessFramePacketAtLevel(30, QuicFrame(&frame1), ENCRYPTION_INITIAL);
9449
9450 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
9451 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
9452 NO_FIN);
9453 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 4,
9454 NO_FIN);
9455
9456 // Received ACK for packets 2 and 3 in wrong packet number space.
9457 QuicAckFrame invalid_ack =
9458 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(4)}});
fkastenholz5d880a92019-06-21 09:01:56 -07009459 EXPECT_CALL(visitor_,
9460 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07009461 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teamcd098022019-03-22 18:49:55 -07009462 ProcessFramePacketAtLevel(300, QuicFrame(&invalid_ack), ENCRYPTION_INITIAL);
fkastenholz5d880a92019-06-21 09:01:56 -07009463 TestConnectionCloseQuicErrorCode(QUIC_INVALID_ACK_DATA);
QUICHE teamcd098022019-03-22 18:49:55 -07009464}
9465
9466TEST_P(QuicConnectionTest, MultiplePacketNumberSpacesBasicReceiving) {
9467 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
9468 return;
9469 }
9470 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
nharper46833c32019-05-15 21:33:05 -07009471 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9472 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9473 }
QUICHE teamcd098022019-03-22 18:49:55 -07009474 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
9475 use_tagging_decrypter();
9476 // Receives packet 1000 in initial data.
nharper46833c32019-05-15 21:33:05 -07009477 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
fayang9adfb532020-06-04 06:58:45 -07009478 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teamcd098022019-03-22 18:49:55 -07009479 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07009480 std::make_unique<TaggingEncrypter>(0x02));
zhongyi546cc452019-04-12 15:27:49 -07009481 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07009482 std::make_unique<StrictTaggingDecrypter>(0x02));
QUICHE teamcd098022019-03-22 18:49:55 -07009483 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07009484 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teamcd098022019-03-22 18:49:55 -07009485 // Receives packet 1000 in application data.
9486 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
fayang9adfb532020-06-04 06:58:45 -07009487 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teamcd098022019-03-22 18:49:55 -07009488 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
9489 NO_FIN);
9490 // Verify application data ACK gets bundled with outgoing data.
9491 EXPECT_EQ(2u, writer_->frame_count());
9492 // Make sure ACK alarm is still set because initial data is not ACKed.
fayang9adfb532020-06-04 06:58:45 -07009493 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teamcd098022019-03-22 18:49:55 -07009494 // Receive packet 1001 in application data.
9495 ProcessDataPacketAtLevel(1001, false, ENCRYPTION_ZERO_RTT);
9496 clock_.AdvanceTime(DefaultRetransmissionTime());
9497 // Simulates ACK alarm fires and verify two ACKs are flushed.
9498 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
9499 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07009500 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teamcd098022019-03-22 18:49:55 -07009501 connection_.GetAckAlarm()->Fire();
fayang9adfb532020-06-04 06:58:45 -07009502 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teamcd098022019-03-22 18:49:55 -07009503 // Receives more packets in application data.
9504 ProcessDataPacketAtLevel(1002, false, ENCRYPTION_ZERO_RTT);
fayang9adfb532020-06-04 06:58:45 -07009505 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teamcd098022019-03-22 18:49:55 -07009506
9507 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07009508 std::make_unique<TaggingEncrypter>(0x02));
zhongyi546cc452019-04-12 15:27:49 -07009509 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07009510 std::make_unique<StrictTaggingDecrypter>(0x02));
QUICHE teamcd098022019-03-22 18:49:55 -07009511 // Verify zero rtt and forward secure packets get acked in the same packet.
9512 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
nharper2c9f02a2019-05-08 10:25:50 -07009513 ProcessDataPacket(1003);
fayang9adfb532020-06-04 06:58:45 -07009514 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teamcd098022019-03-22 18:49:55 -07009515}
9516
QUICHE team552f71f2019-03-23 15:37:59 -07009517TEST_P(QuicConnectionTest, CancelAckAlarmOnWriteBlocked) {
9518 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
9519 return;
9520 }
9521 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
nharper46833c32019-05-15 21:33:05 -07009522 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9523 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9524 }
QUICHE team552f71f2019-03-23 15:37:59 -07009525 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
9526 use_tagging_decrypter();
9527 // Receives packet 1000 in initial data.
nharper46833c32019-05-15 21:33:05 -07009528 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
fayang9adfb532020-06-04 06:58:45 -07009529 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE team552f71f2019-03-23 15:37:59 -07009530 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07009531 std::make_unique<TaggingEncrypter>(0x02));
zhongyi546cc452019-04-12 15:27:49 -07009532 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07009533 std::make_unique<StrictTaggingDecrypter>(0x02));
QUICHE team552f71f2019-03-23 15:37:59 -07009534 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07009535 std::make_unique<TaggingEncrypter>(0x02));
QUICHE team552f71f2019-03-23 15:37:59 -07009536 // Receives packet 1000 in application data.
9537 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
fayang9adfb532020-06-04 06:58:45 -07009538 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE team552f71f2019-03-23 15:37:59 -07009539
9540 writer_->SetWriteBlocked();
9541 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AnyNumber());
9542 // Simulates ACK alarm fires and verify no ACK is flushed because of write
9543 // blocked.
9544 clock_.AdvanceTime(DefaultDelayedAckTime());
9545 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9546 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07009547 std::make_unique<TaggingEncrypter>(0x02));
QUICHE team552f71f2019-03-23 15:37:59 -07009548 connection_.GetAckAlarm()->Fire();
9549 // Verify ACK alarm is not set.
fayang9adfb532020-06-04 06:58:45 -07009550 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE team552f71f2019-03-23 15:37:59 -07009551
9552 writer_->SetWritable();
9553 // Verify 2 ACKs are sent when connection gets unblocked.
9554 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
9555 connection_.OnCanWrite();
fayang9adfb532020-06-04 06:58:45 -07009556 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE team552f71f2019-03-23 15:37:59 -07009557}
9558
dschinazi346b7ce2019-06-05 01:38:18 -07009559// Make sure a packet received with the right client connection ID is processed.
9560TEST_P(QuicConnectionTest, ValidClientConnectionId) {
dschinazi346b7ce2019-06-05 01:38:18 -07009561 if (!framer_.version().SupportsClientConnectionIds()) {
9562 return;
9563 }
9564 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9565 connection_.set_client_connection_id(TestConnectionId(0x33));
9566 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_FORWARD_SECURE);
9567 header.destination_connection_id = TestConnectionId(0x33);
9568 header.destination_connection_id_included = CONNECTION_ID_PRESENT;
9569 header.source_connection_id_included = CONNECTION_ID_ABSENT;
9570 QuicFrames frames;
9571 QuicPingFrame ping_frame;
9572 QuicPaddingFrame padding_frame;
9573 frames.push_back(QuicFrame(ping_frame));
9574 frames.push_back(QuicFrame(padding_frame));
9575 std::unique_ptr<QuicPacket> packet =
9576 BuildUnsizedDataPacket(&framer_, header, frames);
9577 char buffer[kMaxOutgoingPacketSize];
9578 size_t encrypted_length = peer_framer_.EncryptPayload(
9579 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
9580 kMaxOutgoingPacketSize);
9581 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9582 false);
9583 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9584 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9585 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9586}
9587
9588// Make sure a packet received with a different client connection ID is dropped.
9589TEST_P(QuicConnectionTest, InvalidClientConnectionId) {
dschinazi346b7ce2019-06-05 01:38:18 -07009590 if (!framer_.version().SupportsClientConnectionIds()) {
9591 return;
9592 }
9593 connection_.set_client_connection_id(TestConnectionId(0x33));
9594 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_FORWARD_SECURE);
9595 header.destination_connection_id = TestConnectionId(0xbad);
9596 header.destination_connection_id_included = CONNECTION_ID_PRESENT;
9597 header.source_connection_id_included = CONNECTION_ID_ABSENT;
9598 QuicFrames frames;
9599 QuicPingFrame ping_frame;
9600 QuicPaddingFrame padding_frame;
9601 frames.push_back(QuicFrame(ping_frame));
9602 frames.push_back(QuicFrame(padding_frame));
9603 std::unique_ptr<QuicPacket> packet =
9604 BuildUnsizedDataPacket(&framer_, header, frames);
9605 char buffer[kMaxOutgoingPacketSize];
9606 size_t encrypted_length = peer_framer_.EncryptPayload(
9607 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
9608 kMaxOutgoingPacketSize);
9609 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9610 false);
9611 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9612 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9613 EXPECT_EQ(1u, connection_.GetStats().packets_dropped);
9614}
9615
9616// Make sure the first packet received with a different client connection ID on
9617// the server is processed and it changes the client connection ID.
9618TEST_P(QuicConnectionTest, UpdateClientConnectionIdFromFirstPacket) {
dschinazi346b7ce2019-06-05 01:38:18 -07009619 if (!framer_.version().SupportsClientConnectionIds()) {
9620 return;
9621 }
dschinazi346b7ce2019-06-05 01:38:18 -07009622 set_perspective(Perspective::IS_SERVER);
9623 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_INITIAL);
9624 header.source_connection_id = TestConnectionId(0x33);
9625 header.source_connection_id_included = CONNECTION_ID_PRESENT;
9626 QuicFrames frames;
9627 QuicPingFrame ping_frame;
9628 QuicPaddingFrame padding_frame;
9629 frames.push_back(QuicFrame(ping_frame));
9630 frames.push_back(QuicFrame(padding_frame));
9631 std::unique_ptr<QuicPacket> packet =
9632 BuildUnsizedDataPacket(&framer_, header, frames);
9633 char buffer[kMaxOutgoingPacketSize];
nharperc6b99512019-09-19 11:13:48 -07009634 size_t encrypted_length =
9635 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(1),
9636 *packet, buffer, kMaxOutgoingPacketSize);
dschinazi346b7ce2019-06-05 01:38:18 -07009637 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9638 false);
9639 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9640 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9641 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9642 EXPECT_EQ(TestConnectionId(0x33), connection_.client_connection_id());
9643}
9644
fayang40ec3ac2019-06-05 09:07:54 -07009645// Regression test for b/134416344.
9646TEST_P(QuicConnectionTest, CheckConnectedBeforeFlush) {
9647 // This test mimics a scenario where a connection processes 2 packets and the
9648 // 2nd packet contains connection close frame. When the 2nd flusher goes out
9649 // of scope, a delayed ACK is pending, and ACK alarm should not be scheduled
9650 // because connection is disconnected.
9651 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fkastenholz5d880a92019-06-21 09:01:56 -07009652 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
fayang40ec3ac2019-06-05 09:07:54 -07009653 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
fkastenholz88d08f42019-09-06 07:38:04 -07009654 const QuicErrorCode kErrorCode = QUIC_INTERNAL_ERROR;
fayang40ec3ac2019-06-05 09:07:54 -07009655 std::unique_ptr<QuicConnectionCloseFrame> connection_close_frame(
fkastenholz591814c2019-09-06 12:11:46 -07009656 new QuicConnectionCloseFrame(connection_.transport_version(), kErrorCode,
9657 "",
9658 /*transport_close_frame_type=*/0));
9659
fayang40ec3ac2019-06-05 09:07:54 -07009660 // Received 2 packets.
fayang40ec3ac2019-06-05 09:07:54 -07009661 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
fayang40ec3ac2019-06-05 09:07:54 -07009662 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9663 } else {
fayang40ec3ac2019-06-05 09:07:54 -07009664 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
9665 }
wub8a5dafa2020-05-13 12:30:17 -07009666 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
9667 kPeerAddress);
fayang9adfb532020-06-04 06:58:45 -07009668 EXPECT_TRUE(connection_.HasPendingAcks());
wub8a5dafa2020-05-13 12:30:17 -07009669 ProcessFramePacketWithAddresses(QuicFrame(connection_close_frame.release()),
fayang40ec3ac2019-06-05 09:07:54 -07009670 kSelfAddress, kPeerAddress);
fayang0f0c4e62019-07-16 08:55:54 -07009671 // Verify ack alarm is not set.
fayang9adfb532020-06-04 06:58:45 -07009672 EXPECT_FALSE(connection_.HasPendingAcks());
fayang40ec3ac2019-06-05 09:07:54 -07009673}
9674
dschinazi8d551132019-08-02 19:17:16 -07009675// Verify that a packet containing three coalesced packets is parsed correctly.
9676TEST_P(QuicConnectionTest, CoalescedPacket) {
9677 if (!QuicVersionHasLongHeaderLengths(connection_.transport_version())) {
9678 // Coalesced packets can only be encoded using long header lengths.
9679 return;
9680 }
9681 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9682 EXPECT_TRUE(connection_.connected());
9683 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9684 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(3);
9685 } else {
9686 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(3);
9687 }
9688
9689 uint64_t packet_numbers[3] = {1, 2, 3};
9690 EncryptionLevel encryption_levels[3] = {
9691 ENCRYPTION_INITIAL, ENCRYPTION_INITIAL, ENCRYPTION_FORWARD_SECURE};
9692 char buffer[kMaxOutgoingPacketSize] = {};
9693 size_t total_encrypted_length = 0;
9694 for (int i = 0; i < 3; i++) {
9695 QuicPacketHeader header =
9696 ConstructPacketHeader(packet_numbers[i], encryption_levels[i]);
9697 QuicFrames frames;
9698 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9699 frames.push_back(QuicFrame(&crypto_frame_));
9700 } else {
9701 frames.push_back(QuicFrame(frame1_));
9702 }
9703 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
9704 peer_creator_.set_encryption_level(encryption_levels[i]);
9705 size_t encrypted_length = peer_framer_.EncryptPayload(
9706 encryption_levels[i], QuicPacketNumber(packet_numbers[i]), *packet,
9707 buffer + total_encrypted_length,
9708 sizeof(buffer) - total_encrypted_length);
9709 EXPECT_GT(encrypted_length, 0u);
9710 total_encrypted_length += encrypted_length;
9711 }
9712 connection_.ProcessUdpPacket(
9713 kSelfAddress, kPeerAddress,
9714 QuicReceivedPacket(buffer, total_encrypted_length, clock_.Now(), false));
9715 if (connection_.GetSendAlarm()->IsSet()) {
9716 connection_.GetSendAlarm()->Fire();
9717 }
9718
9719 EXPECT_TRUE(connection_.connected());
9720}
9721
dschinazi66fc0242019-08-16 10:00:25 -07009722// Regression test for crbug.com/992831.
9723TEST_P(QuicConnectionTest, CoalescedPacketThatSavesFrames) {
9724 if (!QuicVersionHasLongHeaderLengths(connection_.transport_version())) {
9725 // Coalesced packets can only be encoded using long header lengths.
9726 return;
9727 }
9728 if (connection_.SupportsMultiplePacketNumberSpaces()) {
9729 // TODO(b/129151114) Enable this test with multiple packet number spaces.
9730 return;
9731 }
9732 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9733 EXPECT_TRUE(connection_.connected());
9734 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9735 EXPECT_CALL(visitor_, OnCryptoFrame(_))
9736 .Times(3)
9737 .WillRepeatedly([this](const QuicCryptoFrame& /*frame*/) {
9738 // QuicFrame takes ownership of the QuicBlockedFrame.
9739 connection_.SendControlFrame(QuicFrame(new QuicBlockedFrame(1, 3)));
9740 });
9741 } else {
9742 EXPECT_CALL(visitor_, OnStreamFrame(_))
9743 .Times(3)
9744 .WillRepeatedly([this](const QuicStreamFrame& /*frame*/) {
9745 // QuicFrame takes ownership of the QuicBlockedFrame.
9746 connection_.SendControlFrame(QuicFrame(new QuicBlockedFrame(1, 3)));
9747 });
9748 }
9749
9750 uint64_t packet_numbers[3] = {1, 2, 3};
9751 EncryptionLevel encryption_levels[3] = {
9752 ENCRYPTION_INITIAL, ENCRYPTION_INITIAL, ENCRYPTION_FORWARD_SECURE};
9753 char buffer[kMaxOutgoingPacketSize] = {};
9754 size_t total_encrypted_length = 0;
9755 for (int i = 0; i < 3; i++) {
9756 QuicPacketHeader header =
9757 ConstructPacketHeader(packet_numbers[i], encryption_levels[i]);
9758 QuicFrames frames;
9759 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9760 frames.push_back(QuicFrame(&crypto_frame_));
9761 } else {
9762 frames.push_back(QuicFrame(frame1_));
9763 }
9764 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
9765 peer_creator_.set_encryption_level(encryption_levels[i]);
9766 size_t encrypted_length = peer_framer_.EncryptPayload(
9767 encryption_levels[i], QuicPacketNumber(packet_numbers[i]), *packet,
9768 buffer + total_encrypted_length,
9769 sizeof(buffer) - total_encrypted_length);
9770 EXPECT_GT(encrypted_length, 0u);
9771 total_encrypted_length += encrypted_length;
9772 }
9773 connection_.ProcessUdpPacket(
9774 kSelfAddress, kPeerAddress,
9775 QuicReceivedPacket(buffer, total_encrypted_length, clock_.Now(), false));
9776 if (connection_.GetSendAlarm()->IsSet()) {
9777 connection_.GetSendAlarm()->Fire();
9778 }
9779
9780 EXPECT_TRUE(connection_.connected());
9781
9782 SendAckPacketToPeer();
9783}
9784
fayangd3016832019-08-08 07:24:45 -07009785// Regresstion test for b/138962304.
9786TEST_P(QuicConnectionTest, RtoAndWriteBlocked) {
fayangd3016832019-08-08 07:24:45 -07009787 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9788
9789 QuicStreamId stream_id = 2;
9790 QuicPacketNumber last_data_packet;
9791 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
9792 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9793
9794 // Writer gets blocked.
9795 writer_->SetWriteBlocked();
9796
9797 // Cancel the stream.
9798 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9799 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
fayang67f82272019-08-14 16:08:45 -07009800 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
9801 .WillRepeatedly(
9802 Invoke(&notifier_, &SimpleSessionNotifier::WillingToWrite));
fayangd3016832019-08-08 07:24:45 -07009803 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9804
9805 // Retransmission timer fires in RTO mode.
9806 connection_.GetRetransmissionAlarm()->Fire();
9807 // Verify no packets get flushed when writer is blocked.
9808 EXPECT_EQ(0u, connection_.NumQueuedPackets());
9809}
9810
9811// Regresstion test for b/138962304.
9812TEST_P(QuicConnectionTest, TlpAndWriteBlocked) {
fayangd3016832019-08-08 07:24:45 -07009813 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9814 connection_.SetMaxTailLossProbes(1);
9815
9816 QuicStreamId stream_id = 2;
9817 QuicPacketNumber last_data_packet;
9818 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
9819 SendStreamDataToPeer(4, "foo", 0, NO_FIN, &last_data_packet);
9820 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9821
9822 // Writer gets blocked.
9823 writer_->SetWriteBlocked();
9824
9825 // Cancel stream 2.
9826 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9827 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
9828 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9829
fayange62e63c2019-12-04 07:16:25 -08009830 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
fayangd3016832019-08-08 07:24:45 -07009831 // Retransmission timer fires in TLP mode.
9832 connection_.GetRetransmissionAlarm()->Fire();
9833 // Verify one packets is forced flushed when writer is blocked.
9834 EXPECT_EQ(1u, connection_.NumQueuedPackets());
9835}
9836
fayang67f82272019-08-14 16:08:45 -07009837// Regresstion test for b/139375344.
9838TEST_P(QuicConnectionTest, RtoForcesSendingPing) {
fayangcff885a2019-10-22 07:39:04 -07009839 if (connection_.PtoEnabled()) {
fayang67f82272019-08-14 16:08:45 -07009840 return;
9841 }
9842 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9843 connection_.SetMaxTailLossProbes(2);
9844 EXPECT_EQ(0u, connection_.GetStats().tlp_count);
9845 EXPECT_EQ(0u, connection_.GetStats().rto_count);
9846
9847 SendStreamDataToPeer(2, "foo", 0, NO_FIN, nullptr);
9848 QuicTime retransmission_time =
9849 connection_.GetRetransmissionAlarm()->deadline();
9850 EXPECT_NE(QuicTime::Zero(), retransmission_time);
9851 // TLP fires.
9852 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
9853 clock_.AdvanceTime(retransmission_time - clock_.Now());
9854 connection_.GetRetransmissionAlarm()->Fire();
9855 EXPECT_EQ(1u, connection_.GetStats().tlp_count);
9856 EXPECT_EQ(0u, connection_.GetStats().rto_count);
9857 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9858
9859 // Packet 1 gets acked.
9860 QuicAckFrame frame = InitAckFrame(1);
9861 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
9862 ProcessAckPacket(1, &frame);
9863 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9864 retransmission_time = connection_.GetRetransmissionAlarm()->deadline();
9865
9866 // RTO fires, verify a PING packet gets sent because there is no data to send.
9867 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(3), _, _));
9868 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
9869 clock_.AdvanceTime(retransmission_time - clock_.Now());
9870 connection_.GetRetransmissionAlarm()->Fire();
9871 EXPECT_EQ(1u, connection_.GetStats().tlp_count);
9872 EXPECT_EQ(1u, connection_.GetStats().rto_count);
9873 EXPECT_EQ(1u, writer_->ping_frames().size());
9874}
9875
fayangce0a3162019-08-15 09:05:36 -07009876TEST_P(QuicConnectionTest, ProbeTimeout) {
fayangce0a3162019-08-15 09:05:36 -07009877 QuicConfig config;
9878 QuicTagVector connection_options;
9879 connection_options.push_back(k2PTO);
9880 config.SetConnectionOptionsToSend(connection_options);
9881 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9882 connection_.SetFromConfig(config);
9883 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9884
9885 QuicStreamId stream_id = 2;
9886 QuicPacketNumber last_packet;
9887 SendStreamDataToPeer(stream_id, "foooooo", 0, NO_FIN, &last_packet);
9888 SendStreamDataToPeer(stream_id, "foooooo", 7, NO_FIN, &last_packet);
9889 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9890
9891 // Reset stream.
9892 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9893 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9894
9895 // Fire the PTO and verify only the RST_STREAM is resent, not stream data.
9896 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9897 connection_.GetRetransmissionAlarm()->Fire();
9898 EXPECT_EQ(0u, writer_->stream_frames().size());
9899 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
9900 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9901}
9902
fayang97ce41e2019-10-07 08:37:29 -07009903TEST_P(QuicConnectionTest, CloseConnectionAfter6ClientPTOs) {
fayang97ce41e2019-10-07 08:37:29 -07009904 QuicConfig config;
9905 QuicTagVector connection_options;
9906 connection_options.push_back(k1PTO);
9907 connection_options.push_back(k6PTO);
9908 config.SetConnectionOptionsToSend(connection_options);
dschinazif7c6a912020-05-05 11:39:53 -07009909 QuicConfigPeer::SetNegotiated(&config, true);
dschinazie7c38a52020-05-29 15:25:45 -07009910 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
9911 QuicConfigPeer::SetReceivedOriginalConnectionId(
9912 &config, connection_.connection_id());
9913 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
9914 &config, connection_.connection_id());
9915 }
fayang97ce41e2019-10-07 08:37:29 -07009916 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9917 connection_.SetFromConfig(config);
fayang656cbb52020-06-09 13:29:35 -07009918 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangaa4f3f22020-06-05 16:22:00 -07009919 EXPECT_CALL(visitor_, GetHandshakeState())
9920 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
9921 }
fayang97ce41e2019-10-07 08:37:29 -07009922 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9923
9924 // Send stream data.
9925 SendStreamDataToPeer(
9926 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
9927 0, FIN, nullptr);
9928
fayang97ce41e2019-10-07 08:37:29 -07009929 // Fire the retransmission alarm 5 times.
9930 for (int i = 0; i < 5; ++i) {
ianswett825b48b2020-05-11 06:25:04 -07009931 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
fayang97ce41e2019-10-07 08:37:29 -07009932 connection_.GetRetransmissionAlarm()->Fire();
9933 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
9934 EXPECT_TRUE(connection_.connected());
9935 }
fayang2205d952020-05-12 13:45:56 -07009936 EXPECT_CALL(visitor_, OnPathDegrading());
9937 connection_.PathDegradingTimeout();
fayang97ce41e2019-10-07 08:37:29 -07009938
9939 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveTlpCount());
9940 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveRtoCount());
9941 EXPECT_EQ(5u, connection_.sent_packet_manager().GetConsecutivePtoCount());
9942 // Closes connection on 6th PTO.
ianswett825b48b2020-05-11 06:25:04 -07009943 // May send multiple connecction close packets with multiple PN spaces.
9944 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
fayang97ce41e2019-10-07 08:37:29 -07009945 EXPECT_CALL(visitor_,
9946 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
fayang2205d952020-05-12 13:45:56 -07009947 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
9948 connection_.GetBlackholeDetectorAlarm()->Fire();
fayang97ce41e2019-10-07 08:37:29 -07009949 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
9950 EXPECT_FALSE(connection_.connected());
9951 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
9952}
9953
fayangce0a3162019-08-15 09:05:36 -07009954TEST_P(QuicConnectionTest, CloseConnectionAfter7ClientPTOs) {
fayangce0a3162019-08-15 09:05:36 -07009955 QuicConfig config;
9956 QuicTagVector connection_options;
9957 connection_options.push_back(k2PTO);
9958 connection_options.push_back(k7PTO);
9959 config.SetConnectionOptionsToSend(connection_options);
dschinazif7c6a912020-05-05 11:39:53 -07009960 QuicConfigPeer::SetNegotiated(&config, true);
dschinazie7c38a52020-05-29 15:25:45 -07009961 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
9962 QuicConfigPeer::SetReceivedOriginalConnectionId(
9963 &config, connection_.connection_id());
9964 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
9965 &config, connection_.connection_id());
9966 }
fayangce0a3162019-08-15 09:05:36 -07009967 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9968 connection_.SetFromConfig(config);
fayang656cbb52020-06-09 13:29:35 -07009969 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangaa4f3f22020-06-05 16:22:00 -07009970 EXPECT_CALL(visitor_, GetHandshakeState())
9971 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
9972 }
fayangce0a3162019-08-15 09:05:36 -07009973 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9974
9975 // Send stream data.
9976 SendStreamDataToPeer(
9977 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
9978 0, FIN, nullptr);
9979
9980 // Fire the retransmission alarm 6 times.
9981 for (int i = 0; i < 6; ++i) {
9982 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
9983 connection_.GetRetransmissionAlarm()->Fire();
9984 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
9985 EXPECT_TRUE(connection_.connected());
9986 }
fayang2205d952020-05-12 13:45:56 -07009987 EXPECT_CALL(visitor_, OnPathDegrading());
9988 connection_.PathDegradingTimeout();
fayangce0a3162019-08-15 09:05:36 -07009989
9990 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveTlpCount());
9991 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveRtoCount());
9992 EXPECT_EQ(6u, connection_.sent_packet_manager().GetConsecutivePtoCount());
9993 // Closes connection on 7th PTO.
9994 EXPECT_CALL(visitor_,
9995 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07009996 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
fayang2205d952020-05-12 13:45:56 -07009997 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
9998 connection_.GetBlackholeDetectorAlarm()->Fire();
fayangce0a3162019-08-15 09:05:36 -07009999 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
10000 EXPECT_FALSE(connection_.connected());
10001 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
10002}
10003
10004TEST_P(QuicConnectionTest, CloseConnectionAfter8ClientPTOs) {
fayangce0a3162019-08-15 09:05:36 -070010005 QuicConfig config;
10006 QuicTagVector connection_options;
10007 connection_options.push_back(k2PTO);
10008 connection_options.push_back(k8PTO);
dschinazif7c6a912020-05-05 11:39:53 -070010009 QuicConfigPeer::SetNegotiated(&config, true);
dschinazie7c38a52020-05-29 15:25:45 -070010010 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
10011 QuicConfigPeer::SetReceivedOriginalConnectionId(
10012 &config, connection_.connection_id());
10013 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
10014 &config, connection_.connection_id());
10015 }
fayangce0a3162019-08-15 09:05:36 -070010016 config.SetConnectionOptionsToSend(connection_options);
10017 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10018 connection_.SetFromConfig(config);
fayang656cbb52020-06-09 13:29:35 -070010019 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangaa4f3f22020-06-05 16:22:00 -070010020 EXPECT_CALL(visitor_, GetHandshakeState())
10021 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
10022 }
fayangce0a3162019-08-15 09:05:36 -070010023 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
10024
10025 // Send stream data.
10026 SendStreamDataToPeer(
10027 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
10028 0, FIN, nullptr);
10029
10030 // Fire the retransmission alarm 7 times.
10031 for (int i = 0; i < 7; ++i) {
10032 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
10033 connection_.GetRetransmissionAlarm()->Fire();
10034 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
10035 EXPECT_TRUE(connection_.connected());
10036 }
fayang2205d952020-05-12 13:45:56 -070010037 EXPECT_CALL(visitor_, OnPathDegrading());
10038 connection_.PathDegradingTimeout();
fayangce0a3162019-08-15 09:05:36 -070010039
10040 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveTlpCount());
10041 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveRtoCount());
10042 EXPECT_EQ(7u, connection_.sent_packet_manager().GetConsecutivePtoCount());
10043 // Closes connection on 8th PTO.
10044 EXPECT_CALL(visitor_,
10045 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -070010046 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
fayang2205d952020-05-12 13:45:56 -070010047 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
10048 connection_.GetBlackholeDetectorAlarm()->Fire();
fayangce0a3162019-08-15 09:05:36 -070010049 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
10050 EXPECT_FALSE(connection_.connected());
10051 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
10052}
10053
fayang5f135052019-08-22 17:59:40 -070010054TEST_P(QuicConnectionTest, DeprecateHandshakeMode) {
10055 if (!connection_.version().SupportsAntiAmplificationLimit()) {
10056 return;
10057 }
10058 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10059 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
10060
10061 // Send CHLO.
10062 connection_.SendCryptoStreamData();
10063 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
10064
10065 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
10066 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
10067 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
10068 QuicAckFrame frame1 = InitAckFrame(1);
10069 // Received ACK for packet 1.
10070 ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL);
10071
10072 // Verify retransmission alarm is still set because handshake is not
10073 // confirmed although there is nothing in flight.
10074 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
10075 EXPECT_EQ(0u, connection_.GetStats().pto_count);
10076 EXPECT_EQ(0u, connection_.GetStats().crypto_retransmit_count);
10077
10078 // PTO fires, verify a PING packet gets sent because there is no data to send.
fayang5d011982020-05-13 14:14:38 -070010079 EXPECT_CALL(*send_algorithm_,
10080 OnPacketSent(_, _,
10081 GetQuicReloadableFlag(quic_default_on_pto)
10082 ? QuicPacketNumber(2)
10083 : QuicPacketNumber(3),
10084 _, _));
fayang5f135052019-08-22 17:59:40 -070010085 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
10086 connection_.GetRetransmissionAlarm()->Fire();
10087 EXPECT_EQ(1u, connection_.GetStats().pto_count);
fayangaf9903b2020-05-14 14:34:28 -070010088 EXPECT_EQ(1u, connection_.GetStats().crypto_retransmit_count);
fayang5f135052019-08-22 17:59:40 -070010089 EXPECT_EQ(1u, writer_->ping_frames().size());
10090}
10091
10092TEST_P(QuicConnectionTest, AntiAmplificationLimit) {
10093 if (!connection_.version().SupportsAntiAmplificationLimit()) {
10094 return;
10095 }
fayang5f135052019-08-22 17:59:40 -070010096 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10097
10098 set_perspective(Perspective::IS_SERVER);
10099 // Verify no data can be sent at the beginning because bytes received is 0.
10100 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
10101 connection_.SendCryptoDataWithString("foo", 0);
fayang6a258412020-05-28 08:57:12 -070010102 if (GetQuicReloadableFlag(quic_move_amplification_limit)) {
10103 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
10104 EXPECT_FALSE(connection_.CanWrite(NO_RETRANSMITTABLE_DATA));
10105 }
fayang5f135052019-08-22 17:59:40 -070010106 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
10107
10108 // Receives packet 1.
10109 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
10110
10111 const size_t anti_amplification_factor =
fayang6a258412020-05-28 08:57:12 -070010112 connection_.anti_amplification_factor();
fayang5f135052019-08-22 17:59:40 -070010113 // Verify now packets can be sent.
10114 for (size_t i = 0; i < anti_amplification_factor; ++i) {
10115 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10116 connection_.SendCryptoDataWithString("foo", i * 3);
10117 // Verify retransmission alarm is not set if throttled by anti-amplification
10118 // limit.
10119 EXPECT_EQ(i != anti_amplification_factor - 1,
10120 connection_.GetRetransmissionAlarm()->IsSet());
10121 }
10122 // Verify server is throttled by anti-amplification limit.
10123 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
10124 connection_.SendCryptoDataWithString("foo", anti_amplification_factor * 3);
10125
10126 // Receives packet 2.
10127 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
10128 // Verify more packets can be sent.
10129 for (size_t i = anti_amplification_factor; i < anti_amplification_factor * 2;
10130 ++i) {
10131 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10132 connection_.SendCryptoDataWithString("foo", i * 3);
10133 }
10134 // Verify server is throttled by anti-amplification limit.
10135 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
10136 connection_.SendCryptoDataWithString("foo",
10137 2 * anti_amplification_factor * 3);
10138
10139 ProcessPacket(3);
10140 // Verify anti-amplification limit is gone after address validation.
10141 for (size_t i = 0; i < 100; ++i) {
10142 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10143 connection_.SendStreamDataWithString(3, "first", i * 0, NO_FIN);
10144 }
10145}
10146
fayang6a258412020-05-28 08:57:12 -070010147TEST_P(QuicConnectionTest, AckPendingWithAmplificationLimited) {
10148 if (!connection_.version().SupportsAntiAmplificationLimit() ||
10149 !GetQuicReloadableFlag(quic_move_amplification_limit)) {
10150 return;
10151 }
10152 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10153 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(AnyNumber());
10154 set_perspective(Perspective::IS_SERVER);
10155 use_tagging_decrypter();
10156 connection_.SetEncrypter(ENCRYPTION_INITIAL,
10157 std::make_unique<TaggingEncrypter>(0x01));
10158 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10159 // Receives packet 1.
10160 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
10161 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10162 std::make_unique<TaggingEncrypter>(0x02));
10163 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
fayang9adfb532020-06-04 06:58:45 -070010164 EXPECT_TRUE(connection_.HasPendingAcks());
fayang6a258412020-05-28 08:57:12 -070010165 // Send response in different encryption level and cause amplification factor
10166 // throttled.
10167 size_t i = 0;
10168 while (connection_.CanWrite(HAS_RETRANSMITTABLE_DATA)) {
10169 connection_.SendCryptoDataWithString(std::string(1024, 'a'), i * 1024,
10170 ENCRYPTION_HANDSHAKE);
10171 ++i;
10172 }
10173 // Verify ACK is still pending.
fayang9adfb532020-06-04 06:58:45 -070010174 EXPECT_TRUE(connection_.HasPendingAcks());
fayang6a258412020-05-28 08:57:12 -070010175
10176 // Fire ACK alarm and verify ACK cannot be sent due to amplification factor.
10177 clock_.AdvanceTime(connection_.GetAckAlarm()->deadline() - clock_.Now());
10178 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
10179 connection_.GetAckAlarm()->Fire();
10180 // Verify ACK alarm is cancelled.
fayang9adfb532020-06-04 06:58:45 -070010181 EXPECT_FALSE(connection_.HasPendingAcks());
fayang6a258412020-05-28 08:57:12 -070010182
10183 // Receives packet 2 and verify ACK gets flushed.
10184 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10185 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
10186 EXPECT_FALSE(writer_->ack_frames().empty());
10187}
10188
fkastenholza3660102019-08-28 05:19:24 -070010189TEST_P(QuicConnectionTest, ConnectionCloseFrameType) {
10190 if (!VersionHasIetfQuicFrames(version().transport_version)) {
10191 // Test relevent only for IETF QUIC.
10192 return;
10193 }
10194 const QuicErrorCode kQuicErrorCode = IETF_QUIC_PROTOCOL_VIOLATION;
10195 // Use the (unknown) frame type of 9999 to avoid triggering any logic
10196 // which might be associated with the processing of a known frame type.
10197 const uint64_t kTransportCloseFrameType = 9999u;
10198 QuicFramerPeer::set_current_received_frame_type(
10199 QuicConnectionPeer::GetFramer(&connection_), kTransportCloseFrameType);
10200 // Do a transport connection close
10201 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10202 connection_.CloseConnection(
10203 kQuicErrorCode, "Some random error message",
10204 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10205 const std::vector<QuicConnectionCloseFrame>& connection_close_frames =
10206 writer_->connection_close_frames();
10207 ASSERT_EQ(1u, connection_close_frames.size());
10208 EXPECT_EQ(IETF_QUIC_TRANSPORT_CONNECTION_CLOSE,
10209 connection_close_frames[0].close_type);
bnc77e77b82020-04-05 10:36:49 -070010210 EXPECT_EQ(kQuicErrorCode, connection_close_frames[0].quic_error_code);
fkastenholza3660102019-08-28 05:19:24 -070010211 EXPECT_EQ(kTransportCloseFrameType,
10212 connection_close_frames[0].transport_close_frame_type);
10213}
10214
fayang0fcbf352019-08-30 11:15:58 -070010215// Regression test for b/137401387 and b/138962304.
10216TEST_P(QuicConnectionTest, RtoPacketAsTwo) {
fayangcff885a2019-10-22 07:39:04 -070010217 if (connection_.PtoEnabled()) {
fayang0fcbf352019-08-30 11:15:58 -070010218 return;
10219 }
10220 connection_.SetMaxTailLossProbes(1);
10221 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10222 std::string stream_data(3000, 's');
10223 // Send packets 1 - 66 and exhaust cwnd.
10224 for (size_t i = 0; i < 22; ++i) {
10225 // 3 packets for each stream, the first 2 are guaranteed to be full packets.
10226 SendStreamDataToPeer(i + 2, stream_data, 0, FIN, nullptr);
10227 }
10228 CongestionBlockWrites();
10229
10230 // Fires TLP. Please note, this tail loss probe has 1 byte less stream data
10231 // compared to packet 1 because packet number length increases.
10232 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(67), _, _));
10233 connection_.GetRetransmissionAlarm()->Fire();
10234 // Fires RTO. Please note, although packets 2 and 3 *should* be RTOed, but
10235 // packet 2 gets RTOed to two packets because packet number length increases.
10236 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(68), _, _));
10237 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(69), _, _));
10238 connection_.GetRetransmissionAlarm()->Fire();
10239
10240 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10241 // Resets all streams except 2 and ack packets 1 and 2. Now, packet 3 is the
10242 // only one containing retransmittable frames.
10243 for (size_t i = 1; i < 22; ++i) {
10244 notifier_.OnStreamReset(i + 2, QUIC_STREAM_CANCELLED);
10245 }
10246 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
10247 QuicAckFrame frame =
10248 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(3)}});
10249 ProcessAckPacket(1, &frame);
10250 CongestionUnblockWrites();
10251
10252 // Fires TLP, verify a PING gets sent because packet 3 is marked
10253 // RTO_RETRANSMITTED.
10254 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(70), _, _));
10255 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
10256 connection_.GetRetransmissionAlarm()->Fire();
10257}
10258
fayang4c1c2362019-09-13 07:20:01 -070010259TEST_P(QuicConnectionTest, PtoSkipsPacketNumber) {
fayang4c1c2362019-09-13 07:20:01 -070010260 QuicConfig config;
10261 QuicTagVector connection_options;
10262 connection_options.push_back(k1PTO);
10263 connection_options.push_back(kPTOS);
10264 config.SetConnectionOptionsToSend(connection_options);
10265 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10266 connection_.SetFromConfig(config);
10267 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
10268
10269 QuicStreamId stream_id = 2;
10270 QuicPacketNumber last_packet;
10271 SendStreamDataToPeer(stream_id, "foooooo", 0, NO_FIN, &last_packet);
10272 SendStreamDataToPeer(stream_id, "foooooo", 7, NO_FIN, &last_packet);
10273 EXPECT_EQ(QuicPacketNumber(2), last_packet);
10274 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
10275
10276 // Fire PTO and verify the PTO retransmission skips one packet number.
10277 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10278 connection_.GetRetransmissionAlarm()->Fire();
10279 EXPECT_EQ(1u, writer_->stream_frames().size());
10280 EXPECT_EQ(QuicPacketNumber(4), writer_->last_packet_header().packet_number);
10281 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
10282}
10283
fayang58f71072019-11-05 08:47:02 -080010284TEST_P(QuicConnectionTest, SendCoalescedPackets) {
10285 if (!connection_.version().CanSendCoalescedPackets()) {
10286 return;
10287 }
fayang6100ab72020-03-18 13:16:25 -070010288 MockQuicConnectionDebugVisitor debug_visitor;
10289 connection_.set_debug_visitor(&debug_visitor);
10290 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(3);
10291 EXPECT_CALL(debug_visitor, OnCoalescedPacketSent(_, _)).Times(1);
fayang44ae4e92020-04-28 13:09:42 -070010292 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
fayang58f71072019-11-05 08:47:02 -080010293 {
10294 QuicConnection::ScopedPacketFlusher flusher(&connection_);
10295 use_tagging_decrypter();
10296 connection_.SetEncrypter(ENCRYPTION_INITIAL,
10297 std::make_unique<TaggingEncrypter>(0x01));
10298 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10299 connection_.SendCryptoDataWithString("foo", 0);
10300 // Verify this packet is on hold.
10301 EXPECT_EQ(0u, writer_->packets_write_attempts());
10302
10303 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10304 std::make_unique<TaggingEncrypter>(0x02));
10305 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10306 connection_.SendCryptoDataWithString("bar", 3);
10307 EXPECT_EQ(0u, writer_->packets_write_attempts());
10308
10309 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
10310 std::make_unique<TaggingEncrypter>(0x03));
10311 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10312 SendStreamDataToPeer(2, "baz", 3, NO_FIN, nullptr);
10313 }
10314 // Verify all 3 packets are coalesced in the same UDP datagram.
10315 EXPECT_EQ(1u, writer_->packets_write_attempts());
10316 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
10317 // Verify the packet is padded to full.
10318 EXPECT_EQ(connection_.max_packet_length(), writer_->last_packet_size());
10319
10320 // Verify packet process.
10321 EXPECT_EQ(1u, writer_->crypto_frames().size());
10322 EXPECT_EQ(0u, writer_->stream_frames().size());
10323 // Verify there is coalesced packet.
10324 EXPECT_NE(nullptr, writer_->coalesced_packet());
10325}
10326
dschinazi6458eb32020-06-23 12:38:41 -070010327TEST_P(QuicConnectionTest, LegacyVersionEncapsulation) {
10328 connection_.EnableLegacyVersionEncapsulation("test.example.org");
10329
10330 MockQuicConnectionDebugVisitor debug_visitor;
10331 connection_.set_debug_visitor(&debug_visitor);
10332 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(1);
10333
10334 // Our TestPacketWriter normally parses the sent packet using the version
10335 // from the connection, so here we need to tell it to use the encapsulation
10336 // version, and reset the initial decrypter for that version.
10337 writer_->framer()->SetSupportedVersions(
10338 SupportedVersions(LegacyVersionForEncapsulation()));
10339 writer_->framer()->framer()->SetInitialObfuscators(
10340 connection_.connection_id());
10341
10342 {
10343 QuicConnection::ScopedPacketFlusher flusher(&connection_);
10344 connection_.SendCryptoDataWithString("TEST_CRYPTO_DATA", /*offset=*/0);
10345 }
10346
10347 EXPECT_EQ(1u, writer_->packets_write_attempts());
10348 // Verify that the packet is fully padded.
10349 EXPECT_EQ(connection_.max_packet_length(), writer_->last_packet_size());
10350
10351 // Check that the connection stats show Legacy Version Encapsulation was used.
10352 EXPECT_GT(connection_.GetStats().sent_legacy_version_encapsulated_packets,
10353 0u);
10354
10355 // Verify that the sent packet was in fact encapsulated, and check header.
10356 const QuicPacketHeader& encapsulated_header = writer_->last_packet_header();
10357 EXPECT_TRUE(encapsulated_header.version_flag);
10358 EXPECT_EQ(encapsulated_header.version, LegacyVersionForEncapsulation());
10359 EXPECT_EQ(encapsulated_header.destination_connection_id,
10360 connection_.connection_id());
10361
10362 // Encapsulated packet should contain a stream frame for the crypto stream,
10363 // optionally padding, and nothing else.
10364 EXPECT_EQ(0u, writer_->crypto_frames().size());
10365 EXPECT_EQ(1u, writer_->stream_frames().size());
10366 EXPECT_EQ(writer_->frame_count(), writer_->framer()->padding_frames().size() +
10367 writer_->stream_frames().size());
10368}
10369
fayang01062942020-01-22 07:23:23 -080010370TEST_P(QuicConnectionTest, ClientReceivedHandshakeDone) {
10371 if (!connection_.version().HasHandshakeDone()) {
10372 return;
10373 }
10374 EXPECT_CALL(visitor_, OnHandshakeDoneReceived());
10375 QuicFrames frames;
10376 frames.push_back(QuicFrame(QuicHandshakeDoneFrame()));
10377 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10378 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10379}
10380
10381TEST_P(QuicConnectionTest, ServerReceivedHandshakeDone) {
10382 if (!connection_.version().HasHandshakeDone()) {
10383 return;
10384 }
10385 set_perspective(Perspective::IS_SERVER);
10386 EXPECT_CALL(visitor_, OnHandshakeDoneReceived()).Times(0);
10387 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10388 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
10389 QuicFrames frames;
10390 frames.push_back(QuicFrame(QuicHandshakeDoneFrame()));
10391 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10392 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10393 EXPECT_EQ(1, connection_close_frame_count_);
10394 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
10395 IsError(IETF_QUIC_PROTOCOL_VIOLATION));
10396}
10397
fayang18ff23b2020-01-28 09:19:00 -080010398TEST_P(QuicConnectionTest, MultiplePacketNumberSpacePto) {
10399 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10400 return;
10401 }
10402 use_tagging_decrypter();
10403 // Send handshake packet.
10404 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10405 std::make_unique<TaggingEncrypter>(0x02));
10406 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
fayang44ae4e92020-04-28 13:09:42 -070010407 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
fayang18ff23b2020-01-28 09:19:00 -080010408 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
10409 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
10410
10411 // Send application data.
10412 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
10413 0, NO_FIN);
10414 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
10415 QuicTime retransmission_time =
10416 connection_.GetRetransmissionAlarm()->deadline();
10417 EXPECT_NE(QuicTime::Zero(), retransmission_time);
10418
10419 // Retransmit handshake data.
10420 clock_.AdvanceTime(retransmission_time - clock_.Now());
fayang5d011982020-05-13 14:14:38 -070010421 EXPECT_CALL(*send_algorithm_,
10422 OnPacketSent(_, _,
10423 GetQuicReloadableFlag(quic_default_on_pto)
10424 ? QuicPacketNumber(3)
10425 : QuicPacketNumber(4),
10426 _, _));
fayang44ae4e92020-04-28 13:09:42 -070010427 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
fayang18ff23b2020-01-28 09:19:00 -080010428 connection_.GetRetransmissionAlarm()->Fire();
10429 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
10430
10431 // Send application data.
10432 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
10433 4, NO_FIN);
10434 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
10435 retransmission_time = connection_.GetRetransmissionAlarm()->deadline();
10436 EXPECT_NE(QuicTime::Zero(), retransmission_time);
10437
10438 // Retransmit handshake data again.
10439 clock_.AdvanceTime(retransmission_time - clock_.Now());
fayang5d011982020-05-13 14:14:38 -070010440 EXPECT_CALL(*send_algorithm_,
10441 OnPacketSent(_, _,
10442 GetQuicReloadableFlag(quic_default_on_pto)
10443 ? QuicPacketNumber(5)
10444 : QuicPacketNumber(7),
10445 _, _));
fayang44ae4e92020-04-28 13:09:42 -070010446 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
fayang18ff23b2020-01-28 09:19:00 -080010447 connection_.GetRetransmissionAlarm()->Fire();
10448 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
10449
10450 // Discard handshake key.
10451 connection_.OnHandshakeComplete();
10452 retransmission_time = connection_.GetRetransmissionAlarm()->deadline();
10453 EXPECT_NE(QuicTime::Zero(), retransmission_time);
10454
10455 // Retransmit application data.
10456 clock_.AdvanceTime(retransmission_time - clock_.Now());
fayang5d011982020-05-13 14:14:38 -070010457 EXPECT_CALL(*send_algorithm_,
10458 OnPacketSent(_, _,
10459 GetQuicReloadableFlag(quic_default_on_pto)
10460 ? QuicPacketNumber(6)
10461 : QuicPacketNumber(9),
10462 _, _));
fayang18ff23b2020-01-28 09:19:00 -080010463 connection_.GetRetransmissionAlarm()->Fire();
10464 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
10465}
10466
dschinazie7c38a52020-05-29 15:25:45 -070010467void QuicConnectionTest::TestClientRetryHandling(
10468 bool invalid_retry_tag,
10469 bool missing_original_id_in_config,
10470 bool wrong_original_id_in_config,
10471 bool missing_retry_id_in_config,
10472 bool wrong_retry_id_in_config) {
dschinazi39e5e552020-05-06 13:55:24 -070010473 if (invalid_retry_tag) {
dschinazie7c38a52020-05-29 15:25:45 -070010474 ASSERT_FALSE(missing_original_id_in_config);
10475 ASSERT_FALSE(wrong_original_id_in_config);
10476 ASSERT_FALSE(missing_retry_id_in_config);
10477 ASSERT_FALSE(wrong_retry_id_in_config);
dschinazi39e5e552020-05-06 13:55:24 -070010478 } else {
dschinazie7c38a52020-05-29 15:25:45 -070010479 ASSERT_FALSE(missing_original_id_in_config && wrong_original_id_in_config);
10480 ASSERT_FALSE(missing_retry_id_in_config && wrong_retry_id_in_config);
dschinazi39e5e552020-05-06 13:55:24 -070010481 }
dschinazi278efae2020-01-28 17:03:09 -080010482 if (!version().HasRetryIntegrityTag()) {
10483 return;
10484 }
dschinazi39e5e552020-05-06 13:55:24 -070010485
10486 // These values come from draft-ietf-quic-tls Appendix A.4.
10487 char retry_packet25[] = {
10488 0xff, 0xff, 0x00, 0x00, 0x19, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a,
10489 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x1e, 0x5e, 0xc5, 0xb0,
10490 0x14, 0xcb, 0xb1, 0xf0, 0xfd, 0x93, 0xdf, 0x40, 0x48, 0xc4, 0x46, 0xa6};
10491 char retry_packet27[] = {
10492 0xff, 0xff, 0x00, 0x00, 0x1b, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a,
10493 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0xa5, 0x23, 0xcb, 0x5b,
10494 0xa5, 0x24, 0x69, 0x5f, 0x65, 0x69, 0xf2, 0x93, 0xa1, 0x35, 0x9d, 0x8e};
dschinazib3fed9e2020-06-11 11:59:33 -070010495 char retry_packet29[] = {
10496 0xff, 0xff, 0x00, 0x00, 0x1d, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a,
10497 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0xd1, 0x69, 0x26, 0xd8,
10498 0x1f, 0x6f, 0x9c, 0xa2, 0x95, 0x3a, 0x8a, 0xa4, 0x57, 0x5e, 0x1e, 0x49};
dschinazi39e5e552020-05-06 13:55:24 -070010499
10500 char* retry_packet;
10501 size_t retry_packet_length;
dschinazib3fed9e2020-06-11 11:59:33 -070010502 if (version() == ParsedQuicVersion::Draft29()) {
10503 retry_packet = retry_packet29;
10504 retry_packet_length = QUICHE_ARRAYSIZE(retry_packet29);
dschinazib3fed9e2020-06-11 11:59:33 -070010505 } else if (version() == ParsedQuicVersion::Draft27()) {
dschinazi39e5e552020-05-06 13:55:24 -070010506 retry_packet = retry_packet27;
10507 retry_packet_length = QUICHE_ARRAYSIZE(retry_packet27);
dschinazib3fed9e2020-06-11 11:59:33 -070010508 } else if (version() == ParsedQuicVersion::Draft25()) {
dschinazi39e5e552020-05-06 13:55:24 -070010509 retry_packet = retry_packet25;
10510 retry_packet_length = QUICHE_ARRAYSIZE(retry_packet25);
10511 } else {
dschinazi278efae2020-01-28 17:03:09 -080010512 // TODO(dschinazi) generate retry packets for all versions once we have
10513 // server-side support for generating these programmatically.
10514 return;
10515 }
10516
dschinazi278efae2020-01-28 17:03:09 -080010517 char original_connection_id_bytes[] = {0x83, 0x94, 0xc8, 0xf0,
10518 0x3e, 0x51, 0x57, 0x08};
10519 char new_connection_id_bytes[] = {0xf0, 0x67, 0xa5, 0x50,
10520 0x2a, 0x42, 0x62, 0xb5};
10521 char retry_token_bytes[] = {0x74, 0x6f, 0x6b, 0x65, 0x6e};
10522
10523 QuicConnectionId original_connection_id(
10524 original_connection_id_bytes,
10525 QUICHE_ARRAYSIZE(original_connection_id_bytes));
10526 QuicConnectionId new_connection_id(new_connection_id_bytes,
10527 QUICHE_ARRAYSIZE(new_connection_id_bytes));
10528
10529 std::string retry_token(retry_token_bytes,
10530 QUICHE_ARRAYSIZE(retry_token_bytes));
10531
dschinazi39e5e552020-05-06 13:55:24 -070010532 if (invalid_retry_tag) {
10533 // Flip the last bit of the retry packet to prevent the integrity tag
10534 // from validating correctly.
10535 retry_packet[retry_packet_length - 1] ^= 1;
dschinazi278efae2020-01-28 17:03:09 -080010536 }
10537
dschinazi39e5e552020-05-06 13:55:24 -070010538 QuicConnectionId config_original_connection_id = original_connection_id;
dschinazie7c38a52020-05-29 15:25:45 -070010539 if (wrong_original_id_in_config) {
dschinazi39e5e552020-05-06 13:55:24 -070010540 // Flip the first bit of the connection ID.
10541 ASSERT_FALSE(config_original_connection_id.IsEmpty());
10542 config_original_connection_id.mutable_data()[0] ^= 0x80;
10543 }
dschinazie7c38a52020-05-29 15:25:45 -070010544 QuicConnectionId config_retry_source_connection_id = new_connection_id;
10545 if (wrong_retry_id_in_config) {
10546 // Flip the first bit of the connection ID.
10547 ASSERT_FALSE(config_retry_source_connection_id.IsEmpty());
10548 config_retry_source_connection_id.mutable_data()[0] ^= 0x80;
10549 }
dschinazi278efae2020-01-28 17:03:09 -080010550
dschinazi39e5e552020-05-06 13:55:24 -070010551 // Make sure the connection uses the connection ID from the test vectors,
10552 QuicConnectionPeer::SetServerConnectionId(&connection_,
10553 original_connection_id);
dschinazi278efae2020-01-28 17:03:09 -080010554
dschinazi39e5e552020-05-06 13:55:24 -070010555 // Process the RETRY packet.
10556 connection_.ProcessUdpPacket(
10557 kSelfAddress, kPeerAddress,
10558 QuicReceivedPacket(retry_packet, retry_packet_length, clock_.Now()));
10559
10560 if (invalid_retry_tag) {
10561 // Make sure we refuse to process a RETRY with invalid tag.
10562 EXPECT_FALSE(connection_.GetStats().retry_packet_processed);
10563 EXPECT_EQ(connection_.connection_id(), original_connection_id);
dschinazi278efae2020-01-28 17:03:09 -080010564 EXPECT_TRUE(QuicPacketCreatorPeer::GetRetryToken(
dschinazi39e5e552020-05-06 13:55:24 -070010565 QuicConnectionPeer::GetPacketCreator(&connection_))
dschinazi278efae2020-01-28 17:03:09 -080010566 .empty());
dschinazi39e5e552020-05-06 13:55:24 -070010567 return;
dschinazi278efae2020-01-28 17:03:09 -080010568 }
dschinazi39e5e552020-05-06 13:55:24 -070010569
10570 // Make sure we correctly parsed the RETRY.
10571 EXPECT_TRUE(connection_.GetStats().retry_packet_processed);
10572 EXPECT_EQ(connection_.connection_id(), new_connection_id);
10573 EXPECT_EQ(QuicPacketCreatorPeer::GetRetryToken(
10574 QuicConnectionPeer::GetPacketCreator(&connection_)),
10575 retry_token);
10576 // Make sure our fake framer has the new post-retry INITIAL keys.
10577 writer_->framer()->framer()->SetInitialObfuscators(new_connection_id);
10578
10579 // Test validating the original_connection_id from the config.
10580 QuicConfig received_config;
10581 QuicConfigPeer::SetNegotiated(&received_config, true);
dschinazie7c38a52020-05-29 15:25:45 -070010582 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
10583 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
10584 &received_config, connection_.connection_id());
10585 if (!missing_retry_id_in_config) {
10586 QuicConfigPeer::SetReceivedRetrySourceConnectionId(
10587 &received_config, config_retry_source_connection_id);
10588 }
10589 }
10590 if (!missing_original_id_in_config) {
dschinazi39e5e552020-05-06 13:55:24 -070010591 QuicConfigPeer::SetReceivedOriginalConnectionId(
10592 &received_config, config_original_connection_id);
10593 }
dschinazie7c38a52020-05-29 15:25:45 -070010594
10595 if (missing_original_id_in_config || wrong_original_id_in_config ||
10596 missing_retry_id_in_config || wrong_retry_id_in_config) {
dschinazi39e5e552020-05-06 13:55:24 -070010597 EXPECT_CALL(visitor_,
10598 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10599 .Times(1);
10600 } else {
10601 EXPECT_CALL(visitor_,
10602 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10603 .Times(0);
10604 }
10605 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
10606 connection_.SetFromConfig(received_config);
dschinazie7c38a52020-05-29 15:25:45 -070010607 if (missing_original_id_in_config || wrong_original_id_in_config ||
10608 missing_retry_id_in_config || wrong_retry_id_in_config) {
10609 ASSERT_FALSE(connection_.connected());
dschinazi39e5e552020-05-06 13:55:24 -070010610 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
10611 } else {
10612 EXPECT_TRUE(connection_.connected());
10613 }
10614}
10615
10616TEST_P(QuicConnectionTest, ClientParsesRetry) {
10617 TestClientRetryHandling(/*invalid_retry_tag=*/false,
dschinazie7c38a52020-05-29 15:25:45 -070010618 /*missing_original_id_in_config=*/false,
10619 /*wrong_original_id_in_config=*/false,
10620 /*missing_retry_id_in_config=*/false,
10621 /*wrong_retry_id_in_config=*/false);
dschinazi39e5e552020-05-06 13:55:24 -070010622}
10623
dschinazie7c38a52020-05-29 15:25:45 -070010624TEST_P(QuicConnectionTest, ClientParsesRetryInvalidTag) {
dschinazi39e5e552020-05-06 13:55:24 -070010625 TestClientRetryHandling(/*invalid_retry_tag=*/true,
dschinazie7c38a52020-05-29 15:25:45 -070010626 /*missing_original_id_in_config=*/false,
10627 /*wrong_original_id_in_config=*/false,
10628 /*missing_retry_id_in_config=*/false,
10629 /*wrong_retry_id_in_config=*/false);
dschinazi39e5e552020-05-06 13:55:24 -070010630}
10631
dschinazie7c38a52020-05-29 15:25:45 -070010632TEST_P(QuicConnectionTest, ClientParsesRetryMissingOriginalId) {
dschinazi39e5e552020-05-06 13:55:24 -070010633 TestClientRetryHandling(/*invalid_retry_tag=*/false,
dschinazie7c38a52020-05-29 15:25:45 -070010634 /*missing_original_id_in_config=*/true,
10635 /*wrong_original_id_in_config=*/false,
10636 /*missing_retry_id_in_config=*/false,
10637 /*wrong_retry_id_in_config=*/false);
dschinazi39e5e552020-05-06 13:55:24 -070010638}
10639
dschinazie7c38a52020-05-29 15:25:45 -070010640TEST_P(QuicConnectionTest, ClientParsesRetryWrongOriginalId) {
dschinazi39e5e552020-05-06 13:55:24 -070010641 TestClientRetryHandling(/*invalid_retry_tag=*/false,
dschinazie7c38a52020-05-29 15:25:45 -070010642 /*missing_original_id_in_config=*/false,
10643 /*wrong_original_id_in_config=*/true,
10644 /*missing_retry_id_in_config=*/false,
10645 /*wrong_retry_id_in_config=*/false);
10646}
10647
10648TEST_P(QuicConnectionTest, ClientParsesRetryMissingRetryId) {
10649 if (!connection_.version().AuthenticatesHandshakeConnectionIds()) {
10650 // Versions that do not authenticate connection IDs never send the
10651 // retry_source_connection_id transport parameter.
10652 return;
10653 }
10654 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10655 /*missing_original_id_in_config=*/false,
10656 /*wrong_original_id_in_config=*/false,
10657 /*missing_retry_id_in_config=*/true,
10658 /*wrong_retry_id_in_config=*/false);
10659}
10660
10661TEST_P(QuicConnectionTest, ClientParsesRetryWrongRetryId) {
10662 if (!connection_.version().AuthenticatesHandshakeConnectionIds()) {
10663 // Versions that do not authenticate connection IDs never send the
10664 // retry_source_connection_id transport parameter.
10665 return;
10666 }
10667 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10668 /*missing_original_id_in_config=*/false,
10669 /*wrong_original_id_in_config=*/false,
10670 /*missing_retry_id_in_config=*/false,
10671 /*wrong_retry_id_in_config=*/true);
dschinazi39e5e552020-05-06 13:55:24 -070010672}
10673
10674TEST_P(QuicConnectionTest, ClientReceivesOriginalConnectionIdWithoutRetry) {
dschinazie7c38a52020-05-29 15:25:45 -070010675 if (!connection_.version().UsesTls()) {
10676 // QUIC+TLS is required to transmit connection ID transport parameters.
10677 return;
10678 }
10679 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
10680 // Versions that authenticate connection IDs always send the
10681 // original_destination_connection_id transport parameter.
10682 return;
10683 }
10684 // Make sure that receiving the original_destination_connection_id transport
10685 // parameter fails the handshake when no RETRY packet was received before it.
dschinazi39e5e552020-05-06 13:55:24 -070010686 QuicConfig received_config;
10687 QuicConfigPeer::SetNegotiated(&received_config, true);
10688 QuicConfigPeer::SetReceivedOriginalConnectionId(&received_config,
10689 TestConnectionId(0x12345));
10690 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
10691 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10692 .Times(1);
10693 connection_.SetFromConfig(received_config);
10694 EXPECT_FALSE(connection_.connected());
10695 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
dschinazi278efae2020-01-28 17:03:09 -080010696}
10697
dschinazie7c38a52020-05-29 15:25:45 -070010698TEST_P(QuicConnectionTest, ClientReceivesRetrySourceConnectionIdWithoutRetry) {
10699 if (!connection_.version().AuthenticatesHandshakeConnectionIds()) {
10700 // Versions that do not authenticate connection IDs never send the
10701 // retry_source_connection_id transport parameter.
10702 return;
10703 }
10704 // Make sure that receiving the retry_source_connection_id transport parameter
10705 // fails the handshake when no RETRY packet was received before it.
10706 QuicConfig received_config;
10707 QuicConfigPeer::SetNegotiated(&received_config, true);
10708 QuicConfigPeer::SetReceivedRetrySourceConnectionId(&received_config,
10709 TestConnectionId(0x12345));
10710 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
10711 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10712 .Times(1);
10713 connection_.SetFromConfig(received_config);
10714 EXPECT_FALSE(connection_.connected());
10715 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
10716}
10717
fayang0e3035e2020-02-03 13:30:36 -080010718// Regression test for http://crbug/1047977
10719TEST_P(QuicConnectionTest, MaxStreamsFrameCausesConnectionClose) {
10720 if (!VersionHasIetfQuicFrames(connection_.transport_version())) {
10721 return;
10722 }
10723 // Received frame causes connection close.
10724 EXPECT_CALL(visitor_, OnMaxStreamsFrame(_))
10725 .WillOnce(InvokeWithoutArgs([this]() {
10726 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10727 connection_.CloseConnection(
10728 QUIC_TOO_MANY_BUFFERED_CONTROL_FRAMES, "error",
10729 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10730 return true;
10731 }));
10732 QuicFrames frames;
10733 frames.push_back(QuicFrame(QuicMaxStreamsFrame()));
10734 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10735 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10736}
10737
10738TEST_P(QuicConnectionTest, StreamsBlockedFrameCausesConnectionClose) {
10739 if (!VersionHasIetfQuicFrames(connection_.transport_version())) {
10740 return;
10741 }
10742 // Received frame causes connection close.
10743 EXPECT_CALL(visitor_, OnStreamsBlockedFrame(_))
10744 .WillOnce(InvokeWithoutArgs([this]() {
10745 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10746 connection_.CloseConnection(
10747 QUIC_TOO_MANY_BUFFERED_CONTROL_FRAMES, "error",
10748 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10749 return true;
10750 }));
10751 QuicFrames frames;
10752 frames.push_back(
10753 QuicFrame(QuicStreamsBlockedFrame(kInvalidControlFrameId, 10, false)));
10754 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10755 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10756}
10757
fayang79400d52020-02-13 10:13:05 -080010758TEST_P(QuicConnectionTest,
10759 BundleAckWithConnectionCloseMultiplePacketNumberSpace) {
10760 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10761 return;
10762 }
10763 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10764 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10765 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
10766 // Receives packet 1000 in initial data.
10767 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
10768 // Receives packet 2000 in application data.
10769 ProcessDataPacketAtLevel(2000, false, ENCRYPTION_FORWARD_SECURE);
10770 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10771 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
10772 connection_.CloseConnection(
10773 kQuicErrorCode, "Some random error message",
10774 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10775
10776 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
10777
10778 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
10779 EXPECT_EQ(1u, writer_->connection_close_frames().size());
10780 // Verify ack is bundled.
10781 EXPECT_EQ(1u, writer_->ack_frames().size());
10782
10783 if (!connection_.version().CanSendCoalescedPackets()) {
10784 // Each connection close packet should be sent in distinct UDP packets.
10785 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
10786 writer_->connection_close_packets());
10787 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
10788 writer_->packets_write_attempts());
10789 return;
10790 }
10791
10792 // A single UDP packet should be sent with multiple connection close packets
10793 // coalesced together.
10794 EXPECT_EQ(1u, writer_->packets_write_attempts());
10795
10796 // Only the first packet has been processed yet.
10797 EXPECT_EQ(1u, writer_->connection_close_packets());
10798
10799 // ProcessPacket resets the visitor and frees the coalesced packet.
10800 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
10801 auto packet = writer_->coalesced_packet()->Clone();
10802 writer_->framer()->ProcessPacket(*packet);
10803 EXPECT_EQ(1u, writer_->connection_close_packets());
10804 EXPECT_EQ(1u, writer_->connection_close_frames().size());
10805 // Verify ack is bundled.
10806 EXPECT_EQ(1u, writer_->ack_frames().size());
10807 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
10808}
10809
fayang61453cb2020-03-11 11:32:26 -070010810// Regression test for b/151220135.
10811TEST_P(QuicConnectionTest, SendPingWhenSkipPacketNumberForPto) {
10812 if (!VersionSupportsMessageFrames(connection_.transport_version())) {
10813 return;
10814 }
10815 QuicConfig config;
10816 QuicTagVector connection_options;
10817 connection_options.push_back(kPTOS);
10818 connection_options.push_back(k1PTO);
10819 config.SetConnectionOptionsToSend(connection_options);
dschinazied459c02020-05-07 16:12:23 -070010820 if (connection_.version().UsesTls()) {
10821 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
10822 &config, kMaxAcceptedDatagramFrameSize);
10823 }
fayang61453cb2020-03-11 11:32:26 -070010824 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10825 connection_.SetFromConfig(config);
10826 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
10827
10828 EXPECT_EQ(MESSAGE_STATUS_SUCCESS, SendMessage("message"));
10829 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
10830
fayang80f9cc62020-04-22 08:08:20 -070010831 // PTO fires, verify a PING packet gets sent because there is no data to
10832 // send.
10833 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(3), _, _));
10834 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
fayang61453cb2020-03-11 11:32:26 -070010835 connection_.GetRetransmissionAlarm()->Fire();
fayang80f9cc62020-04-22 08:08:20 -070010836 EXPECT_EQ(1u, connection_.GetStats().pto_count);
10837 EXPECT_EQ(0u, connection_.GetStats().crypto_retransmit_count);
10838 EXPECT_EQ(1u, writer_->ping_frames().size());
fayang61453cb2020-03-11 11:32:26 -070010839}
10840
fayangcc210e72020-05-05 14:41:34 -070010841// Regression test for b/155757133
10842TEST_P(QuicConnectionTest, DonotChangeQueuedAcks) {
10843 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10844 return;
10845 }
10846 const size_t kMinRttMs = 40;
10847 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
10848 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
10849 QuicTime::Delta::Zero(), QuicTime::Zero());
10850 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10851 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
10852 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10853
10854 ProcessPacket(2);
10855 ProcessPacket(3);
10856 ProcessPacket(4);
10857 // Process a packet containing stream frame followed by ACK of packets 1.
10858 QuicFrames frames;
10859 frames.push_back(QuicFrame(QuicStreamFrame(
10860 QuicUtils::GetFirstBidirectionalStreamId(
10861 connection_.version().transport_version, Perspective::IS_CLIENT),
10862 false, 0u, quiche::QuicheStringPiece())));
10863 QuicAckFrame ack_frame = InitAckFrame(1);
10864 frames.push_back(QuicFrame(&ack_frame));
10865 // Receiving stream frame causes something to send.
10866 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([this]() {
10867 connection_.SendControlFrame(QuicFrame(new QuicWindowUpdateFrame(1, 0, 0)));
10868 // Verify now the queued ACK contains packet number 2.
10869 EXPECT_TRUE(QuicPacketCreatorPeer::QueuedFrames(
10870 QuicConnectionPeer::GetPacketCreator(&connection_))[0]
10871 .ack_frame->packets.Contains(QuicPacketNumber(2)));
10872 }));
10873 ProcessFramesPacketAtLevel(9, frames, ENCRYPTION_FORWARD_SECURE);
fayang97da12c2020-06-29 08:22:42 -070010874 EXPECT_TRUE(writer_->ack_frames()[0].packets.Contains(QuicPacketNumber(2)));
fayangcc210e72020-05-05 14:41:34 -070010875}
10876
fayange9304002020-05-07 11:57:48 -070010877TEST_P(QuicConnectionTest, DonotExtendIdleTimeOnUndecryptablePackets) {
10878 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10879 QuicConfig config;
10880 connection_.SetFromConfig(config);
10881 // Subtract a second from the idle timeout on the client side.
10882 QuicTime initial_deadline =
10883 clock_.ApproximateNow() +
10884 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
10885 EXPECT_EQ(initial_deadline, connection_.GetTimeoutAlarm()->deadline());
10886
10887 // Received an undecryptable packet.
10888 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
10889 const uint8_t tag = 0x07;
10890 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
10891 std::make_unique<TaggingEncrypter>(tag));
10892 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
fayang655bb412020-06-24 10:20:47 -070010893 // Verify deadline does not get extended.
10894 EXPECT_EQ(initial_deadline, connection_.GetTimeoutAlarm()->deadline());
10895 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
fayange9304002020-05-07 11:57:48 -070010896 QuicTime::Delta delay = initial_deadline - clock_.ApproximateNow();
10897 clock_.AdvanceTime(delay);
fayang655bb412020-06-24 10:20:47 -070010898 connection_.GetTimeoutAlarm()->Fire();
10899 // Verify connection gets closed.
10900 EXPECT_FALSE(connection_.connected());
fayange9304002020-05-07 11:57:48 -070010901}
10902
fayang9f430a52020-05-08 07:28:33 -070010903TEST_P(QuicConnectionTest, BundleAckWithImmediateResponse) {
10904 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10905 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10906
10907 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([this]() {
10908 connection_.SendControlFrame(QuicFrame(new QuicWindowUpdateFrame(1, 0, 0)));
10909 }));
10910 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10911 ProcessDataPacket(1);
fayangf0fa58f2020-06-24 09:13:11 -070010912 // Verify ACK is bundled with WINDOW_UPDATE.
10913 EXPECT_FALSE(writer_->ack_frames().empty());
10914 EXPECT_FALSE(connection_.HasPendingAcks());
fayang9f430a52020-05-08 07:28:33 -070010915}
10916
fayangf44a6672020-05-27 12:51:45 -070010917TEST_P(QuicConnectionTest, AckAlarmFiresEarly) {
10918 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10919 return;
10920 }
10921 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10922 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
10923 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10924 }
10925 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
10926 use_tagging_decrypter();
10927 // Receives packet 1000 in initial data.
10928 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
fayang9adfb532020-06-04 06:58:45 -070010929 EXPECT_TRUE(connection_.HasPendingAcks());
fayangf44a6672020-05-27 12:51:45 -070010930
10931 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
10932 std::make_unique<TaggingEncrypter>(0x02));
10933 SetDecrypter(ENCRYPTION_ZERO_RTT,
10934 std::make_unique<StrictTaggingDecrypter>(0x02));
10935 connection_.SetEncrypter(ENCRYPTION_INITIAL,
10936 std::make_unique<TaggingEncrypter>(0x02));
10937 // Receives packet 1000 in application data.
10938 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
fayang9adfb532020-06-04 06:58:45 -070010939 EXPECT_TRUE(connection_.HasPendingAcks());
fayangf44a6672020-05-27 12:51:45 -070010940 // Verify ACK deadline does not change.
10941 EXPECT_EQ(clock_.ApproximateNow() + kAlarmGranularity,
10942 connection_.GetAckAlarm()->deadline());
10943
10944 // Ack alarm fires early.
10945 if (GetQuicReloadableFlag(quic_always_send_earliest_ack)) {
10946 // Verify the earliest ACK is flushed.
10947 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10948 } else {
10949 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
10950 }
10951 connection_.GetAckAlarm()->Fire();
fayang9adfb532020-06-04 06:58:45 -070010952 EXPECT_TRUE(connection_.HasPendingAcks());
fayangf44a6672020-05-27 12:51:45 -070010953 if (GetQuicReloadableFlag(quic_always_send_earliest_ack)) {
10954 EXPECT_EQ(clock_.ApproximateNow() + DefaultDelayedAckTime(),
10955 connection_.GetAckAlarm()->deadline());
10956 } else {
10957 // No forward progress has been made.
10958 EXPECT_EQ(clock_.ApproximateNow() + kAlarmGranularity,
10959 connection_.GetAckAlarm()->deadline());
10960 }
10961}
10962
fayangf78b6932020-06-08 08:36:45 -070010963TEST_P(QuicConnectionTest, ClientOnlyBlackholeDetectionClient) {
fayang656cbb52020-06-09 13:29:35 -070010964 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangf78b6932020-06-08 08:36:45 -070010965 return;
10966 }
10967 QuicConfig config;
10968 QuicTagVector connection_options;
10969 connection_options.push_back(kCBHD);
10970 config.SetConnectionOptionsToSend(connection_options);
10971 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10972 connection_.SetFromConfig(config);
10973 EXPECT_CALL(visitor_, GetHandshakeState())
10974 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
10975 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
10976 // Send stream data.
10977 SendStreamDataToPeer(
10978 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
10979 0, FIN, nullptr);
10980 // Verify blackhole detection is in progress.
10981 EXPECT_TRUE(connection_.GetBlackholeDetectorAlarm()->IsSet());
10982}
10983
10984TEST_P(QuicConnectionTest, ClientOnlyBlackholeDetectionServer) {
fayang656cbb52020-06-09 13:29:35 -070010985 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangf78b6932020-06-08 08:36:45 -070010986 return;
10987 }
10988 set_perspective(Perspective::IS_SERVER);
10989 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
10990 if (version().SupportsAntiAmplificationLimit()) {
10991 QuicConnectionPeer::SetAddressValidated(&connection_);
10992 }
10993 QuicConfig config;
10994 QuicTagVector connection_options;
10995 connection_options.push_back(kCBHD);
10996 config.SetInitialReceivedConnectionOptions(connection_options);
10997 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10998 connection_.SetFromConfig(config);
10999 EXPECT_CALL(visitor_, GetHandshakeState())
11000 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
11001 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
11002 // Send stream data.
11003 SendStreamDataToPeer(
11004 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
11005 0, FIN, nullptr);
11006 // Verify blackhole detection is disabled.
11007 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
11008}
11009
11010TEST_P(QuicConnectionTest, 2RtoBlackholeDetection) {
fayang656cbb52020-06-09 13:29:35 -070011011 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangf78b6932020-06-08 08:36:45 -070011012 return;
11013 }
11014 QuicConfig config;
11015 QuicTagVector connection_options;
11016 connection_options.push_back(k2RTO);
11017 config.SetConnectionOptionsToSend(connection_options);
11018 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11019 connection_.SetFromConfig(config);
11020 const size_t kMinRttMs = 40;
11021 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
11022 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
11023 QuicTime::Delta::Zero(), QuicTime::Zero());
11024 EXPECT_CALL(visitor_, GetHandshakeState())
11025 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
11026 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
11027 // Send stream data.
11028 SendStreamDataToPeer(
11029 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
11030 0, FIN, nullptr);
11031 // Verify blackhole delay is expected.
11032 EXPECT_EQ(clock_.Now() +
11033 connection_.sent_packet_manager().GetNetworkBlackholeDelay(2),
11034 QuicConnectionPeer::GetBlackholeDetectionDeadline(&connection_));
11035}
11036
11037TEST_P(QuicConnectionTest, 3RtoBlackholeDetection) {
fayang656cbb52020-06-09 13:29:35 -070011038 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangf78b6932020-06-08 08:36:45 -070011039 return;
11040 }
11041 QuicConfig config;
11042 QuicTagVector connection_options;
11043 connection_options.push_back(k3RTO);
11044 config.SetConnectionOptionsToSend(connection_options);
11045 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11046 connection_.SetFromConfig(config);
11047 const size_t kMinRttMs = 40;
11048 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
11049 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
11050 QuicTime::Delta::Zero(), QuicTime::Zero());
11051 EXPECT_CALL(visitor_, GetHandshakeState())
11052 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
11053 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
11054 // Send stream data.
11055 SendStreamDataToPeer(
11056 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
11057 0, FIN, nullptr);
11058 // Verify blackhole delay is expected.
11059 EXPECT_EQ(clock_.Now() +
11060 connection_.sent_packet_manager().GetNetworkBlackholeDelay(3),
11061 QuicConnectionPeer::GetBlackholeDetectionDeadline(&connection_));
11062}
11063
11064TEST_P(QuicConnectionTest, 4RtoBlackholeDetection) {
fayang656cbb52020-06-09 13:29:35 -070011065 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangf78b6932020-06-08 08:36:45 -070011066 return;
11067 }
11068 QuicConfig config;
11069 QuicTagVector connection_options;
11070 connection_options.push_back(k4RTO);
11071 config.SetConnectionOptionsToSend(connection_options);
11072 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11073 connection_.SetFromConfig(config);
11074 const size_t kMinRttMs = 40;
11075 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
11076 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
11077 QuicTime::Delta::Zero(), QuicTime::Zero());
11078 EXPECT_CALL(visitor_, GetHandshakeState())
11079 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
11080 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
11081 // Send stream data.
11082 SendStreamDataToPeer(
11083 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
11084 0, FIN, nullptr);
11085 // Verify blackhole delay is expected.
11086 EXPECT_EQ(clock_.Now() +
11087 connection_.sent_packet_manager().GetNetworkBlackholeDelay(4),
11088 QuicConnectionPeer::GetBlackholeDetectionDeadline(&connection_));
11089}
11090
11091TEST_P(QuicConnectionTest, 6RtoBlackholeDetection) {
fayang656cbb52020-06-09 13:29:35 -070011092 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangf78b6932020-06-08 08:36:45 -070011093 return;
11094 }
11095 QuicConfig config;
11096 QuicTagVector connection_options;
11097 connection_options.push_back(k6RTO);
11098 config.SetConnectionOptionsToSend(connection_options);
11099 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11100 connection_.SetFromConfig(config);
11101 const size_t kMinRttMs = 40;
11102 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
11103 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
11104 QuicTime::Delta::Zero(), QuicTime::Zero());
11105 EXPECT_CALL(visitor_, GetHandshakeState())
11106 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
11107 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
11108 // Send stream data.
11109 SendStreamDataToPeer(
11110 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
11111 0, FIN, nullptr);
11112 // Verify blackhole delay is expected.
11113 EXPECT_EQ(clock_.Now() +
11114 connection_.sent_packet_manager().GetNetworkBlackholeDelay(6),
11115 QuicConnectionPeer::GetBlackholeDetectionDeadline(&connection_));
11116}
11117
fayang656cbb52020-06-09 13:29:35 -070011118// Regresstion test for b/158491591.
11119TEST_P(QuicConnectionTest, MadeForwardProgressOnDiscardingKeys) {
11120 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
11121 return;
11122 }
11123 use_tagging_decrypter();
11124 // Send handshake packet.
11125 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
11126 std::make_unique<TaggingEncrypter>(0x02));
11127 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11128 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
11129 QuicConfig config;
11130 QuicTagVector connection_options;
11131 connection_options.push_back(k5RTO);
11132 config.SetConnectionOptionsToSend(connection_options);
11133 QuicConfigPeer::SetNegotiated(&config, true);
11134 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
11135 EXPECT_CALL(visitor_, GetHandshakeState())
11136 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
11137 }
11138 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
11139 QuicConfigPeer::SetReceivedOriginalConnectionId(
11140 &config, connection_.connection_id());
11141 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
11142 &config, connection_.connection_id());
11143 }
11144 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11145 connection_.SetFromConfig(config);
11146
11147 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
11148 EXPECT_TRUE(connection_.BlackholeDetectionInProgress());
11149 // Discard handshake keys.
11150 connection_.OnHandshakeComplete();
11151 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
11152 // Verify blackhole detection stops.
11153 EXPECT_FALSE(connection_.BlackholeDetectionInProgress());
11154 } else {
11155 // Problematic: although there is nothing in flight, blackhole detection is
11156 // still in progress.
11157 EXPECT_TRUE(connection_.BlackholeDetectionInProgress());
11158 }
11159}
11160
fayang750b54f2020-06-18 06:26:54 -070011161TEST_P(QuicConnectionTest, ProcessUndecryptablePacketsBasedOnEncryptionLevel) {
11162 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
11163 return;
11164 }
11165 // SetFromConfig is always called after construction from InitializeSession.
11166 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
11167 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11168 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(AnyNumber());
11169 QuicConfig config;
11170 connection_.SetFromConfig(config);
11171 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
11172 connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
11173 use_tagging_decrypter();
11174
11175 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
11176 std::make_unique<TaggingEncrypter>(0x01));
11177 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
11178 std::make_unique<TaggingEncrypter>(0x02));
11179
11180 for (uint64_t i = 1; i <= 3; ++i) {
11181 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
11182 }
11183 ProcessDataPacketAtLevel(4, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
11184 for (uint64_t j = 5; j <= 7; ++j) {
11185 ProcessDataPacketAtLevel(j, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
11186 }
11187 EXPECT_EQ(7u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
11188 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
11189 SetDecrypter(ENCRYPTION_HANDSHAKE,
11190 std::make_unique<StrictTaggingDecrypter>(0x01));
11191 EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
11192 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11193 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
11194 std::make_unique<TaggingEncrypter>(0x01));
11195 if (GetQuicReloadableFlag(quic_fix_undecryptable_packets)) {
11196 // Verify all ENCRYPTION_HANDSHAKE packets get processed.
11197 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(6);
11198 } else {
11199 // Verify packets before 4 get processed.
11200 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(3);
11201 }
11202 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
11203 EXPECT_EQ(4u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
11204
11205 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
11206 std::make_unique<StrictTaggingDecrypter>(0x02));
11207 EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
11208 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
11209 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
11210 std::make_unique<TaggingEncrypter>(0x02));
11211 if (GetQuicReloadableFlag(quic_fix_undecryptable_packets)) {
11212 // Verify the 1-RTT packet gets processed.
11213 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
11214 } else {
11215 // Verify all packets get processed.
11216 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(4);
11217 }
11218 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
11219 EXPECT_EQ(0u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
11220}
11221
fayanga39d0362020-06-22 08:57:35 -070011222TEST_P(QuicConnectionTest, ServerBundlesInitialDataWithInitialAck) {
fayang7d4b0172020-06-18 14:05:45 -070011223 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
11224 return;
11225 }
11226 set_perspective(Perspective::IS_SERVER);
11227 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
11228 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
11229 }
11230 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
11231 use_tagging_decrypter();
11232 // Receives packet 1000 in initial data.
11233 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
11234 EXPECT_TRUE(connection_.HasPendingAcks());
11235
11236 connection_.SetEncrypter(ENCRYPTION_INITIAL,
11237 std::make_unique<TaggingEncrypter>(0x01));
11238 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
11239 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
11240 QuicTime expected_pto_time =
11241 connection_.sent_packet_manager().GetRetransmissionTime();
11242
11243 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
11244 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
11245 std::make_unique<TaggingEncrypter>(0x02));
11246 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11247 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
11248 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
11249 // Verify PTO time does not change.
11250 EXPECT_EQ(expected_pto_time,
11251 connection_.sent_packet_manager().GetRetransmissionTime());
11252
11253 // Receives packet 1001 in initial data.
11254 ProcessCryptoPacketAtLevel(1001, ENCRYPTION_INITIAL);
11255 EXPECT_TRUE(connection_.HasPendingAcks());
11256 // Receives packet 1002 in initial data.
11257 ProcessCryptoPacketAtLevel(1002, ENCRYPTION_INITIAL);
11258 EXPECT_FALSE(writer_->ack_frames().empty());
fayangc6312d42020-07-06 08:15:28 -070011259 // Verify CRYPTO frame is bundled with INITIAL ACK.
11260 EXPECT_FALSE(writer_->crypto_frames().empty());
11261 // Verify PTO time changes.
11262 EXPECT_NE(expected_pto_time,
11263 connection_.sent_packet_manager().GetRetransmissionTime());
fayang7d4b0172020-06-18 14:05:45 -070011264}
11265
fayanga39d0362020-06-22 08:57:35 -070011266TEST_P(QuicConnectionTest, ClientBundlesHandshakeDataWithHandshakeAck) {
11267 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
11268 return;
11269 }
11270 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
11271 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
11272 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
11273 }
11274 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
11275 use_tagging_decrypter();
11276 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
11277 std::make_unique<TaggingEncrypter>(0x02));
11278 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11279 SetDecrypter(ENCRYPTION_HANDSHAKE,
11280 std::make_unique<StrictTaggingDecrypter>(0x02));
11281 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
11282 std::make_unique<TaggingEncrypter>(0x02));
11283 // Receives packet 1000 in handshake data.
11284 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_HANDSHAKE);
11285 EXPECT_TRUE(connection_.HasPendingAcks());
11286
11287 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(2);
11288 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
11289
11290 // Receives packet 1001 in handshake data.
11291 ProcessCryptoPacketAtLevel(1001, ENCRYPTION_HANDSHAKE);
11292 EXPECT_TRUE(connection_.HasPendingAcks());
11293 // Receives packet 1002 in handshake data.
11294 ProcessCryptoPacketAtLevel(1002, ENCRYPTION_HANDSHAKE);
11295 EXPECT_FALSE(writer_->ack_frames().empty());
fayangc6312d42020-07-06 08:15:28 -070011296 // Verify CRYPTO frame is bundled with HANDSHAKE ACK.
11297 EXPECT_FALSE(writer_->crypto_frames().empty());
fayanga39d0362020-06-22 08:57:35 -070011298}
11299
fayang04bd30d2020-06-22 15:04:57 -070011300// Regresstion test for b/156232673.
11301TEST_P(QuicConnectionTest, CoalescePacketOfLowerEncryptionLevel) {
11302 if (!connection_.version().CanSendCoalescedPackets()) {
11303 return;
11304 }
fayangfce2f722020-06-26 10:27:32 -070011305 if (GetQuicReloadableFlag(quic_fix_extra_padding_bytes) ||
11306 GetQuicReloadableFlag(quic_fix_min_crypto_frame_size)) {
fayang04bd30d2020-06-22 15:04:57 -070011307 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
11308 } else {
11309 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(0);
11310 }
11311 {
11312 QuicConnection::ScopedPacketFlusher flusher(&connection_);
11313 use_tagging_decrypter();
11314 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
11315 std::make_unique<TaggingEncrypter>(0x01));
11316 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
11317 std::make_unique<TaggingEncrypter>(0x02));
11318 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
fayangbd7ad682020-06-23 10:49:12 -070011319 SendStreamDataToPeer(2, std::string(1286, 'a'), 0, NO_FIN, nullptr);
fayang04bd30d2020-06-22 15:04:57 -070011320 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11321 // Try to coalesce a HANDSHAKE packet after 1-RTT packet.
fayangfce2f722020-06-26 10:27:32 -070011322 if (GetQuicReloadableFlag(quic_fix_extra_padding_bytes) ||
11323 GetQuicReloadableFlag(quic_fix_min_crypto_frame_size)) {
fayang04bd30d2020-06-22 15:04:57 -070011324 // Verify soft max packet length gets resumed and handshake packet gets
11325 // successfully sent.
11326 connection_.SendCryptoDataWithString("a", 0, ENCRYPTION_HANDSHAKE);
11327 } else {
11328 // Problematic: creator thinks there is space to consume 1-byte, however,
11329 // extra paddings make the serialization fail because of
11330 // MinPlaintextPacketSize.
11331 EXPECT_CALL(visitor_,
11332 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
11333 EXPECT_QUIC_BUG(
11334 connection_.SendCryptoDataWithString("a", 0, ENCRYPTION_HANDSHAKE),
11335 "AppendPaddingFrame of 3 failed");
11336 }
11337 }
11338}
11339
QUICHE teama6ef0a62019-03-07 20:34:33 -050011340} // namespace
11341} // namespace test
11342} // namespace quic