blob: a2453163367f89b5ac30f73f58a83eabd3bd6333 [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;
53using testing::Exactly;
54using testing::Ge;
55using testing::IgnoreResult;
56using testing::InSequence;
57using testing::Invoke;
58using testing::InvokeWithoutArgs;
59using testing::Lt;
60using testing::Ref;
61using testing::Return;
62using testing::SaveArg;
63using testing::SetArgPointee;
64using testing::StrictMock;
65
66namespace quic {
67namespace test {
68namespace {
69
nharper55fa6132019-05-07 19:37:21 -070070const char data1[] = "foo data";
71const char data2[] = "bar data";
QUICHE teama6ef0a62019-03-07 20:34:33 -050072
73const bool kHasStopWaiting = true;
74
75const int kDefaultRetransmissionTimeMs = 500;
76
QUICHE team548d51b2019-03-14 10:06:54 -070077DiversificationNonce kTestDiversificationNonce = {
78 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a',
79 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b',
80 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b',
81};
82
QUICHE teama6ef0a62019-03-07 20:34:33 -050083const QuicSocketAddress kPeerAddress =
84 QuicSocketAddress(QuicIpAddress::Loopback6(),
85 /*port=*/12345);
86const QuicSocketAddress kSelfAddress =
87 QuicSocketAddress(QuicIpAddress::Loopback6(),
88 /*port=*/443);
89
QUICHE teama6ef0a62019-03-07 20:34:33 -050090QuicStreamId GetNthClientInitiatedStreamId(int n,
91 QuicTransportVersion version) {
dschinazi552accc2019-06-17 17:07:34 -070092 return QuicUtils::GetFirstBidirectionalStreamId(version,
93 Perspective::IS_CLIENT) +
94 n * 2;
QUICHE teama6ef0a62019-03-07 20:34:33 -050095}
96
QUICHE team8c1daa22019-03-13 08:33:41 -070097QuicLongHeaderType EncryptionlevelToLongHeaderType(EncryptionLevel level) {
98 switch (level) {
QUICHE team6987b4a2019-03-15 16:23:04 -070099 case ENCRYPTION_INITIAL:
QUICHE team8c1daa22019-03-13 08:33:41 -0700100 return INITIAL;
QUICHE team88ea0082019-03-15 10:05:26 -0700101 case ENCRYPTION_HANDSHAKE:
102 return HANDSHAKE;
QUICHE team8c1daa22019-03-13 08:33:41 -0700103 case ENCRYPTION_ZERO_RTT:
104 return ZERO_RTT_PROTECTED;
105 case ENCRYPTION_FORWARD_SECURE:
106 DCHECK(false);
107 return INVALID_PACKET_TYPE;
108 default:
109 DCHECK(false);
110 return INVALID_PACKET_TYPE;
111 }
112}
113
QUICHE teama6ef0a62019-03-07 20:34:33 -0500114// TaggingEncrypter appends kTagSize bytes of |tag| to the end of each message.
115class TaggingEncrypter : public QuicEncrypter {
116 public:
117 explicit TaggingEncrypter(uint8_t tag) : tag_(tag) {}
118 TaggingEncrypter(const TaggingEncrypter&) = delete;
119 TaggingEncrypter& operator=(const TaggingEncrypter&) = delete;
120
121 ~TaggingEncrypter() override {}
122
123 // QuicEncrypter interface.
dmcardlecf0bfcf2019-12-13 08:08:21 -0800124 bool SetKey(quiche::QuicheStringPiece /*key*/) override { return true; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500125
dmcardlecf0bfcf2019-12-13 08:08:21 -0800126 bool SetNoncePrefix(quiche::QuicheStringPiece /*nonce_prefix*/) override {
dschinazi17d42422019-06-18 16:35:07 -0700127 return true;
128 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500129
dmcardlecf0bfcf2019-12-13 08:08:21 -0800130 bool SetIV(quiche::QuicheStringPiece /*iv*/) override { return true; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500131
dmcardlecf0bfcf2019-12-13 08:08:21 -0800132 bool SetHeaderProtectionKey(quiche::QuicheStringPiece /*key*/) override {
133 return true;
134 }
QUICHE team2d187972019-03-19 16:23:47 -0700135
dschinazi17d42422019-06-18 16:35:07 -0700136 bool EncryptPacket(uint64_t /*packet_number*/,
dmcardlecf0bfcf2019-12-13 08:08:21 -0800137 quiche::QuicheStringPiece /*associated_data*/,
138 quiche::QuicheStringPiece plaintext,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500139 char* output,
140 size_t* output_length,
141 size_t max_output_length) override {
142 const size_t len = plaintext.size() + kTagSize;
143 if (max_output_length < len) {
144 return false;
145 }
146 // Memmove is safe for inplace encryption.
147 memmove(output, plaintext.data(), plaintext.size());
148 output += plaintext.size();
149 memset(output, tag_, kTagSize);
150 *output_length = len;
151 return true;
152 }
153
dschinazi17d42422019-06-18 16:35:07 -0700154 std::string GenerateHeaderProtectionMask(
dmcardlecf0bfcf2019-12-13 08:08:21 -0800155 quiche::QuicheStringPiece /*sample*/) override {
QUICHE team2d187972019-03-19 16:23:47 -0700156 return std::string(5, 0);
157 }
158
QUICHE teama6ef0a62019-03-07 20:34:33 -0500159 size_t GetKeySize() const override { return 0; }
160 size_t GetNoncePrefixSize() const override { return 0; }
161 size_t GetIVSize() const override { return 0; }
162
163 size_t GetMaxPlaintextSize(size_t ciphertext_size) const override {
164 return ciphertext_size - kTagSize;
165 }
166
167 size_t GetCiphertextSize(size_t plaintext_size) const override {
168 return plaintext_size + kTagSize;
169 }
170
dmcardlecf0bfcf2019-12-13 08:08:21 -0800171 quiche::QuicheStringPiece GetKey() const override {
172 return quiche::QuicheStringPiece();
173 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500174
dmcardlecf0bfcf2019-12-13 08:08:21 -0800175 quiche::QuicheStringPiece GetNoncePrefix() const override {
176 return quiche::QuicheStringPiece();
177 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500178
179 private:
180 enum {
181 kTagSize = 12,
182 };
183
184 const uint8_t tag_;
185};
186
187// TaggingDecrypter ensures that the final kTagSize bytes of the message all
188// have the same value and then removes them.
189class TaggingDecrypter : public QuicDecrypter {
190 public:
191 ~TaggingDecrypter() override {}
192
193 // QuicDecrypter interface
dmcardlecf0bfcf2019-12-13 08:08:21 -0800194 bool SetKey(quiche::QuicheStringPiece /*key*/) override { return true; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500195
dmcardlecf0bfcf2019-12-13 08:08:21 -0800196 bool SetNoncePrefix(quiche::QuicheStringPiece /*nonce_prefix*/) override {
dschinazi17d42422019-06-18 16:35:07 -0700197 return true;
198 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500199
dmcardlecf0bfcf2019-12-13 08:08:21 -0800200 bool SetIV(quiche::QuicheStringPiece /*iv*/) override { return true; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500201
dmcardlecf0bfcf2019-12-13 08:08:21 -0800202 bool SetHeaderProtectionKey(quiche::QuicheStringPiece /*key*/) override {
203 return true;
204 }
QUICHE team2d187972019-03-19 16:23:47 -0700205
dmcardlecf0bfcf2019-12-13 08:08:21 -0800206 bool SetPreliminaryKey(quiche::QuicheStringPiece /*key*/) override {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500207 QUIC_BUG << "should not be called";
208 return false;
209 }
210
dschinazi17d42422019-06-18 16:35:07 -0700211 bool SetDiversificationNonce(const DiversificationNonce& /*key*/) override {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500212 return true;
213 }
214
dschinazi17d42422019-06-18 16:35:07 -0700215 bool DecryptPacket(uint64_t /*packet_number*/,
dmcardlecf0bfcf2019-12-13 08:08:21 -0800216 quiche::QuicheStringPiece /*associated_data*/,
217 quiche::QuicheStringPiece ciphertext,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500218 char* output,
219 size_t* output_length,
dschinazi17d42422019-06-18 16:35:07 -0700220 size_t /*max_output_length*/) override {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500221 if (ciphertext.size() < kTagSize) {
222 return false;
223 }
224 if (!CheckTag(ciphertext, GetTag(ciphertext))) {
225 return false;
226 }
227 *output_length = ciphertext.size() - kTagSize;
228 memcpy(output, ciphertext.data(), *output_length);
229 return true;
230 }
231
QUICHE team2d187972019-03-19 16:23:47 -0700232 std::string GenerateHeaderProtectionMask(
dschinazi17d42422019-06-18 16:35:07 -0700233 QuicDataReader* /*sample_reader*/) override {
QUICHE team2d187972019-03-19 16:23:47 -0700234 return std::string(5, 0);
235 }
236
QUICHE teama6ef0a62019-03-07 20:34:33 -0500237 size_t GetKeySize() const override { return 0; }
nharper965e5922019-09-23 22:33:54 -0700238 size_t GetNoncePrefixSize() const override { return 0; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500239 size_t GetIVSize() const override { return 0; }
dmcardlecf0bfcf2019-12-13 08:08:21 -0800240 quiche::QuicheStringPiece GetKey() const override {
241 return quiche::QuicheStringPiece();
242 }
243 quiche::QuicheStringPiece GetNoncePrefix() const override {
244 return quiche::QuicheStringPiece();
245 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500246 // Use a distinct value starting with 0xFFFFFF, which is never used by TLS.
247 uint32_t cipher_id() const override { return 0xFFFFFFF0; }
248
249 protected:
dmcardlecf0bfcf2019-12-13 08:08:21 -0800250 virtual uint8_t GetTag(quiche::QuicheStringPiece ciphertext) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500251 return ciphertext.data()[ciphertext.size() - 1];
252 }
253
254 private:
255 enum {
256 kTagSize = 12,
257 };
258
dmcardlecf0bfcf2019-12-13 08:08:21 -0800259 bool CheckTag(quiche::QuicheStringPiece ciphertext, uint8_t tag) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500260 for (size_t i = ciphertext.size() - kTagSize; i < ciphertext.size(); i++) {
261 if (ciphertext.data()[i] != tag) {
262 return false;
263 }
264 }
265
266 return true;
267 }
268};
269
270// StringTaggingDecrypter ensures that the final kTagSize bytes of the message
271// match the expected value.
272class StrictTaggingDecrypter : public TaggingDecrypter {
273 public:
274 explicit StrictTaggingDecrypter(uint8_t tag) : tag_(tag) {}
275 ~StrictTaggingDecrypter() override {}
276
277 // TaggingQuicDecrypter
dmcardlecf0bfcf2019-12-13 08:08:21 -0800278 uint8_t GetTag(quiche::QuicheStringPiece /*ciphertext*/) override {
279 return tag_;
280 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500281
282 // Use a distinct value starting with 0xFFFFFF, which is never used by TLS.
283 uint32_t cipher_id() const override { return 0xFFFFFFF1; }
284
285 private:
286 const uint8_t tag_;
287};
288
289class TestConnectionHelper : public QuicConnectionHelperInterface {
290 public:
291 TestConnectionHelper(MockClock* clock, MockRandom* random_generator)
292 : clock_(clock), random_generator_(random_generator) {
293 clock_->AdvanceTime(QuicTime::Delta::FromSeconds(1));
294 }
295 TestConnectionHelper(const TestConnectionHelper&) = delete;
296 TestConnectionHelper& operator=(const TestConnectionHelper&) = delete;
297
298 // QuicConnectionHelperInterface
299 const QuicClock* GetClock() const override { return clock_; }
300
301 QuicRandom* GetRandomGenerator() override { return random_generator_; }
302
303 QuicBufferAllocator* GetStreamSendBufferAllocator() override {
304 return &buffer_allocator_;
305 }
306
307 private:
308 MockClock* clock_;
309 MockRandom* random_generator_;
310 SimpleBufferAllocator buffer_allocator_;
311};
312
313class TestAlarmFactory : public QuicAlarmFactory {
314 public:
315 class TestAlarm : public QuicAlarm {
316 public:
317 explicit TestAlarm(QuicArenaScopedPtr<QuicAlarm::Delegate> delegate)
318 : QuicAlarm(std::move(delegate)) {}
319
320 void SetImpl() override {}
321 void CancelImpl() override {}
322 using QuicAlarm::Fire;
323 };
324
325 TestAlarmFactory() {}
326 TestAlarmFactory(const TestAlarmFactory&) = delete;
327 TestAlarmFactory& operator=(const TestAlarmFactory&) = delete;
328
329 QuicAlarm* CreateAlarm(QuicAlarm::Delegate* delegate) override {
330 return new TestAlarm(QuicArenaScopedPtr<QuicAlarm::Delegate>(delegate));
331 }
332
333 QuicArenaScopedPtr<QuicAlarm> CreateAlarm(
334 QuicArenaScopedPtr<QuicAlarm::Delegate> delegate,
335 QuicConnectionArena* arena) override {
336 return arena->New<TestAlarm>(std::move(delegate));
337 }
338};
339
340class TestPacketWriter : public QuicPacketWriter {
wub50d4c712020-05-19 15:48:28 -0700341 struct PacketBuffer {
342 QUIC_CACHELINE_ALIGNED char buffer[1500];
343 bool in_use = false;
344 };
345
QUICHE teama6ef0a62019-03-07 20:34:33 -0500346 public:
347 TestPacketWriter(ParsedQuicVersion version, MockClock* clock)
348 : version_(version),
349 framer_(SupportedVersions(version_), Perspective::IS_SERVER),
wubb442b862020-01-31 08:16:21 -0800350 clock_(clock) {
dschinazib953d022019-08-01 18:05:58 -0700351 QuicFramerPeer::SetLastSerializedServerConnectionId(framer_.framer(),
352 TestConnectionId());
nharperc6b99512019-09-19 11:13:48 -0700353 framer_.framer()->SetInitialObfuscators(TestConnectionId());
wub50d4c712020-05-19 15:48:28 -0700354
355 for (int i = 0; i < 128; ++i) {
356 PacketBuffer* p = new PacketBuffer();
357 packet_buffer_pool_.push_back(p);
358 packet_buffer_pool_index_[p->buffer] = p;
359 packet_buffer_free_list_.push_back(p);
360 }
dschinazib953d022019-08-01 18:05:58 -0700361 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500362 TestPacketWriter(const TestPacketWriter&) = delete;
363 TestPacketWriter& operator=(const TestPacketWriter&) = delete;
364
wub50d4c712020-05-19 15:48:28 -0700365 ~TestPacketWriter() override {
366 EXPECT_EQ(packet_buffer_pool_.size(), packet_buffer_free_list_.size())
367 << packet_buffer_pool_.size() - packet_buffer_free_list_.size()
368 << " out of " << packet_buffer_pool_.size()
369 << " packet buffers have been leaked.";
370 for (auto p : packet_buffer_pool_) {
371 delete p;
372 }
373 }
374
QUICHE teama6ef0a62019-03-07 20:34:33 -0500375 // QuicPacketWriter interface
376 WriteResult WritePacket(const char* buffer,
377 size_t buf_len,
dschinazi17d42422019-06-18 16:35:07 -0700378 const QuicIpAddress& /*self_address*/,
379 const QuicSocketAddress& /*peer_address*/,
380 PerPacketOptions* /*options*/) override {
wub50d4c712020-05-19 15:48:28 -0700381 // If the buffer is allocated from the pool, return it back to the pool.
382 // Note the buffer content doesn't change.
383 if (packet_buffer_pool_index_.find(const_cast<char*>(buffer)) !=
384 packet_buffer_pool_index_.end()) {
385 FreePacketBuffer(buffer);
386 }
387
QUICHE teama6ef0a62019-03-07 20:34:33 -0500388 QuicEncryptedPacket packet(buffer, buf_len);
389 ++packets_write_attempts_;
390
391 if (packet.length() >= sizeof(final_bytes_of_last_packet_)) {
392 final_bytes_of_previous_packet_ = final_bytes_of_last_packet_;
393 memcpy(&final_bytes_of_last_packet_, packet.data() + packet.length() - 4,
394 sizeof(final_bytes_of_last_packet_));
395 }
396
397 if (use_tagging_decrypter_) {
zhongyi546cc452019-04-12 15:27:49 -0700398 if (framer_.framer()->version().KnowsWhichDecrypterToUse()) {
vasilvv0fc587f2019-09-06 13:33:08 -0700399 framer_.framer()->InstallDecrypter(
400 ENCRYPTION_INITIAL, std::make_unique<TaggingDecrypter>());
401 framer_.framer()->InstallDecrypter(
fayang18ff23b2020-01-28 09:19:00 -0800402 ENCRYPTION_HANDSHAKE, std::make_unique<TaggingDecrypter>());
403 framer_.framer()->InstallDecrypter(
vasilvv0fc587f2019-09-06 13:33:08 -0700404 ENCRYPTION_ZERO_RTT, std::make_unique<TaggingDecrypter>());
405 framer_.framer()->InstallDecrypter(
406 ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingDecrypter>());
zhongyi546cc452019-04-12 15:27:49 -0700407 } else {
408 framer_.framer()->SetDecrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -0700409 std::make_unique<TaggingDecrypter>());
zhongyi546cc452019-04-12 15:27:49 -0700410 }
411 } else if (framer_.framer()->version().KnowsWhichDecrypterToUse()) {
412 framer_.framer()->InstallDecrypter(
413 ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -0700414 std::make_unique<NullDecrypter>(Perspective::IS_SERVER));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500415 }
dschinazi39e5e552020-05-06 13:55:24 -0700416 EXPECT_TRUE(framer_.ProcessPacket(packet))
417 << framer_.framer()->detailed_error();
QUICHE teama6ef0a62019-03-07 20:34:33 -0500418 if (block_on_next_write_) {
419 write_blocked_ = true;
420 block_on_next_write_ = false;
421 }
422 if (next_packet_too_large_) {
423 next_packet_too_large_ = false;
424 return WriteResult(WRITE_STATUS_ERROR, QUIC_EMSGSIZE);
425 }
426 if (always_get_packet_too_large_) {
427 return WriteResult(WRITE_STATUS_ERROR, QUIC_EMSGSIZE);
428 }
429 if (IsWriteBlocked()) {
430 return WriteResult(is_write_blocked_data_buffered_
431 ? WRITE_STATUS_BLOCKED_DATA_BUFFERED
432 : WRITE_STATUS_BLOCKED,
433 0);
434 }
435
436 if (ShouldWriteFail()) {
437 return WriteResult(WRITE_STATUS_ERROR, 0);
438 }
439
440 last_packet_size_ = packet.length();
441 last_packet_header_ = framer_.header();
rchd672c6d2019-11-27 15:30:54 -0800442 if (!framer_.connection_close_frames().empty()) {
443 ++connection_close_packets_;
444 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500445 if (!write_pause_time_delta_.IsZero()) {
446 clock_->AdvanceTime(write_pause_time_delta_);
447 }
wubb442b862020-01-31 08:16:21 -0800448 if (is_batch_mode_) {
449 bytes_buffered_ += last_packet_size_;
450 return WriteResult(WRITE_STATUS_OK, 0);
451 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500452 return WriteResult(WRITE_STATUS_OK, last_packet_size_);
453 }
454
455 bool ShouldWriteFail() { return write_should_fail_; }
456
457 bool IsWriteBlocked() const override { return write_blocked_; }
458
459 void SetWriteBlocked() { write_blocked_ = true; }
460
461 void SetWritable() override { write_blocked_ = false; }
462
463 void SetShouldWriteFail() { write_should_fail_ = true; }
464
465 QuicByteCount GetMaxPacketSize(
466 const QuicSocketAddress& /*peer_address*/) const override {
467 return max_packet_size_;
468 }
469
dschinazi61eb6432019-06-14 16:27:16 -0700470 bool SupportsReleaseTime() const override { return supports_release_time_; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500471
472 bool IsBatchMode() const override { return is_batch_mode_; }
473
wub50d4c712020-05-19 15:48:28 -0700474 QuicPacketBuffer GetNextWriteLocation(
dschinazi17d42422019-06-18 16:35:07 -0700475 const QuicIpAddress& /*self_address*/,
476 const QuicSocketAddress& /*peer_address*/) override {
wub50d4c712020-05-19 15:48:28 -0700477 if (GetQuicReloadableFlag(quic_avoid_leak_writer_buffer)) {
478 return {AllocPacketBuffer(),
479 [this](const char* p) { FreePacketBuffer(p); }};
480 }
481 // Do not use writer buffer for serializing packets.
482 return {nullptr, nullptr};
QUICHE teama6ef0a62019-03-07 20:34:33 -0500483 }
484
485 WriteResult Flush() override {
wubb442b862020-01-31 08:16:21 -0800486 flush_attempts_++;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500487 if (block_on_next_flush_) {
488 block_on_next_flush_ = false;
489 SetWriteBlocked();
490 return WriteResult(WRITE_STATUS_BLOCKED, /*errno*/ -1);
491 }
wub748e20b2020-03-20 14:33:59 -0700492 if (write_should_fail_) {
493 return WriteResult(WRITE_STATUS_ERROR, /*errno*/ -1);
494 }
wubb442b862020-01-31 08:16:21 -0800495 int bytes_flushed = bytes_buffered_;
496 bytes_buffered_ = 0;
497 return WriteResult(WRITE_STATUS_OK, bytes_flushed);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500498 }
499
500 void BlockOnNextFlush() { block_on_next_flush_ = true; }
501
502 void BlockOnNextWrite() { block_on_next_write_ = true; }
503
504 void SimulateNextPacketTooLarge() { next_packet_too_large_ = true; }
505
506 void AlwaysGetPacketTooLarge() { always_get_packet_too_large_ = true; }
507
508 // Sets the amount of time that the writer should before the actual write.
509 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
510 write_pause_time_delta_ = delta;
511 }
512
513 void SetBatchMode(bool new_value) { is_batch_mode_ = new_value; }
514
515 const QuicPacketHeader& header() { return framer_.header(); }
516
517 size_t frame_count() const { return framer_.num_frames(); }
518
519 const std::vector<QuicAckFrame>& ack_frames() const {
520 return framer_.ack_frames();
521 }
522
523 const std::vector<QuicStopWaitingFrame>& stop_waiting_frames() const {
524 return framer_.stop_waiting_frames();
525 }
526
527 const std::vector<QuicConnectionCloseFrame>& connection_close_frames() const {
528 return framer_.connection_close_frames();
529 }
530
531 const std::vector<QuicRstStreamFrame>& rst_stream_frames() const {
532 return framer_.rst_stream_frames();
533 }
534
535 const std::vector<std::unique_ptr<QuicStreamFrame>>& stream_frames() const {
536 return framer_.stream_frames();
537 }
538
539 const std::vector<std::unique_ptr<QuicCryptoFrame>>& crypto_frames() const {
540 return framer_.crypto_frames();
541 }
542
543 const std::vector<QuicPingFrame>& ping_frames() const {
544 return framer_.ping_frames();
545 }
546
547 const std::vector<QuicMessageFrame>& message_frames() const {
548 return framer_.message_frames();
549 }
550
551 const std::vector<QuicWindowUpdateFrame>& window_update_frames() const {
552 return framer_.window_update_frames();
553 }
554
555 const std::vector<QuicPaddingFrame>& padding_frames() const {
556 return framer_.padding_frames();
557 }
558
559 const std::vector<QuicPathChallengeFrame>& path_challenge_frames() const {
560 return framer_.path_challenge_frames();
561 }
562
563 const std::vector<QuicPathResponseFrame>& path_response_frames() const {
564 return framer_.path_response_frames();
565 }
566
fayang58f71072019-11-05 08:47:02 -0800567 const QuicEncryptedPacket* coalesced_packet() const {
568 return framer_.coalesced_packet();
569 }
570
QUICHE teama6ef0a62019-03-07 20:34:33 -0500571 size_t last_packet_size() { return last_packet_size_; }
572
573 const QuicPacketHeader& last_packet_header() const {
574 return last_packet_header_;
575 }
576
577 const QuicVersionNegotiationPacket* version_negotiation_packet() {
578 return framer_.version_negotiation_packet();
579 }
580
581 void set_is_write_blocked_data_buffered(bool buffered) {
582 is_write_blocked_data_buffered_ = buffered;
583 }
584
585 void set_perspective(Perspective perspective) {
586 // We invert perspective here, because the framer needs to parse packets
587 // we send.
588 QuicFramerPeer::SetPerspective(framer_.framer(),
nharper4eba09b2019-06-26 20:17:25 -0700589 QuicUtils::InvertPerspective(perspective));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500590 }
591
592 // final_bytes_of_last_packet_ returns the last four bytes of the previous
593 // packet as a little-endian, uint32_t. This is intended to be used with a
594 // TaggingEncrypter so that tests can determine which encrypter was used for
595 // a given packet.
596 uint32_t final_bytes_of_last_packet() { return final_bytes_of_last_packet_; }
597
598 // Returns the final bytes of the second to last packet.
599 uint32_t final_bytes_of_previous_packet() {
600 return final_bytes_of_previous_packet_;
601 }
602
603 void use_tagging_decrypter() { use_tagging_decrypter_ = true; }
604
wubb442b862020-01-31 08:16:21 -0800605 uint32_t packets_write_attempts() const { return packets_write_attempts_; }
606
607 uint32_t flush_attempts() const { return flush_attempts_; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500608
rchd672c6d2019-11-27 15:30:54 -0800609 uint32_t connection_close_packets() const {
610 return connection_close_packets_;
611 }
612
QUICHE teama6ef0a62019-03-07 20:34:33 -0500613 void Reset() { framer_.Reset(); }
614
615 void SetSupportedVersions(const ParsedQuicVersionVector& versions) {
616 framer_.SetSupportedVersions(versions);
617 }
618
619 void set_max_packet_size(QuicByteCount max_packet_size) {
620 max_packet_size_ = max_packet_size;
621 }
622
623 void set_supports_release_time(bool supports_release_time) {
624 supports_release_time_ = supports_release_time;
625 }
626
627 SimpleQuicFramer* framer() { return &framer_; }
628
629 private:
wub50d4c712020-05-19 15:48:28 -0700630 char* AllocPacketBuffer() {
631 PacketBuffer* p = packet_buffer_free_list_.front();
632 EXPECT_FALSE(p->in_use);
633 p->in_use = true;
634 packet_buffer_free_list_.pop_front();
635 return p->buffer;
636 }
637
638 void FreePacketBuffer(const char* buffer) {
639 auto iter = packet_buffer_pool_index_.find(const_cast<char*>(buffer));
640 ASSERT_TRUE(iter != packet_buffer_pool_index_.end());
641 PacketBuffer* p = iter->second;
642 ASSERT_TRUE(p->in_use);
643 p->in_use = false;
644 packet_buffer_free_list_.push_back(p);
645 }
646
QUICHE teama6ef0a62019-03-07 20:34:33 -0500647 ParsedQuicVersion version_;
648 SimpleQuicFramer framer_;
wubb442b862020-01-31 08:16:21 -0800649 size_t last_packet_size_ = 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500650 QuicPacketHeader last_packet_header_;
wubb442b862020-01-31 08:16:21 -0800651 bool write_blocked_ = false;
652 bool write_should_fail_ = false;
653 bool block_on_next_flush_ = false;
654 bool block_on_next_write_ = false;
655 bool next_packet_too_large_ = false;
656 bool always_get_packet_too_large_ = false;
657 bool is_write_blocked_data_buffered_ = false;
658 bool is_batch_mode_ = false;
659 // Number of times Flush() was called.
660 uint32_t flush_attempts_ = 0;
661 // (Batch mode only) Number of bytes buffered in writer. It is used as the
662 // return value of a successful Flush().
663 uint32_t bytes_buffered_ = 0;
664 uint32_t final_bytes_of_last_packet_ = 0;
665 uint32_t final_bytes_of_previous_packet_ = 0;
666 bool use_tagging_decrypter_ = false;
667 uint32_t packets_write_attempts_ = 0;
668 uint32_t connection_close_packets_ = 0;
669 MockClock* clock_ = nullptr;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500670 // If non-zero, the clock will pause during WritePacket for this amount of
671 // time.
wubb442b862020-01-31 08:16:21 -0800672 QuicTime::Delta write_pause_time_delta_ = QuicTime::Delta::Zero();
673 QuicByteCount max_packet_size_ = kMaxOutgoingPacketSize;
674 bool supports_release_time_ = false;
wub50d4c712020-05-19 15:48:28 -0700675 // Used to verify writer-allocated packet buffers are properly released.
676 std::vector<PacketBuffer*> packet_buffer_pool_;
677 // Buffer address => Address of the owning PacketBuffer.
678 QuicHashMap<char*, PacketBuffer*> packet_buffer_pool_index_;
679 // Indices in packet_buffer_pool_ that are not allocated.
680 std::list<PacketBuffer*> packet_buffer_free_list_;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500681};
682
683class TestConnection : public QuicConnection {
684 public:
685 TestConnection(QuicConnectionId connection_id,
686 QuicSocketAddress address,
687 TestConnectionHelper* helper,
688 TestAlarmFactory* alarm_factory,
689 TestPacketWriter* writer,
690 Perspective perspective,
691 ParsedQuicVersion version)
692 : QuicConnection(connection_id,
693 address,
694 helper,
695 alarm_factory,
696 writer,
697 /* owns_writer= */ false,
698 perspective,
699 SupportedVersions(version)),
700 notifier_(nullptr) {
701 writer->set_perspective(perspective);
702 SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -0700703 std::make_unique<NullEncrypter>(perspective));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500704 SetDataProducer(&producer_);
705 }
706 TestConnection(const TestConnection&) = delete;
707 TestConnection& operator=(const TestConnection&) = delete;
708
QUICHE teama6ef0a62019-03-07 20:34:33 -0500709 void SetSendAlgorithm(SendAlgorithmInterface* send_algorithm) {
710 QuicConnectionPeer::SetSendAlgorithm(this, send_algorithm);
711 }
712
713 void SetLossAlgorithm(LossDetectionInterface* loss_algorithm) {
714 QuicConnectionPeer::SetLossAlgorithm(this, loss_algorithm);
715 }
716
dschinazi17d42422019-06-18 16:35:07 -0700717 void SendPacket(EncryptionLevel /*level*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500718 uint64_t packet_number,
719 std::unique_ptr<QuicPacket> packet,
720 HasRetransmittableData retransmittable,
721 bool has_ack,
722 bool has_pending_frames) {
fayang58f71072019-11-05 08:47:02 -0800723 ScopedPacketFlusher flusher(this);
dschinazi66dea072019-04-09 11:41:06 -0700724 char buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -0500725 size_t encrypted_length =
726 QuicConnectionPeer::GetFramer(this)->EncryptPayload(
QUICHE team6987b4a2019-03-15 16:23:04 -0700727 ENCRYPTION_INITIAL, QuicPacketNumber(packet_number), *packet,
dschinazi66dea072019-04-09 11:41:06 -0700728 buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500729 SerializedPacket serialized_packet(
730 QuicPacketNumber(packet_number), PACKET_4BYTE_PACKET_NUMBER, buffer,
731 encrypted_length, has_ack, has_pending_frames);
732 if (retransmittable == HAS_RETRANSMITTABLE_DATA) {
733 serialized_packet.retransmittable_frames.push_back(
fayang58f71072019-11-05 08:47:02 -0800734 QuicFrame(QuicPingFrame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500735 }
wub8a5dafa2020-05-13 12:30:17 -0700736 OnSerializedPacket(std::move(serialized_packet));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500737 }
738
739 QuicConsumedData SaveAndSendStreamData(QuicStreamId id,
740 const struct iovec* iov,
741 int iov_count,
742 size_t total_length,
743 QuicStreamOffset offset,
744 StreamSendingState state) {
fayanga4b37b22019-06-18 13:37:47 -0700745 ScopedPacketFlusher flusher(this);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500746 producer_.SaveStreamData(id, iov, iov_count, 0u, total_length);
747 if (notifier_ != nullptr) {
748 return notifier_->WriteOrBufferData(id, total_length, state);
749 }
750 return QuicConnection::SendStreamData(id, total_length, offset, state);
751 }
752
753 QuicConsumedData SendStreamDataWithString(QuicStreamId id,
dmcardlecf0bfcf2019-12-13 08:08:21 -0800754 quiche::QuicheStringPiece data,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500755 QuicStreamOffset offset,
756 StreamSendingState state) {
fayanga4b37b22019-06-18 13:37:47 -0700757 ScopedPacketFlusher flusher(this);
nharper46833c32019-05-15 21:33:05 -0700758 if (!QuicUtils::IsCryptoStreamId(transport_version(), id) &&
QUICHE team6987b4a2019-03-15 16:23:04 -0700759 this->encryption_level() == ENCRYPTION_INITIAL) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500760 this->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
fayangfa3b1d62019-11-18 08:02:13 -0800761 if (perspective() == Perspective::IS_CLIENT && !IsHandshakeComplete()) {
fayang5f135052019-08-22 17:59:40 -0700762 OnHandshakeComplete();
763 }
764 if (version().SupportsAntiAmplificationLimit()) {
765 QuicConnectionPeer::SetAddressValidated(this);
766 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500767 }
768 struct iovec iov;
769 MakeIOVector(data, &iov);
770 return SaveAndSendStreamData(id, &iov, 1, data.length(), offset, state);
771 }
772
QUICHE teamcd098022019-03-22 18:49:55 -0700773 QuicConsumedData SendApplicationDataAtLevel(EncryptionLevel encryption_level,
774 QuicStreamId id,
dmcardlecf0bfcf2019-12-13 08:08:21 -0800775 quiche::QuicheStringPiece data,
QUICHE teamcd098022019-03-22 18:49:55 -0700776 QuicStreamOffset offset,
777 StreamSendingState state) {
fayanga4b37b22019-06-18 13:37:47 -0700778 ScopedPacketFlusher flusher(this);
QUICHE teamcd098022019-03-22 18:49:55 -0700779 DCHECK(encryption_level >= ENCRYPTION_ZERO_RTT);
vasilvv0fc587f2019-09-06 13:33:08 -0700780 SetEncrypter(encryption_level, std::make_unique<TaggingEncrypter>(0x01));
QUICHE teamcd098022019-03-22 18:49:55 -0700781 SetDefaultEncryptionLevel(encryption_level);
782 struct iovec iov;
783 MakeIOVector(data, &iov);
784 return SaveAndSendStreamData(id, &iov, 1, data.length(), offset, state);
785 }
786
QUICHE teama6ef0a62019-03-07 20:34:33 -0500787 QuicConsumedData SendStreamData3() {
788 return SendStreamDataWithString(
789 GetNthClientInitiatedStreamId(1, transport_version()), "food", 0,
790 NO_FIN);
791 }
792
793 QuicConsumedData SendStreamData5() {
794 return SendStreamDataWithString(
795 GetNthClientInitiatedStreamId(2, transport_version()), "food2", 0,
796 NO_FIN);
797 }
798
799 // Ensures the connection can write stream data before writing.
800 QuicConsumedData EnsureWritableAndSendStreamData5() {
ianswettfc16a2b2020-05-18 16:05:49 -0700801 EXPECT_TRUE(CanWrite(HAS_RETRANSMITTABLE_DATA));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500802 return SendStreamData5();
803 }
804
805 // The crypto stream has special semantics so that it is not blocked by a
806 // congestion window limitation, and also so that it gets put into a separate
807 // packet (so that it is easier to reason about a crypto frame not being
808 // split needlessly across packet boundaries). As a result, we have separate
809 // tests for some cases for this stream.
810 QuicConsumedData SendCryptoStreamData() {
811 QuicStreamOffset offset = 0;
dmcardlecf0bfcf2019-12-13 08:08:21 -0800812 quiche::QuicheStringPiece data("chlo");
fayang2ce66082019-10-02 06:29:04 -0700813 if (!QuicVersionUsesCryptoFrames(transport_version())) {
814 return SendCryptoDataWithString(data, offset);
815 }
816 producer_.SaveCryptoData(ENCRYPTION_INITIAL, offset, data);
817 size_t bytes_written;
818 if (notifier_) {
819 bytes_written =
820 notifier_->WriteCryptoData(ENCRYPTION_INITIAL, data.length(), offset);
821 } else {
822 bytes_written = QuicConnection::SendCryptoData(ENCRYPTION_INITIAL,
823 data.length(), offset);
824 }
825 return QuicConsumedData(bytes_written, /*fin_consumed*/ false);
nharper46833c32019-05-15 21:33:05 -0700826 }
827
dmcardlecf0bfcf2019-12-13 08:08:21 -0800828 QuicConsumedData SendCryptoDataWithString(quiche::QuicheStringPiece data,
nharper46833c32019-05-15 21:33:05 -0700829 QuicStreamOffset offset) {
fayang18ff23b2020-01-28 09:19:00 -0800830 return SendCryptoDataWithString(data, offset, ENCRYPTION_INITIAL);
831 }
832
833 QuicConsumedData SendCryptoDataWithString(quiche::QuicheStringPiece data,
834 QuicStreamOffset offset,
835 EncryptionLevel encryption_level) {
QUICHE teamea740082019-03-11 17:58:43 -0700836 if (!QuicVersionUsesCryptoFrames(transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500837 return SendStreamDataWithString(
838 QuicUtils::GetCryptoStreamId(transport_version()), data, offset,
839 NO_FIN);
840 }
fayang18ff23b2020-01-28 09:19:00 -0800841 producer_.SaveCryptoData(encryption_level, offset, data);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500842 size_t bytes_written;
843 if (notifier_) {
844 bytes_written =
fayang18ff23b2020-01-28 09:19:00 -0800845 notifier_->WriteCryptoData(encryption_level, data.length(), offset);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500846 } else {
fayang18ff23b2020-01-28 09:19:00 -0800847 bytes_written = QuicConnection::SendCryptoData(encryption_level,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500848 data.length(), offset);
849 }
850 return QuicConsumedData(bytes_written, /*fin_consumed*/ false);
851 }
852
853 void set_version(ParsedQuicVersion version) {
854 QuicConnectionPeer::GetFramer(this)->set_version(version);
855 }
856
857 void SetSupportedVersions(const ParsedQuicVersionVector& versions) {
858 QuicConnectionPeer::GetFramer(this)->SetSupportedVersions(versions);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500859 writer()->SetSupportedVersions(versions);
860 }
861
862 void set_perspective(Perspective perspective) {
863 writer()->set_perspective(perspective);
864 QuicConnectionPeer::SetPerspective(this, perspective);
865 }
866
867 // Enable path MTU discovery. Assumes that the test is performed from the
wub031d47c2019-11-21 08:04:07 -0800868 // server perspective and the higher value of MTU target is used.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500869 void EnablePathMtuDiscovery(MockSendAlgorithm* send_algorithm) {
wub031d47c2019-11-21 08:04:07 -0800870 ASSERT_EQ(Perspective::IS_SERVER, perspective());
QUICHE teama6ef0a62019-03-07 20:34:33 -0500871
872 QuicConfig config;
873 QuicTagVector connection_options;
874 connection_options.push_back(kMTUH);
wub031d47c2019-11-21 08:04:07 -0800875 config.SetInitialReceivedConnectionOptions(connection_options);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500876 EXPECT_CALL(*send_algorithm, SetFromConfig(_, _));
877 SetFromConfig(config);
878
879 // Normally, the pacing would be disabled in the test, but calling
880 // SetFromConfig enables it. Set nearly-infinite bandwidth to make the
881 // pacing algorithm work.
882 EXPECT_CALL(*send_algorithm, PacingRate(_))
883 .WillRepeatedly(Return(QuicBandwidth::Infinite()));
884 }
885
886 TestAlarmFactory::TestAlarm* GetAckAlarm() {
887 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
888 QuicConnectionPeer::GetAckAlarm(this));
889 }
890
891 TestAlarmFactory::TestAlarm* GetPingAlarm() {
892 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
893 QuicConnectionPeer::GetPingAlarm(this));
894 }
895
896 TestAlarmFactory::TestAlarm* GetRetransmissionAlarm() {
897 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
898 QuicConnectionPeer::GetRetransmissionAlarm(this));
899 }
900
901 TestAlarmFactory::TestAlarm* GetSendAlarm() {
902 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
903 QuicConnectionPeer::GetSendAlarm(this));
904 }
905
906 TestAlarmFactory::TestAlarm* GetTimeoutAlarm() {
fayang2205d952020-05-12 13:45:56 -0700907 if (GetQuicReloadableFlag(quic_use_idle_network_detector)) {
fayangb9c88442020-03-26 07:03:57 -0700908 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
909 QuicConnectionPeer::GetIdleNetworkDetectorAlarm(this));
910 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500911 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
912 QuicConnectionPeer::GetTimeoutAlarm(this));
913 }
914
915 TestAlarmFactory::TestAlarm* GetMtuDiscoveryAlarm() {
916 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
917 QuicConnectionPeer::GetMtuDiscoveryAlarm(this));
918 }
919
QUICHE teama6ef0a62019-03-07 20:34:33 -0500920 TestAlarmFactory::TestAlarm* GetProcessUndecryptablePacketsAlarm() {
921 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
922 QuicConnectionPeer::GetProcessUndecryptablePacketsAlarm(this));
923 }
924
fayangb59c6f12020-03-23 15:06:14 -0700925 TestAlarmFactory::TestAlarm* GetBlackholeDetectorAlarm() {
fayangb59c6f12020-03-23 15:06:14 -0700926 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
927 QuicConnectionPeer::GetBlackholeDetectorAlarm(this));
928 }
929
930 void PathDegradingTimeout() {
931 DCHECK(PathDegradingDetectionInProgress());
fayang2205d952020-05-12 13:45:56 -0700932 GetBlackholeDetectorAlarm()->Fire();
fayangb59c6f12020-03-23 15:06:14 -0700933 }
934
935 bool PathDegradingDetectionInProgress() {
fayang2205d952020-05-12 13:45:56 -0700936 return QuicConnectionPeer::GetPathDegradingDeadline(this).IsInitialized();
fayangb59c6f12020-03-23 15:06:14 -0700937 }
938
939 bool BlackholeDetectionInProgress() {
fayangb59c6f12020-03-23 15:06:14 -0700940 return QuicConnectionPeer::GetBlackholeDetectionDeadline(this)
941 .IsInitialized();
942 }
943
QUICHE teama6ef0a62019-03-07 20:34:33 -0500944 void SetMaxTailLossProbes(size_t max_tail_loss_probes) {
945 QuicSentPacketManagerPeer::SetMaxTailLossProbes(
946 QuicConnectionPeer::GetSentPacketManager(this), max_tail_loss_probes);
947 }
948
949 QuicByteCount GetBytesInFlight() {
ianswett9f459cb2019-04-21 06:39:59 -0700950 return QuicConnectionPeer::GetSentPacketManager(this)->GetBytesInFlight();
QUICHE teama6ef0a62019-03-07 20:34:33 -0500951 }
952
953 void set_notifier(SimpleSessionNotifier* notifier) { notifier_ = notifier; }
954
955 void ReturnEffectivePeerAddressForNextPacket(const QuicSocketAddress& addr) {
vasilvv0fc587f2019-09-06 13:33:08 -0700956 next_effective_peer_addr_ = std::make_unique<QuicSocketAddress>(addr);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500957 }
958
fayang5f135052019-08-22 17:59:40 -0700959 bool PtoEnabled() {
960 if (QuicConnectionPeer::GetSentPacketManager(this)->pto_enabled()) {
961 // PTO mode is default enabled for T099. And TLP/RTO related tests are
962 // stale.
fayang5d011982020-05-13 14:14:38 -0700963 DCHECK(PROTOCOL_TLS1_3 == version().handshake_protocol ||
964 GetQuicReloadableFlag(quic_default_on_pto));
fayang5f135052019-08-22 17:59:40 -0700965 return true;
966 }
967 return false;
968 }
969
nharper46833c32019-05-15 21:33:05 -0700970 SimpleDataProducer* producer() { return &producer_; }
971
QUICHE teama6ef0a62019-03-07 20:34:33 -0500972 using QuicConnection::active_effective_peer_migration_type;
973 using QuicConnection::IsCurrentPacketConnectivityProbing;
974 using QuicConnection::SelectMutualVersion;
975 using QuicConnection::SendProbingRetransmissions;
976 using QuicConnection::set_defer_send_in_response_to_packets;
977
978 protected:
979 QuicSocketAddress GetEffectivePeerAddressFromCurrentPacket() const override {
980 if (next_effective_peer_addr_) {
981 return *std::move(next_effective_peer_addr_);
982 }
983 return QuicConnection::GetEffectivePeerAddressFromCurrentPacket();
984 }
985
986 private:
987 TestPacketWriter* writer() {
988 return static_cast<TestPacketWriter*>(QuicConnection::writer());
989 }
990
991 SimpleDataProducer producer_;
992
993 SimpleSessionNotifier* notifier_;
994
995 std::unique_ptr<QuicSocketAddress> next_effective_peer_addr_;
996};
997
998enum class AckResponse { kDefer, kImmediate };
999
1000// Run tests with combinations of {ParsedQuicVersion, AckResponse}.
1001struct TestParams {
1002 TestParams(ParsedQuicVersion version,
1003 AckResponse ack_response,
1004 bool no_stop_waiting)
1005 : version(version),
1006 ack_response(ack_response),
1007 no_stop_waiting(no_stop_waiting) {}
1008
QUICHE teama6ef0a62019-03-07 20:34:33 -05001009 ParsedQuicVersion version;
1010 AckResponse ack_response;
1011 bool no_stop_waiting;
1012};
1013
dschinazi142051a2019-09-18 18:17:29 -07001014// Used by ::testing::PrintToStringParamName().
1015std::string PrintToString(const TestParams& p) {
dmcardlecf0bfcf2019-12-13 08:08:21 -08001016 return quiche::QuicheStrCat(
dschinazi142051a2019-09-18 18:17:29 -07001017 ParsedQuicVersionToString(p.version), "_",
1018 (p.ack_response == AckResponse::kDefer ? "defer" : "immediate"), "_",
1019 (p.no_stop_waiting ? "No" : ""), "StopWaiting");
1020}
1021
QUICHE teama6ef0a62019-03-07 20:34:33 -05001022// Constructs various test permutations.
1023std::vector<TestParams> GetTestParams() {
1024 QuicFlagSaver flags;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001025 std::vector<TestParams> params;
1026 ParsedQuicVersionVector all_supported_versions = AllSupportedVersions();
1027 for (size_t i = 0; i < all_supported_versions.size(); ++i) {
1028 for (AckResponse ack_response :
1029 {AckResponse::kDefer, AckResponse::kImmediate}) {
dschinazi142051a2019-09-18 18:17:29 -07001030 params.push_back(
1031 TestParams(all_supported_versions[i], ack_response, true));
1032 if (!VersionHasIetfInvariantHeader(
1033 all_supported_versions[i].transport_version)) {
fayangd4291e42019-05-30 10:31:21 -07001034 params.push_back(
dschinazi142051a2019-09-18 18:17:29 -07001035 TestParams(all_supported_versions[i], ack_response, false));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001036 }
1037 }
1038 }
1039 return params;
1040}
1041
1042class QuicConnectionTest : public QuicTestWithParam<TestParams> {
fkastenholz5d880a92019-06-21 09:01:56 -07001043 public:
1044 // For tests that do silent connection closes, no such packet is generated. In
1045 // order to verify the contents of the OnConnectionClosed upcall, EXPECTs
1046 // should invoke this method, saving the frame, and then the test can verify
1047 // the contents.
1048 void SaveConnectionCloseFrame(const QuicConnectionCloseFrame& frame,
1049 ConnectionCloseSource /*source*/) {
1050 saved_connection_close_frame_ = frame;
1051 connection_close_frame_count_++;
1052 }
1053
QUICHE teama6ef0a62019-03-07 20:34:33 -05001054 protected:
1055 QuicConnectionTest()
1056 : connection_id_(TestConnectionId()),
1057 framer_(SupportedVersions(version()),
1058 QuicTime::Zero(),
1059 Perspective::IS_CLIENT,
1060 connection_id_.length()),
1061 send_algorithm_(new StrictMock<MockSendAlgorithm>),
1062 loss_algorithm_(new MockLossAlgorithm()),
1063 helper_(new TestConnectionHelper(&clock_, &random_generator_)),
1064 alarm_factory_(new TestAlarmFactory()),
1065 peer_framer_(SupportedVersions(version()),
1066 QuicTime::Zero(),
1067 Perspective::IS_SERVER,
1068 connection_id_.length()),
1069 peer_creator_(connection_id_,
1070 &peer_framer_,
1071 /*delegate=*/nullptr),
1072 writer_(new TestPacketWriter(version(), &clock_)),
1073 connection_(connection_id_,
1074 kPeerAddress,
1075 helper_.get(),
1076 alarm_factory_.get(),
1077 writer_.get(),
1078 Perspective::IS_CLIENT,
1079 version()),
1080 creator_(QuicConnectionPeer::GetPacketCreator(&connection_)),
QUICHE teama6ef0a62019-03-07 20:34:33 -05001081 manager_(QuicConnectionPeer::GetSentPacketManager(&connection_)),
dmcardlecf0bfcf2019-12-13 08:08:21 -08001082 frame1_(0, false, 0, quiche::QuicheStringPiece(data1)),
1083 frame2_(0, false, 3, quiche::QuicheStringPiece(data2)),
1084 crypto_frame_(ENCRYPTION_INITIAL, 0, quiche::QuicheStringPiece(data1)),
QUICHE teama6ef0a62019-03-07 20:34:33 -05001085 packet_number_length_(PACKET_4BYTE_PACKET_NUMBER),
1086 connection_id_included_(CONNECTION_ID_PRESENT),
fkastenholz5d880a92019-06-21 09:01:56 -07001087 notifier_(&connection_),
1088 connection_close_frame_count_(0) {
dschinazi142051a2019-09-18 18:17:29 -07001089 QUIC_DVLOG(2) << "QuicConnectionTest(" << PrintToString(GetParam()) << ")";
QUICHE teama6ef0a62019-03-07 20:34:33 -05001090 connection_.set_defer_send_in_response_to_packets(GetParam().ack_response ==
1091 AckResponse::kDefer);
nharperc6b99512019-09-19 11:13:48 -07001092 framer_.SetInitialObfuscators(TestConnectionId());
1093 connection_.InstallInitialCrypters(TestConnectionId());
1094 CrypterPair crypters;
1095 CryptoUtils::CreateInitialObfuscators(Perspective::IS_SERVER, version(),
1096 TestConnectionId(), &crypters);
1097 peer_creator_.SetEncrypter(ENCRYPTION_INITIAL,
1098 std::move(crypters.encrypter));
1099 if (version().KnowsWhichDecrypterToUse()) {
1100 peer_framer_.InstallDecrypter(ENCRYPTION_INITIAL,
1101 std::move(crypters.decrypter));
1102 } else {
1103 peer_framer_.SetDecrypter(ENCRYPTION_INITIAL,
1104 std::move(crypters.decrypter));
1105 }
nharper2c9f02a2019-05-08 10:25:50 -07001106 for (EncryptionLevel level :
1107 {ENCRYPTION_ZERO_RTT, ENCRYPTION_FORWARD_SECURE}) {
1108 peer_creator_.SetEncrypter(
vasilvv0fc587f2019-09-06 13:33:08 -07001109 level, std::make_unique<NullEncrypter>(peer_framer_.perspective()));
nharper2c9f02a2019-05-08 10:25:50 -07001110 }
dschinazi7b9278c2019-05-20 07:36:21 -07001111 QuicFramerPeer::SetLastSerializedServerConnectionId(
QUICHE teama6ef0a62019-03-07 20:34:33 -05001112 QuicConnectionPeer::GetFramer(&connection_), connection_id_);
nharperc6b99512019-09-19 11:13:48 -07001113 QuicFramerPeer::SetLastWrittenPacketNumberLength(
1114 QuicConnectionPeer::GetFramer(&connection_), packet_number_length_);
fayangd4291e42019-05-30 10:31:21 -07001115 if (VersionHasIetfInvariantHeader(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001116 EXPECT_TRUE(QuicConnectionPeer::GetNoStopWaitingFrames(&connection_));
1117 } else {
1118 QuicConnectionPeer::SetNoStopWaitingFrames(&connection_,
1119 GetParam().no_stop_waiting);
1120 }
nharper46833c32019-05-15 21:33:05 -07001121 QuicStreamId stream_id;
1122 if (QuicVersionUsesCryptoFrames(version().transport_version)) {
1123 stream_id = QuicUtils::GetFirstBidirectionalStreamId(
1124 version().transport_version, Perspective::IS_CLIENT);
1125 } else {
1126 stream_id = QuicUtils::GetCryptoStreamId(version().transport_version);
1127 }
1128 frame1_.stream_id = stream_id;
1129 frame2_.stream_id = stream_id;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001130 connection_.set_visitor(&visitor_);
fayangcff885a2019-10-22 07:39:04 -07001131 connection_.SetSessionNotifier(&notifier_);
1132 connection_.set_notifier(&notifier_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001133 connection_.SetSendAlgorithm(send_algorithm_);
1134 connection_.SetLossAlgorithm(loss_algorithm_.get());
1135 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
1136 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1137 .Times(AnyNumber());
wubf4ab9652020-02-20 14:45:43 -08001138 EXPECT_CALL(*send_algorithm_, OnPacketNeutered(_)).Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -05001139 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
1140 .WillRepeatedly(Return(kDefaultTCPMSS));
1141 EXPECT_CALL(*send_algorithm_, PacingRate(_))
1142 .WillRepeatedly(Return(QuicBandwidth::Zero()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001143 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
1144 .Times(AnyNumber())
1145 .WillRepeatedly(Return(QuicBandwidth::Zero()));
wub5cd49592019-11-25 15:17:13 -08001146 EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_))
1147 .Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -05001148 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
1149 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
1150 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
1151 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).Times(AnyNumber());
fayangd58736d2019-11-27 13:35:31 -08001152 EXPECT_CALL(visitor_, OnPacketDecrypted(_)).Times(AnyNumber());
fayangcff885a2019-10-22 07:39:04 -07001153 EXPECT_CALL(visitor_, OnCanWrite())
1154 .WillRepeatedly(Invoke(&notifier_, &SimpleSessionNotifier::OnCanWrite));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001155 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
1156 .WillRepeatedly(Return(false));
1157 EXPECT_CALL(visitor_, OnCongestionWindowChange(_)).Times(AnyNumber());
zhongyi83161e42019-08-19 09:06:25 -07001158 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(AnyNumber());
wub256b2d62019-11-25 08:46:55 -08001159 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
fayang2f2915d2020-01-24 06:47:15 -08001160 EXPECT_CALL(visitor_, OnOneRttPacketAcknowledged())
1161 .Times(testing::AtMost(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001162 EXPECT_CALL(*loss_algorithm_, GetLossTimeout())
1163 .WillRepeatedly(Return(QuicTime::Zero()));
1164 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
1165 .Times(AnyNumber());
fayang5014e922020-01-22 12:28:11 -08001166 EXPECT_CALL(visitor_, GetHandshakeState())
1167 .WillRepeatedly(Return(HANDSHAKE_START));
zhongyi546cc452019-04-12 15:27:49 -07001168 if (connection_.version().KnowsWhichDecrypterToUse()) {
1169 connection_.InstallDecrypter(
1170 ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07001171 std::make_unique<NullDecrypter>(Perspective::IS_CLIENT));
zhongyi546cc452019-04-12 15:27:49 -07001172 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001173 }
1174
1175 QuicConnectionTest(const QuicConnectionTest&) = delete;
1176 QuicConnectionTest& operator=(const QuicConnectionTest&) = delete;
1177
1178 ParsedQuicVersion version() { return GetParam().version; }
1179
QUICHE teama6ef0a62019-03-07 20:34:33 -05001180 QuicStopWaitingFrame* stop_waiting() {
1181 QuicConnectionPeer::PopulateStopWaitingFrame(&connection_, &stop_waiting_);
1182 return &stop_waiting_;
1183 }
1184
1185 QuicPacketNumber least_unacked() {
1186 if (writer_->stop_waiting_frames().empty()) {
1187 return QuicPacketNumber();
1188 }
1189 return writer_->stop_waiting_frames()[0].least_unacked;
1190 }
1191
1192 void use_tagging_decrypter() { writer_->use_tagging_decrypter(); }
1193
zhongyi546cc452019-04-12 15:27:49 -07001194 void SetDecrypter(EncryptionLevel level,
1195 std::unique_ptr<QuicDecrypter> decrypter) {
1196 if (connection_.version().KnowsWhichDecrypterToUse()) {
1197 connection_.InstallDecrypter(level, std::move(decrypter));
1198 connection_.RemoveDecrypter(ENCRYPTION_INITIAL);
1199 } else {
1200 connection_.SetDecrypter(level, std::move(decrypter));
1201 }
1202 }
1203
QUICHE teama6ef0a62019-03-07 20:34:33 -05001204 void ProcessPacket(uint64_t number) {
1205 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
1206 ProcessDataPacket(number);
1207 if (connection_.GetSendAlarm()->IsSet()) {
1208 connection_.GetSendAlarm()->Fire();
1209 }
1210 }
1211
1212 void ProcessReceivedPacket(const QuicSocketAddress& self_address,
1213 const QuicSocketAddress& peer_address,
1214 const QuicReceivedPacket& packet) {
1215 connection_.ProcessUdpPacket(self_address, peer_address, packet);
1216 if (connection_.GetSendAlarm()->IsSet()) {
1217 connection_.GetSendAlarm()->Fire();
1218 }
1219 }
1220
wub8a5dafa2020-05-13 12:30:17 -07001221 QuicFrame MakeCryptoFrame() const {
1222 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1223 return QuicFrame(new QuicCryptoFrame(crypto_frame_));
1224 }
1225 return QuicFrame(QuicStreamFrame(
1226 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
1227 0u, quiche::QuicheStringPiece()));
1228 }
1229
QUICHE teama6ef0a62019-03-07 20:34:33 -05001230 void ProcessFramePacket(QuicFrame frame) {
1231 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
1232 }
1233
1234 void ProcessFramePacketWithAddresses(QuicFrame frame,
1235 QuicSocketAddress self_address,
1236 QuicSocketAddress peer_address) {
1237 QuicFrames frames;
1238 frames.push_back(QuicFrame(frame));
zhongyif06ca342020-02-24 14:11:13 -08001239 return ProcessFramesPacketWithAddresses(frames, self_address, peer_address);
1240 }
1241
1242 void ProcessFramesPacketWithAddresses(QuicFrames frames,
1243 QuicSocketAddress self_address,
1244 QuicSocketAddress peer_address) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001245 QuicPacketCreatorPeer::SetSendVersionInPacket(
wub031d47c2019-11-21 08:04:07 -08001246 &peer_creator_,
1247 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_) <
1248 ENCRYPTION_FORWARD_SECURE &&
1249 connection_.perspective() == Perspective::IS_SERVER);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001250
dschinazi66dea072019-04-09 11:41:06 -07001251 char buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05001252 SerializedPacket serialized_packet =
dschinazi66dea072019-04-09 11:41:06 -07001253 QuicPacketCreatorPeer::SerializeAllFrames(
1254 &peer_creator_, frames, buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001255 connection_.ProcessUdpPacket(
1256 self_address, peer_address,
1257 QuicReceivedPacket(serialized_packet.encrypted_buffer,
1258 serialized_packet.encrypted_length, clock_.Now()));
1259 if (connection_.GetSendAlarm()->IsSet()) {
1260 connection_.GetSendAlarm()->Fire();
1261 }
1262 }
1263
1264 // Bypassing the packet creator is unrealistic, but allows us to process
1265 // packets the QuicPacketCreator won't allow us to create.
1266 void ForceProcessFramePacket(QuicFrame frame) {
1267 QuicFrames frames;
1268 frames.push_back(QuicFrame(frame));
zhongyi546cc452019-04-12 15:27:49 -07001269 bool send_version = connection_.perspective() == Perspective::IS_SERVER;
1270 if (connection_.version().KnowsWhichDecrypterToUse()) {
1271 send_version = true;
1272 }
1273 QuicPacketCreatorPeer::SetSendVersionInPacket(&peer_creator_, send_version);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001274 QuicPacketHeader header;
1275 QuicPacketCreatorPeer::FillPacketHeader(&peer_creator_, &header);
dschinazi66dea072019-04-09 11:41:06 -07001276 char encrypted_buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05001277 size_t length = peer_framer_.BuildDataPacket(
dschinazi66dea072019-04-09 11:41:06 -07001278 header, frames, encrypted_buffer, kMaxOutgoingPacketSize,
1279 ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001280 DCHECK_GT(length, 0u);
1281
1282 const size_t encrypted_length = peer_framer_.EncryptInPlace(
QUICHE team6987b4a2019-03-15 16:23:04 -07001283 ENCRYPTION_INITIAL, header.packet_number,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001284 GetStartOfEncryptedData(peer_framer_.version().transport_version,
1285 header),
dschinazi66dea072019-04-09 11:41:06 -07001286 length, kMaxOutgoingPacketSize, encrypted_buffer);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001287 DCHECK_GT(encrypted_length, 0u);
1288
1289 connection_.ProcessUdpPacket(
1290 kSelfAddress, kPeerAddress,
1291 QuicReceivedPacket(encrypted_buffer, encrypted_length, clock_.Now()));
1292 }
1293
1294 size_t ProcessFramePacketAtLevel(uint64_t number,
1295 QuicFrame frame,
1296 EncryptionLevel level) {
fayang01062942020-01-22 07:23:23 -08001297 QuicFrames frames;
1298 frames.push_back(frame);
1299 return ProcessFramesPacketAtLevel(number, frames, level);
1300 }
1301
1302 size_t ProcessFramesPacketAtLevel(uint64_t number,
1303 const QuicFrames& frames,
1304 EncryptionLevel level) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001305 QuicPacketHeader header;
1306 header.destination_connection_id = connection_id_;
1307 header.packet_number_length = packet_number_length_;
1308 header.destination_connection_id_included = connection_id_included_;
dschinazi5e1a7b22019-07-31 12:23:21 -07001309 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001310 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1311 }
zhongyi546cc452019-04-12 15:27:49 -07001312 if (level == ENCRYPTION_INITIAL &&
1313 peer_framer_.version().KnowsWhichDecrypterToUse()) {
1314 header.version_flag = true;
nharperd43f1d62019-07-01 15:18:20 -07001315 if (QuicVersionHasLongHeaderLengths(peer_framer_.transport_version())) {
1316 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
1317 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
1318 }
QUICHE team2252b702019-05-14 23:55:14 -04001319 }
dschinazi5e1a7b22019-07-31 12:23:21 -07001320 if (header.version_flag &&
QUICHE team2252b702019-05-14 23:55:14 -04001321 peer_framer_.perspective() == Perspective::IS_SERVER) {
1322 header.source_connection_id = connection_id_;
1323 header.source_connection_id_included = CONNECTION_ID_PRESENT;
zhongyi546cc452019-04-12 15:27:49 -07001324 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001325 header.packet_number = QuicPacketNumber(number);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001326 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
QUICHE teamcd098022019-03-22 18:49:55 -07001327 // Set the correct encryption level and encrypter on peer_creator and
1328 // peer_framer, respectively.
1329 peer_creator_.set_encryption_level(level);
1330 if (QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_) >
1331 ENCRYPTION_INITIAL) {
1332 peer_framer_.SetEncrypter(
1333 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
vasilvv0fc587f2019-09-06 13:33:08 -07001334 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teamcd098022019-03-22 18:49:55 -07001335 // Set the corresponding decrypter.
zhongyi546cc452019-04-12 15:27:49 -07001336 if (connection_.version().KnowsWhichDecrypterToUse()) {
1337 connection_.InstallDecrypter(
1338 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
vasilvv0fc587f2019-09-06 13:33:08 -07001339 std::make_unique<StrictTaggingDecrypter>(0x01));
zhongyi546cc452019-04-12 15:27:49 -07001340 connection_.RemoveDecrypter(ENCRYPTION_INITIAL);
1341 } else {
1342 connection_.SetDecrypter(
1343 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
vasilvv0fc587f2019-09-06 13:33:08 -07001344 std::make_unique<StrictTaggingDecrypter>(0x01));
zhongyi546cc452019-04-12 15:27:49 -07001345 }
QUICHE teamcd098022019-03-22 18:49:55 -07001346 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001347
dschinazi66dea072019-04-09 11:41:06 -07001348 char buffer[kMaxOutgoingPacketSize];
1349 size_t encrypted_length =
1350 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
1351 buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001352 connection_.ProcessUdpPacket(
1353 kSelfAddress, kPeerAddress,
QUICHE teamcd098022019-03-22 18:49:55 -07001354 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1355 if (connection_.GetSendAlarm()->IsSet()) {
1356 connection_.GetSendAlarm()->Fire();
1357 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001358 return encrypted_length;
1359 }
1360
1361 size_t ProcessDataPacket(uint64_t number) {
nharper2c9f02a2019-05-08 10:25:50 -07001362 return ProcessDataPacketAtLevel(number, false, ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001363 }
1364
1365 size_t ProcessDataPacket(QuicPacketNumber packet_number) {
nharper2c9f02a2019-05-08 10:25:50 -07001366 return ProcessDataPacketAtLevel(packet_number, false,
1367 ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001368 }
1369
1370 size_t ProcessDataPacketAtLevel(QuicPacketNumber packet_number,
1371 bool has_stop_waiting,
1372 EncryptionLevel level) {
1373 return ProcessDataPacketAtLevel(packet_number.ToUint64(), has_stop_waiting,
1374 level);
1375 }
1376
dschinazi17d42422019-06-18 16:35:07 -07001377 size_t ProcessCryptoPacketAtLevel(uint64_t number,
1378 EncryptionLevel /*level*/) {
fayangc31c9952019-06-05 13:54:48 -07001379 QuicPacketHeader header = ConstructPacketHeader(number, ENCRYPTION_INITIAL);
nharper46833c32019-05-15 21:33:05 -07001380 QuicFrames frames;
1381 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1382 frames.push_back(QuicFrame(&crypto_frame_));
1383 } else {
1384 frames.push_back(QuicFrame(frame1_));
1385 }
fayang5f135052019-08-22 17:59:40 -07001386 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
nharper46833c32019-05-15 21:33:05 -07001387 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
1388 char buffer[kMaxOutgoingPacketSize];
1389 peer_creator_.set_encryption_level(ENCRYPTION_INITIAL);
fayangc31c9952019-06-05 13:54:48 -07001390 size_t encrypted_length = peer_framer_.EncryptPayload(
1391 ENCRYPTION_INITIAL, QuicPacketNumber(number), *packet, buffer,
1392 kMaxOutgoingPacketSize);
nharper46833c32019-05-15 21:33:05 -07001393 connection_.ProcessUdpPacket(
1394 kSelfAddress, kPeerAddress,
1395 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1396 if (connection_.GetSendAlarm()->IsSet()) {
1397 connection_.GetSendAlarm()->Fire();
1398 }
1399 return encrypted_length;
1400 }
1401
QUICHE teama6ef0a62019-03-07 20:34:33 -05001402 size_t ProcessDataPacketAtLevel(uint64_t number,
1403 bool has_stop_waiting,
1404 EncryptionLevel level) {
1405 std::unique_ptr<QuicPacket> packet(
QUICHE team8c1daa22019-03-13 08:33:41 -07001406 ConstructDataPacket(number, has_stop_waiting, level));
dschinazi66dea072019-04-09 11:41:06 -07001407 char buffer[kMaxOutgoingPacketSize];
QUICHE teamcd098022019-03-22 18:49:55 -07001408 peer_creator_.set_encryption_level(level);
dschinazi66dea072019-04-09 11:41:06 -07001409 size_t encrypted_length =
1410 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
1411 buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001412 connection_.ProcessUdpPacket(
1413 kSelfAddress, kPeerAddress,
1414 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1415 if (connection_.GetSendAlarm()->IsSet()) {
1416 connection_.GetSendAlarm()->Fire();
1417 }
1418 return encrypted_length;
1419 }
1420
1421 void ProcessClosePacket(uint64_t number) {
1422 std::unique_ptr<QuicPacket> packet(ConstructClosePacket(number));
dschinazi66dea072019-04-09 11:41:06 -07001423 char buffer[kMaxOutgoingPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07001424 size_t encrypted_length = peer_framer_.EncryptPayload(
nharperc6b99512019-09-19 11:13:48 -07001425 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(number), *packet, buffer,
dschinazi66dea072019-04-09 11:41:06 -07001426 kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001427 connection_.ProcessUdpPacket(
1428 kSelfAddress, kPeerAddress,
1429 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
1430 }
1431
1432 QuicByteCount SendStreamDataToPeer(QuicStreamId id,
dmcardlecf0bfcf2019-12-13 08:08:21 -08001433 quiche::QuicheStringPiece data,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001434 QuicStreamOffset offset,
1435 StreamSendingState state,
1436 QuicPacketNumber* last_packet) {
1437 QuicByteCount packet_size;
fayang0fcbf352019-08-30 11:15:58 -07001438 // Save the last packet's size.
QUICHE teama6ef0a62019-03-07 20:34:33 -05001439 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
fayang0fcbf352019-08-30 11:15:58 -07001440 .Times(AnyNumber())
1441 .WillRepeatedly(SaveArg<3>(&packet_size));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001442 connection_.SendStreamDataWithString(id, data, offset, state);
1443 if (last_packet != nullptr) {
1444 *last_packet = creator_->packet_number();
1445 }
1446 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1447 .Times(AnyNumber());
1448 return packet_size;
1449 }
1450
1451 void SendAckPacketToPeer() {
1452 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1453 {
fayanga4b37b22019-06-18 13:37:47 -07001454 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001455 connection_.SendAck();
1456 }
1457 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1458 .Times(AnyNumber());
1459 }
1460
1461 void SendRstStream(QuicStreamId id,
1462 QuicRstStreamErrorCode error,
1463 QuicStreamOffset bytes_written) {
fayangcff885a2019-10-22 07:39:04 -07001464 notifier_.WriteOrBufferRstStream(id, error, bytes_written);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001465 connection_.OnStreamReset(id, error);
1466 }
1467
fayangcff885a2019-10-22 07:39:04 -07001468 void SendPing() { notifier_.WriteOrBufferPing(); }
zhongyifbb25772019-04-10 16:54:08 -07001469
fayang61453cb2020-03-11 11:32:26 -07001470 MessageStatus SendMessage(quiche::QuicheStringPiece message) {
1471 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1472 QuicMemSliceStorage storage(nullptr, 0, nullptr, 0);
1473 return connection_.SendMessage(
1474 1,
1475 MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(), message,
1476 &storage),
1477 false);
1478 }
1479
QUICHE teama6ef0a62019-03-07 20:34:33 -05001480 void ProcessAckPacket(uint64_t packet_number, QuicAckFrame* frame) {
1481 if (packet_number > 1) {
1482 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, packet_number - 1);
1483 } else {
1484 QuicPacketCreatorPeer::ClearPacketNumber(&peer_creator_);
1485 }
1486 ProcessFramePacket(QuicFrame(frame));
1487 }
1488
1489 void ProcessAckPacket(QuicAckFrame* frame) {
1490 ProcessFramePacket(QuicFrame(frame));
1491 }
1492
1493 void ProcessStopWaitingPacket(QuicStopWaitingFrame frame) {
1494 ProcessFramePacket(QuicFrame(frame));
1495 }
1496
1497 size_t ProcessStopWaitingPacketAtLevel(uint64_t number,
1498 QuicStopWaitingFrame frame,
dschinazi17d42422019-06-18 16:35:07 -07001499 EncryptionLevel /*level*/) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001500 return ProcessFramePacketAtLevel(number, QuicFrame(frame),
1501 ENCRYPTION_ZERO_RTT);
1502 }
1503
1504 void ProcessGoAwayPacket(QuicGoAwayFrame* frame) {
1505 ProcessFramePacket(QuicFrame(frame));
1506 }
1507
1508 bool IsMissing(uint64_t number) {
fayangc31c9952019-06-05 13:54:48 -07001509 return IsAwaitingPacket(connection_.ack_frame(), QuicPacketNumber(number),
QUICHE teama6ef0a62019-03-07 20:34:33 -05001510 QuicPacketNumber());
1511 }
1512
1513 std::unique_ptr<QuicPacket> ConstructPacket(const QuicPacketHeader& header,
1514 const QuicFrames& frames) {
1515 auto packet = BuildUnsizedDataPacket(&peer_framer_, header, frames);
1516 EXPECT_NE(nullptr, packet.get());
1517 return packet;
1518 }
1519
nharper46833c32019-05-15 21:33:05 -07001520 QuicPacketHeader ConstructPacketHeader(uint64_t number,
1521 EncryptionLevel level) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001522 QuicPacketHeader header;
fayangd4291e42019-05-30 10:31:21 -07001523 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version()) &&
QUICHE team8c1daa22019-03-13 08:33:41 -07001524 level < ENCRYPTION_FORWARD_SECURE) {
1525 // Set long header type accordingly.
1526 header.version_flag = true;
nharperc6b99512019-09-19 11:13:48 -07001527 header.form = IETF_QUIC_LONG_HEADER_PACKET;
QUICHE team8c1daa22019-03-13 08:33:41 -07001528 header.long_packet_type = EncryptionlevelToLongHeaderType(level);
1529 if (QuicVersionHasLongHeaderLengths(
1530 peer_framer_.version().transport_version)) {
1531 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
1532 if (header.long_packet_type == INITIAL) {
1533 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
1534 }
1535 }
1536 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001537 // Set connection_id to peer's in memory representation as this data packet
1538 // is created by peer_framer.
dschinazi5e1a7b22019-07-31 12:23:21 -07001539 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
QUICHE team2252b702019-05-14 23:55:14 -04001540 header.source_connection_id = connection_id_;
1541 header.source_connection_id_included = connection_id_included_;
1542 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1543 } else {
1544 header.destination_connection_id = connection_id_;
1545 header.destination_connection_id_included = connection_id_included_;
1546 }
fayangd4291e42019-05-30 10:31:21 -07001547 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version()) &&
QUICHE teama6ef0a62019-03-07 20:34:33 -05001548 peer_framer_.perspective() == Perspective::IS_SERVER) {
1549 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
QUICHE team8c1daa22019-03-13 08:33:41 -07001550 if (header.version_flag) {
1551 header.source_connection_id = connection_id_;
1552 header.source_connection_id_included = CONNECTION_ID_PRESENT;
1553 if (GetParam().version.handshake_protocol == PROTOCOL_QUIC_CRYPTO &&
1554 header.long_packet_type == ZERO_RTT_PROTECTED) {
QUICHE team548d51b2019-03-14 10:06:54 -07001555 header.nonce = &kTestDiversificationNonce;
QUICHE team8c1daa22019-03-13 08:33:41 -07001556 }
1557 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001558 }
QUICHE team2252b702019-05-14 23:55:14 -04001559 header.packet_number_length = packet_number_length_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001560 header.packet_number = QuicPacketNumber(number);
nharper46833c32019-05-15 21:33:05 -07001561 return header;
1562 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001563
nharper46833c32019-05-15 21:33:05 -07001564 std::unique_ptr<QuicPacket> ConstructDataPacket(uint64_t number,
1565 bool has_stop_waiting,
1566 EncryptionLevel level) {
1567 QuicPacketHeader header = ConstructPacketHeader(number, level);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001568 QuicFrames frames;
1569 frames.push_back(QuicFrame(frame1_));
1570 if (has_stop_waiting) {
1571 frames.push_back(QuicFrame(stop_waiting_));
1572 }
1573 return ConstructPacket(header, frames);
1574 }
1575
wub8a5dafa2020-05-13 12:30:17 -07001576 std::unique_ptr<SerializedPacket> ConstructProbingPacket() {
fkastenholz305e1732019-06-18 05:01:22 -07001577 if (VersionHasIetfQuicFrames(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001578 QuicPathFrameBuffer payload = {
1579 {0xde, 0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xfe}};
1580 return QuicPacketCreatorPeer::
1581 SerializePathChallengeConnectivityProbingPacket(&peer_creator_,
1582 &payload);
1583 }
1584 return QuicPacketCreatorPeer::SerializeConnectivityProbingPacket(
1585 &peer_creator_);
1586 }
1587
1588 std::unique_ptr<QuicPacket> ConstructClosePacket(uint64_t number) {
1589 QuicPacketHeader header;
1590 // Set connection_id to peer's in memory representation as this connection
1591 // close packet is created by peer_framer.
dschinazi5e1a7b22019-07-31 12:23:21 -07001592 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
QUICHE team2252b702019-05-14 23:55:14 -04001593 header.source_connection_id = connection_id_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001594 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
fayangd4291e42019-05-30 10:31:21 -07001595 if (!VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04001596 header.source_connection_id_included = CONNECTION_ID_PRESENT;
1597 }
1598 } else {
1599 header.destination_connection_id = connection_id_;
fayangd4291e42019-05-30 10:31:21 -07001600 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04001601 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1602 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001603 }
1604
QUICHE team2252b702019-05-14 23:55:14 -04001605 header.packet_number = QuicPacketNumber(number);
1606
fkastenholz0d6554a2019-08-05 12:20:35 -07001607 QuicErrorCode kQuicErrorCode = QUIC_PEER_GOING_AWAY;
fkastenholz591814c2019-09-06 12:11:46 -07001608 QuicConnectionCloseFrame qccf(peer_framer_.transport_version(),
1609 kQuicErrorCode, "",
1610 /*transport_close_frame_type=*/0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001611 QuicFrames frames;
1612 frames.push_back(QuicFrame(&qccf));
1613 return ConstructPacket(header, frames);
1614 }
1615
1616 QuicTime::Delta DefaultRetransmissionTime() {
1617 return QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
1618 }
1619
1620 QuicTime::Delta DefaultDelayedAckTime() {
1621 return QuicTime::Delta::FromMilliseconds(kDefaultDelayedAckTimeMs);
1622 }
1623
1624 const QuicStopWaitingFrame InitStopWaitingFrame(uint64_t least_unacked) {
1625 QuicStopWaitingFrame frame;
1626 frame.least_unacked = QuicPacketNumber(least_unacked);
1627 return frame;
1628 }
1629
1630 // Construct a ack_frame that acks all packet numbers between 1 and
1631 // |largest_acked|, except |missing|.
1632 // REQUIRES: 1 <= |missing| < |largest_acked|
1633 QuicAckFrame ConstructAckFrame(uint64_t largest_acked, uint64_t missing) {
1634 return ConstructAckFrame(QuicPacketNumber(largest_acked),
1635 QuicPacketNumber(missing));
1636 }
1637
1638 QuicAckFrame ConstructAckFrame(QuicPacketNumber largest_acked,
1639 QuicPacketNumber missing) {
1640 if (missing == QuicPacketNumber(1)) {
1641 return InitAckFrame({{missing + 1, largest_acked + 1}});
1642 }
1643 return InitAckFrame(
1644 {{QuicPacketNumber(1), missing}, {missing + 1, largest_acked + 1}});
1645 }
1646
1647 // Undo nacking a packet within the frame.
1648 void AckPacket(QuicPacketNumber arrived, QuicAckFrame* frame) {
1649 EXPECT_FALSE(frame->packets.Contains(arrived));
1650 frame->packets.Add(arrived);
1651 }
1652
1653 void TriggerConnectionClose() {
1654 // Send an erroneous packet to close the connection.
fkastenholz5d880a92019-06-21 09:01:56 -07001655 EXPECT_CALL(visitor_,
1656 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
1657 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
1658
QUICHE teamcd098022019-03-22 18:49:55 -07001659 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1660 // Triggers a connection by receiving ACK of unsent packet.
1661 QuicAckFrame frame = InitAckFrame(10000);
1662 ProcessAckPacket(1, &frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001663 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1664 nullptr);
fkastenholz5d880a92019-06-21 09:01:56 -07001665 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08001666 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
1667 IsError(QUIC_INVALID_ACK_DATA));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001668 }
1669
1670 void BlockOnNextWrite() {
1671 writer_->BlockOnNextWrite();
1672 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
1673 }
1674
1675 void SimulateNextPacketTooLarge() { writer_->SimulateNextPacketTooLarge(); }
1676
1677 void AlwaysGetPacketTooLarge() { writer_->AlwaysGetPacketTooLarge(); }
1678
1679 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
1680 writer_->SetWritePauseTimeDelta(delta);
1681 }
1682
1683 void CongestionBlockWrites() {
1684 EXPECT_CALL(*send_algorithm_, CanSend(_))
1685 .WillRepeatedly(testing::Return(false));
1686 }
1687
1688 void CongestionUnblockWrites() {
1689 EXPECT_CALL(*send_algorithm_, CanSend(_))
1690 .WillRepeatedly(testing::Return(true));
1691 }
1692
1693 void set_perspective(Perspective perspective) {
1694 connection_.set_perspective(perspective);
1695 if (perspective == Perspective::IS_SERVER) {
1696 connection_.set_can_truncate_connection_ids(true);
wub256b2d62019-11-25 08:46:55 -08001697 QuicConnectionPeer::SetNegotiatedVersion(&connection_);
wubbea386e2020-01-27 09:04:51 -08001698 connection_.OnSuccessfulVersionNegotiation();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001699 }
1700 QuicFramerPeer::SetPerspective(&peer_framer_,
nharper4eba09b2019-06-26 20:17:25 -07001701 QuicUtils::InvertPerspective(perspective));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001702 }
1703
1704 void set_packets_between_probes_base(
1705 const QuicPacketCount packets_between_probes_base) {
wub173916e2019-11-27 14:36:24 -08001706 QuicConnectionPeer::ReInitializeMtuDiscoverer(
1707 &connection_, packets_between_probes_base,
1708 QuicPacketNumber(packets_between_probes_base));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001709 }
1710
1711 bool IsDefaultTestConfiguration() {
1712 TestParams p = GetParam();
1713 return p.ack_response == AckResponse::kImmediate &&
1714 p.version == AllSupportedVersions()[0] && p.no_stop_waiting;
1715 }
1716
fkastenholz5d880a92019-06-21 09:01:56 -07001717 void TestConnectionCloseQuicErrorCode(QuicErrorCode expected_code) {
1718 // Not strictly needed for this test, but is commonly done.
1719 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1720 nullptr);
1721 const std::vector<QuicConnectionCloseFrame>& connection_close_frames =
1722 writer_->connection_close_frames();
1723 ASSERT_EQ(1u, connection_close_frames.size());
bnc77e77b82020-04-05 10:36:49 -07001724
dschinazi39e5e552020-05-06 13:55:24 -07001725 EXPECT_THAT(connection_close_frames[0].quic_error_code,
1726 IsError(expected_code));
bnc77e77b82020-04-05 10:36:49 -07001727
fkastenholz0d6554a2019-08-05 12:20:35 -07001728 if (!VersionHasIetfQuicFrames(version().transport_version)) {
dschinazi39e5e552020-05-06 13:55:24 -07001729 EXPECT_THAT(connection_close_frames[0].wire_error_code,
1730 IsError(expected_code));
fkastenholz0d6554a2019-08-05 12:20:35 -07001731 EXPECT_EQ(GOOGLE_QUIC_CONNECTION_CLOSE,
1732 connection_close_frames[0].close_type);
1733 return;
1734 }
1735
1736 QuicErrorCodeToIetfMapping mapping =
1737 QuicErrorCodeToTransportErrorCode(expected_code);
1738
bnc0054cc62020-04-09 18:22:57 -07001739 if (mapping.is_transport_close) {
fkastenholz0d6554a2019-08-05 12:20:35 -07001740 // This Google QUIC Error Code maps to a transport close,
1741 EXPECT_EQ(IETF_QUIC_TRANSPORT_CONNECTION_CLOSE,
1742 connection_close_frames[0].close_type);
fkastenholz0d6554a2019-08-05 12:20:35 -07001743 } else {
1744 // This maps to an application close.
fkastenholz0d6554a2019-08-05 12:20:35 -07001745 EXPECT_EQ(IETF_QUIC_APPLICATION_CONNECTION_CLOSE,
1746 connection_close_frames[0].close_type);
fkastenholz0d6554a2019-08-05 12:20:35 -07001747 }
bnc0054cc62020-04-09 18:22:57 -07001748 EXPECT_EQ(mapping.error_code, connection_close_frames[0].wire_error_code);
fkastenholz5d880a92019-06-21 09:01:56 -07001749 }
1750
wub031d47c2019-11-21 08:04:07 -08001751 void MtuDiscoveryTestInit() {
1752 set_perspective(Perspective::IS_SERVER);
wub031d47c2019-11-21 08:04:07 -08001753 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
fayang6a258412020-05-28 08:57:12 -07001754 if (version().SupportsAntiAmplificationLimit()) {
1755 QuicConnectionPeer::SetAddressValidated(&connection_);
1756 }
wub031d47c2019-11-21 08:04:07 -08001757 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1758 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
1759 // QuicFramer::GetMaxPlaintextSize uses the smallest max plaintext size
1760 // across all encrypters. The initial encrypter used with IETF QUIC has a
1761 // 16-byte overhead, while the NullEncrypter used throughout this test has a
1762 // 12-byte overhead. This test tests behavior that relies on computing the
1763 // packet size correctly, so by unsetting the initial encrypter, we avoid
1764 // having a mismatch between the overheads for the encrypters used. In
1765 // non-test scenarios all encrypters used for a given connection have the
1766 // same overhead, either 12 bytes for ones using Google QUIC crypto, or 16
1767 // bytes for ones using TLS.
1768 connection_.SetEncrypter(ENCRYPTION_INITIAL, nullptr);
wubecb643f2020-03-19 08:58:46 -07001769 // Prevent packets from being coalesced.
1770 EXPECT_CALL(visitor_, GetHandshakeState())
1771 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
wub031d47c2019-11-21 08:04:07 -08001772 EXPECT_TRUE(connection_.connected());
1773 }
1774
dschinazi39e5e552020-05-06 13:55:24 -07001775 void TestClientRetryHandling(bool invalid_retry_tag,
dschinazie7c38a52020-05-29 15:25:45 -07001776 bool missing_original_id_in_config,
1777 bool wrong_original_id_in_config,
1778 bool missing_retry_id_in_config,
1779 bool wrong_retry_id_in_config);
dschinazi39e5e552020-05-06 13:55:24 -07001780
QUICHE teama6ef0a62019-03-07 20:34:33 -05001781 QuicConnectionId connection_id_;
1782 QuicFramer framer_;
1783
1784 MockSendAlgorithm* send_algorithm_;
1785 std::unique_ptr<MockLossAlgorithm> loss_algorithm_;
1786 MockClock clock_;
1787 MockRandom random_generator_;
1788 SimpleBufferAllocator buffer_allocator_;
1789 std::unique_ptr<TestConnectionHelper> helper_;
1790 std::unique_ptr<TestAlarmFactory> alarm_factory_;
1791 QuicFramer peer_framer_;
1792 QuicPacketCreator peer_creator_;
1793 std::unique_ptr<TestPacketWriter> writer_;
1794 TestConnection connection_;
1795 QuicPacketCreator* creator_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001796 QuicSentPacketManager* manager_;
1797 StrictMock<MockQuicConnectionVisitor> visitor_;
1798
1799 QuicStreamFrame frame1_;
1800 QuicStreamFrame frame2_;
nharper46833c32019-05-15 21:33:05 -07001801 QuicCryptoFrame crypto_frame_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001802 QuicAckFrame ack_;
1803 QuicStopWaitingFrame stop_waiting_;
1804 QuicPacketNumberLength packet_number_length_;
1805 QuicConnectionIdIncluded connection_id_included_;
1806
1807 SimpleSessionNotifier notifier_;
fkastenholz5d880a92019-06-21 09:01:56 -07001808
1809 QuicConnectionCloseFrame saved_connection_close_frame_;
1810 int connection_close_frame_count_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001811};
1812
1813// Run all end to end tests with all supported versions.
dschinazi39e5e552020-05-06 13:55:24 -07001814INSTANTIATE_TEST_SUITE_P(QuicConnectionTests,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001815 QuicConnectionTest,
dschinazi142051a2019-09-18 18:17:29 -07001816 ::testing::ValuesIn(GetTestParams()),
1817 ::testing::PrintToStringParamName());
QUICHE teama6ef0a62019-03-07 20:34:33 -05001818
fkastenholz0d6554a2019-08-05 12:20:35 -07001819// These two tests ensure that the QuicErrorCode mapping works correctly.
1820// Both tests expect to see a Google QUIC close if not running IETF QUIC.
1821// If running IETF QUIC, the first will generate a transport connection
1822// close, the second an application connection close.
1823// The connection close codes for the two tests are manually chosen;
1824// they are expected to always map to transport- and application-
dschinazi39e5e552020-05-06 13:55:24 -07001825// closes, respectively. If that changes, new codes should be chosen.
fkastenholz0d6554a2019-08-05 12:20:35 -07001826TEST_P(QuicConnectionTest, CloseErrorCodeTestTransport) {
1827 EXPECT_TRUE(connection_.connected());
1828 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
1829 connection_.CloseConnection(
1830 IETF_QUIC_PROTOCOL_VIOLATION, "Should be transport close",
1831 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1832 EXPECT_FALSE(connection_.connected());
1833 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
1834}
1835
1836// Test that the IETF QUIC Error code mapping function works
1837// properly for application connection close codes.
1838TEST_P(QuicConnectionTest, CloseErrorCodeTestApplication) {
1839 EXPECT_TRUE(connection_.connected());
1840 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
1841 connection_.CloseConnection(
1842 QUIC_HEADERS_STREAM_DATA_DECOMPRESS_FAILURE,
1843 "Should be application close",
1844 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1845 EXPECT_FALSE(connection_.connected());
1846 TestConnectionCloseQuicErrorCode(QUIC_HEADERS_STREAM_DATA_DECOMPRESS_FAILURE);
1847}
1848
QUICHE teama6ef0a62019-03-07 20:34:33 -05001849TEST_P(QuicConnectionTest, SelfAddressChangeAtClient) {
1850 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1851
1852 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
1853 EXPECT_TRUE(connection_.connected());
1854
nharper46833c32019-05-15 21:33:05 -07001855 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07001856 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1857 } else {
nharper46833c32019-05-15 21:33:05 -07001858 EXPECT_CALL(visitor_, OnStreamFrame(_));
1859 }
wub8a5dafa2020-05-13 12:30:17 -07001860 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
1861 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001862 // Cause change in self_address.
1863 QuicIpAddress host;
1864 host.FromString("1.1.1.1");
1865 QuicSocketAddress self_address(host, 123);
nharper46833c32019-05-15 21:33:05 -07001866 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1867 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1868 } else {
1869 EXPECT_CALL(visitor_, OnStreamFrame(_));
1870 }
wub8a5dafa2020-05-13 12:30:17 -07001871 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address,
1872 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001873 EXPECT_TRUE(connection_.connected());
1874}
1875
1876TEST_P(QuicConnectionTest, SelfAddressChangeAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001877 set_perspective(Perspective::IS_SERVER);
1878 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1879
1880 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1881 EXPECT_TRUE(connection_.connected());
1882
nharper46833c32019-05-15 21:33:05 -07001883 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07001884 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1885 } else {
nharper46833c32019-05-15 21:33:05 -07001886 EXPECT_CALL(visitor_, OnStreamFrame(_));
1887 }
wub8a5dafa2020-05-13 12:30:17 -07001888 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
1889 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001890 // Cause change in self_address.
1891 QuicIpAddress host;
1892 host.FromString("1.1.1.1");
1893 QuicSocketAddress self_address(host, 123);
1894 EXPECT_CALL(visitor_, AllowSelfAddressChange()).WillOnce(Return(false));
fkastenholz5d880a92019-06-21 09:01:56 -07001895 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
wub8a5dafa2020-05-13 12:30:17 -07001896 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address,
1897 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001898 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07001899 TestConnectionCloseQuicErrorCode(QUIC_ERROR_MIGRATING_ADDRESS);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001900}
1901
1902TEST_P(QuicConnectionTest, AllowSelfAddressChangeToMappedIpv4AddressAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001903 set_perspective(Perspective::IS_SERVER);
1904 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1905
1906 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1907 EXPECT_TRUE(connection_.connected());
1908
nharper46833c32019-05-15 21:33:05 -07001909 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07001910 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(3);
1911 } else {
nharper46833c32019-05-15 21:33:05 -07001912 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(3);
1913 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001914 QuicIpAddress host;
1915 host.FromString("1.1.1.1");
1916 QuicSocketAddress self_address1(host, 443);
wub8a5dafa2020-05-13 12:30:17 -07001917 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address1,
1918 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001919 // Cause self_address change to mapped Ipv4 address.
1920 QuicIpAddress host2;
dmcardlecf0bfcf2019-12-13 08:08:21 -08001921 host2.FromString(quiche::QuicheStrCat(
1922 "::ffff:", connection_.self_address().host().ToString()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001923 QuicSocketAddress self_address2(host2, connection_.self_address().port());
wub8a5dafa2020-05-13 12:30:17 -07001924 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address2,
1925 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001926 EXPECT_TRUE(connection_.connected());
1927 // self_address change back to Ipv4 address.
wub8a5dafa2020-05-13 12:30:17 -07001928 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address1,
1929 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001930 EXPECT_TRUE(connection_.connected());
1931}
1932
1933TEST_P(QuicConnectionTest, ClientAddressChangeAndPacketReordered) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001934 set_perspective(Perspective::IS_SERVER);
1935 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1936
1937 // Clear direct_peer_address.
1938 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1939 // Clear effective_peer_address, it is the same as direct_peer_address for
1940 // this test.
1941 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1942 QuicSocketAddress());
1943
nharper46833c32019-05-15 21:33:05 -07001944 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07001945 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1946 } else {
nharper46833c32019-05-15 21:33:05 -07001947 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1948 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001949 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001950 const QuicSocketAddress kNewPeerAddress =
1951 QuicSocketAddress(QuicIpAddress::Loopback6(),
1952 /*port=*/23456);
wub8a5dafa2020-05-13 12:30:17 -07001953 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
1954 kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001955 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1956 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1957
1958 // Decrease packet number to simulate out-of-order packets.
1959 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 4);
1960 // This is an old packet, do not migrate.
1961 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
wub8a5dafa2020-05-13 12:30:17 -07001962 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
1963 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001964 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1965 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1966}
1967
1968TEST_P(QuicConnectionTest, PeerAddressChangeAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001969 set_perspective(Perspective::IS_SERVER);
1970 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1971 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1972
1973 // Clear direct_peer_address.
1974 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1975 // Clear effective_peer_address, it is the same as direct_peer_address for
1976 // this test.
1977 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1978 QuicSocketAddress());
1979 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1980
nharper46833c32019-05-15 21:33:05 -07001981 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07001982 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1983 } else {
nharper46833c32019-05-15 21:33:05 -07001984 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1985 }
wub8a5dafa2020-05-13 12:30:17 -07001986 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
1987 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001988 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1989 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1990
1991 // Process another packet with a different peer address on server side will
1992 // start connection migration.
1993 const QuicSocketAddress kNewPeerAddress =
1994 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
1995 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
wub8a5dafa2020-05-13 12:30:17 -07001996 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
1997 kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001998 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1999 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2000}
2001
2002TEST_P(QuicConnectionTest, EffectivePeerAddressChangeAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002003 set_perspective(Perspective::IS_SERVER);
2004 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2005 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
fayang6a258412020-05-28 08:57:12 -07002006 if (version().SupportsAntiAmplificationLimit()) {
2007 QuicConnectionPeer::SetAddressValidated(&connection_);
2008 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002009
2010 // Clear direct_peer_address.
2011 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2012 // Clear effective_peer_address, it is different from direct_peer_address for
2013 // this test.
2014 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2015 QuicSocketAddress());
2016 const QuicSocketAddress kEffectivePeerAddress =
2017 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/43210);
2018 connection_.ReturnEffectivePeerAddressForNextPacket(kEffectivePeerAddress);
2019
nharper46833c32019-05-15 21:33:05 -07002020 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07002021 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2022 } else {
nharper46833c32019-05-15 21:33:05 -07002023 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2024 }
wub8a5dafa2020-05-13 12:30:17 -07002025 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2026 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002027 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2028 EXPECT_EQ(kEffectivePeerAddress, connection_.effective_peer_address());
2029
2030 // Process another packet with the same direct peer address and different
2031 // effective peer address on server side will start connection migration.
2032 const QuicSocketAddress kNewEffectivePeerAddress =
2033 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/54321);
2034 connection_.ReturnEffectivePeerAddressForNextPacket(kNewEffectivePeerAddress);
2035 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
wub8a5dafa2020-05-13 12:30:17 -07002036 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2037 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002038 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2039 EXPECT_EQ(kNewEffectivePeerAddress, connection_.effective_peer_address());
2040
2041 // Process another packet with a different direct peer address and the same
2042 // effective peer address on server side will not start connection migration.
2043 const QuicSocketAddress kNewPeerAddress =
2044 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2045 connection_.ReturnEffectivePeerAddressForNextPacket(kNewEffectivePeerAddress);
2046 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2047 // ack_frame is used to complete the migration started by the last packet, we
2048 // need to make sure a new migration does not start after the previous one is
2049 // completed.
2050 QuicAckFrame ack_frame = InitAckFrame(1);
2051 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
2052 ProcessFramePacketWithAddresses(QuicFrame(&ack_frame), kSelfAddress,
2053 kNewPeerAddress);
2054 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2055 EXPECT_EQ(kNewEffectivePeerAddress, connection_.effective_peer_address());
2056
2057 // Process another packet with different direct peer address and different
2058 // effective peer address on server side will start connection migration.
2059 const QuicSocketAddress kNewerEffectivePeerAddress =
2060 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/65432);
2061 const QuicSocketAddress kFinalPeerAddress =
2062 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/34567);
2063 connection_.ReturnEffectivePeerAddressForNextPacket(
2064 kNewerEffectivePeerAddress);
2065 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
wub8a5dafa2020-05-13 12:30:17 -07002066 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2067 kFinalPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002068 EXPECT_EQ(kFinalPeerAddress, connection_.peer_address());
2069 EXPECT_EQ(kNewerEffectivePeerAddress, connection_.effective_peer_address());
2070 EXPECT_EQ(PORT_CHANGE, connection_.active_effective_peer_migration_type());
2071
2072 // While the previous migration is ongoing, process another packet with the
2073 // same direct peer address and different effective peer address on server
2074 // side will start a new connection migration.
2075 const QuicSocketAddress kNewestEffectivePeerAddress =
2076 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/65430);
2077 connection_.ReturnEffectivePeerAddressForNextPacket(
2078 kNewestEffectivePeerAddress);
2079 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
2080 EXPECT_CALL(*send_algorithm_, OnConnectionMigration()).Times(1);
wub8a5dafa2020-05-13 12:30:17 -07002081 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2082 kFinalPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002083 EXPECT_EQ(kFinalPeerAddress, connection_.peer_address());
2084 EXPECT_EQ(kNewestEffectivePeerAddress, connection_.effective_peer_address());
2085 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
2086 connection_.active_effective_peer_migration_type());
2087}
2088
zhongyif06ca342020-02-24 14:11:13 -08002089TEST_P(QuicConnectionTest, ReceivePathProbeWithNoAddressChangeAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002090 set_perspective(Perspective::IS_SERVER);
2091 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2092 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2093
2094 // Clear direct_peer_address.
2095 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2096 // Clear effective_peer_address, it is the same as direct_peer_address for
2097 // this test.
2098 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2099 QuicSocketAddress());
2100 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2101
nharper46833c32019-05-15 21:33:05 -07002102 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07002103 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2104 } else {
nharper46833c32019-05-15 21:33:05 -07002105 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2106 }
wub8a5dafa2020-05-13 12:30:17 -07002107 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2108 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002109 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2110 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2111
2112 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyi83161e42019-08-19 09:06:25 -07002113 EXPECT_CALL(visitor_, OnPacketReceived(_, _, false)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002114
2115 // Process a padded PING or PATH CHALLENGE packet with no peer address change
2116 // on server side will be ignored.
wub8a5dafa2020-05-13 12:30:17 -07002117 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
zhongyif06ca342020-02-24 14:11:13 -08002118
QUICHE teama6ef0a62019-03-07 20:34:33 -05002119 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2120 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2121 probing_packet->encrypted_length),
2122 clock_.Now()));
2123
2124 uint64_t num_probing_received =
2125 connection_.GetStats().num_connectivity_probing_received;
2126 ProcessReceivedPacket(kSelfAddress, kPeerAddress, *received);
2127
2128 EXPECT_EQ(num_probing_received,
2129 connection_.GetStats().num_connectivity_probing_received);
2130 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2131 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2132}
2133
wub54bd5bf2020-05-13 13:02:16 -07002134// Regression test for b/150161358.
2135TEST_P(QuicConnectionTest, BufferedMtuPacketTooBig) {
wub54bd5bf2020-05-13 13:02:16 -07002136 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
2137 writer_->SetWriteBlocked();
2138
2139 // Send a MTU packet while blocked. It should be buffered.
2140 connection_.SendMtuDiscoveryPacket(kMaxOutgoingPacketSize);
2141 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2142 EXPECT_TRUE(writer_->IsWriteBlocked());
2143
2144 writer_->AlwaysGetPacketTooLarge();
2145 writer_->SetWritable();
2146 connection_.OnCanWrite();
2147}
2148
QUICHE teama6ef0a62019-03-07 20:34:33 -05002149TEST_P(QuicConnectionTest, WriteOutOfOrderQueuedPackets) {
2150 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
fayangc31c9952019-06-05 13:54:48 -07002151 if (!IsDefaultTestConfiguration()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002152 return;
2153 }
2154
2155 set_perspective(Perspective::IS_CLIENT);
2156
2157 BlockOnNextWrite();
2158
2159 QuicStreamId stream_id = 2;
2160 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
2161
2162 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2163
2164 writer_->SetWritable();
2165 connection_.SendConnectivityProbingPacket(writer_.get(),
2166 connection_.peer_address());
fayange62e63c2019-12-04 07:16:25 -08002167 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
2168 connection_.OnCanWrite();
QUICHE teama6ef0a62019-03-07 20:34:33 -05002169}
2170
2171TEST_P(QuicConnectionTest, DiscardQueuedPacketsAfterConnectionClose) {
2172 // Regression test for b/74073386.
2173 {
2174 InSequence seq;
rch39c88ab2019-10-16 19:24:40 -07002175 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2176 .Times(AtLeast(1));
2177 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002178 }
2179
2180 set_perspective(Perspective::IS_CLIENT);
2181
2182 writer_->SimulateNextPacketTooLarge();
2183
2184 // This packet write should fail, which should cause the connection to close
2185 // after sending a connection close packet, then the failed packet should be
2186 // queued.
2187 connection_.SendStreamDataWithString(/*id=*/2, "foo", 0, NO_FIN);
2188
2189 EXPECT_FALSE(connection_.connected());
fayange62e63c2019-12-04 07:16:25 -08002190 // No need to buffer packets.
2191 EXPECT_EQ(0u, connection_.NumQueuedPackets());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002192
2193 EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
2194 connection_.OnCanWrite();
fayang0f0c4e62019-07-16 08:55:54 -07002195 EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002196}
2197
zhongyif06ca342020-02-24 14:11:13 -08002198// Receive a path probe request at the server side, i.e.,
2199// in non-IETF version: receive a padded PING packet with a peer addess change;
2200// in IETF version: receive a packet contains PATH CHALLENGE with peer address
2201// change.
2202TEST_P(QuicConnectionTest, ReceivePathProbingAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002203 set_perspective(Perspective::IS_SERVER);
2204 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2205 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2206
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) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002343 set_perspective(Perspective::IS_SERVER);
2344 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2345 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2346
2347 // Clear direct_peer_address.
2348 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2349 // Clear effective_peer_address, it is the same as direct_peer_address for
2350 // this test.
2351 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2352 QuicSocketAddress());
2353 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2354
nharper46833c32019-05-15 21:33:05 -07002355 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07002356 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2357 } else {
nharper46833c32019-05-15 21:33:05 -07002358 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2359 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002360 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
wub8a5dafa2020-05-13 12:30:17 -07002361 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2362 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002363 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2364 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2365
2366 // Decrease packet number to simulate out-of-order packets.
2367 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 4);
2368
2369 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyif06ca342020-02-24 14:11:13 -08002370 if (!GetParam().version.HasIetfQuicFrames()) {
2371 EXPECT_CALL(visitor_,
2372 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2373 .Times(1);
2374 } else {
2375 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2376 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002377
2378 // Process a padded PING packet from a new peer address on server side
2379 // is effectively receiving a connectivity probing, even if a newer packet has
2380 // been received before this one.
2381 const QuicSocketAddress kNewPeerAddress =
2382 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2383
wub8a5dafa2020-05-13 12:30:17 -07002384 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
QUICHE teama6ef0a62019-03-07 20:34:33 -05002385 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2386 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2387 probing_packet->encrypted_length),
2388 clock_.Now()));
2389
2390 uint64_t num_probing_received =
2391 connection_.GetStats().num_connectivity_probing_received;
2392 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2393
2394 EXPECT_EQ(num_probing_received + 1,
2395 connection_.GetStats().num_connectivity_probing_received);
2396 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2397 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2398}
2399
2400TEST_P(QuicConnectionTest, MigrateAfterProbingAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002401 set_perspective(Perspective::IS_SERVER);
2402 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2403 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2404
2405 // Clear direct_peer_address.
2406 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2407 // Clear effective_peer_address, it is the same as direct_peer_address for
2408 // this test.
2409 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2410 QuicSocketAddress());
2411 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2412
nharper46833c32019-05-15 21:33:05 -07002413 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07002414 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2415 } else {
nharper46833c32019-05-15 21:33:05 -07002416 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2417 }
wub8a5dafa2020-05-13 12:30:17 -07002418 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2419 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002420 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2421 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2422
2423 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyif06ca342020-02-24 14:11:13 -08002424 if (!GetParam().version.HasIetfQuicFrames()) {
2425 EXPECT_CALL(visitor_,
2426 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2427 .Times(1);
2428 } else {
2429 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2430 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002431
2432 // Process a padded PING packet from a new peer address on server side
2433 // is effectively receiving a connectivity probing.
2434 const QuicSocketAddress kNewPeerAddress =
2435 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2436
wub8a5dafa2020-05-13 12:30:17 -07002437 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
QUICHE teama6ef0a62019-03-07 20:34:33 -05002438 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2439 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2440 probing_packet->encrypted_length),
2441 clock_.Now()));
2442 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2443 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2444 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2445
2446 // Process another non-probing packet with the new peer address on server
2447 // side will start peer migration.
2448 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2449
wub8a5dafa2020-05-13 12:30:17 -07002450 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2451 kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002452 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2453 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2454}
2455
2456TEST_P(QuicConnectionTest, ReceivePaddedPingAtClient) {
2457 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2458 set_perspective(Perspective::IS_CLIENT);
2459 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2460
2461 // Clear direct_peer_address.
2462 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2463 // Clear effective_peer_address, it is the same as direct_peer_address for
2464 // this test.
2465 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2466 QuicSocketAddress());
2467 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2468
nharper46833c32019-05-15 21:33:05 -07002469 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07002470 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2471 } else {
nharper46833c32019-05-15 21:33:05 -07002472 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2473 }
wub8a5dafa2020-05-13 12:30:17 -07002474 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2475 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002476 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2477 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2478
2479 // Client takes all padded PING packet as speculative connectivity
2480 // probing packet, and reports to visitor.
2481 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyi83161e42019-08-19 09:06:25 -07002482 EXPECT_CALL(visitor_, OnPacketReceived(_, _, false)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002483
wub8a5dafa2020-05-13 12:30:17 -07002484 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
QUICHE teama6ef0a62019-03-07 20:34:33 -05002485 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2486 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2487 probing_packet->encrypted_length),
2488 clock_.Now()));
2489 uint64_t num_probing_received =
2490 connection_.GetStats().num_connectivity_probing_received;
2491 ProcessReceivedPacket(kSelfAddress, kPeerAddress, *received);
2492
2493 EXPECT_EQ(num_probing_received,
2494 connection_.GetStats().num_connectivity_probing_received);
2495 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2496 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2497}
2498
zhongyif06ca342020-02-24 14:11:13 -08002499TEST_P(QuicConnectionTest, ReceiveConnectivityProbingResponseAtClient) {
2500 // TODO(b/150095484): add test coverage for IETF to verify that client takes
2501 // PATH RESPONSE with peer address change as correct validation on the new
2502 // path.
2503 if (GetParam().version.HasIetfQuicFrames()) {
2504 return;
2505 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002506 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2507 set_perspective(Perspective::IS_CLIENT);
2508 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2509
2510 // Clear direct_peer_address.
2511 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2512 // Clear effective_peer_address, it is the same as direct_peer_address for
2513 // this test.
2514 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2515 QuicSocketAddress());
2516 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2517
nharper46833c32019-05-15 21:33:05 -07002518 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07002519 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2520 } else {
nharper46833c32019-05-15 21:33:05 -07002521 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2522 }
wub8a5dafa2020-05-13 12:30:17 -07002523 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2524 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002525 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2526 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2527
2528 // Process a padded PING packet with a different self address on client side
2529 // is effectively receiving a connectivity probing.
2530 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyif06ca342020-02-24 14:11:13 -08002531 if (!GetParam().version.HasIetfQuicFrames()) {
2532 EXPECT_CALL(visitor_,
2533 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2534 .Times(1);
2535 } else {
2536 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2537 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002538
2539 const QuicSocketAddress kNewSelfAddress =
2540 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2541
wub8a5dafa2020-05-13 12:30:17 -07002542 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
QUICHE teama6ef0a62019-03-07 20:34:33 -05002543 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2544 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2545 probing_packet->encrypted_length),
2546 clock_.Now()));
2547 uint64_t num_probing_received =
2548 connection_.GetStats().num_connectivity_probing_received;
2549 ProcessReceivedPacket(kNewSelfAddress, kPeerAddress, *received);
2550
2551 EXPECT_EQ(num_probing_received + 1,
2552 connection_.GetStats().num_connectivity_probing_received);
2553 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2554 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2555}
2556
2557TEST_P(QuicConnectionTest, PeerAddressChangeAtClient) {
2558 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2559 set_perspective(Perspective::IS_CLIENT);
2560 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2561
2562 // Clear direct_peer_address.
2563 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2564 // Clear effective_peer_address, it is the same as direct_peer_address for
2565 // this test.
2566 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2567 QuicSocketAddress());
2568 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2569
nharper46833c32019-05-15 21:33:05 -07002570 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07002571 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2572 } else {
nharper46833c32019-05-15 21:33:05 -07002573 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2574 }
wub8a5dafa2020-05-13 12:30:17 -07002575 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2576 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002577 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2578 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2579
2580 // Process another packet with a different peer address on client side will
2581 // only update peer address.
2582 const QuicSocketAddress kNewPeerAddress =
2583 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2584 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
wub8a5dafa2020-05-13 12:30:17 -07002585 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2586 kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002587 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2588 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2589}
2590
2591TEST_P(QuicConnectionTest, MaxPacketSize) {
2592 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2593 EXPECT_EQ(1350u, connection_.max_packet_length());
2594}
2595
dschinazi4ad1f462020-01-16 11:56:52 -08002596TEST_P(QuicConnectionTest, PeerLowersMaxPacketSize) {
2597 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2598
2599 // SetFromConfig is always called after construction from InitializeSession.
2600 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
2601 constexpr uint32_t kTestMaxPacketSize = 1233u;
2602 QuicConfig config;
2603 QuicConfigPeer::SetReceivedMaxPacketSize(&config, kTestMaxPacketSize);
2604 connection_.SetFromConfig(config);
2605
2606 EXPECT_EQ(kTestMaxPacketSize, connection_.max_packet_length());
2607}
2608
vasilvvebc5d0c2020-01-16 15:19:21 -08002609TEST_P(QuicConnectionTest, PeerCannotRaiseMaxPacketSize) {
2610 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2611
2612 // SetFromConfig is always called after construction from InitializeSession.
2613 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
2614 constexpr uint32_t kTestMaxPacketSize = 1450u;
2615 QuicConfig config;
2616 QuicConfigPeer::SetReceivedMaxPacketSize(&config, kTestMaxPacketSize);
2617 connection_.SetFromConfig(config);
2618
2619 EXPECT_EQ(kDefaultMaxPacketSize, connection_.max_packet_length());
2620}
2621
QUICHE teama6ef0a62019-03-07 20:34:33 -05002622TEST_P(QuicConnectionTest, SmallerServerMaxPacketSize) {
2623 TestConnection connection(TestConnectionId(), kPeerAddress, helper_.get(),
2624 alarm_factory_.get(), writer_.get(),
2625 Perspective::IS_SERVER, version());
2626 EXPECT_EQ(Perspective::IS_SERVER, connection.perspective());
2627 EXPECT_EQ(1000u, connection.max_packet_length());
2628}
2629
2630TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSize) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002631 set_perspective(Perspective::IS_SERVER);
2632 connection_.SetMaxPacketLength(1000);
2633
2634 QuicPacketHeader header;
2635 header.destination_connection_id = connection_id_;
2636 header.version_flag = true;
nharper21af28e2019-06-17 15:54:34 -07002637 header.packet_number = QuicPacketNumber(12);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002638
2639 if (QuicVersionHasLongHeaderLengths(
2640 peer_framer_.version().transport_version)) {
2641 header.long_packet_type = INITIAL;
2642 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
2643 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
2644 }
2645
2646 QuicFrames frames;
2647 QuicPaddingFrame padding;
nharper46833c32019-05-15 21:33:05 -07002648 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2649 frames.push_back(QuicFrame(&crypto_frame_));
2650 } else {
2651 frames.push_back(QuicFrame(frame1_));
2652 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002653 frames.push_back(QuicFrame(padding));
2654 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
dschinazi66dea072019-04-09 11:41:06 -07002655 char buffer[kMaxOutgoingPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07002656 size_t encrypted_length =
2657 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12),
dschinazi66dea072019-04-09 11:41:06 -07002658 *packet, buffer, kMaxOutgoingPacketSize);
2659 EXPECT_EQ(kMaxOutgoingPacketSize, encrypted_length);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002660
2661 framer_.set_version(version());
nharper46833c32019-05-15 21:33:05 -07002662 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2663 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
2664 } else {
2665 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2666 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002667 connection_.ProcessUdpPacket(
2668 kSelfAddress, kPeerAddress,
2669 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
2670
dschinazi66dea072019-04-09 11:41:06 -07002671 EXPECT_EQ(kMaxOutgoingPacketSize, connection_.max_packet_length());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002672}
2673
2674TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSizeWhileWriterLimited) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002675 const QuicByteCount lower_max_packet_size = 1240;
2676 writer_->set_max_packet_size(lower_max_packet_size);
2677 set_perspective(Perspective::IS_SERVER);
2678 connection_.SetMaxPacketLength(1000);
2679 EXPECT_EQ(1000u, connection_.max_packet_length());
2680
2681 QuicPacketHeader header;
2682 header.destination_connection_id = connection_id_;
2683 header.version_flag = true;
nharper21af28e2019-06-17 15:54:34 -07002684 header.packet_number = QuicPacketNumber(12);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002685
2686 if (QuicVersionHasLongHeaderLengths(
2687 peer_framer_.version().transport_version)) {
2688 header.long_packet_type = INITIAL;
2689 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
2690 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
2691 }
2692
2693 QuicFrames frames;
2694 QuicPaddingFrame padding;
nharper46833c32019-05-15 21:33:05 -07002695 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2696 frames.push_back(QuicFrame(&crypto_frame_));
2697 } else {
2698 frames.push_back(QuicFrame(frame1_));
2699 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002700 frames.push_back(QuicFrame(padding));
2701 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
dschinazi66dea072019-04-09 11:41:06 -07002702 char buffer[kMaxOutgoingPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07002703 size_t encrypted_length =
2704 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12),
dschinazi66dea072019-04-09 11:41:06 -07002705 *packet, buffer, kMaxOutgoingPacketSize);
2706 EXPECT_EQ(kMaxOutgoingPacketSize, encrypted_length);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002707
2708 framer_.set_version(version());
nharper46833c32019-05-15 21:33:05 -07002709 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2710 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
2711 } else {
2712 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2713 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002714 connection_.ProcessUdpPacket(
2715 kSelfAddress, kPeerAddress,
2716 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
2717
2718 // Here, the limit imposed by the writer is lower than the size of the packet
2719 // received, so the writer max packet size is used.
2720 EXPECT_EQ(lower_max_packet_size, connection_.max_packet_length());
2721}
2722
2723TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriter) {
2724 const QuicByteCount lower_max_packet_size = 1240;
2725 writer_->set_max_packet_size(lower_max_packet_size);
2726
2727 static_assert(lower_max_packet_size < kDefaultMaxPacketSize,
2728 "Default maximum packet size is too low");
2729 connection_.SetMaxPacketLength(kDefaultMaxPacketSize);
2730
2731 EXPECT_EQ(lower_max_packet_size, connection_.max_packet_length());
2732}
2733
2734TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriterForNewConnection) {
2735 const QuicConnectionId connection_id = TestConnectionId(17);
2736 const QuicByteCount lower_max_packet_size = 1240;
2737 writer_->set_max_packet_size(lower_max_packet_size);
2738 TestConnection connection(connection_id, kPeerAddress, helper_.get(),
2739 alarm_factory_.get(), writer_.get(),
2740 Perspective::IS_CLIENT, version());
2741 EXPECT_EQ(Perspective::IS_CLIENT, connection.perspective());
2742 EXPECT_EQ(lower_max_packet_size, connection.max_packet_length());
2743}
2744
2745TEST_P(QuicConnectionTest, PacketsInOrder) {
2746 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2747
2748 ProcessPacket(1);
fayangc31c9952019-06-05 13:54:48 -07002749 EXPECT_EQ(QuicPacketNumber(1u), LargestAcked(connection_.ack_frame()));
2750 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002751
2752 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07002753 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(connection_.ack_frame()));
2754 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002755
2756 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002757 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
2758 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002759}
2760
2761TEST_P(QuicConnectionTest, PacketsOutOfOrder) {
2762 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2763
2764 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002765 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002766 EXPECT_TRUE(IsMissing(2));
2767 EXPECT_TRUE(IsMissing(1));
2768
2769 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07002770 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002771 EXPECT_FALSE(IsMissing(2));
2772 EXPECT_TRUE(IsMissing(1));
2773
2774 ProcessPacket(1);
fayangc31c9952019-06-05 13:54:48 -07002775 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002776 EXPECT_FALSE(IsMissing(2));
2777 EXPECT_FALSE(IsMissing(1));
2778}
2779
2780TEST_P(QuicConnectionTest, DuplicatePacket) {
2781 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2782
2783 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002784 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002785 EXPECT_TRUE(IsMissing(2));
2786 EXPECT_TRUE(IsMissing(1));
2787
2788 // Send packet 3 again, but do not set the expectation that
2789 // the visitor OnStreamFrame() will be called.
2790 ProcessDataPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002791 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002792 EXPECT_TRUE(IsMissing(2));
2793 EXPECT_TRUE(IsMissing(1));
2794}
2795
2796TEST_P(QuicConnectionTest, PacketsOutOfOrderWithAdditionsAndLeastAwaiting) {
QUICHE teamcd098022019-03-22 18:49:55 -07002797 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2798 return;
2799 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002800 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2801
2802 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002803 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002804 EXPECT_TRUE(IsMissing(2));
2805 EXPECT_TRUE(IsMissing(1));
2806
2807 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07002808 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002809 EXPECT_TRUE(IsMissing(1));
2810
2811 ProcessPacket(5);
fayangc31c9952019-06-05 13:54:48 -07002812 EXPECT_EQ(QuicPacketNumber(5u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002813 EXPECT_TRUE(IsMissing(1));
2814 EXPECT_TRUE(IsMissing(4));
2815
2816 // Pretend at this point the client has gotten acks for 2 and 3 and 1 is a
2817 // packet the peer will not retransmit. It indicates this by sending 'least
2818 // awaiting' is 4. The connection should then realize 1 will not be
2819 // retransmitted, and will remove it from the missing list.
2820 QuicAckFrame frame = InitAckFrame(1);
2821 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
2822 ProcessAckPacket(6, &frame);
2823
2824 // Force an ack to be sent.
2825 SendAckPacketToPeer();
2826 EXPECT_TRUE(IsMissing(4));
2827}
2828
QUICHE teama6ef0a62019-03-07 20:34:33 -05002829TEST_P(QuicConnectionTest, RejectUnencryptedStreamData) {
2830 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
2831 if (!IsDefaultTestConfiguration()) {
2832 return;
2833 }
2834
2835 // Process an unencrypted packet from the non-crypto stream.
2836 frame1_.stream_id = 3;
2837 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fkastenholz5d880a92019-06-21 09:01:56 -07002838 EXPECT_CALL(visitor_,
2839 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
nharper2c9f02a2019-05-08 10:25:50 -07002840 EXPECT_QUIC_PEER_BUG(ProcessDataPacketAtLevel(1, false, ENCRYPTION_INITIAL),
2841 "");
fkastenholz5d880a92019-06-21 09:01:56 -07002842 TestConnectionCloseQuicErrorCode(QUIC_UNENCRYPTED_STREAM_DATA);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002843}
2844
2845TEST_P(QuicConnectionTest, OutOfOrderReceiptCausesAckSend) {
2846 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2847
2848 ProcessPacket(3);
fayang6dba4902019-06-17 10:04:23 -07002849 // Should not cause an ack.
2850 EXPECT_EQ(0u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002851
2852 ProcessPacket(2);
fayang6dba4902019-06-17 10:04:23 -07002853 // Should ack immediately, since this fills the last hole.
2854 EXPECT_EQ(1u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002855
2856 ProcessPacket(1);
2857 // Should ack immediately, since this fills the last hole.
fayang6dba4902019-06-17 10:04:23 -07002858 EXPECT_EQ(2u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002859
2860 ProcessPacket(4);
2861 // Should not cause an ack.
fayang6dba4902019-06-17 10:04:23 -07002862 EXPECT_EQ(2u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002863}
2864
2865TEST_P(QuicConnectionTest, OutOfOrderAckReceiptCausesNoAck) {
2866 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2867
2868 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
2869 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
2870 EXPECT_EQ(2u, writer_->packets_write_attempts());
2871
2872 QuicAckFrame ack1 = InitAckFrame(1);
2873 QuicAckFrame ack2 = InitAckFrame(2);
2874 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
fayang2f2915d2020-01-24 06:47:15 -08002875 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2876 EXPECT_CALL(visitor_, OnOneRttPacketAcknowledged()).Times(1);
2877 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002878 ProcessAckPacket(2, &ack2);
2879 // Should ack immediately since we have missing packets.
2880 EXPECT_EQ(2u, writer_->packets_write_attempts());
2881
fayang2f2915d2020-01-24 06:47:15 -08002882 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2883 EXPECT_CALL(visitor_, OnOneRttPacketAcknowledged()).Times(0);
2884 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002885 ProcessAckPacket(1, &ack1);
2886 // Should not ack an ack filling a missing packet.
2887 EXPECT_EQ(2u, writer_->packets_write_attempts());
2888}
2889
2890TEST_P(QuicConnectionTest, AckReceiptCausesAckSend) {
2891 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2892 QuicPacketNumber original, second;
2893
2894 QuicByteCount packet_size =
2895 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &original); // 1st packet.
2896 SendStreamDataToPeer(3, "bar", 3, NO_FIN, &second); // 2nd packet.
2897
2898 QuicAckFrame frame = InitAckFrame({{second, second + 1}});
2899 // First nack triggers early retransmit.
2900 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07002901 lost_packets.push_back(LostPacket(original, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002902 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07002903 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
2904 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002905 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2906 QuicPacketNumber retransmission;
2907 // Packet 1 is short header for IETF QUIC because the encryption level
2908 // switched to ENCRYPTION_FORWARD_SECURE in SendStreamDataToPeer.
fayangd4291e42019-05-30 10:31:21 -07002909 EXPECT_CALL(*send_algorithm_,
2910 OnPacketSent(_, _, _,
2911 VersionHasIetfInvariantHeader(
2912 GetParam().version.transport_version)
2913 ? packet_size
2914 : packet_size - kQuicVersionSize,
2915 _))
QUICHE teama6ef0a62019-03-07 20:34:33 -05002916 .WillOnce(SaveArg<2>(&retransmission));
2917
2918 ProcessAckPacket(&frame);
2919
2920 QuicAckFrame frame2 = ConstructAckFrame(retransmission, original);
2921 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2922 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
2923 ProcessAckPacket(&frame2);
2924
2925 // Now if the peer sends an ack which still reports the retransmitted packet
2926 // as missing, that will bundle an ack with data after two acks in a row
2927 // indicate the high water mark needs to be raised.
2928 EXPECT_CALL(*send_algorithm_,
2929 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA));
2930 connection_.SendStreamDataWithString(3, "foo", 6, NO_FIN);
2931 // No ack sent.
nharper55fa6132019-05-07 19:37:21 -07002932 size_t padding_frame_count = writer_->padding_frames().size();
2933 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002934 EXPECT_EQ(1u, writer_->stream_frames().size());
2935
2936 // No more packet loss for the rest of the test.
2937 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
2938 .Times(AnyNumber());
2939 ProcessAckPacket(&frame2);
2940 EXPECT_CALL(*send_algorithm_,
2941 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA));
fayang03916692019-05-22 17:57:18 -07002942 connection_.SendStreamDataWithString(3, "foofoofoo", 9, NO_FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002943 // Ack bundled.
2944 if (GetParam().no_stop_waiting) {
fayang8a27b0f2019-11-04 11:27:40 -08002945 // Do not ACK acks.
2946 EXPECT_EQ(1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002947 } else {
2948 EXPECT_EQ(3u, writer_->frame_count());
2949 }
2950 EXPECT_EQ(1u, writer_->stream_frames().size());
fayang8a27b0f2019-11-04 11:27:40 -08002951 if (GetParam().no_stop_waiting) {
fayang03916692019-05-22 17:57:18 -07002952 EXPECT_TRUE(writer_->ack_frames().empty());
2953 } else {
2954 EXPECT_FALSE(writer_->ack_frames().empty());
2955 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002956
2957 // But an ack with no missing packets will not send an ack.
2958 AckPacket(original, &frame2);
2959 ProcessAckPacket(&frame2);
2960 ProcessAckPacket(&frame2);
2961}
2962
2963TEST_P(QuicConnectionTest, AckSentEveryNthPacket) {
2964 connection_.set_ack_frequency_before_ack_decimation(3);
2965
2966 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2967 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(39);
2968
2969 // Expect 13 acks, every 3rd packet.
2970 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(13);
2971 // Receives packets 1 - 39.
2972 for (size_t i = 1; i <= 39; ++i) {
2973 ProcessDataPacket(i);
2974 }
2975}
2976
2977TEST_P(QuicConnectionTest, AckDecimationReducesAcks) {
2978 const size_t kMinRttMs = 40;
2979 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
2980 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
2981 QuicTime::Delta::Zero(), QuicTime::Zero());
2982 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
2983
2984 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
2985
2986 // Start ack decimation from 10th packet.
2987 connection_.set_min_received_before_ack_decimation(10);
2988
2989 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2990 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(30);
2991
2992 // Expect 6 acks: 5 acks between packets 1-10, and ack at 20.
2993 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(6);
2994 // Receives packets 1 - 29.
2995 for (size_t i = 1; i <= 29; ++i) {
2996 ProcessDataPacket(i);
2997 }
2998
2999 // We now receive the 30th packet, and so we send an ack.
3000 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3001 ProcessDataPacket(30);
3002}
3003
3004TEST_P(QuicConnectionTest, AckNeedsRetransmittableFrames) {
ianswett68cf0042019-05-09 08:37:58 -07003005 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003006 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3007 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(99);
3008
3009 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(19);
3010 // Receives packets 1 - 39.
3011 for (size_t i = 1; i <= 39; ++i) {
3012 ProcessDataPacket(i);
3013 }
3014 // Receiving Packet 40 causes 20th ack to send. Session is informed and adds
3015 // WINDOW_UPDATE.
3016 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
3017 .WillOnce(Invoke([this]() {
3018 connection_.SendControlFrame(
3019 QuicFrame(new QuicWindowUpdateFrame(1, 0, 0)));
3020 }));
3021 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3022 EXPECT_EQ(0u, writer_->window_update_frames().size());
3023 ProcessDataPacket(40);
3024 EXPECT_EQ(1u, writer_->window_update_frames().size());
3025
3026 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(9);
3027 // Receives packets 41 - 59.
3028 for (size_t i = 41; i <= 59; ++i) {
3029 ProcessDataPacket(i);
3030 }
3031 // Send a packet containing stream frame.
QUICHE team8c1daa22019-03-13 08:33:41 -07003032 SendStreamDataToPeer(
nharper46833c32019-05-15 21:33:05 -07003033 QuicUtils::GetFirstBidirectionalStreamId(
3034 connection_.version().transport_version, Perspective::IS_CLIENT),
QUICHE team8c1daa22019-03-13 08:33:41 -07003035 "bar", 0, NO_FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003036
3037 // Session will not be informed until receiving another 20 packets.
3038 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(19);
3039 for (size_t i = 60; i <= 98; ++i) {
3040 ProcessDataPacket(i);
3041 EXPECT_EQ(0u, writer_->window_update_frames().size());
3042 }
3043 // Session does not add a retransmittable frame.
3044 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
3045 .WillOnce(Invoke([this]() {
3046 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
3047 }));
3048 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3049 EXPECT_EQ(0u, writer_->ping_frames().size());
3050 ProcessDataPacket(99);
3051 EXPECT_EQ(0u, writer_->window_update_frames().size());
3052 // A ping frame will be added.
3053 EXPECT_EQ(1u, writer_->ping_frames().size());
3054}
3055
ianswett6083a102020-02-09 12:04:04 -08003056TEST_P(QuicConnectionTest, AckNeedsRetransmittableFramesAfterPto) {
ianswett6083a102020-02-09 12:04:04 -08003057 // Disable TLP so the RTO fires immediately.
3058 connection_.SetMaxTailLossProbes(0);
3059 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3060 QuicConfig config;
3061 QuicTagVector connection_options;
3062 connection_options.push_back(kEACK);
3063 config.SetConnectionOptionsToSend(connection_options);
3064 connection_.SetFromConfig(config);
3065
3066 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3067 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3068 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(10);
3069
3070 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(4);
3071 // Receive packets 1 - 9.
3072 for (size_t i = 1; i <= 9; ++i) {
3073 ProcessDataPacket(i);
3074 }
3075
3076 // Send a ping and fire the retransmission alarm.
3077 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3078 SendPing();
3079 QuicTime retransmission_time =
3080 connection_.GetRetransmissionAlarm()->deadline();
3081 clock_.AdvanceTime(retransmission_time - clock_.Now());
3082 connection_.GetRetransmissionAlarm()->Fire();
3083 ASSERT_TRUE(manager_->GetConsecutiveRtoCount() > 0 ||
3084 manager_->GetConsecutivePtoCount() > 0);
3085
3086 // Process a packet, which requests a retransmittable frame be bundled
3087 // with the ACK.
3088 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
3089 .WillOnce(Invoke([this]() {
3090 connection_.SendControlFrame(
3091 QuicFrame(new QuicWindowUpdateFrame(1, 0, 0)));
3092 }));
3093 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3094 ProcessDataPacket(11);
3095 EXPECT_EQ(1u, writer_->window_update_frames().size());
3096}
3097
QUICHE teama6ef0a62019-03-07 20:34:33 -05003098TEST_P(QuicConnectionTest, LeastUnackedLower) {
fayangc31c9952019-06-05 13:54:48 -07003099 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003100 return;
3101 }
3102 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3103
3104 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
3105 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
3106 SendStreamDataToPeer(1, "eep", 6, NO_FIN, nullptr);
3107
3108 // Start out saying the least unacked is 2.
3109 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
3110 ProcessStopWaitingPacket(InitStopWaitingFrame(2));
3111
3112 // Change it to 1, but lower the packet number to fake out-of-order packets.
3113 // This should be fine.
3114 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 1);
3115 // The scheduler will not process out of order acks, but all packet processing
3116 // causes the connection to try to write.
3117 if (!GetParam().no_stop_waiting) {
3118 EXPECT_CALL(visitor_, OnCanWrite());
3119 }
3120 ProcessStopWaitingPacket(InitStopWaitingFrame(1));
3121
3122 // Now claim it's one, but set the ordering so it was sent "after" the first
3123 // one. This should cause a connection error.
3124 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 7);
3125 if (!GetParam().no_stop_waiting) {
rch39c88ab2019-10-16 19:24:40 -07003126 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3127 .Times(AtLeast(1));
fkastenholz5d880a92019-06-21 09:01:56 -07003128 EXPECT_CALL(visitor_,
rch39c88ab2019-10-16 19:24:40 -07003129 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
3130 .Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003131 }
3132 ProcessStopWaitingPacket(InitStopWaitingFrame(1));
fkastenholz5d880a92019-06-21 09:01:56 -07003133 if (!GetParam().no_stop_waiting) {
3134 TestConnectionCloseQuicErrorCode(QUIC_INVALID_STOP_WAITING_DATA);
3135 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003136}
3137
3138TEST_P(QuicConnectionTest, TooManySentPackets) {
3139 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3140
3141 QuicPacketCount max_tracked_packets = 50;
3142 QuicConnectionPeer::SetMaxTrackedPackets(&connection_, max_tracked_packets);
3143
3144 const int num_packets = max_tracked_packets + 5;
3145
3146 for (int i = 0; i < num_packets; ++i) {
3147 SendStreamDataToPeer(1, "foo", 3 * i, NO_FIN, nullptr);
3148 }
3149
3150 // Ack packet 1, which leaves more than the limit outstanding.
3151 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3152 EXPECT_CALL(visitor_,
fkastenholz5d880a92019-06-21 09:01:56 -07003153 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003154
3155 // Nack the first packet and ack the rest, leaving a huge gap.
3156 QuicAckFrame frame1 = ConstructAckFrame(num_packets, 1);
3157 ProcessAckPacket(&frame1);
fkastenholz5d880a92019-06-21 09:01:56 -07003158 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003159}
3160
3161TEST_P(QuicConnectionTest, LargestObservedLower) {
3162 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3163
3164 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
3165 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
3166 SendStreamDataToPeer(1, "eep", 6, NO_FIN, nullptr);
3167 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3168
3169 // Start out saying the largest observed is 2.
3170 QuicAckFrame frame1 = InitAckFrame(1);
3171 QuicAckFrame frame2 = InitAckFrame(2);
3172 ProcessAckPacket(&frame2);
3173
fayang745c93a2019-06-21 13:43:04 -07003174 EXPECT_CALL(visitor_, OnCanWrite());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003175 ProcessAckPacket(&frame1);
3176}
3177
3178TEST_P(QuicConnectionTest, AckUnsentData) {
3179 // Ack a packet which has not been sent.
fkastenholz5d880a92019-06-21 09:01:56 -07003180 EXPECT_CALL(visitor_,
3181 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003182 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
rch39c88ab2019-10-16 19:24:40 -07003183 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003184 QuicAckFrame frame = InitAckFrame(1);
3185 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
3186 ProcessAckPacket(&frame);
fkastenholz5d880a92019-06-21 09:01:56 -07003187 TestConnectionCloseQuicErrorCode(QUIC_INVALID_ACK_DATA);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003188}
3189
3190TEST_P(QuicConnectionTest, BasicSending) {
QUICHE teamcd098022019-03-22 18:49:55 -07003191 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3192 return;
3193 }
fayang643c7dd2020-05-18 07:11:27 -07003194 const QuicConnectionStats& stats = connection_.GetStats();
3195 EXPECT_FALSE(stats.first_decrypted_packet.IsInitialized());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003196 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3197 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3198 ProcessDataPacket(1);
fayang643c7dd2020-05-18 07:11:27 -07003199 EXPECT_EQ(QuicPacketNumber(1), stats.first_decrypted_packet);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003200 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
3201 QuicPacketNumber last_packet;
3202 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
3203 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
3204 SendAckPacketToPeer(); // Packet 2
3205
3206 if (GetParam().no_stop_waiting) {
3207 // Expect no stop waiting frame is sent.
3208 EXPECT_FALSE(least_unacked().IsInitialized());
3209 } else {
3210 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
3211 }
3212
3213 SendAckPacketToPeer(); // Packet 3
3214 if (GetParam().no_stop_waiting) {
3215 // Expect no stop waiting frame is sent.
3216 EXPECT_FALSE(least_unacked().IsInitialized());
3217 } else {
3218 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
3219 }
3220
3221 SendStreamDataToPeer(1, "bar", 3, NO_FIN, &last_packet); // Packet 4
3222 EXPECT_EQ(QuicPacketNumber(4u), last_packet);
3223 SendAckPacketToPeer(); // Packet 5
3224 if (GetParam().no_stop_waiting) {
3225 // Expect no stop waiting frame is sent.
3226 EXPECT_FALSE(least_unacked().IsInitialized());
3227 } else {
3228 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
3229 }
3230
3231 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3232
3233 // Peer acks up to packet 3.
3234 QuicAckFrame frame = InitAckFrame(3);
3235 ProcessAckPacket(&frame);
3236 SendAckPacketToPeer(); // Packet 6
3237
3238 // As soon as we've acked one, we skip ack packets 2 and 3 and note lack of
3239 // ack for 4.
3240 if (GetParam().no_stop_waiting) {
3241 // Expect no stop waiting frame is sent.
3242 EXPECT_FALSE(least_unacked().IsInitialized());
3243 } else {
3244 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
3245 }
3246
3247 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3248
3249 // Peer acks up to packet 4, the last packet.
3250 QuicAckFrame frame2 = InitAckFrame(6);
3251 ProcessAckPacket(&frame2); // Acks don't instigate acks.
3252
3253 // Verify that we did not send an ack.
3254 EXPECT_EQ(QuicPacketNumber(6u), writer_->header().packet_number);
3255
3256 // So the last ack has not changed.
3257 if (GetParam().no_stop_waiting) {
3258 // Expect no stop waiting frame is sent.
3259 EXPECT_FALSE(least_unacked().IsInitialized());
3260 } else {
3261 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
3262 }
3263
3264 // If we force an ack, we shouldn't change our retransmit state.
3265 SendAckPacketToPeer(); // Packet 7
3266 if (GetParam().no_stop_waiting) {
3267 // Expect no stop waiting frame is sent.
3268 EXPECT_FALSE(least_unacked().IsInitialized());
3269 } else {
3270 EXPECT_EQ(QuicPacketNumber(7u), least_unacked());
3271 }
3272
3273 // But if we send more data it should.
3274 SendStreamDataToPeer(1, "eep", 6, NO_FIN, &last_packet); // Packet 8
3275 EXPECT_EQ(QuicPacketNumber(8u), last_packet);
3276 SendAckPacketToPeer(); // Packet 9
3277 if (GetParam().no_stop_waiting) {
3278 // Expect no stop waiting frame is sent.
3279 EXPECT_FALSE(least_unacked().IsInitialized());
3280 } else {
3281 EXPECT_EQ(QuicPacketNumber(7u), least_unacked());
3282 }
fayang643c7dd2020-05-18 07:11:27 -07003283 EXPECT_EQ(QuicPacketNumber(1), stats.first_decrypted_packet);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003284}
3285
3286// QuicConnection should record the packet sent-time prior to sending the
3287// packet.
3288TEST_P(QuicConnectionTest, RecordSentTimeBeforePacketSent) {
3289 // We're using a MockClock for the tests, so we have complete control over the
3290 // time.
3291 // Our recorded timestamp for the last packet sent time will be passed in to
3292 // the send_algorithm. Make sure that it is set to the correct value.
3293 QuicTime actual_recorded_send_time = QuicTime::Zero();
3294 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3295 .WillOnce(SaveArg<0>(&actual_recorded_send_time));
3296
3297 // First send without any pause and check the result.
3298 QuicTime expected_recorded_send_time = clock_.Now();
3299 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3300 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
3301 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
3302 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
3303
3304 // Now pause during the write, and check the results.
3305 actual_recorded_send_time = QuicTime::Zero();
3306 const QuicTime::Delta write_pause_time_delta =
3307 QuicTime::Delta::FromMilliseconds(5000);
3308 SetWritePauseTimeDelta(write_pause_time_delta);
3309 expected_recorded_send_time = clock_.Now();
3310
3311 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3312 .WillOnce(SaveArg<0>(&actual_recorded_send_time));
3313 connection_.SendStreamDataWithString(2, "baz", 0, NO_FIN);
3314 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
3315 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
3316 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
3317}
3318
3319TEST_P(QuicConnectionTest, FramePacking) {
3320 // Send two stream frames in 1 packet by queueing them.
3321 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3322 {
fayanga4b37b22019-06-18 13:37:47 -07003323 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003324 connection_.SendStreamData3();
3325 connection_.SendStreamData5();
3326 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3327 }
3328 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3329 EXPECT_FALSE(connection_.HasQueuedData());
3330
3331 // Parse the last packet and ensure it's an ack and two stream frames from
3332 // two different streams.
3333 if (GetParam().no_stop_waiting) {
3334 EXPECT_EQ(2u, writer_->frame_count());
3335 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
3336 } else {
3337 EXPECT_EQ(2u, writer_->frame_count());
3338 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
3339 }
3340
3341 EXPECT_TRUE(writer_->ack_frames().empty());
3342
3343 ASSERT_EQ(2u, writer_->stream_frames().size());
3344 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3345 writer_->stream_frames()[0]->stream_id);
3346 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3347 writer_->stream_frames()[1]->stream_id);
3348}
3349
3350TEST_P(QuicConnectionTest, FramePackingNonCryptoThenCrypto) {
3351 // Send two stream frames (one non-crypto, then one crypto) in 2 packets by
3352 // queueing them.
3353 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3354 {
3355 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
fayanga4b37b22019-06-18 13:37:47 -07003356 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003357 connection_.SendStreamData3();
fayang58f71072019-11-05 08:47:02 -08003358 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003359 connection_.SendCryptoStreamData();
fayang58f71072019-11-05 08:47:02 -08003360 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003361 }
3362 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3363 EXPECT_FALSE(connection_.HasQueuedData());
3364
3365 // Parse the last packet and ensure it's the crypto stream frame.
3366 EXPECT_EQ(2u, writer_->frame_count());
3367 ASSERT_EQ(1u, writer_->padding_frames().size());
QUICHE teamea740082019-03-11 17:58:43 -07003368 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003369 ASSERT_EQ(1u, writer_->stream_frames().size());
3370 EXPECT_EQ(QuicUtils::GetCryptoStreamId(connection_.transport_version()),
3371 writer_->stream_frames()[0]->stream_id);
3372 } else {
3373 EXPECT_EQ(1u, writer_->crypto_frames().size());
3374 }
3375}
3376
3377TEST_P(QuicConnectionTest, FramePackingCryptoThenNonCrypto) {
3378 // Send two stream frames (one crypto, then one non-crypto) in 2 packets by
3379 // queueing them.
3380 {
3381 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3382 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
fayanga4b37b22019-06-18 13:37:47 -07003383 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003384 connection_.SendCryptoStreamData();
3385 connection_.SendStreamData3();
3386 }
3387 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3388 EXPECT_FALSE(connection_.HasQueuedData());
3389
3390 // Parse the last packet and ensure it's the stream frame from stream 3.
nharper55fa6132019-05-07 19:37:21 -07003391 size_t padding_frame_count = writer_->padding_frames().size();
3392 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003393 ASSERT_EQ(1u, writer_->stream_frames().size());
3394 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3395 writer_->stream_frames()[0]->stream_id);
3396}
3397
3398TEST_P(QuicConnectionTest, FramePackingAckResponse) {
3399 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3400 // Process a data packet to queue up a pending ack.
fayang3451f6e2019-06-11 08:18:12 -07003401 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3402 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
3403 } else {
3404 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3405 }
3406 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
3407
QUICHE teama6ef0a62019-03-07 20:34:33 -05003408 QuicPacketNumber last_packet;
nharper46833c32019-05-15 21:33:05 -07003409 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3410 connection_.SendCryptoDataWithString("foo", 0);
3411 } else {
3412 SendStreamDataToPeer(
3413 QuicUtils::GetCryptoStreamId(connection_.transport_version()), "foo", 0,
3414 NO_FIN, &last_packet);
3415 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003416 // Verify ack is bundled with outging packet.
3417 EXPECT_FALSE(writer_->ack_frames().empty());
3418
3419 EXPECT_CALL(visitor_, OnCanWrite())
3420 .WillOnce(DoAll(IgnoreResult(InvokeWithoutArgs(
3421 &connection_, &TestConnection::SendStreamData3)),
3422 IgnoreResult(InvokeWithoutArgs(
3423 &connection_, &TestConnection::SendStreamData5))));
3424
3425 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3426
3427 // Process a data packet to cause the visitor's OnCanWrite to be invoked.
3428 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
QUICHE team8c1daa22019-03-13 08:33:41 -07003429 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07003430 std::make_unique<TaggingEncrypter>(0x01));
zhongyi546cc452019-04-12 15:27:49 -07003431 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07003432 std::make_unique<StrictTaggingDecrypter>(0x01));
nharper2c9f02a2019-05-08 10:25:50 -07003433 ProcessDataPacket(2);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003434
3435 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3436 EXPECT_FALSE(connection_.HasQueuedData());
3437
3438 // Parse the last packet and ensure it's an ack and two stream frames from
3439 // two different streams.
3440 if (GetParam().no_stop_waiting) {
3441 EXPECT_EQ(3u, writer_->frame_count());
3442 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
3443 } else {
3444 EXPECT_EQ(4u, writer_->frame_count());
3445 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3446 }
3447 EXPECT_FALSE(writer_->ack_frames().empty());
3448 ASSERT_EQ(2u, writer_->stream_frames().size());
3449 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3450 writer_->stream_frames()[0]->stream_id);
3451 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3452 writer_->stream_frames()[1]->stream_id);
3453}
3454
3455TEST_P(QuicConnectionTest, FramePackingSendv) {
nharper46833c32019-05-15 21:33:05 -07003456 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003457 // Send data in 1 packet by writing multiple blocks in a single iovector
3458 // using writev.
3459 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3460
3461 char data[] = "ABCDEF";
3462 struct iovec iov[2];
3463 iov[0].iov_base = data;
3464 iov[0].iov_len = 4;
3465 iov[1].iov_base = data + 4;
3466 iov[1].iov_len = 2;
nharper46833c32019-05-15 21:33:05 -07003467 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
3468 connection_.transport_version(), Perspective::IS_CLIENT);
3469 connection_.SaveAndSendStreamData(stream_id, iov, 2, 6, 0, NO_FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003470
3471 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3472 EXPECT_FALSE(connection_.HasQueuedData());
3473
3474 // Parse the last packet and ensure multiple iovector blocks have
3475 // been packed into a single stream frame from one stream.
nharper46833c32019-05-15 21:33:05 -07003476 EXPECT_EQ(1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003477 EXPECT_EQ(1u, writer_->stream_frames().size());
nharper46833c32019-05-15 21:33:05 -07003478 EXPECT_EQ(0u, writer_->padding_frames().size());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003479 QuicStreamFrame* frame = writer_->stream_frames()[0].get();
nharper46833c32019-05-15 21:33:05 -07003480 EXPECT_EQ(stream_id, frame->stream_id);
dmcardlecf0bfcf2019-12-13 08:08:21 -08003481 EXPECT_EQ("ABCDEF",
3482 quiche::QuicheStringPiece(frame->data_buffer, frame->data_length));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003483}
3484
3485TEST_P(QuicConnectionTest, FramePackingSendvQueued) {
nharper46833c32019-05-15 21:33:05 -07003486 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003487 // Try to send two stream frames in 1 packet by using writev.
3488 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3489
3490 BlockOnNextWrite();
3491 char data[] = "ABCDEF";
3492 struct iovec iov[2];
3493 iov[0].iov_base = data;
3494 iov[0].iov_len = 4;
3495 iov[1].iov_base = data + 4;
3496 iov[1].iov_len = 2;
nharper46833c32019-05-15 21:33:05 -07003497 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
3498 connection_.transport_version(), Perspective::IS_CLIENT);
3499 connection_.SaveAndSendStreamData(stream_id, iov, 2, 6, 0, NO_FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003500
3501 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3502 EXPECT_TRUE(connection_.HasQueuedData());
3503
3504 // Unblock the writes and actually send.
3505 writer_->SetWritable();
3506 connection_.OnCanWrite();
3507 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3508
3509 // Parse the last packet and ensure it's one stream frame from one stream.
nharper46833c32019-05-15 21:33:05 -07003510 EXPECT_EQ(1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003511 EXPECT_EQ(1u, writer_->stream_frames().size());
nharper46833c32019-05-15 21:33:05 -07003512 EXPECT_EQ(0u, writer_->padding_frames().size());
3513 EXPECT_EQ(stream_id, writer_->stream_frames()[0]->stream_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003514}
3515
3516TEST_P(QuicConnectionTest, SendingZeroBytes) {
3517 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3518 // Send a zero byte write with a fin using writev.
3519 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
nharper46833c32019-05-15 21:33:05 -07003520 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
3521 connection_.transport_version(), Perspective::IS_CLIENT);
3522 connection_.SaveAndSendStreamData(stream_id, nullptr, 0, 0, 0, FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003523
3524 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3525 EXPECT_FALSE(connection_.HasQueuedData());
3526
nharper55fa6132019-05-07 19:37:21 -07003527 // Padding frames are added by v99 to ensure a minimum packet size.
3528 size_t extra_padding_frames = 0;
3529 if (GetParam().version.HasHeaderProtection()) {
3530 extra_padding_frames = 1;
3531 }
3532
QUICHE teama6ef0a62019-03-07 20:34:33 -05003533 // Parse the last packet and ensure it's one stream frame from one stream.
nharper55fa6132019-05-07 19:37:21 -07003534 EXPECT_EQ(1u + extra_padding_frames, writer_->frame_count());
3535 EXPECT_EQ(extra_padding_frames, writer_->padding_frames().size());
3536 ASSERT_EQ(1u, writer_->stream_frames().size());
nharper46833c32019-05-15 21:33:05 -07003537 EXPECT_EQ(stream_id, writer_->stream_frames()[0]->stream_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003538 EXPECT_TRUE(writer_->stream_frames()[0]->fin);
3539}
3540
3541TEST_P(QuicConnectionTest, LargeSendWithPendingAck) {
3542 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3543 // Set the ack alarm by processing a ping frame.
3544 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3545
3546 // Processs a PING frame.
3547 ProcessFramePacket(QuicFrame(QuicPingFrame()));
3548 // Ensure that this has caused the ACK alarm to be set.
fayang9adfb532020-06-04 06:58:45 -07003549 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003550
3551 // Send data and ensure the ack is bundled.
3552 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(8);
3553 size_t len = 10000;
3554 std::unique_ptr<char[]> data_array(new char[len]);
3555 memset(data_array.get(), '?', len);
3556 struct iovec iov;
3557 iov.iov_base = data_array.get();
3558 iov.iov_len = len;
3559 QuicConsumedData consumed = connection_.SaveAndSendStreamData(
dschinazi552accc2019-06-17 17:07:34 -07003560 GetNthClientInitiatedStreamId(0, connection_.transport_version()), &iov,
3561 1, len, 0, FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003562 EXPECT_EQ(len, consumed.bytes_consumed);
3563 EXPECT_TRUE(consumed.fin_consumed);
3564 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3565 EXPECT_FALSE(connection_.HasQueuedData());
3566
3567 // Parse the last packet and ensure it's one stream frame with a fin.
3568 EXPECT_EQ(1u, writer_->frame_count());
nharper55fa6132019-05-07 19:37:21 -07003569 ASSERT_EQ(1u, writer_->stream_frames().size());
dschinazi552accc2019-06-17 17:07:34 -07003570 EXPECT_EQ(GetNthClientInitiatedStreamId(0, connection_.transport_version()),
QUICHE teama6ef0a62019-03-07 20:34:33 -05003571 writer_->stream_frames()[0]->stream_id);
3572 EXPECT_TRUE(writer_->stream_frames()[0]->fin);
3573 // Ensure the ack alarm was cancelled when the ack was sent.
fayang9adfb532020-06-04 06:58:45 -07003574 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003575}
3576
3577TEST_P(QuicConnectionTest, OnCanWrite) {
3578 // Visitor's OnCanWrite will send data, but will have more pending writes.
3579 EXPECT_CALL(visitor_, OnCanWrite())
3580 .WillOnce(DoAll(IgnoreResult(InvokeWithoutArgs(
3581 &connection_, &TestConnection::SendStreamData3)),
3582 IgnoreResult(InvokeWithoutArgs(
3583 &connection_, &TestConnection::SendStreamData5))));
3584 {
3585 InSequence seq;
3586 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillOnce(Return(true));
3587 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
3588 .WillRepeatedly(Return(false));
3589 }
3590
3591 EXPECT_CALL(*send_algorithm_, CanSend(_))
3592 .WillRepeatedly(testing::Return(true));
3593
3594 connection_.OnCanWrite();
3595
3596 // Parse the last packet and ensure it's the two stream frames from
3597 // two different streams.
3598 EXPECT_EQ(2u, writer_->frame_count());
3599 EXPECT_EQ(2u, writer_->stream_frames().size());
3600 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3601 writer_->stream_frames()[0]->stream_id);
3602 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3603 writer_->stream_frames()[1]->stream_id);
3604}
3605
3606TEST_P(QuicConnectionTest, RetransmitOnNack) {
3607 QuicPacketNumber last_packet;
3608 QuicByteCount second_packet_size;
3609 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet); // Packet 1
3610 second_packet_size =
3611 SendStreamDataToPeer(3, "foos", 3, NO_FIN, &last_packet); // Packet 2
3612 SendStreamDataToPeer(3, "fooos", 7, NO_FIN, &last_packet); // Packet 3
3613
3614 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3615
3616 // Don't lose a packet on an ack, and nothing is retransmitted.
3617 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3618 QuicAckFrame ack_one = InitAckFrame(1);
3619 ProcessAckPacket(&ack_one);
3620
3621 // Lose a packet and ensure it triggers retransmission.
3622 QuicAckFrame nack_two = ConstructAckFrame(3, 2);
3623 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003624 lost_packets.push_back(
3625 LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003626 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07003627 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
3628 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003629 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3630 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3631 EXPECT_FALSE(QuicPacketCreatorPeer::SendVersionInPacket(creator_));
3632 ProcessAckPacket(&nack_two);
3633}
3634
3635TEST_P(QuicConnectionTest, DoNotSendQueuedPacketForResetStream) {
3636 // Block the connection to queue the packet.
3637 BlockOnNextWrite();
3638
3639 QuicStreamId stream_id = 2;
3640 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
3641
3642 // Now that there is a queued packet, reset the stream.
3643 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
3644
3645 // Unblock the connection and verify that only the RST_STREAM is sent.
3646 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3647 writer_->SetWritable();
3648 connection_.OnCanWrite();
nharper55fa6132019-05-07 19:37:21 -07003649 size_t padding_frame_count = writer_->padding_frames().size();
3650 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003651 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3652}
3653
3654TEST_P(QuicConnectionTest, SendQueuedPacketForQuicRstStreamNoError) {
3655 // Block the connection to queue the packet.
3656 BlockOnNextWrite();
3657
3658 QuicStreamId stream_id = 2;
fayange62e63c2019-12-04 07:16:25 -08003659 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003660 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
3661
3662 // Now that there is a queued packet, reset the stream.
3663 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 3);
3664
3665 // Unblock the connection and verify that the RST_STREAM is sent and the data
3666 // packet is sent.
fayange62e63c2019-12-04 07:16:25 -08003667 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003668 writer_->SetWritable();
3669 connection_.OnCanWrite();
nharper55fa6132019-05-07 19:37:21 -07003670 size_t padding_frame_count = writer_->padding_frames().size();
3671 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003672 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3673}
3674
3675TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnNack) {
3676 QuicStreamId stream_id = 2;
3677 QuicPacketNumber last_packet;
3678 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3679 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3680 SendStreamDataToPeer(stream_id, "fooos", 7, NO_FIN, &last_packet);
3681
3682 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3683 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 12);
3684
3685 // Lose a packet and ensure it does not trigger retransmission.
3686 QuicAckFrame nack_two = ConstructAckFrame(last_packet, last_packet - 1);
3687 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3688 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3689 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3690 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3691 ProcessAckPacket(&nack_two);
3692}
3693
3694TEST_P(QuicConnectionTest, RetransmitForQuicRstStreamNoErrorOnNack) {
3695 QuicStreamId stream_id = 2;
3696 QuicPacketNumber last_packet;
3697 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3698 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3699 SendStreamDataToPeer(stream_id, "fooos", 7, NO_FIN, &last_packet);
3700
3701 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3702 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 12);
3703
3704 // Lose a packet, ensure it triggers retransmission.
3705 QuicAckFrame nack_two = ConstructAckFrame(last_packet, last_packet - 1);
3706 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3707 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003708 lost_packets.push_back(LostPacket(last_packet - 1, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003709 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07003710 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
3711 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003712 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3713 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
3714 ProcessAckPacket(&nack_two);
3715}
3716
3717TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnRTO) {
3718 QuicStreamId stream_id = 2;
3719 QuicPacketNumber last_packet;
3720 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3721
3722 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3723 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
3724
3725 // Fire the RTO and verify that the RST_STREAM is resent, not stream data.
3726 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3727 clock_.AdvanceTime(DefaultRetransmissionTime());
3728 connection_.GetRetransmissionAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07003729 size_t padding_frame_count = writer_->padding_frames().size();
3730 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003731 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3732 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
3733}
3734
3735// Ensure that if the only data in flight is non-retransmittable, the
3736// retransmission alarm is not set.
3737TEST_P(QuicConnectionTest, CancelRetransmissionAlarmAfterResetStream) {
3738 QuicStreamId stream_id = 2;
3739 QuicPacketNumber last_data_packet;
3740 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
3741
3742 // Cancel the stream.
3743 const QuicPacketNumber rst_packet = last_data_packet + 1;
3744 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, rst_packet, _, _)).Times(1);
3745 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
3746
3747 // Ack the RST_STREAM frame (since it's retransmittable), but not the data
3748 // packet, which is no longer retransmittable since the stream was cancelled.
3749 QuicAckFrame nack_stream_data =
3750 ConstructAckFrame(rst_packet, last_data_packet);
3751 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3752 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3753 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3754 ProcessAckPacket(&nack_stream_data);
3755
3756 // Ensure that the data is still in flight, but the retransmission alarm is no
3757 // longer set.
ianswett9f459cb2019-04-21 06:39:59 -07003758 EXPECT_GT(manager_->GetBytesInFlight(), 0u);
fayangcff885a2019-10-22 07:39:04 -07003759 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003760}
3761
3762TEST_P(QuicConnectionTest, RetransmitForQuicRstStreamNoErrorOnRTO) {
3763 connection_.SetMaxTailLossProbes(0);
3764
3765 QuicStreamId stream_id = 2;
3766 QuicPacketNumber last_packet;
3767 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3768
3769 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3770 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 3);
3771
3772 // Fire the RTO and verify that the RST_STREAM is resent, the stream data
3773 // is sent.
fayang1c2d1ab2020-03-11 12:08:41 -07003774 const size_t num_retransmissions =
3775 connection_.SupportsMultiplePacketNumberSpaces() ? 1 : 2;
3776 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3777 .Times(AtLeast(num_retransmissions));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003778 clock_.AdvanceTime(DefaultRetransmissionTime());
3779 connection_.GetRetransmissionAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07003780 size_t padding_frame_count = writer_->padding_frames().size();
3781 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
fayang1c2d1ab2020-03-11 12:08:41 -07003782 if (num_retransmissions == 2) {
3783 ASSERT_EQ(1u, writer_->rst_stream_frames().size());
3784 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
3785 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003786}
3787
3788TEST_P(QuicConnectionTest, DoNotSendPendingRetransmissionForResetStream) {
3789 QuicStreamId stream_id = 2;
3790 QuicPacketNumber last_packet;
3791 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3792 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3793 BlockOnNextWrite();
3794 connection_.SendStreamDataWithString(stream_id, "fooos", 7, NO_FIN);
3795
3796 // Lose a packet which will trigger a pending retransmission.
3797 QuicAckFrame ack = ConstructAckFrame(last_packet, last_packet - 1);
3798 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3799 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3800 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3801 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3802 ProcessAckPacket(&ack);
3803
3804 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 12);
3805
3806 // Unblock the connection and verify that the RST_STREAM is sent but not the
3807 // second data packet nor a retransmit.
3808 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3809 writer_->SetWritable();
3810 connection_.OnCanWrite();
nharper55fa6132019-05-07 19:37:21 -07003811 size_t padding_frame_count = writer_->padding_frames().size();
3812 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
zhongyi546cc452019-04-12 15:27:49 -07003813 ASSERT_EQ(1u, writer_->rst_stream_frames().size());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003814 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
3815}
3816
3817TEST_P(QuicConnectionTest, SendPendingRetransmissionForQuicRstStreamNoError) {
3818 QuicStreamId stream_id = 2;
3819 QuicPacketNumber last_packet;
3820 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3821 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3822 BlockOnNextWrite();
3823 connection_.SendStreamDataWithString(stream_id, "fooos", 7, NO_FIN);
3824
3825 // Lose a packet which will trigger a pending retransmission.
3826 QuicAckFrame ack = ConstructAckFrame(last_packet, last_packet - 1);
3827 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3828 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003829 lost_packets.push_back(LostPacket(last_packet - 1, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003830 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07003831 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
3832 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003833 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3834 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3835 ProcessAckPacket(&ack);
3836
3837 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 12);
3838
3839 // Unblock the connection and verify that the RST_STREAM is sent and the
3840 // second data packet or a retransmit is sent.
3841 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(2));
3842 writer_->SetWritable();
3843 connection_.OnCanWrite();
3844 // The RST_STREAM_FRAME is sent after queued packets and pending
3845 // retransmission.
3846 connection_.SendControlFrame(QuicFrame(
3847 new QuicRstStreamFrame(1, stream_id, QUIC_STREAM_NO_ERROR, 14)));
nharper55fa6132019-05-07 19:37:21 -07003848 size_t padding_frame_count = writer_->padding_frames().size();
3849 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003850 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3851}
3852
3853TEST_P(QuicConnectionTest, RetransmitAckedPacket) {
3854 QuicPacketNumber last_packet;
3855 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
3856 SendStreamDataToPeer(1, "foos", 3, NO_FIN, &last_packet); // Packet 2
3857 SendStreamDataToPeer(1, "fooos", 7, NO_FIN, &last_packet); // Packet 3
3858
3859 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3860
3861 // Instigate a loss with an ack.
3862 QuicAckFrame nack_two = ConstructAckFrame(3, 2);
3863 // The first nack should trigger a fast retransmission, but we'll be
3864 // write blocked, so the packet will be queued.
3865 BlockOnNextWrite();
3866
3867 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003868 lost_packets.push_back(
3869 LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003870 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07003871 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
3872 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003873 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
fayange62e63c2019-12-04 07:16:25 -08003874 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _))
3875 .Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003876 ProcessAckPacket(&nack_two);
3877 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3878
3879 // Now, ack the previous transmission.
3880 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3881 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(false, _, _, _, _));
3882 QuicAckFrame ack_all = InitAckFrame(3);
3883 ProcessAckPacket(&ack_all);
3884
fayange62e63c2019-12-04 07:16:25 -08003885 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _))
3886 .Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003887
3888 writer_->SetWritable();
3889 connection_.OnCanWrite();
3890
3891 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3892 // We do not store retransmittable frames of this retransmission.
3893 EXPECT_FALSE(QuicConnectionPeer::HasRetransmittableFrames(&connection_, 4));
3894}
3895
3896TEST_P(QuicConnectionTest, RetransmitNackedLargestObserved) {
3897 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3898 QuicPacketNumber original, second;
3899
3900 QuicByteCount packet_size =
3901 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &original); // 1st packet.
3902 SendStreamDataToPeer(3, "bar", 3, NO_FIN, &second); // 2nd packet.
3903
3904 QuicAckFrame frame = InitAckFrame({{second, second + 1}});
3905 // The first nack should retransmit the largest observed packet.
3906 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003907 lost_packets.push_back(LostPacket(original, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003908 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07003909 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
3910 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003911 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3912 // Packet 1 is short header for IETF QUIC because the encryption level
3913 // switched to ENCRYPTION_FORWARD_SECURE in SendStreamDataToPeer.
fayangd4291e42019-05-30 10:31:21 -07003914 EXPECT_CALL(*send_algorithm_,
3915 OnPacketSent(_, _, _,
3916 VersionHasIetfInvariantHeader(
3917 GetParam().version.transport_version)
3918 ? packet_size
3919 : packet_size - kQuicVersionSize,
3920 _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003921 ProcessAckPacket(&frame);
3922}
3923
3924TEST_P(QuicConnectionTest, QueueAfterTwoRTOs) {
fayangcff885a2019-10-22 07:39:04 -07003925 if (connection_.PtoEnabled()) {
fayang5f135052019-08-22 17:59:40 -07003926 return;
3927 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003928 connection_.SetMaxTailLossProbes(0);
3929
3930 for (int i = 0; i < 10; ++i) {
3931 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3932 connection_.SendStreamDataWithString(3, "foo", i * 3, NO_FIN);
3933 }
3934
3935 // Block the writer and ensure they're queued.
3936 BlockOnNextWrite();
3937 clock_.AdvanceTime(DefaultRetransmissionTime());
fayange62e63c2019-12-04 07:16:25 -08003938 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003939 connection_.GetRetransmissionAlarm()->Fire();
3940 EXPECT_TRUE(connection_.HasQueuedData());
3941
3942 // Unblock the writer.
3943 writer_->SetWritable();
3944 clock_.AdvanceTime(QuicTime::Delta::FromMicroseconds(
3945 2 * DefaultRetransmissionTime().ToMicroseconds()));
fayange62e63c2019-12-04 07:16:25 -08003946 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003947 connection_.GetRetransmissionAlarm()->Fire();
3948 connection_.OnCanWrite();
3949}
3950
3951TEST_P(QuicConnectionTest, WriteBlockedBufferedThenSent) {
3952 BlockOnNextWrite();
3953 writer_->set_is_write_blocked_data_buffered(true);
3954 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3955 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3956 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3957
3958 writer_->SetWritable();
3959 connection_.OnCanWrite();
3960 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3961}
3962
3963TEST_P(QuicConnectionTest, WriteBlockedThenSent) {
3964 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3965 BlockOnNextWrite();
fayange62e63c2019-12-04 07:16:25 -08003966 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003967 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
fayange62e63c2019-12-04 07:16:25 -08003968 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003969 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3970
3971 // The second packet should also be queued, in order to ensure packets are
3972 // never sent out of order.
3973 writer_->SetWritable();
fayange62e63c2019-12-04 07:16:25 -08003974 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003975 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3976 EXPECT_EQ(2u, connection_.NumQueuedPackets());
3977
3978 // Now both are sent in order when we unblock.
fayange62e63c2019-12-04 07:16:25 -08003979 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003980 connection_.OnCanWrite();
3981 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
fayang2ce66082019-10-02 06:29:04 -07003982 EXPECT_EQ(0u, connection_.NumQueuedPackets());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003983}
3984
3985TEST_P(QuicConnectionTest, RetransmitWriteBlockedAckedOriginalThenSent) {
3986 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3987 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
3988 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3989
3990 BlockOnNextWrite();
3991 writer_->set_is_write_blocked_data_buffered(true);
3992 // Simulate the retransmission alarm firing.
3993 clock_.AdvanceTime(DefaultRetransmissionTime());
3994 connection_.GetRetransmissionAlarm()->Fire();
3995
3996 // Ack the sent packet before the callback returns, which happens in
3997 // rare circumstances with write blocked sockets.
3998 QuicAckFrame ack = InitAckFrame(1);
3999 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4000 ProcessAckPacket(&ack);
4001
4002 writer_->SetWritable();
4003 connection_.OnCanWrite();
fayangcff885a2019-10-22 07:39:04 -07004004 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
fayang5d011982020-05-13 14:14:38 -07004005 uint64_t retransmission = connection_.SupportsMultiplePacketNumberSpaces() &&
4006 !GetQuicReloadableFlag(quic_default_on_pto)
4007 ? 3
4008 : 2;
fayang1c2d1ab2020-03-11 12:08:41 -07004009 EXPECT_FALSE(QuicConnectionPeer::HasRetransmittableFrames(&connection_,
4010 retransmission));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004011}
4012
4013TEST_P(QuicConnectionTest, AlarmsWhenWriteBlocked) {
4014 // Block the connection.
4015 BlockOnNextWrite();
4016 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
4017 EXPECT_EQ(1u, writer_->packets_write_attempts());
4018 EXPECT_TRUE(writer_->IsWriteBlocked());
4019
4020 // Set the send alarm. Fire the alarm and ensure it doesn't attempt to write.
4021 connection_.GetSendAlarm()->Set(clock_.ApproximateNow());
4022 connection_.GetSendAlarm()->Fire();
4023 EXPECT_TRUE(writer_->IsWriteBlocked());
4024 EXPECT_EQ(1u, writer_->packets_write_attempts());
4025}
4026
4027TEST_P(QuicConnectionTest, NoSendAlarmAfterProcessPacketWhenWriteBlocked) {
4028 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4029
4030 // Block the connection.
4031 BlockOnNextWrite();
4032 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
4033 EXPECT_TRUE(writer_->IsWriteBlocked());
4034 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4035 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4036
4037 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4038 // Process packet number 1. Can not call ProcessPacket or ProcessDataPacket
4039 // here, because they will fire the alarm after QuicConnection::ProcessPacket
4040 // is returned.
4041 const uint64_t received_packet_num = 1;
4042 const bool has_stop_waiting = false;
nharperc6b99512019-09-19 11:13:48 -07004043 const EncryptionLevel level = ENCRYPTION_FORWARD_SECURE;
4044 std::unique_ptr<QuicPacket> packet(
4045 ConstructDataPacket(received_packet_num, has_stop_waiting, level));
dschinazi66dea072019-04-09 11:41:06 -07004046 char buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05004047 size_t encrypted_length =
4048 peer_framer_.EncryptPayload(level, QuicPacketNumber(received_packet_num),
dschinazi66dea072019-04-09 11:41:06 -07004049 *packet, buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004050 connection_.ProcessUdpPacket(
4051 kSelfAddress, kPeerAddress,
4052 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
4053
4054 EXPECT_TRUE(writer_->IsWriteBlocked());
4055 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4056}
4057
4058TEST_P(QuicConnectionTest, AddToWriteBlockedListIfWriterBlockedWhenProcessing) {
4059 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4060 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
4061
4062 // Simulate the case where a shared writer gets blocked by another connection.
4063 writer_->SetWriteBlocked();
4064
4065 // Process an ACK, make sure the connection calls visitor_->OnWriteBlocked().
4066 QuicAckFrame ack1 = InitAckFrame(1);
4067 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
4068 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
4069 ProcessAckPacket(1, &ack1);
4070}
4071
4072TEST_P(QuicConnectionTest, DoNotAddToWriteBlockedListAfterDisconnect) {
4073 writer_->SetBatchMode(true);
4074 EXPECT_TRUE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07004075 // Have to explicitly grab the OnConnectionClosed frame and check
4076 // its parameters because this is a silent connection close and the
4077 // frame is not also transmitted to the peer.
4078 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
4079 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004080
4081 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
4082
4083 {
fayanga4b37b22019-06-18 13:37:47 -07004084 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004085 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
4086 ConnectionCloseBehavior::SILENT_CLOSE);
4087
4088 EXPECT_FALSE(connection_.connected());
4089 writer_->SetWriteBlocked();
4090 }
fkastenholz5d880a92019-06-21 09:01:56 -07004091 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08004092 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
4093 IsError(QUIC_PEER_GOING_AWAY));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004094}
4095
4096TEST_P(QuicConnectionTest, AddToWriteBlockedListIfBlockedOnFlushPackets) {
4097 writer_->SetBatchMode(true);
4098 writer_->BlockOnNextFlush();
4099
4100 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
4101 {
fayanga4b37b22019-06-18 13:37:47 -07004102 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004103 // flusher's destructor will call connection_.FlushPackets, which should add
4104 // the connection to the write blocked list.
4105 }
4106}
4107
4108TEST_P(QuicConnectionTest, NoLimitPacketsPerNack) {
4109 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4110 int offset = 0;
4111 // Send packets 1 to 15.
4112 for (int i = 0; i < 15; ++i) {
4113 SendStreamDataToPeer(1, "foo", offset, NO_FIN, nullptr);
4114 offset += 3;
4115 }
4116
4117 // Ack 15, nack 1-14.
4118
4119 QuicAckFrame nack =
4120 InitAckFrame({{QuicPacketNumber(15), QuicPacketNumber(16)}});
4121
4122 // 14 packets have been NACK'd and lost.
4123 LostPacketVector lost_packets;
4124 for (int i = 1; i < 15; ++i) {
dschinazi66dea072019-04-09 11:41:06 -07004125 lost_packets.push_back(
4126 LostPacket(QuicPacketNumber(i), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004127 }
4128 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07004129 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
4130 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004131 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
fayangcff885a2019-10-22 07:39:04 -07004132 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004133 ProcessAckPacket(&nack);
4134}
4135
4136// Test sending multiple acks from the connection to the session.
4137TEST_P(QuicConnectionTest, MultipleAcks) {
QUICHE teamcd098022019-03-22 18:49:55 -07004138 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4139 return;
4140 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004141 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4142 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4143 ProcessDataPacket(1);
4144 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
4145 QuicPacketNumber last_packet;
4146 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
4147 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4148 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet); // Packet 2
4149 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
4150 SendAckPacketToPeer(); // Packet 3
4151 SendStreamDataToPeer(5, "foo", 0, NO_FIN, &last_packet); // Packet 4
4152 EXPECT_EQ(QuicPacketNumber(4u), last_packet);
4153 SendStreamDataToPeer(1, "foo", 3, NO_FIN, &last_packet); // Packet 5
4154 EXPECT_EQ(QuicPacketNumber(5u), last_packet);
4155 SendStreamDataToPeer(3, "foo", 3, NO_FIN, &last_packet); // Packet 6
4156 EXPECT_EQ(QuicPacketNumber(6u), last_packet);
4157
4158 // Client will ack packets 1, 2, [!3], 4, 5.
4159 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4160 QuicAckFrame frame1 = ConstructAckFrame(5, 3);
4161 ProcessAckPacket(&frame1);
4162
4163 // Now the client implicitly acks 3, and explicitly acks 6.
4164 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4165 QuicAckFrame frame2 = InitAckFrame(6);
4166 ProcessAckPacket(&frame2);
4167}
4168
4169TEST_P(QuicConnectionTest, DontLatchUnackedPacket) {
QUICHE teamcd098022019-03-22 18:49:55 -07004170 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4171 return;
4172 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004173 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4174 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4175 ProcessDataPacket(1);
4176 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
4177 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr); // Packet 1;
4178 // From now on, we send acks, so the send algorithm won't mark them pending.
4179 SendAckPacketToPeer(); // Packet 2
4180
4181 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4182 QuicAckFrame frame = InitAckFrame(1);
4183 ProcessAckPacket(&frame);
4184
4185 // Verify that our internal state has least-unacked as 2, because we're still
4186 // waiting for a potential ack for 2.
4187
4188 EXPECT_EQ(QuicPacketNumber(2u), stop_waiting()->least_unacked);
4189
4190 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4191 frame = InitAckFrame(2);
4192 ProcessAckPacket(&frame);
4193 EXPECT_EQ(QuicPacketNumber(3u), stop_waiting()->least_unacked);
4194
4195 // When we send an ack, we make sure our least-unacked makes sense. In this
4196 // case since we're not waiting on an ack for 2 and all packets are acked, we
4197 // set it to 3.
4198 SendAckPacketToPeer(); // Packet 3
4199 // Least_unacked remains at 3 until another ack is received.
4200 EXPECT_EQ(QuicPacketNumber(3u), stop_waiting()->least_unacked);
4201 if (GetParam().no_stop_waiting) {
4202 // Expect no stop waiting frame is sent.
4203 EXPECT_FALSE(least_unacked().IsInitialized());
4204 } else {
4205 // Check that the outgoing ack had its packet number as least_unacked.
4206 EXPECT_EQ(QuicPacketNumber(3u), least_unacked());
4207 }
4208
4209 // Ack the ack, which updates the rtt and raises the least unacked.
4210 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4211 frame = InitAckFrame(3);
4212 ProcessAckPacket(&frame);
4213
4214 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr); // Packet 4
4215 EXPECT_EQ(QuicPacketNumber(4u), stop_waiting()->least_unacked);
4216 SendAckPacketToPeer(); // Packet 5
4217 if (GetParam().no_stop_waiting) {
4218 // Expect no stop waiting frame is sent.
4219 EXPECT_FALSE(least_unacked().IsInitialized());
4220 } else {
4221 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
4222 }
4223
4224 // Send two data packets at the end, and ensure if the last one is acked,
4225 // the least unacked is raised above the ack packets.
4226 SendStreamDataToPeer(1, "bar", 6, NO_FIN, nullptr); // Packet 6
4227 SendStreamDataToPeer(1, "bar", 9, NO_FIN, nullptr); // Packet 7
4228
4229 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4230 frame = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(5)},
4231 {QuicPacketNumber(7), QuicPacketNumber(8)}});
4232 ProcessAckPacket(&frame);
4233
4234 EXPECT_EQ(QuicPacketNumber(6u), stop_waiting()->least_unacked);
4235}
4236
4237TEST_P(QuicConnectionTest, TLP) {
fayang5d011982020-05-13 14:14:38 -07004238 if (connection_.PtoEnabled()) {
4239 return;
4240 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004241 connection_.SetMaxTailLossProbes(1);
4242
4243 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
4244 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4245 QuicTime retransmission_time =
4246 connection_.GetRetransmissionAlarm()->deadline();
4247 EXPECT_NE(QuicTime::Zero(), retransmission_time);
4248
4249 EXPECT_EQ(QuicPacketNumber(1u), writer_->header().packet_number);
4250 // Simulate the retransmission alarm firing and sending a tlp,
4251 // so send algorithm's OnRetransmissionTimeout is not called.
4252 clock_.AdvanceTime(retransmission_time - clock_.Now());
fayang1c2d1ab2020-03-11 12:08:41 -07004253 const QuicPacketNumber retransmission(
4254 connection_.SupportsMultiplePacketNumberSpaces() ? 3 : 2);
4255 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, retransmission, _, _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004256 connection_.GetRetransmissionAlarm()->Fire();
fayang1c2d1ab2020-03-11 12:08:41 -07004257 EXPECT_EQ(retransmission, writer_->header().packet_number);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004258 // We do not raise the high water mark yet.
4259 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4260}
4261
zhongyifbb25772019-04-10 16:54:08 -07004262TEST_P(QuicConnectionTest, TailLossProbeDelayForStreamDataInTLPR) {
fayangcff885a2019-10-22 07:39:04 -07004263 if (connection_.PtoEnabled()) {
zhongyi1b2f7832019-06-14 13:31:34 -07004264 return;
4265 }
4266
zhongyifbb25772019-04-10 16:54:08 -07004267 // Set TLPR from QuicConfig.
4268 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4269 QuicConfig config;
4270 QuicTagVector options;
4271 options.push_back(kTLPR);
4272 config.SetConnectionOptionsToSend(options);
4273 connection_.SetFromConfig(config);
4274 connection_.SetMaxTailLossProbes(1);
4275
4276 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
4277 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4278
4279 QuicTime retransmission_time =
4280 connection_.GetRetransmissionAlarm()->deadline();
4281 EXPECT_NE(QuicTime::Zero(), retransmission_time);
4282 QuicTime::Delta expected_tlp_delay =
4283 0.5 * manager_->GetRttStats()->SmoothedOrInitialRtt();
4284 EXPECT_EQ(expected_tlp_delay, retransmission_time - clock_.Now());
4285
4286 EXPECT_EQ(QuicPacketNumber(1u), writer_->header().packet_number);
4287 // Simulate firing of the retransmission alarm and retransmit the packet.
4288 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
4289 clock_.AdvanceTime(retransmission_time - clock_.Now());
4290 connection_.GetRetransmissionAlarm()->Fire();
4291 EXPECT_EQ(QuicPacketNumber(2u), writer_->header().packet_number);
4292
4293 // We do not raise the high water mark yet.
4294 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4295}
4296
4297TEST_P(QuicConnectionTest, TailLossProbeDelayForNonStreamDataInTLPR) {
fayangcff885a2019-10-22 07:39:04 -07004298 if (connection_.PtoEnabled()) {
zhongyi1b2f7832019-06-14 13:31:34 -07004299 return;
4300 }
4301
zhongyifbb25772019-04-10 16:54:08 -07004302 // Set TLPR from QuicConfig.
4303 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4304 QuicConfig config;
4305 QuicTagVector options;
4306 options.push_back(kTLPR);
4307 config.SetConnectionOptionsToSend(options);
dschinazif7c6a912020-05-05 11:39:53 -07004308 QuicConfigPeer::SetNegotiated(&config, true);
dschinazie7c38a52020-05-29 15:25:45 -07004309 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
4310 QuicConfigPeer::SetReceivedOriginalConnectionId(
4311 &config, connection_.connection_id());
4312 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
4313 &config, connection_.connection_id());
4314 }
zhongyifbb25772019-04-10 16:54:08 -07004315 connection_.SetFromConfig(config);
4316 connection_.SetMaxTailLossProbes(1);
4317
4318 // Sets retransmittable on wire.
4319 const QuicTime::Delta retransmittable_on_wire_timeout =
4320 QuicTime::Delta::FromMilliseconds(50);
zhongyi79ace162019-10-21 15:57:09 -07004321 connection_.set_initial_retransmittable_on_wire_timeout(
zhongyifbb25772019-04-10 16:54:08 -07004322 retransmittable_on_wire_timeout);
4323
4324 EXPECT_TRUE(connection_.connected());
4325 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4326 .WillRepeatedly(Return(true));
fayangb59c6f12020-03-23 15:06:14 -07004327 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
zhongyifbb25772019-04-10 16:54:08 -07004328 EXPECT_FALSE(connection_.IsPathDegrading());
4329 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4330
4331 const char data[] = "data";
4332 size_t data_size = strlen(data);
4333 QuicStreamOffset offset = 0;
4334
4335 // Send a data packet.
4336 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
4337 offset += data_size;
4338
4339 // Path degrading alarm should be set when there is a retransmittable packet
4340 // on the wire.
fayangb59c6f12020-03-23 15:06:14 -07004341 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
zhongyifbb25772019-04-10 16:54:08 -07004342
4343 // Verify the path degrading delay.
4344 // First TLP with stream data.
4345 QuicTime::Delta srtt = manager_->GetRttStats()->SmoothedOrInitialRtt();
4346 QuicTime::Delta expected_delay = 0.5 * srtt;
4347 // Add 1st RTO.
4348 QuicTime::Delta retransmission_delay =
4349 QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
4350 expected_delay = expected_delay + retransmission_delay;
4351 // Add 2nd RTO.
4352 expected_delay = expected_delay + retransmission_delay * 2;
4353 EXPECT_EQ(expected_delay,
4354 QuicConnectionPeer::GetSentPacketManager(&connection_)
4355 ->GetPathDegradingDelay());
4356 ASSERT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
4357
4358 // The ping alarm is set for the ping timeout, not the shorter
4359 // retransmittable_on_wire_timeout.
4360 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004361 EXPECT_EQ(connection_.ping_timeout(),
zhongyifbb25772019-04-10 16:54:08 -07004362 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
4363
4364 // Receive an ACK for the data packet.
4365 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4366 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4367 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4368 QuicAckFrame frame =
4369 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
4370 ProcessAckPacket(&frame);
4371
4372 // Path degrading alarm should be cancelled as there is no more
4373 // reretransmittable packets on the wire.
fayangb59c6f12020-03-23 15:06:14 -07004374 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
zhongyifbb25772019-04-10 16:54:08 -07004375 // The ping alarm should be set to the retransmittable_on_wire_timeout.
4376 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4377 EXPECT_EQ(retransmittable_on_wire_timeout,
4378 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
4379
4380 // Simulate firing of the retransmittable on wire and send a PING.
4381 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
4382 clock_.AdvanceTime(retransmittable_on_wire_timeout);
4383 connection_.GetPingAlarm()->Fire();
4384
4385 // The retransmission alarm and the path degrading alarm should be set as
4386 // there is a retransmittable packet (PING) on the wire,
4387 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
fayangb59c6f12020-03-23 15:06:14 -07004388 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
zhongyifbb25772019-04-10 16:54:08 -07004389
4390 // Verify the retransmission delay.
4391 QuicTime::Delta min_rto_timeout =
4392 QuicTime::Delta::FromMilliseconds(kMinRetransmissionTimeMs);
4393 srtt = manager_->GetRttStats()->SmoothedOrInitialRtt();
zhongyi9fa2be32019-09-10 12:39:01 -07004394
4395 // First TLP without unacked stream data will no longer use TLPR.
4396 expected_delay = std::max(2 * srtt, 1.5 * srtt + 0.5 * min_rto_timeout);
zhongyifbb25772019-04-10 16:54:08 -07004397 EXPECT_EQ(expected_delay,
4398 connection_.GetRetransmissionAlarm()->deadline() - clock_.Now());
4399
zhongyi1b2f7832019-06-14 13:31:34 -07004400 // Verify the path degrading delay = TLP delay + 1st RTO + 2nd RTO.
zhongyifbb25772019-04-10 16:54:08 -07004401 // Add 1st RTO.
4402 retransmission_delay =
4403 std::max(manager_->GetRttStats()->smoothed_rtt() +
4404 4 * manager_->GetRttStats()->mean_deviation(),
4405 min_rto_timeout);
4406 expected_delay = expected_delay + retransmission_delay;
4407 // Add 2nd RTO.
4408 expected_delay = expected_delay + retransmission_delay * 2;
4409 EXPECT_EQ(expected_delay,
4410 QuicConnectionPeer::GetSentPacketManager(&connection_)
4411 ->GetPathDegradingDelay());
4412
4413 // The ping alarm is set for the ping timeout, not the shorter
4414 // retransmittable_on_wire_timeout.
4415 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004416 EXPECT_EQ(connection_.ping_timeout(),
zhongyifbb25772019-04-10 16:54:08 -07004417 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
zhongyi1b2f7832019-06-14 13:31:34 -07004418
4419 // Advance a small period of time: 5ms. And receive a retransmitted ACK.
4420 // This will update the retransmission alarm, verify the retransmission delay
4421 // is correct.
4422 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4423 QuicAckFrame ack = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
4424 ProcessAckPacket(&ack);
4425
4426 // Verify the retransmission delay.
zhongyi9fa2be32019-09-10 12:39:01 -07004427 // First TLP without unacked stream data will no longer use TLPR.
4428 expected_delay = std::max(2 * srtt, 1.5 * srtt + 0.5 * min_rto_timeout);
zhongyi1b2f7832019-06-14 13:31:34 -07004429 expected_delay = expected_delay - QuicTime::Delta::FromMilliseconds(5);
4430 EXPECT_EQ(expected_delay,
4431 connection_.GetRetransmissionAlarm()->deadline() - clock_.Now());
zhongyifbb25772019-04-10 16:54:08 -07004432}
4433
QUICHE teama6ef0a62019-03-07 20:34:33 -05004434TEST_P(QuicConnectionTest, RTO) {
fayang5f135052019-08-22 17:59:40 -07004435 if (connection_.PtoEnabled()) {
4436 return;
4437 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004438 connection_.SetMaxTailLossProbes(0);
4439
4440 QuicTime default_retransmission_time =
4441 clock_.ApproximateNow() + DefaultRetransmissionTime();
4442 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
4443 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4444
4445 EXPECT_EQ(QuicPacketNumber(1u), writer_->header().packet_number);
4446 EXPECT_EQ(default_retransmission_time,
4447 connection_.GetRetransmissionAlarm()->deadline());
4448 // Simulate the retransmission alarm firing.
4449 clock_.AdvanceTime(DefaultRetransmissionTime());
4450 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
4451 connection_.GetRetransmissionAlarm()->Fire();
4452 EXPECT_EQ(QuicPacketNumber(2u), writer_->header().packet_number);
4453 // We do not raise the high water mark yet.
4454 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4455}
4456
fayanga29eb242019-07-16 12:25:38 -07004457// Regression test of b/133771183.
4458TEST_P(QuicConnectionTest, RtoWithNoDataToRetransmit) {
fayangcff885a2019-10-22 07:39:04 -07004459 if (connection_.PtoEnabled()) {
fayanga29eb242019-07-16 12:25:38 -07004460 return;
4461 }
4462 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4463 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4464 connection_.SetMaxTailLossProbes(0);
4465
4466 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
4467 // Connection is cwnd limited.
4468 CongestionBlockWrites();
4469 // Stream gets reset.
4470 SendRstStream(3, QUIC_ERROR_PROCESSING_STREAM, 3);
4471 // Simulate the retransmission alarm firing.
4472 clock_.AdvanceTime(DefaultRetransmissionTime());
4473 // RTO fires, but there is no packet to be RTOed.
fayange861aee2019-10-16 13:40:39 -07004474 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
fayanga29eb242019-07-16 12:25:38 -07004475 connection_.GetRetransmissionAlarm()->Fire();
fayange861aee2019-10-16 13:40:39 -07004476 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
fayanga29eb242019-07-16 12:25:38 -07004477
4478 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(40);
4479 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(20);
fayange861aee2019-10-16 13:40:39 -07004480 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(false));
4481 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(1);
fayanga29eb242019-07-16 12:25:38 -07004482 // Receives packets 1 - 40.
4483 for (size_t i = 1; i <= 40; ++i) {
4484 ProcessDataPacket(i);
4485 }
4486}
4487
QUICHE teama6ef0a62019-03-07 20:34:33 -05004488TEST_P(QuicConnectionTest, SendHandshakeMessages) {
4489 use_tagging_decrypter();
4490 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
4491 // the end of the packet. We can test this to check which encrypter was used.
QUICHE team6987b4a2019-03-15 16:23:04 -07004492 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07004493 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004494
4495 // Attempt to send a handshake message and have the socket block.
4496 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
4497 BlockOnNextWrite();
nharper46833c32019-05-15 21:33:05 -07004498 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004499 // The packet should be serialized, but not queued.
4500 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4501
4502 // Switch to the new encrypter.
4503 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004504 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004505 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4506
4507 // Now become writeable and flush the packets.
4508 writer_->SetWritable();
4509 EXPECT_CALL(visitor_, OnCanWrite());
4510 connection_.OnCanWrite();
4511 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4512
4513 // Verify that the handshake packet went out at the null encryption.
4514 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
4515}
4516
4517TEST_P(QuicConnectionTest,
4518 DropRetransmitsForNullEncryptedPacketAfterForwardSecure) {
4519 use_tagging_decrypter();
QUICHE team6987b4a2019-03-15 16:23:04 -07004520 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07004521 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004522 connection_.SendCryptoStreamData();
4523
4524 // Simulate the retransmission alarm firing and the socket blocking.
4525 BlockOnNextWrite();
4526 clock_.AdvanceTime(DefaultRetransmissionTime());
fayange62e63c2019-12-04 07:16:25 -08004527 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004528 connection_.GetRetransmissionAlarm()->Fire();
fayang2ce66082019-10-02 06:29:04 -07004529 EXPECT_EQ(1u, connection_.NumQueuedPackets());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004530
4531 // Go forward secure.
4532 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07004533 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004534 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4535 notifier_.NeuterUnencryptedData();
4536 connection_.NeuterUnencryptedPackets();
fayang2ce66082019-10-02 06:29:04 -07004537 connection_.OnHandshakeComplete();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004538
4539 EXPECT_EQ(QuicTime::Zero(), connection_.GetRetransmissionAlarm()->deadline());
4540 // Unblock the socket and ensure that no packets are sent.
4541 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4542 writer_->SetWritable();
4543 connection_.OnCanWrite();
4544}
4545
4546TEST_P(QuicConnectionTest, RetransmitPacketsWithInitialEncryption) {
4547 use_tagging_decrypter();
QUICHE team6987b4a2019-03-15 16:23:04 -07004548 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07004549 std::make_unique<TaggingEncrypter>(0x01));
QUICHE team6987b4a2019-03-15 16:23:04 -07004550 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004551
nharper46833c32019-05-15 21:33:05 -07004552 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004553
4554 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004555 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004556 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4557
4558 SendStreamDataToPeer(2, "bar", 0, NO_FIN, nullptr);
4559 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4560
renjietangc0080082020-05-26 18:35:19 -07004561 connection_.RetransmitZeroRttPackets();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004562}
4563
4564TEST_P(QuicConnectionTest, BufferNonDecryptablePackets) {
QUICHE teamcd098022019-03-22 18:49:55 -07004565 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4566 return;
4567 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004568 // SetFromConfig is always called after construction from InitializeSession.
4569 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4570 QuicConfig config;
4571 connection_.SetFromConfig(config);
4572 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4573 use_tagging_decrypter();
4574
4575 const uint8_t tag = 0x07;
4576 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004577 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004578
4579 // Process an encrypted packet which can not yet be decrypted which should
4580 // result in the packet being buffered.
4581 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4582
4583 // Transition to the new encryption state and process another encrypted packet
4584 // which should result in the original packet being processed.
zhongyi546cc452019-04-12 15:27:49 -07004585 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004586 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004587 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4588 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004589 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004590 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(2);
4591 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4592
4593 // Finally, process a third packet and note that we do not reprocess the
4594 // buffered packet.
4595 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4596 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4597}
4598
4599TEST_P(QuicConnectionTest, TestRetransmitOrder) {
fayang5f135052019-08-22 17:59:40 -07004600 if (connection_.PtoEnabled()) {
4601 return;
4602 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004603 connection_.SetMaxTailLossProbes(0);
4604
4605 QuicByteCount first_packet_size;
4606 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4607 .WillOnce(SaveArg<3>(&first_packet_size));
4608
4609 connection_.SendStreamDataWithString(3, "first_packet", 0, NO_FIN);
4610 QuicByteCount second_packet_size;
4611 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4612 .WillOnce(SaveArg<3>(&second_packet_size));
4613 connection_.SendStreamDataWithString(3, "second_packet", 12, NO_FIN);
4614 EXPECT_NE(first_packet_size, second_packet_size);
4615 // Advance the clock by huge time to make sure packets will be retransmitted.
4616 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
4617 {
4618 InSequence s;
4619 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, first_packet_size, _));
4620 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, second_packet_size, _));
4621 }
4622 connection_.GetRetransmissionAlarm()->Fire();
4623
4624 // Advance again and expect the packets to be sent again in the same order.
4625 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(20));
4626 {
4627 InSequence s;
4628 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, first_packet_size, _));
4629 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, second_packet_size, _));
4630 }
4631 connection_.GetRetransmissionAlarm()->Fire();
4632}
4633
4634TEST_P(QuicConnectionTest, Buffer100NonDecryptablePacketsThenKeyChange) {
QUICHE teamcd098022019-03-22 18:49:55 -07004635 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4636 return;
4637 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004638 // SetFromConfig is always called after construction from InitializeSession.
4639 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4640 QuicConfig config;
4641 config.set_max_undecryptable_packets(100);
4642 connection_.SetFromConfig(config);
4643 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4644 use_tagging_decrypter();
4645
4646 const uint8_t tag = 0x07;
4647 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004648 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004649
4650 // Process an encrypted packet which can not yet be decrypted which should
4651 // result in the packet being buffered.
4652 for (uint64_t i = 1; i <= 100; ++i) {
4653 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4654 }
4655
4656 // Transition to the new encryption state and process another encrypted packet
4657 // which should result in the original packets being processed.
4658 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
zhongyi546cc452019-04-12 15:27:49 -07004659 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004660 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004661 EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
4662 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4663 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004664 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004665
4666 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(100);
4667 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
4668
4669 // Finally, process a third packet and note that we do not reprocess the
4670 // buffered packet.
4671 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4672 ProcessDataPacketAtLevel(102, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4673}
4674
4675TEST_P(QuicConnectionTest, SetRTOAfterWritingToSocket) {
4676 BlockOnNextWrite();
fayange62e63c2019-12-04 07:16:25 -08004677 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004678 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
fayange62e63c2019-12-04 07:16:25 -08004679 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004680
4681 // Test that RTO is started once we write to the socket.
4682 writer_->SetWritable();
fayange62e63c2019-12-04 07:16:25 -08004683 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004684 connection_.OnCanWrite();
4685 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4686}
4687
4688TEST_P(QuicConnectionTest, DelayRTOWithAckReceipt) {
fayang5f135052019-08-22 17:59:40 -07004689 if (connection_.PtoEnabled()) {
4690 return;
4691 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004692 connection_.SetMaxTailLossProbes(0);
4693
4694 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4695 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
4696 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
4697 connection_.SendStreamDataWithString(3, "bar", 0, NO_FIN);
4698 QuicAlarm* retransmission_alarm = connection_.GetRetransmissionAlarm();
4699 EXPECT_TRUE(retransmission_alarm->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004700 EXPECT_EQ(DefaultRetransmissionTime(),
4701 retransmission_alarm->deadline() - clock_.Now());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004702
4703 // Advance the time right before the RTO, then receive an ack for the first
4704 // packet to delay the RTO.
4705 clock_.AdvanceTime(DefaultRetransmissionTime());
4706 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4707 QuicAckFrame ack = InitAckFrame(1);
4708 ProcessAckPacket(&ack);
4709 // Now we have an RTT sample of DefaultRetransmissionTime(500ms),
4710 // so the RTO has increased to 2 * SRTT.
4711 EXPECT_TRUE(retransmission_alarm->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004712 EXPECT_EQ(retransmission_alarm->deadline() - clock_.Now(),
4713 2 * DefaultRetransmissionTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004714
4715 // Move forward past the original RTO and ensure the RTO is still pending.
4716 clock_.AdvanceTime(2 * DefaultRetransmissionTime());
4717
4718 // Ensure the second packet gets retransmitted when it finally fires.
4719 EXPECT_TRUE(retransmission_alarm->IsSet());
4720 EXPECT_EQ(retransmission_alarm->deadline(), clock_.ApproximateNow());
4721 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4722 // Manually cancel the alarm to simulate a real test.
4723 connection_.GetRetransmissionAlarm()->Fire();
4724
4725 // The new retransmitted packet number should set the RTO to a larger value
4726 // than previously.
4727 EXPECT_TRUE(retransmission_alarm->IsSet());
4728 QuicTime next_rto_time = retransmission_alarm->deadline();
4729 QuicTime expected_rto_time =
4730 connection_.sent_packet_manager().GetRetransmissionTime();
4731 EXPECT_EQ(next_rto_time, expected_rto_time);
4732}
4733
4734TEST_P(QuicConnectionTest, TestQueued) {
4735 connection_.SetMaxTailLossProbes(0);
4736
4737 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4738 BlockOnNextWrite();
4739 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4740 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4741
4742 // Unblock the writes and actually send.
4743 writer_->SetWritable();
4744 connection_.OnCanWrite();
4745 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4746}
4747
4748TEST_P(QuicConnectionTest, InitialTimeout) {
4749 EXPECT_TRUE(connection_.connected());
4750 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4751 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4752
4753 // SetFromConfig sets the initial timeouts before negotiation.
4754 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4755 QuicConfig config;
4756 connection_.SetFromConfig(config);
4757 // Subtract a second from the idle timeout on the client side.
4758 QuicTime default_timeout =
4759 clock_.ApproximateNow() +
4760 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4761 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
4762
fkastenholz5d880a92019-06-21 09:01:56 -07004763 EXPECT_CALL(visitor_,
4764 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004765 // Simulate the timeout alarm firing.
4766 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1));
4767 connection_.GetTimeoutAlarm()->Fire();
4768
4769 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4770 EXPECT_FALSE(connection_.connected());
4771
fayang9adfb532020-06-04 06:58:45 -07004772 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004773 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4774 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4775 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4776 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
renjietang11e4a3d2019-05-03 11:27:26 -07004777 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07004778 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004779}
4780
4781TEST_P(QuicConnectionTest, IdleTimeoutAfterFirstSentPacket) {
4782 EXPECT_TRUE(connection_.connected());
4783 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4784 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4785
4786 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4787 QuicConfig config;
4788 connection_.SetFromConfig(config);
4789 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4790 QuicTime initial_ddl =
4791 clock_.ApproximateNow() +
4792 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4793 EXPECT_EQ(initial_ddl, connection_.GetTimeoutAlarm()->deadline());
4794 EXPECT_TRUE(connection_.connected());
4795
4796 // Advance the time and send the first packet to the peer.
fayangb9c88442020-03-26 07:03:57 -07004797 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004798 QuicPacketNumber last_packet;
4799 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4800 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4801 // This will be the updated deadline for the connection to idle time out.
4802 QuicTime new_ddl = clock_.ApproximateNow() +
4803 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4804
4805 // Simulate the timeout alarm firing, the connection should not be closed as
4806 // a new packet has been sent.
fkastenholz5d880a92019-06-21 09:01:56 -07004807 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004808 QuicTime::Delta delay = initial_ddl - clock_.ApproximateNow();
4809 clock_.AdvanceTime(delay);
fayang2205d952020-05-12 13:45:56 -07004810 if (!GetQuicReloadableFlag(quic_use_idle_network_detector)) {
fayangb9c88442020-03-26 07:03:57 -07004811 connection_.GetTimeoutAlarm()->Fire();
4812 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004813 // Verify the timeout alarm deadline is updated.
4814 EXPECT_TRUE(connection_.connected());
4815 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4816 EXPECT_EQ(new_ddl, connection_.GetTimeoutAlarm()->deadline());
4817
4818 // Simulate the timeout alarm firing again, the connection now should be
4819 // closed.
fkastenholz5d880a92019-06-21 09:01:56 -07004820 EXPECT_CALL(visitor_,
4821 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004822 clock_.AdvanceTime(new_ddl - clock_.ApproximateNow());
4823 connection_.GetTimeoutAlarm()->Fire();
4824 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4825 EXPECT_FALSE(connection_.connected());
4826
fayang9adfb532020-06-04 06:58:45 -07004827 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004828 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4829 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4830 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4831 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07004832 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004833}
4834
4835TEST_P(QuicConnectionTest, IdleTimeoutAfterSendTwoPackets) {
4836 EXPECT_TRUE(connection_.connected());
4837 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4838 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4839
4840 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4841 QuicConfig config;
4842 connection_.SetFromConfig(config);
4843 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4844 QuicTime initial_ddl =
4845 clock_.ApproximateNow() +
4846 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4847 EXPECT_EQ(initial_ddl, connection_.GetTimeoutAlarm()->deadline());
4848 EXPECT_TRUE(connection_.connected());
4849
4850 // Immediately send the first packet, this is a rare case but test code will
4851 // hit this issue often as MockClock used for tests doesn't move with code
4852 // execution until manually adjusted.
4853 QuicPacketNumber last_packet;
4854 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4855 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4856
4857 // Advance the time and send the second packet to the peer.
4858 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
4859 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4860 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
4861
zhongyic1cab062019-06-19 12:02:24 -07004862 // Simulate the timeout alarm firing, the connection will be closed.
fkastenholz5d880a92019-06-21 09:01:56 -07004863 EXPECT_CALL(visitor_,
4864 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
zhongyic1cab062019-06-19 12:02:24 -07004865 clock_.AdvanceTime(initial_ddl - clock_.ApproximateNow());
4866 connection_.GetTimeoutAlarm()->Fire();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004867
4868 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4869 EXPECT_FALSE(connection_.connected());
4870
fayang9adfb532020-06-04 06:58:45 -07004871 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004872 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4873 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4874 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4875 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07004876 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004877}
4878
4879TEST_P(QuicConnectionTest, HandshakeTimeout) {
4880 // Use a shorter handshake timeout than idle timeout for this test.
4881 const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(5);
4882 connection_.SetNetworkTimeouts(timeout, timeout);
4883 EXPECT_TRUE(connection_.connected());
4884 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4885
4886 QuicTime handshake_timeout =
4887 clock_.ApproximateNow() + timeout - QuicTime::Delta::FromSeconds(1);
4888 EXPECT_EQ(handshake_timeout, connection_.GetTimeoutAlarm()->deadline());
4889 EXPECT_TRUE(connection_.connected());
4890
4891 // Send and ack new data 3 seconds later to lengthen the idle timeout.
4892 SendStreamDataToPeer(
dschinazi552accc2019-06-17 17:07:34 -07004893 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
4894 "GET /", 0, FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004895 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(3));
4896 QuicAckFrame frame = InitAckFrame(1);
4897 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4898 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4899 ProcessAckPacket(&frame);
4900
fayang2205d952020-05-12 13:45:56 -07004901 if (!GetQuicReloadableFlag(quic_use_idle_network_detector)) {
fayangb9c88442020-03-26 07:03:57 -07004902 // Fire early to verify it wouldn't timeout yet.
4903 connection_.GetTimeoutAlarm()->Fire();
4904 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004905 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4906 EXPECT_TRUE(connection_.connected());
4907
4908 clock_.AdvanceTime(timeout - QuicTime::Delta::FromSeconds(2));
4909
fkastenholz5d880a92019-06-21 09:01:56 -07004910 EXPECT_CALL(visitor_,
4911 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004912 // Simulate the timeout alarm firing.
4913 connection_.GetTimeoutAlarm()->Fire();
4914
4915 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4916 EXPECT_FALSE(connection_.connected());
4917
fayang9adfb532020-06-04 06:58:45 -07004918 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004919 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4920 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4921 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07004922 TestConnectionCloseQuicErrorCode(QUIC_HANDSHAKE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004923}
4924
4925TEST_P(QuicConnectionTest, PingAfterSend) {
QUICHE teamcd098022019-03-22 18:49:55 -07004926 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4927 return;
4928 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004929 EXPECT_TRUE(connection_.connected());
4930 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4931 .WillRepeatedly(Return(true));
4932 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4933
4934 // Advance to 5ms, and send a packet to the peer, which will set
4935 // the ping alarm.
4936 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4937 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4938 SendStreamDataToPeer(
dschinazi552accc2019-06-17 17:07:34 -07004939 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
4940 "GET /", 0, FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004941 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004942 EXPECT_EQ(QuicTime::Delta::FromSeconds(15),
4943 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004944
4945 // Now recevie an ACK of the previous packet, which will move the
4946 // ping alarm forward.
4947 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4948 QuicAckFrame frame = InitAckFrame(1);
4949 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4950 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4951 ProcessAckPacket(&frame);
4952 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4953 // The ping timer is set slightly less than 15 seconds in the future, because
4954 // of the 1s ping timer alarm granularity.
zhongyieef848f2019-10-18 07:09:37 -07004955 EXPECT_EQ(
4956 QuicTime::Delta::FromSeconds(15) - QuicTime::Delta::FromMilliseconds(5),
4957 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004958
4959 writer_->Reset();
4960 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15));
zhongyifbb25772019-04-10 16:54:08 -07004961 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004962 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07004963 size_t padding_frame_count = writer_->padding_frames().size();
4964 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004965 ASSERT_EQ(1u, writer_->ping_frames().size());
4966 writer_->Reset();
4967
4968 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4969 .WillRepeatedly(Return(false));
4970 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4971 SendAckPacketToPeer();
4972
4973 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4974}
4975
4976TEST_P(QuicConnectionTest, ReducedPingTimeout) {
QUICHE teamcd098022019-03-22 18:49:55 -07004977 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4978 return;
4979 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004980 EXPECT_TRUE(connection_.connected());
4981 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4982 .WillRepeatedly(Return(true));
4983 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4984
4985 // Use a reduced ping timeout for this connection.
4986 connection_.set_ping_timeout(QuicTime::Delta::FromSeconds(10));
4987
4988 // Advance to 5ms, and send a packet to the peer, which will set
4989 // the ping alarm.
4990 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4991 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4992 SendStreamDataToPeer(
dschinazi552accc2019-06-17 17:07:34 -07004993 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
4994 "GET /", 0, FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004995 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004996 EXPECT_EQ(QuicTime::Delta::FromSeconds(10),
4997 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004998
4999 // Now recevie an ACK of the previous packet, which will move the
5000 // ping alarm forward.
5001 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
5002 QuicAckFrame frame = InitAckFrame(1);
5003 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5004 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5005 ProcessAckPacket(&frame);
5006 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
5007 // The ping timer is set slightly less than 10 seconds in the future, because
5008 // of the 1s ping timer alarm granularity.
zhongyieef848f2019-10-18 07:09:37 -07005009 EXPECT_EQ(
5010 QuicTime::Delta::FromSeconds(10) - QuicTime::Delta::FromMilliseconds(5),
5011 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005012
5013 writer_->Reset();
5014 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
5015 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
5016 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
5017 }));
5018 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07005019 size_t padding_frame_count = writer_->padding_frames().size();
5020 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005021 ASSERT_EQ(1u, writer_->ping_frames().size());
5022 writer_->Reset();
5023
5024 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
5025 .WillRepeatedly(Return(false));
5026 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
5027 SendAckPacketToPeer();
5028
5029 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
5030}
5031
5032// Tests whether sending an MTU discovery packet to peer successfully causes the
5033// maximum packet size to increase.
5034TEST_P(QuicConnectionTest, SendMtuDiscoveryPacket) {
wub031d47c2019-11-21 08:04:07 -08005035 MtuDiscoveryTestInit();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005036
5037 // Send an MTU probe.
5038 const size_t new_mtu = kDefaultMaxPacketSize + 100;
5039 QuicByteCount mtu_probe_size;
5040 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5041 .WillOnce(SaveArg<3>(&mtu_probe_size));
5042 connection_.SendMtuDiscoveryPacket(new_mtu);
5043 EXPECT_EQ(new_mtu, mtu_probe_size);
5044 EXPECT_EQ(QuicPacketNumber(1u), creator_->packet_number());
5045
5046 // Send more than MTU worth of data. No acknowledgement was received so far,
5047 // so the MTU should be at its old value.
vasilvvc48c8712019-03-11 13:38:16 -07005048 const std::string data(kDefaultMaxPacketSize + 1, '.');
QUICHE teama6ef0a62019-03-07 20:34:33 -05005049 QuicByteCount size_before_mtu_change;
5050 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5051 .Times(2)
5052 .WillOnce(SaveArg<3>(&size_before_mtu_change))
5053 .WillOnce(Return());
5054 connection_.SendStreamDataWithString(3, data, 0, FIN);
5055 EXPECT_EQ(QuicPacketNumber(3u), creator_->packet_number());
5056 EXPECT_EQ(kDefaultMaxPacketSize, size_before_mtu_change);
5057
5058 // Acknowledge all packets so far.
5059 QuicAckFrame probe_ack = InitAckFrame(3);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005060 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5061 ProcessAckPacket(&probe_ack);
5062 EXPECT_EQ(new_mtu, connection_.max_packet_length());
5063
5064 // Send the same data again. Check that it fits into a single packet now.
5065 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
5066 connection_.SendStreamDataWithString(3, data, 0, FIN);
5067 EXPECT_EQ(QuicPacketNumber(4u), creator_->packet_number());
5068}
5069
wubb442b862020-01-31 08:16:21 -08005070// Verifies that when a MTU probe packet is sent and buffered in a batch writer,
5071// the writer is flushed immediately.
5072TEST_P(QuicConnectionTest, BatchWriterFlushedAfterMtuDiscoveryPacket) {
5073 writer_->SetBatchMode(true);
5074 MtuDiscoveryTestInit();
5075
5076 // Send an MTU probe.
5077 const size_t target_mtu = kDefaultMaxPacketSize + 100;
5078 QuicByteCount mtu_probe_size;
5079 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5080 .WillOnce(SaveArg<3>(&mtu_probe_size));
5081 const uint32_t prior_flush_attempts = writer_->flush_attempts();
5082 connection_.SendMtuDiscoveryPacket(target_mtu);
5083 EXPECT_EQ(target_mtu, mtu_probe_size);
wub18f47342020-03-16 15:56:03 -07005084 EXPECT_EQ(writer_->flush_attempts(), prior_flush_attempts + 1);
wubb442b862020-01-31 08:16:21 -08005085}
5086
QUICHE teama6ef0a62019-03-07 20:34:33 -05005087// Tests whether MTU discovery does not happen when it is not explicitly enabled
5088// by the connection options.
5089TEST_P(QuicConnectionTest, MtuDiscoveryDisabled) {
wub031d47c2019-11-21 08:04:07 -08005090 MtuDiscoveryTestInit();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005091
5092 const QuicPacketCount packets_between_probes_base = 10;
5093 set_packets_between_probes_base(packets_between_probes_base);
5094
5095 const QuicPacketCount number_of_packets = packets_between_probes_base * 2;
5096 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
5097 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5098 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5099 EXPECT_EQ(0u, connection_.mtu_probe_count());
5100 }
5101}
5102
wubf76cf2a2019-10-11 18:49:07 -07005103// Tests whether MTU discovery works when all probes are acknowledged on the
QUICHE teama6ef0a62019-03-07 20:34:33 -05005104// first try.
5105TEST_P(QuicConnectionTest, MtuDiscoveryEnabled) {
wub031d47c2019-11-21 08:04:07 -08005106 MtuDiscoveryTestInit();
nharperc6b99512019-09-19 11:13:48 -07005107
QUICHE teama6ef0a62019-03-07 20:34:33 -05005108 const QuicPacketCount packets_between_probes_base = 5;
5109 set_packets_between_probes_base(packets_between_probes_base);
5110
wubf76cf2a2019-10-11 18:49:07 -07005111 connection_.EnablePathMtuDiscovery(send_algorithm_);
5112
QUICHE teama6ef0a62019-03-07 20:34:33 -05005113 // Send enough packets so that the next one triggers path MTU discovery.
5114 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5115 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5116 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5117 }
5118
5119 // Trigger the probe.
5120 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5121 nullptr);
5122 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5123 QuicByteCount probe_size;
5124 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5125 .WillOnce(SaveArg<3>(&probe_size));
5126 connection_.GetMtuDiscoveryAlarm()->Fire();
wub173916e2019-11-27 14:36:24 -08005127
5128 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(),
5129 kMtuDiscoveryTargetPacketSizeHigh));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005130
5131 const QuicPacketNumber probe_packet_number =
5132 FirstSendingPacketNumber() + packets_between_probes_base;
5133 ASSERT_EQ(probe_packet_number, creator_->packet_number());
5134
5135 // Acknowledge all packets sent so far.
5136 QuicAckFrame probe_ack = InitAckFrame(probe_packet_number);
wubf76cf2a2019-10-11 18:49:07 -07005137 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5138 .Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005139 ProcessAckPacket(&probe_ack);
wubf76cf2a2019-10-11 18:49:07 -07005140 EXPECT_EQ(probe_size, connection_.max_packet_length());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005141 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5142
wubf76cf2a2019-10-11 18:49:07 -07005143 EXPECT_EQ(1u, connection_.mtu_probe_count());
5144
wubf76cf2a2019-10-11 18:49:07 -07005145 QuicStreamOffset stream_offset = packets_between_probes_base;
wubecb643f2020-03-19 08:58:46 -07005146 QuicByteCount last_probe_size = 0;
wubf76cf2a2019-10-11 18:49:07 -07005147 for (size_t num_probes = 1; num_probes < kMtuDiscoveryAttempts;
5148 ++num_probes) {
5149 // Send just enough packets without triggering the next probe.
5150 for (QuicPacketCount i = 0;
5151 i < (packets_between_probes_base << num_probes) - 1; ++i) {
5152 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5153 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5154 }
5155
5156 // Trigger the next probe.
5157 SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
5158 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5159 QuicByteCount new_probe_size;
5160 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5161 .WillOnce(SaveArg<3>(&new_probe_size));
5162 connection_.GetMtuDiscoveryAlarm()->Fire();
5163 EXPECT_THAT(new_probe_size,
5164 InRange(probe_size, kMtuDiscoveryTargetPacketSizeHigh));
5165 EXPECT_EQ(num_probes + 1, connection_.mtu_probe_count());
5166
5167 // Acknowledge all packets sent so far.
5168 QuicAckFrame probe_ack = InitAckFrame(creator_->packet_number());
5169 ProcessAckPacket(&probe_ack);
5170 EXPECT_EQ(new_probe_size, connection_.max_packet_length());
5171 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5172
wubecb643f2020-03-19 08:58:46 -07005173 last_probe_size = probe_size;
wubf76cf2a2019-10-11 18:49:07 -07005174 probe_size = new_probe_size;
5175 }
5176
5177 // The last probe size should be equal to the target.
5178 EXPECT_EQ(probe_size, kMtuDiscoveryTargetPacketSizeHigh);
wubecb643f2020-03-19 08:58:46 -07005179
wubae6581a2020-05-04 12:13:05 -07005180 writer_->SetShouldWriteFail();
wubecb643f2020-03-19 08:58:46 -07005181
wubae6581a2020-05-04 12:13:05 -07005182 // Ignore PACKET_WRITE_ERROR once.
5183 SendStreamDataToPeer(3, "(", stream_offset++, NO_FIN, nullptr);
5184 EXPECT_EQ(last_probe_size, connection_.max_packet_length());
5185 EXPECT_TRUE(connection_.connected());
wubecb643f2020-03-19 08:58:46 -07005186
wubae6581a2020-05-04 12:13:05 -07005187 // Close connection on another PACKET_WRITE_ERROR.
5188 EXPECT_CALL(visitor_, OnConnectionClosed(_, _))
5189 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
5190 SendStreamDataToPeer(3, ")", stream_offset++, NO_FIN, nullptr);
5191 EXPECT_EQ(last_probe_size, connection_.max_packet_length());
5192 EXPECT_FALSE(connection_.connected());
5193 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
5194 IsError(QUIC_PACKET_WRITE_ERROR));
wubf76cf2a2019-10-11 18:49:07 -07005195}
5196
wub748e20b2020-03-20 14:33:59 -07005197// After a successful MTU probe, one and only one write error should be ignored
5198// if it happened in QuicConnection::FlushPacket.
5199TEST_P(QuicConnectionTest,
5200 MtuDiscoveryIgnoreOneWriteErrorInFlushAfterSuccessfulProbes) {
5201 MtuDiscoveryTestInit();
5202 writer_->SetBatchMode(true);
5203
5204 const QuicPacketCount packets_between_probes_base = 5;
5205 set_packets_between_probes_base(packets_between_probes_base);
5206
5207 connection_.EnablePathMtuDiscovery(send_algorithm_);
5208
5209 const QuicByteCount original_max_packet_length =
5210 connection_.max_packet_length();
5211 // Send enough packets so that the next one triggers path MTU discovery.
5212 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5213 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5214 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5215 }
5216
5217 // Trigger the probe.
5218 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5219 nullptr);
5220 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5221 QuicByteCount probe_size;
5222 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5223 .WillOnce(SaveArg<3>(&probe_size));
5224 connection_.GetMtuDiscoveryAlarm()->Fire();
5225
5226 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(),
5227 kMtuDiscoveryTargetPacketSizeHigh));
5228
5229 const QuicPacketNumber probe_packet_number =
5230 FirstSendingPacketNumber() + packets_between_probes_base;
5231 ASSERT_EQ(probe_packet_number, creator_->packet_number());
5232
5233 // Acknowledge all packets sent so far.
5234 QuicAckFrame probe_ack = InitAckFrame(probe_packet_number);
5235 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5236 .Times(AnyNumber());
5237 ProcessAckPacket(&probe_ack);
5238 EXPECT_EQ(probe_size, connection_.max_packet_length());
5239 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5240
5241 EXPECT_EQ(1u, connection_.mtu_probe_count());
5242
wubae6581a2020-05-04 12:13:05 -07005243 writer_->SetShouldWriteFail();
wub748e20b2020-03-20 14:33:59 -07005244
wubae6581a2020-05-04 12:13:05 -07005245 // Ignore PACKET_WRITE_ERROR once.
5246 {
5247 QuicConnection::ScopedPacketFlusher flusher(&connection_);
5248 // flusher's destructor will call connection_.FlushPackets, which should
5249 // get a WRITE_STATUS_ERROR from the writer and ignore it.
wub748e20b2020-03-20 14:33:59 -07005250 }
wubae6581a2020-05-04 12:13:05 -07005251 EXPECT_EQ(original_max_packet_length, connection_.max_packet_length());
5252 EXPECT_TRUE(connection_.connected());
5253
5254 // Close connection on another PACKET_WRITE_ERROR.
5255 EXPECT_CALL(visitor_, OnConnectionClosed(_, _))
5256 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
5257 {
5258 QuicConnection::ScopedPacketFlusher flusher(&connection_);
5259 // flusher's destructor will call connection_.FlushPackets, which should
5260 // get a WRITE_STATUS_ERROR from the writer and ignore it.
5261 }
5262 EXPECT_EQ(original_max_packet_length, connection_.max_packet_length());
5263 EXPECT_FALSE(connection_.connected());
5264 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
5265 IsError(QUIC_PACKET_WRITE_ERROR));
wub748e20b2020-03-20 14:33:59 -07005266}
5267
wubf76cf2a2019-10-11 18:49:07 -07005268// Simulate the case where the first attempt to send a probe is write blocked,
5269// and after unblock, the second attempt returns a MSG_TOO_BIG error.
5270TEST_P(QuicConnectionTest, MtuDiscoveryWriteBlocked) {
wub031d47c2019-11-21 08:04:07 -08005271 MtuDiscoveryTestInit();
wubf76cf2a2019-10-11 18:49:07 -07005272
5273 const QuicPacketCount packets_between_probes_base = 5;
5274 set_packets_between_probes_base(packets_between_probes_base);
5275
5276 connection_.EnablePathMtuDiscovery(send_algorithm_);
5277
5278 // Send enough packets so that the next one triggers path MTU discovery.
5279 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5280 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005281 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5282 }
5283
wubf76cf2a2019-10-11 18:49:07 -07005284 QuicByteCount original_max_packet_length = connection_.max_packet_length();
5285
5286 // Trigger the probe.
5287 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5288 nullptr);
5289 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
fayange62e63c2019-12-04 07:16:25 -08005290 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
wubf76cf2a2019-10-11 18:49:07 -07005291 BlockOnNextWrite();
5292 EXPECT_EQ(0u, connection_.NumQueuedPackets());
5293 connection_.GetMtuDiscoveryAlarm()->Fire();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005294 EXPECT_EQ(1u, connection_.mtu_probe_count());
wubf76cf2a2019-10-11 18:49:07 -07005295 EXPECT_EQ(1u, connection_.NumQueuedPackets());
5296 ASSERT_TRUE(connection_.connected());
5297
5298 writer_->SetWritable();
5299 SimulateNextPacketTooLarge();
5300 connection_.OnCanWrite();
5301 EXPECT_EQ(0u, connection_.NumQueuedPackets());
5302 EXPECT_EQ(original_max_packet_length, connection_.max_packet_length());
5303 EXPECT_TRUE(connection_.connected());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005304}
5305
5306// Tests whether MTU discovery works correctly when the probes never get
5307// acknowledged.
5308TEST_P(QuicConnectionTest, MtuDiscoveryFailed) {
wub031d47c2019-11-21 08:04:07 -08005309 MtuDiscoveryTestInit();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005310
QUICHE teama6ef0a62019-03-07 20:34:33 -05005311 // Lower the number of probes between packets in order to make the test go
5312 // much faster.
5313 const QuicPacketCount packets_between_probes_base = 5;
5314 set_packets_between_probes_base(packets_between_probes_base);
5315
wubf76cf2a2019-10-11 18:49:07 -07005316 connection_.EnablePathMtuDiscovery(send_algorithm_);
5317
5318 const QuicTime::Delta rtt = QuicTime::Delta::FromMilliseconds(100);
5319
5320 EXPECT_EQ(packets_between_probes_base,
5321 QuicConnectionPeer::GetPacketsBetweenMtuProbes(&connection_));
5322
QUICHE teama6ef0a62019-03-07 20:34:33 -05005323 // This tests sends more packets than strictly necessary to make sure that if
5324 // the connection was to send more discovery packets than needed, those would
5325 // get caught as well.
5326 const QuicPacketCount number_of_packets =
5327 packets_between_probes_base * (1 << (kMtuDiscoveryAttempts + 1));
5328 std::vector<QuicPacketNumber> mtu_discovery_packets;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005329 // Called on many acks.
5330 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5331 .Times(AnyNumber());
5332 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
5333 SendStreamDataToPeer(3, "!", i, NO_FIN, nullptr);
5334 clock_.AdvanceTime(rtt);
5335
5336 // Receive an ACK, which marks all data packets as received, and all MTU
5337 // discovery packets as missing.
5338
5339 QuicAckFrame ack;
5340
5341 if (!mtu_discovery_packets.empty()) {
5342 QuicPacketNumber min_packet = *min_element(mtu_discovery_packets.begin(),
5343 mtu_discovery_packets.end());
5344 QuicPacketNumber max_packet = *max_element(mtu_discovery_packets.begin(),
5345 mtu_discovery_packets.end());
5346 ack.packets.AddRange(QuicPacketNumber(1), min_packet);
5347 ack.packets.AddRange(QuicPacketNumber(max_packet + 1),
5348 creator_->packet_number() + 1);
5349 ack.largest_acked = creator_->packet_number();
5350
5351 } else {
5352 ack.packets.AddRange(QuicPacketNumber(1), creator_->packet_number() + 1);
5353 ack.largest_acked = creator_->packet_number();
5354 }
5355
5356 ProcessAckPacket(&ack);
5357
5358 // Trigger MTU probe if it would be scheduled now.
5359 if (!connection_.GetMtuDiscoveryAlarm()->IsSet()) {
5360 continue;
5361 }
5362
5363 // Fire the alarm. The alarm should cause a packet to be sent.
5364 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5365 connection_.GetMtuDiscoveryAlarm()->Fire();
5366 // Record the packet number of the MTU discovery packet in order to
5367 // mark it as NACK'd.
5368 mtu_discovery_packets.push_back(creator_->packet_number());
5369 }
5370
5371 // Ensure the number of packets between probes grows exponentially by checking
5372 // it against the closed-form expression for the packet number.
5373 ASSERT_EQ(kMtuDiscoveryAttempts, mtu_discovery_packets.size());
5374 for (uint64_t i = 0; i < kMtuDiscoveryAttempts; i++) {
5375 // 2^0 + 2^1 + 2^2 + ... + 2^n = 2^(n + 1) - 1
5376 const QuicPacketCount packets_between_probes =
5377 packets_between_probes_base * ((1 << (i + 1)) - 1);
5378 EXPECT_EQ(QuicPacketNumber(packets_between_probes + (i + 1)),
5379 mtu_discovery_packets[i]);
5380 }
5381
5382 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5383 EXPECT_EQ(kDefaultMaxPacketSize, connection_.max_packet_length());
5384 EXPECT_EQ(kMtuDiscoveryAttempts, connection_.mtu_probe_count());
5385}
5386
wubf76cf2a2019-10-11 18:49:07 -07005387// Probe 3 times, the first one succeeds, then fails, then succeeds again.
5388TEST_P(QuicConnectionTest, MtuDiscoverySecondProbeFailed) {
wub031d47c2019-11-21 08:04:07 -08005389 MtuDiscoveryTestInit();
wubf76cf2a2019-10-11 18:49:07 -07005390
5391 const QuicPacketCount packets_between_probes_base = 5;
5392 set_packets_between_probes_base(packets_between_probes_base);
5393
5394 connection_.EnablePathMtuDiscovery(send_algorithm_);
5395
5396 // Send enough packets so that the next one triggers path MTU discovery.
5397 QuicStreamOffset stream_offset = 0;
5398 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5399 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5400 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5401 }
5402
5403 // Trigger the probe.
5404 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5405 nullptr);
5406 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5407 QuicByteCount probe_size;
5408 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5409 .WillOnce(SaveArg<3>(&probe_size));
5410 connection_.GetMtuDiscoveryAlarm()->Fire();
5411 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(),
5412 kMtuDiscoveryTargetPacketSizeHigh));
5413
5414 const QuicPacketNumber probe_packet_number =
5415 FirstSendingPacketNumber() + packets_between_probes_base;
5416 ASSERT_EQ(probe_packet_number, creator_->packet_number());
5417
5418 // Acknowledge all packets sent so far.
5419 QuicAckFrame first_ack = InitAckFrame(probe_packet_number);
wubf76cf2a2019-10-11 18:49:07 -07005420 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5421 .Times(AnyNumber());
5422 ProcessAckPacket(&first_ack);
5423 EXPECT_EQ(probe_size, connection_.max_packet_length());
5424 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5425
5426 EXPECT_EQ(1u, connection_.mtu_probe_count());
5427
5428 // Send just enough packets without triggering the second probe.
5429 for (QuicPacketCount i = 0; i < (packets_between_probes_base << 1) - 1; ++i) {
5430 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5431 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5432 }
5433
5434 // Trigger the second probe.
5435 SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
5436 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5437 QuicByteCount second_probe_size;
5438 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5439 .WillOnce(SaveArg<3>(&second_probe_size));
5440 connection_.GetMtuDiscoveryAlarm()->Fire();
5441 EXPECT_THAT(second_probe_size,
5442 InRange(probe_size, kMtuDiscoveryTargetPacketSizeHigh));
5443 EXPECT_EQ(2u, connection_.mtu_probe_count());
5444
5445 // Acknowledge all packets sent so far, except the second probe.
5446 QuicPacketNumber second_probe_packet_number = creator_->packet_number();
5447 QuicAckFrame second_ack = InitAckFrame(second_probe_packet_number - 1);
5448 ProcessAckPacket(&first_ack);
5449 EXPECT_EQ(probe_size, connection_.max_packet_length());
5450
5451 // Send just enough packets without triggering the third probe.
5452 for (QuicPacketCount i = 0; i < (packets_between_probes_base << 2) - 1; ++i) {
5453 SendStreamDataToPeer(3, "@", stream_offset++, NO_FIN, nullptr);
5454 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5455 }
5456
5457 // Trigger the third probe.
5458 SendStreamDataToPeer(3, "#", stream_offset++, NO_FIN, nullptr);
5459 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5460 QuicByteCount third_probe_size;
5461 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5462 .WillOnce(SaveArg<3>(&third_probe_size));
5463 connection_.GetMtuDiscoveryAlarm()->Fire();
5464 EXPECT_THAT(third_probe_size, InRange(probe_size, second_probe_size));
5465 EXPECT_EQ(3u, connection_.mtu_probe_count());
5466
5467 // Acknowledge all packets sent so far, except the second probe.
5468 QuicAckFrame third_ack =
5469 ConstructAckFrame(creator_->packet_number(), second_probe_packet_number);
5470 ProcessAckPacket(&third_ack);
5471 EXPECT_EQ(third_probe_size, connection_.max_packet_length());
5472}
5473
QUICHE teama6ef0a62019-03-07 20:34:33 -05005474// Tests whether MTU discovery works when the writer has a limit on how large a
5475// packet can be.
5476TEST_P(QuicConnectionTest, MtuDiscoveryWriterLimited) {
wub031d47c2019-11-21 08:04:07 -08005477 MtuDiscoveryTestInit();
nharperc6b99512019-09-19 11:13:48 -07005478
QUICHE teama6ef0a62019-03-07 20:34:33 -05005479 const QuicByteCount mtu_limit = kMtuDiscoveryTargetPacketSizeHigh - 1;
5480 writer_->set_max_packet_size(mtu_limit);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005481
5482 const QuicPacketCount packets_between_probes_base = 5;
5483 set_packets_between_probes_base(packets_between_probes_base);
5484
wubf76cf2a2019-10-11 18:49:07 -07005485 connection_.EnablePathMtuDiscovery(send_algorithm_);
5486
QUICHE teama6ef0a62019-03-07 20:34:33 -05005487 // Send enough packets so that the next one triggers path MTU discovery.
5488 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5489 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5490 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5491 }
5492
5493 // Trigger the probe.
5494 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5495 nullptr);
5496 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5497 QuicByteCount probe_size;
5498 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5499 .WillOnce(SaveArg<3>(&probe_size));
5500 connection_.GetMtuDiscoveryAlarm()->Fire();
wub173916e2019-11-27 14:36:24 -08005501
5502 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(), mtu_limit));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005503
5504 const QuicPacketNumber probe_sequence_number =
5505 FirstSendingPacketNumber() + packets_between_probes_base;
5506 ASSERT_EQ(probe_sequence_number, creator_->packet_number());
5507
5508 // Acknowledge all packets sent so far.
5509 QuicAckFrame probe_ack = InitAckFrame(probe_sequence_number);
wubf76cf2a2019-10-11 18:49:07 -07005510 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5511 .Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005512 ProcessAckPacket(&probe_ack);
wubf76cf2a2019-10-11 18:49:07 -07005513 EXPECT_EQ(probe_size, connection_.max_packet_length());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005514 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5515
wubf76cf2a2019-10-11 18:49:07 -07005516 EXPECT_EQ(1u, connection_.mtu_probe_count());
5517
wubf76cf2a2019-10-11 18:49:07 -07005518 QuicStreamOffset stream_offset = packets_between_probes_base;
5519 for (size_t num_probes = 1; num_probes < kMtuDiscoveryAttempts;
5520 ++num_probes) {
5521 // Send just enough packets without triggering the next probe.
5522 for (QuicPacketCount i = 0;
5523 i < (packets_between_probes_base << num_probes) - 1; ++i) {
5524 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5525 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5526 }
5527
5528 // Trigger the next probe.
5529 SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
5530 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5531 QuicByteCount new_probe_size;
5532 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5533 .WillOnce(SaveArg<3>(&new_probe_size));
5534 connection_.GetMtuDiscoveryAlarm()->Fire();
5535 EXPECT_THAT(new_probe_size, InRange(probe_size, mtu_limit));
5536 EXPECT_EQ(num_probes + 1, connection_.mtu_probe_count());
5537
5538 // Acknowledge all packets sent so far.
5539 QuicAckFrame probe_ack = InitAckFrame(creator_->packet_number());
5540 ProcessAckPacket(&probe_ack);
5541 EXPECT_EQ(new_probe_size, connection_.max_packet_length());
5542 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5543
5544 probe_size = new_probe_size;
5545 }
5546
5547 // The last probe size should be equal to the target.
5548 EXPECT_EQ(probe_size, mtu_limit);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005549}
5550
5551// Tests whether MTU discovery works when the writer returns an error despite
5552// advertising higher packet length.
5553TEST_P(QuicConnectionTest, MtuDiscoveryWriterFailed) {
wub031d47c2019-11-21 08:04:07 -08005554 MtuDiscoveryTestInit();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005555
5556 const QuicByteCount mtu_limit = kMtuDiscoveryTargetPacketSizeHigh - 1;
5557 const QuicByteCount initial_mtu = connection_.max_packet_length();
5558 EXPECT_LT(initial_mtu, mtu_limit);
5559 writer_->set_max_packet_size(mtu_limit);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005560
5561 const QuicPacketCount packets_between_probes_base = 5;
5562 set_packets_between_probes_base(packets_between_probes_base);
5563
wubf76cf2a2019-10-11 18:49:07 -07005564 connection_.EnablePathMtuDiscovery(send_algorithm_);
5565
QUICHE teama6ef0a62019-03-07 20:34:33 -05005566 // Send enough packets so that the next one triggers path MTU discovery.
5567 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5568 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5569 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5570 }
5571
5572 // Trigger the probe.
5573 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5574 nullptr);
5575 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5576 writer_->SimulateNextPacketTooLarge();
5577 connection_.GetMtuDiscoveryAlarm()->Fire();
5578 ASSERT_TRUE(connection_.connected());
5579
5580 // Send more data.
5581 QuicPacketNumber probe_number = creator_->packet_number();
5582 QuicPacketCount extra_packets = packets_between_probes_base * 3;
5583 for (QuicPacketCount i = 0; i < extra_packets; i++) {
5584 connection_.EnsureWritableAndSendStreamData5();
5585 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5586 }
5587
5588 // Acknowledge all packets sent so far, except for the lost probe.
5589 QuicAckFrame probe_ack =
5590 ConstructAckFrame(creator_->packet_number(), probe_number);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005591 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5592 ProcessAckPacket(&probe_ack);
5593 EXPECT_EQ(initial_mtu, connection_.max_packet_length());
5594
5595 // Send more packets, and ensure that none of them sets the alarm.
5596 for (QuicPacketCount i = 0; i < 4 * packets_between_probes_base; i++) {
5597 connection_.EnsureWritableAndSendStreamData5();
5598 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5599 }
5600
5601 EXPECT_EQ(initial_mtu, connection_.max_packet_length());
5602 EXPECT_EQ(1u, connection_.mtu_probe_count());
5603}
5604
5605TEST_P(QuicConnectionTest, NoMtuDiscoveryAfterConnectionClosed) {
wub031d47c2019-11-21 08:04:07 -08005606 MtuDiscoveryTestInit();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005607
QUICHE teama6ef0a62019-03-07 20:34:33 -05005608 const QuicPacketCount packets_between_probes_base = 10;
5609 set_packets_between_probes_base(packets_between_probes_base);
5610
wubf76cf2a2019-10-11 18:49:07 -07005611 connection_.EnablePathMtuDiscovery(send_algorithm_);
5612
QUICHE teama6ef0a62019-03-07 20:34:33 -05005613 // Send enough packets so that the next one triggers path MTU discovery.
5614 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5615 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5616 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5617 }
5618
5619 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5620 nullptr);
5621 EXPECT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5622
fkastenholz5d880a92019-06-21 09:01:56 -07005623 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005624 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
5625 ConnectionCloseBehavior::SILENT_CLOSE);
5626 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5627}
5628
dschinazi9a6194e2020-04-30 16:21:09 -07005629TEST_P(QuicConnectionTest, TimeoutAfterSendDuringHandshake) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005630 EXPECT_TRUE(connection_.connected());
5631 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5632 QuicConfig config;
5633 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005634
5635 const QuicTime::Delta initial_idle_timeout =
5636 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5637 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5638 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
5639
5640 // When we send a packet, the timeout will change to 5ms +
5641 // kInitialIdleTimeoutSecs.
5642 clock_.AdvanceTime(five_ms);
5643 SendStreamDataToPeer(
5644 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5645 0, FIN, nullptr);
fayang2205d952020-05-12 13:45:56 -07005646 if (GetQuicReloadableFlag(quic_use_idle_network_detector)) {
fayangb9c88442020-03-26 07:03:57 -07005647 EXPECT_EQ(default_timeout + five_ms,
5648 connection_.GetTimeoutAlarm()->deadline());
5649 } else {
5650 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5651 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005652
5653 // Now send more data. This will not move the timeout because
5654 // no data has been received since the previous write.
5655 clock_.AdvanceTime(five_ms);
5656 SendStreamDataToPeer(
5657 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5658 3, FIN, nullptr);
fayang2205d952020-05-12 13:45:56 -07005659 if (GetQuicReloadableFlag(quic_use_idle_network_detector)) {
fayangb9c88442020-03-26 07:03:57 -07005660 EXPECT_EQ(default_timeout + five_ms,
5661 connection_.GetTimeoutAlarm()->deadline());
5662 } else {
5663 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5664 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005665
5666 // The original alarm will fire. We should not time out because we had a
5667 // network event at t=5ms. The alarm will reregister.
5668 clock_.AdvanceTime(initial_idle_timeout - five_ms - five_ms);
5669 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
fayang2205d952020-05-12 13:45:56 -07005670 if (!GetQuicReloadableFlag(quic_use_idle_network_detector)) {
fayangb9c88442020-03-26 07:03:57 -07005671 connection_.GetTimeoutAlarm()->Fire();
5672 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005673 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5674 EXPECT_TRUE(connection_.connected());
5675 EXPECT_EQ(default_timeout + five_ms,
5676 connection_.GetTimeoutAlarm()->deadline());
5677
5678 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07005679 EXPECT_CALL(visitor_,
5680 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07005681 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005682 clock_.AdvanceTime(five_ms);
5683 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5684 connection_.GetTimeoutAlarm()->Fire();
5685 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5686 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005687 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005688}
5689
5690TEST_P(QuicConnectionTest, TimeoutAfterRetransmission) {
fayang5f135052019-08-22 17:59:40 -07005691 if (connection_.PtoEnabled()) {
5692 return;
5693 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005694 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5695 EXPECT_TRUE(connection_.connected());
5696 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5697 QuicConfig config;
5698 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005699
5700 const QuicTime start_time = clock_.Now();
5701 const QuicTime::Delta initial_idle_timeout =
5702 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5703 QuicTime default_timeout = clock_.Now() + initial_idle_timeout;
5704
5705 connection_.SetMaxTailLossProbes(0);
5706 const QuicTime default_retransmission_time =
5707 start_time + DefaultRetransmissionTime();
5708
5709 ASSERT_LT(default_retransmission_time, default_timeout);
5710
5711 // When we send a packet, the timeout will change to 5 ms +
5712 // kInitialIdleTimeoutSecs (but it will not reschedule the alarm).
5713 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5714 const QuicTime send_time = start_time + five_ms;
5715 clock_.AdvanceTime(five_ms);
5716 ASSERT_EQ(send_time, clock_.Now());
5717 SendStreamDataToPeer(
5718 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5719 0, FIN, nullptr);
fayang2205d952020-05-12 13:45:56 -07005720 if (GetQuicReloadableFlag(quic_use_idle_network_detector)) {
fayangb9c88442020-03-26 07:03:57 -07005721 EXPECT_EQ(default_timeout + five_ms,
5722 connection_.GetTimeoutAlarm()->deadline());
5723 } else {
5724 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5725 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005726
5727 // Move forward 5 ms and receive a packet, which will move the timeout
5728 // forward 5 ms more (but will not reschedule the alarm).
5729 const QuicTime receive_time = send_time + five_ms;
5730 clock_.AdvanceTime(receive_time - clock_.Now());
5731 ASSERT_EQ(receive_time, clock_.Now());
5732 ProcessPacket(1);
5733
5734 // Now move forward to the retransmission time and retransmit the
5735 // packet, which should move the timeout forward again (but will not
5736 // reschedule the alarm).
5737 EXPECT_EQ(default_retransmission_time + five_ms,
5738 connection_.GetRetransmissionAlarm()->deadline());
5739 // Simulate the retransmission alarm firing.
5740 const QuicTime rto_time = send_time + DefaultRetransmissionTime();
5741 const QuicTime final_timeout = rto_time + initial_idle_timeout;
5742 clock_.AdvanceTime(rto_time - clock_.Now());
5743 ASSERT_EQ(rto_time, clock_.Now());
5744 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _));
5745 connection_.GetRetransmissionAlarm()->Fire();
5746
5747 // Advance to the original timeout and fire the alarm. The connection should
5748 // timeout, and the alarm should be registered based on the time of the
5749 // retransmission.
5750 clock_.AdvanceTime(default_timeout - clock_.Now());
5751 ASSERT_EQ(default_timeout.ToDebuggingValue(),
5752 clock_.Now().ToDebuggingValue());
5753 EXPECT_EQ(default_timeout, clock_.Now());
fayang2205d952020-05-12 13:45:56 -07005754 if (!GetQuicReloadableFlag(quic_use_idle_network_detector)) {
fayangb9c88442020-03-26 07:03:57 -07005755 connection_.GetTimeoutAlarm()->Fire();
5756 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005757 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5758 EXPECT_TRUE(connection_.connected());
5759 ASSERT_EQ(final_timeout.ToDebuggingValue(),
5760 connection_.GetTimeoutAlarm()->deadline().ToDebuggingValue());
5761
5762 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07005763 EXPECT_CALL(visitor_,
5764 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07005765 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005766 clock_.AdvanceTime(final_timeout - clock_.Now());
5767 EXPECT_EQ(connection_.GetTimeoutAlarm()->deadline(), clock_.Now());
5768 EXPECT_EQ(final_timeout, clock_.Now());
5769 connection_.GetTimeoutAlarm()->Fire();
5770 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5771 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005772 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005773}
5774
dschinazi9a6194e2020-04-30 16:21:09 -07005775TEST_P(QuicConnectionTest, TimeoutAfterSendAfterHandshake) {
5776 // When the idle timeout fires, verify that by default we do not send any
5777 // connection close packets.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005778 EXPECT_TRUE(connection_.connected());
5779 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5780 QuicConfig config;
5781
5782 // Create a handshake message that also enables silent close.
5783 CryptoHandshakeMessage msg;
vasilvvc48c8712019-03-11 13:38:16 -07005784 std::string error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005785 QuicConfig client_config;
5786 client_config.SetInitialStreamFlowControlWindowToSend(
5787 kInitialStreamFlowControlWindowForTest);
5788 client_config.SetInitialSessionFlowControlWindowToSend(
5789 kInitialSessionFlowControlWindowForTest);
5790 client_config.SetIdleNetworkTimeout(
dschinazi027366e2020-05-01 14:31:19 -07005791 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs));
fkastenholzd3a1de92019-05-15 07:00:07 -07005792 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005793 const QuicErrorCode error =
5794 config.ProcessPeerHello(msg, CLIENT, &error_details);
bncf54082a2019-11-27 10:19:47 -08005795 EXPECT_THAT(error, IsQuicNoError());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005796
dschinazie7c38a52020-05-29 15:25:45 -07005797 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
5798 QuicConfigPeer::SetReceivedOriginalConnectionId(
5799 &config, connection_.connection_id());
5800 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
5801 &config, connection_.connection_id());
5802 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005803 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005804
5805 const QuicTime::Delta default_idle_timeout =
dschinazi027366e2020-05-01 14:31:19 -07005806 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs - 1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005807 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5808 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5809
5810 // When we send a packet, the timeout will change to 5ms +
5811 // kInitialIdleTimeoutSecs.
5812 clock_.AdvanceTime(five_ms);
5813 SendStreamDataToPeer(
5814 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5815 0, FIN, nullptr);
fayang2205d952020-05-12 13:45:56 -07005816 if (GetQuicReloadableFlag(quic_use_idle_network_detector)) {
fayangb9c88442020-03-26 07:03:57 -07005817 EXPECT_EQ(default_timeout + five_ms,
5818 connection_.GetTimeoutAlarm()->deadline());
5819 } else {
5820 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5821 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005822
5823 // Now send more data. This will not move the timeout because
5824 // no data has been received since the previous write.
5825 clock_.AdvanceTime(five_ms);
5826 SendStreamDataToPeer(
5827 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5828 3, FIN, nullptr);
fayang2205d952020-05-12 13:45:56 -07005829 if (GetQuicReloadableFlag(quic_use_idle_network_detector)) {
fayangb9c88442020-03-26 07:03:57 -07005830 EXPECT_EQ(default_timeout + five_ms,
5831 connection_.GetTimeoutAlarm()->deadline());
5832 } else {
5833 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5834 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005835
5836 // The original alarm will fire. We should not time out because we had a
5837 // network event at t=5ms. The alarm will reregister.
5838 clock_.AdvanceTime(default_idle_timeout - five_ms - five_ms);
5839 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
fayang2205d952020-05-12 13:45:56 -07005840 if (!GetQuicReloadableFlag(quic_use_idle_network_detector)) {
fayangb9c88442020-03-26 07:03:57 -07005841 connection_.GetTimeoutAlarm()->Fire();
5842 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005843 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5844 EXPECT_TRUE(connection_.connected());
5845 EXPECT_EQ(default_timeout + five_ms,
5846 connection_.GetTimeoutAlarm()->deadline());
5847
5848 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07005849 // This results in a SILENT_CLOSE, so the writer will not be invoked
5850 // and will not save the frame. Grab the frame from OnConnectionClosed
5851 // directly.
5852 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
5853 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
5854
QUICHE teama6ef0a62019-03-07 20:34:33 -05005855 clock_.AdvanceTime(five_ms);
5856 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5857 connection_.GetTimeoutAlarm()->Fire();
5858 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5859 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005860 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08005861 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
5862 IsError(QUIC_NETWORK_IDLE_TIMEOUT));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005863}
5864
5865TEST_P(QuicConnectionTest, TimeoutAfterSendSilentCloseAndTLP) {
fayang5f135052019-08-22 17:59:40 -07005866 if (connection_.PtoEnabled()) {
5867 return;
5868 }
dschinazi9a6194e2020-04-30 16:21:09 -07005869 // Same test as above, but sending TLPs causes a connection close to be sent.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005870 EXPECT_TRUE(connection_.connected());
5871 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5872 QuicConfig config;
5873
5874 // Create a handshake message that also enables silent close.
5875 CryptoHandshakeMessage msg;
vasilvvc48c8712019-03-11 13:38:16 -07005876 std::string error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005877 QuicConfig client_config;
5878 client_config.SetInitialStreamFlowControlWindowToSend(
5879 kInitialStreamFlowControlWindowForTest);
5880 client_config.SetInitialSessionFlowControlWindowToSend(
5881 kInitialSessionFlowControlWindowForTest);
5882 client_config.SetIdleNetworkTimeout(
dschinazi027366e2020-05-01 14:31:19 -07005883 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs));
fkastenholzd3a1de92019-05-15 07:00:07 -07005884 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005885 const QuicErrorCode error =
5886 config.ProcessPeerHello(msg, CLIENT, &error_details);
bncf54082a2019-11-27 10:19:47 -08005887 EXPECT_THAT(error, IsQuicNoError());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005888
5889 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005890
5891 const QuicTime::Delta default_idle_timeout =
dschinazi027366e2020-05-01 14:31:19 -07005892 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs - 1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005893 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5894 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5895
5896 // When we send a packet, the timeout will change to 5ms +
5897 // kInitialIdleTimeoutSecs.
5898 clock_.AdvanceTime(five_ms);
5899 SendStreamDataToPeer(
5900 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5901 0, FIN, nullptr);
fayang2205d952020-05-12 13:45:56 -07005902 if (GetQuicReloadableFlag(quic_use_idle_network_detector)) {
fayangb9c88442020-03-26 07:03:57 -07005903 EXPECT_EQ(default_timeout + five_ms,
5904 connection_.GetTimeoutAlarm()->deadline());
5905 } else {
5906 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5907 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005908
5909 // Retransmit the packet via tail loss probe.
5910 clock_.AdvanceTime(connection_.GetRetransmissionAlarm()->deadline() -
5911 clock_.Now());
5912 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _));
5913 connection_.GetRetransmissionAlarm()->Fire();
5914
5915 // This time, we should time out and send a connection close due to the TLP.
fkastenholz5d880a92019-06-21 09:01:56 -07005916 EXPECT_CALL(visitor_,
5917 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07005918 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005919 clock_.AdvanceTime(connection_.GetTimeoutAlarm()->deadline() -
5920 clock_.ApproximateNow() + five_ms);
5921 connection_.GetTimeoutAlarm()->Fire();
5922 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5923 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005924 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005925}
5926
5927TEST_P(QuicConnectionTest, TimeoutAfterSendSilentCloseWithOpenStreams) {
dschinazi9a6194e2020-04-30 16:21:09 -07005928 // Same test as above, but having open streams causes a connection close
5929 // to be sent.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005930 EXPECT_TRUE(connection_.connected());
5931 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5932 QuicConfig config;
5933
5934 // Create a handshake message that also enables silent close.
5935 CryptoHandshakeMessage msg;
vasilvvc48c8712019-03-11 13:38:16 -07005936 std::string error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005937 QuicConfig client_config;
5938 client_config.SetInitialStreamFlowControlWindowToSend(
5939 kInitialStreamFlowControlWindowForTest);
5940 client_config.SetInitialSessionFlowControlWindowToSend(
5941 kInitialSessionFlowControlWindowForTest);
5942 client_config.SetIdleNetworkTimeout(
dschinazi027366e2020-05-01 14:31:19 -07005943 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs));
fkastenholzd3a1de92019-05-15 07:00:07 -07005944 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005945 const QuicErrorCode error =
5946 config.ProcessPeerHello(msg, CLIENT, &error_details);
bncf54082a2019-11-27 10:19:47 -08005947 EXPECT_THAT(error, IsQuicNoError());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005948
dschinazie7c38a52020-05-29 15:25:45 -07005949 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
5950 QuicConfigPeer::SetReceivedOriginalConnectionId(
5951 &config, connection_.connection_id());
5952 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
5953 &config, connection_.connection_id());
5954 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005955 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005956
5957 const QuicTime::Delta default_idle_timeout =
dschinazi027366e2020-05-01 14:31:19 -07005958 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs - 1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005959 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5960 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5961
5962 // When we send a packet, the timeout will change to 5ms +
5963 // kInitialIdleTimeoutSecs.
5964 clock_.AdvanceTime(five_ms);
5965 SendStreamDataToPeer(
5966 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5967 0, FIN, nullptr);
fayang2205d952020-05-12 13:45:56 -07005968 if (GetQuicReloadableFlag(quic_use_idle_network_detector)) {
fayangb9c88442020-03-26 07:03:57 -07005969 EXPECT_EQ(default_timeout + five_ms,
5970 connection_.GetTimeoutAlarm()->deadline());
5971 } else {
5972 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5973 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005974
5975 // Indicate streams are still open.
5976 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
5977 .WillRepeatedly(Return(true));
5978
5979 // This time, we should time out and send a connection close due to the TLP.
fkastenholz5d880a92019-06-21 09:01:56 -07005980 EXPECT_CALL(visitor_,
5981 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07005982 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005983 clock_.AdvanceTime(connection_.GetTimeoutAlarm()->deadline() -
5984 clock_.ApproximateNow() + five_ms);
5985 connection_.GetTimeoutAlarm()->Fire();
5986 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5987 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005988 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005989}
5990
5991TEST_P(QuicConnectionTest, TimeoutAfterReceive) {
5992 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5993 EXPECT_TRUE(connection_.connected());
5994 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5995 QuicConfig config;
5996 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005997
5998 const QuicTime::Delta initial_idle_timeout =
5999 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
6000 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
6001 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
6002
6003 connection_.SendStreamDataWithString(
6004 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6005 0, NO_FIN);
6006 connection_.SendStreamDataWithString(
6007 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6008 3, NO_FIN);
6009
6010 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
6011 clock_.AdvanceTime(five_ms);
6012
6013 // When we receive a packet, the timeout will change to 5ms +
6014 // kInitialIdleTimeoutSecs.
6015 QuicAckFrame ack = InitAckFrame(2);
6016 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
6017 ProcessAckPacket(&ack);
6018
6019 // The original alarm will fire. We should not time out because we had a
6020 // network event at t=5ms. The alarm will reregister.
6021 clock_.AdvanceTime(initial_idle_timeout - five_ms);
6022 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
fayang2205d952020-05-12 13:45:56 -07006023 if (!GetQuicReloadableFlag(quic_use_idle_network_detector)) {
fayangb9c88442020-03-26 07:03:57 -07006024 connection_.GetTimeoutAlarm()->Fire();
6025 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006026 EXPECT_TRUE(connection_.connected());
6027 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
6028 EXPECT_EQ(default_timeout + five_ms,
6029 connection_.GetTimeoutAlarm()->deadline());
6030
6031 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07006032 EXPECT_CALL(visitor_,
6033 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07006034 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006035 clock_.AdvanceTime(five_ms);
6036 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
6037 connection_.GetTimeoutAlarm()->Fire();
6038 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
6039 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07006040 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006041}
6042
6043TEST_P(QuicConnectionTest, TimeoutAfterReceiveNotSendWhenUnacked) {
6044 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6045 EXPECT_TRUE(connection_.connected());
6046 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6047 QuicConfig config;
6048 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006049
6050 const QuicTime::Delta initial_idle_timeout =
6051 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
6052 connection_.SetNetworkTimeouts(
6053 QuicTime::Delta::Infinite(),
6054 initial_idle_timeout + QuicTime::Delta::FromSeconds(1));
6055 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
6056 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
6057
6058 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
6059 connection_.SendStreamDataWithString(
6060 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6061 0, NO_FIN);
6062 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
6063 connection_.SendStreamDataWithString(
6064 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6065 3, NO_FIN);
6066
6067 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
6068
6069 clock_.AdvanceTime(five_ms);
6070
6071 // When we receive a packet, the timeout will change to 5ms +
6072 // kInitialIdleTimeoutSecs.
6073 QuicAckFrame ack = InitAckFrame(2);
6074 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
6075 ProcessAckPacket(&ack);
6076
6077 // The original alarm will fire. We should not time out because we had a
6078 // network event at t=5ms. The alarm will reregister.
6079 clock_.AdvanceTime(initial_idle_timeout - five_ms);
6080 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
fayang2205d952020-05-12 13:45:56 -07006081 if (!GetQuicReloadableFlag(quic_use_idle_network_detector)) {
fayangb9c88442020-03-26 07:03:57 -07006082 connection_.GetTimeoutAlarm()->Fire();
6083 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006084 EXPECT_TRUE(connection_.connected());
6085 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
6086 EXPECT_EQ(default_timeout + five_ms,
6087 connection_.GetTimeoutAlarm()->deadline());
6088
6089 // Now, send packets while advancing the time and verify that the connection
6090 // eventually times out.
fkastenholz5d880a92019-06-21 09:01:56 -07006091 EXPECT_CALL(visitor_,
6092 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006093 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
6094 for (int i = 0; i < 100 && connection_.connected(); ++i) {
6095 QUIC_LOG(INFO) << "sending data packet";
6096 connection_.SendStreamDataWithString(
6097 GetNthClientInitiatedStreamId(1, connection_.transport_version()),
6098 "foo", 0, NO_FIN);
6099 connection_.GetTimeoutAlarm()->Fire();
6100 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
6101 }
6102 EXPECT_FALSE(connection_.connected());
6103 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07006104 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006105}
6106
6107TEST_P(QuicConnectionTest, TimeoutAfter5ClientRTOs) {
fayang5f135052019-08-22 17:59:40 -07006108 if (connection_.PtoEnabled()) {
6109 return;
6110 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006111 connection_.SetMaxTailLossProbes(2);
6112 EXPECT_TRUE(connection_.connected());
6113 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6114 QuicConfig config;
6115 QuicTagVector connection_options;
6116 connection_options.push_back(k5RTO);
6117 config.SetConnectionOptionsToSend(connection_options);
dschinazif7c6a912020-05-05 11:39:53 -07006118 QuicConfigPeer::SetNegotiated(&config, true);
fayang656cbb52020-06-09 13:29:35 -07006119 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangf78b6932020-06-08 08:36:45 -07006120 EXPECT_CALL(visitor_, GetHandshakeState())
6121 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
6122 }
dschinazie7c38a52020-05-29 15:25:45 -07006123 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
6124 QuicConfigPeer::SetReceivedOriginalConnectionId(
6125 &config, connection_.connection_id());
6126 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
6127 &config, connection_.connection_id());
6128 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006129 connection_.SetFromConfig(config);
6130
6131 // Send stream data.
6132 SendStreamDataToPeer(
6133 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6134 0, FIN, nullptr);
6135
6136 // Fire the retransmission alarm 6 times, twice for TLP and 4 times for RTO.
6137 for (int i = 0; i < 6; ++i) {
6138 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
6139 connection_.GetRetransmissionAlarm()->Fire();
6140 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
6141 EXPECT_TRUE(connection_.connected());
6142 }
fayang2205d952020-05-12 13:45:56 -07006143 EXPECT_CALL(visitor_, OnPathDegrading());
6144 connection_.PathDegradingTimeout();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006145
6146 EXPECT_EQ(2u, connection_.sent_packet_manager().GetConsecutiveTlpCount());
6147 EXPECT_EQ(4u, connection_.sent_packet_manager().GetConsecutiveRtoCount());
6148 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07006149 EXPECT_CALL(visitor_,
6150 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07006151 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
fayang2205d952020-05-12 13:45:56 -07006152 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
6153 connection_.GetBlackholeDetectorAlarm()->Fire();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006154 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
6155 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07006156 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006157}
6158
6159TEST_P(QuicConnectionTest, SendScheduler) {
6160 // Test that if we send a packet without delay, it is not queued.
6161 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
QUICHE team8c1daa22019-03-13 08:33:41 -07006162 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07006163 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006164 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
6165 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
QUICHE team6987b4a2019-03-15 16:23:04 -07006166 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05006167 HAS_RETRANSMITTABLE_DATA, false, false);
6168 EXPECT_EQ(0u, connection_.NumQueuedPackets());
6169}
6170
6171TEST_P(QuicConnectionTest, FailToSendFirstPacket) {
6172 // Test that the connection does not crash when it fails to send the first
6173 // packet at which point self_address_ might be uninitialized.
6174 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
fkastenholz5d880a92019-06-21 09:01:56 -07006175 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
QUICHE team8c1daa22019-03-13 08:33:41 -07006176 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07006177 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006178 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
6179 writer_->SetShouldWriteFail();
QUICHE team6987b4a2019-03-15 16:23:04 -07006180 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05006181 HAS_RETRANSMITTABLE_DATA, false, false);
6182}
6183
6184TEST_P(QuicConnectionTest, SendSchedulerEAGAIN) {
6185 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
QUICHE team8c1daa22019-03-13 08:33:41 -07006186 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07006187 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006188 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
6189 BlockOnNextWrite();
6190 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _))
6191 .Times(0);
QUICHE team6987b4a2019-03-15 16:23:04 -07006192 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05006193 HAS_RETRANSMITTABLE_DATA, false, false);
6194 EXPECT_EQ(1u, connection_.NumQueuedPackets());
6195}
6196
6197TEST_P(QuicConnectionTest, TestQueueLimitsOnSendStreamData) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006198 // Queue the first packet.
ianswett3085da82019-04-04 07:24:24 -07006199 size_t payload_length = connection_.max_packet_length();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006200 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(testing::Return(false));
vasilvvc48c8712019-03-11 13:38:16 -07006201 const std::string payload(payload_length, 'a');
ianswett3085da82019-04-04 07:24:24 -07006202 QuicStreamId first_bidi_stream_id(QuicUtils::GetFirstBidirectionalStreamId(
6203 connection_.version().transport_version, Perspective::IS_CLIENT));
6204 EXPECT_EQ(0u, connection_
6205 .SendStreamDataWithString(first_bidi_stream_id, payload, 0,
6206 NO_FIN)
QUICHE teama6ef0a62019-03-07 20:34:33 -05006207 .bytes_consumed);
6208 EXPECT_EQ(0u, connection_.NumQueuedPackets());
6209}
6210
ianswett3085da82019-04-04 07:24:24 -07006211TEST_P(QuicConnectionTest, SendingThreePackets) {
ianswett3085da82019-04-04 07:24:24 -07006212 // Make the payload twice the size of the packet, so 3 packets are written.
6213 size_t total_payload_length = 2 * connection_.max_packet_length();
vasilvvc48c8712019-03-11 13:38:16 -07006214 const std::string payload(total_payload_length, 'a');
ianswett3085da82019-04-04 07:24:24 -07006215 QuicStreamId first_bidi_stream_id(QuicUtils::GetFirstBidirectionalStreamId(
6216 connection_.version().transport_version, Perspective::IS_CLIENT));
6217 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
6218 EXPECT_EQ(payload.size(), connection_
6219 .SendStreamDataWithString(first_bidi_stream_id,
6220 payload, 0, NO_FIN)
6221 .bytes_consumed);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006222}
6223
6224TEST_P(QuicConnectionTest, LoopThroughSendingPacketsWithTruncation) {
6225 set_perspective(Perspective::IS_SERVER);
fayangd4291e42019-05-30 10:31:21 -07006226 if (!VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006227 // For IETF QUIC, encryption level will be switched to FORWARD_SECURE in
6228 // SendStreamDataWithString.
6229 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
6230 }
6231 // Set up a larger payload than will fit in one packet.
vasilvvc48c8712019-03-11 13:38:16 -07006232 const std::string payload(connection_.max_packet_length(), 'a');
QUICHE teama6ef0a62019-03-07 20:34:33 -05006233 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
6234
6235 // Now send some packets with no truncation.
6236 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
6237 EXPECT_EQ(payload.size(),
6238 connection_.SendStreamDataWithString(3, payload, 0, NO_FIN)
6239 .bytes_consumed);
6240 // Track the size of the second packet here. The overhead will be the largest
6241 // we see in this test, due to the non-truncated connection id.
6242 size_t non_truncated_packet_size = writer_->last_packet_size();
6243
6244 // Change to a 0 byte connection id.
6245 QuicConfig config;
6246 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
6247 connection_.SetFromConfig(config);
6248 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
6249 EXPECT_EQ(payload.size(),
6250 connection_.SendStreamDataWithString(3, payload, 1350, NO_FIN)
6251 .bytes_consumed);
fayangd4291e42019-05-30 10:31:21 -07006252 if (VersionHasIetfInvariantHeader(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006253 // Short header packets sent from server omit connection ID already, and
6254 // stream offset size increases from 0 to 2.
6255 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() - 2);
6256 } else {
6257 // Just like above, we save 8 bytes on payload, and 8 on truncation. -2
6258 // because stream offset size is 2 instead of 0.
6259 EXPECT_EQ(non_truncated_packet_size,
6260 writer_->last_packet_size() + 8 * 2 - 2);
6261 }
6262}
6263
6264TEST_P(QuicConnectionTest, SendDelayedAck) {
6265 QuicTime ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6266 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006267 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006268 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006269 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006270 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006271 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006272 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006273 // Process a packet from the non-crypto stream.
6274 frame1_.stream_id = 3;
6275
6276 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006277 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006278 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6279 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6280
6281 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006282 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006283 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6284 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07006285 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006286 connection_.GetAckAlarm()->Fire();
6287 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006288 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006289 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006290 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006291 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6292 } else {
nharper55fa6132019-05-07 19:37:21 -07006293 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006294 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6295 }
6296 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006297 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006298}
6299
6300TEST_P(QuicConnectionTest, SendDelayedAfterQuiescence) {
6301 QuicConnectionPeer::SetFastAckAfterQuiescence(&connection_, true);
6302
6303 // The beginning of the connection counts as quiescence.
ianswett8f90e512019-12-18 10:50:27 -08006304 QuicTime ack_time = clock_.ApproximateNow() + kAlarmGranularity;
QUICHE teama6ef0a62019-03-07 20:34:33 -05006305 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006306 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006307 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006308 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006309 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006310 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006311 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006312 // Process a packet from the non-crypto stream.
6313 frame1_.stream_id = 3;
6314
6315 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006316 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006317 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6318 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6319
6320 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006321 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006322 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6323 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07006324 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006325 connection_.GetAckAlarm()->Fire();
6326 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006327 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006328 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006329 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006330 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6331 } else {
nharper55fa6132019-05-07 19:37:21 -07006332 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006333 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6334 }
6335 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006336 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006337
6338 // Process another packet immedately after sending the ack and expect the
6339 // ack alarm to be set delayed ack time in the future.
6340 ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6341 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6342 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6343
6344 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006345 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006346 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6347 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07006348 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006349 connection_.GetAckAlarm()->Fire();
6350 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006351 padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006352 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006353 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006354 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6355 } else {
nharper55fa6132019-05-07 19:37:21 -07006356 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006357 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6358 }
6359 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006360 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006361
ianswett8f90e512019-12-18 10:50:27 -08006362 // Wait 1 second and ensure the ack alarm is set to 1ms in the future.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006363 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
6364 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
6365 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6366 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6367
6368 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006369 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006370 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6371}
6372
6373TEST_P(QuicConnectionTest, SendDelayedAckDecimation) {
6374 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6375 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION);
6376
6377 const size_t kMinRttMs = 40;
6378 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6379 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6380 QuicTime::Delta::Zero(), QuicTime::Zero());
6381 // The ack time should be based on min_rtt/4, since it's less than the
6382 // default delayed ack time.
6383 QuicTime ack_time = clock_.ApproximateNow() +
6384 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6385 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006386 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006387 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006388 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006389 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006390 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006391 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006392 // Process a packet from the non-crypto stream.
6393 frame1_.stream_id = 3;
6394
6395 // Process all the initial packets in order so there aren't missing packets.
6396 uint64_t kFirstDecimatedPacket = 101;
6397 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6398 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6399 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6400 }
fayang9adfb532020-06-04 06:58:45 -07006401 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006402 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006403 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006404 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6405 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6406 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
6412 // The 10th received packet causes an ack to be sent.
6413 for (int i = 0; i < 9; ++i) {
fayang9adfb532020-06-04 06:58:45 -07006414 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006415 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6416 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6417 ENCRYPTION_ZERO_RTT);
6418 }
6419 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07006420 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006421 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07006422 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006423 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6424 } else {
nharperc32d8ab2019-10-09 11:09:06 -07006425 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006426 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6427 }
6428 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006429 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006430}
6431
6432TEST_P(QuicConnectionTest, SendDelayedAckAckDecimationAfterQuiescence) {
6433 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6434 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION);
6435 QuicConnectionPeer::SetFastAckAfterQuiescence(&connection_, true);
6436
6437 const size_t kMinRttMs = 40;
6438 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6439 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6440 QuicTime::Delta::Zero(), QuicTime::Zero());
6441
6442 // The beginning of the connection counts as quiescence.
6443 QuicTime ack_time =
6444 clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
6445 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006446 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006447 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006448 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006449 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006450 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006451 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006452 // Process a packet from the non-crypto stream.
6453 frame1_.stream_id = 3;
6454
6455 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006456 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006457 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6458 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6459
6460 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006461 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006462 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6463 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07006464 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006465 connection_.GetAckAlarm()->Fire();
6466 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006467 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006468 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006469 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006470 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6471 } else {
nharper55fa6132019-05-07 19:37:21 -07006472 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006473 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6474 }
6475 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006476 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006477
6478 // Process another packet immedately after sending the ack and expect the
6479 // ack alarm to be set delayed ack time in the future.
6480 ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6481 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6482 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6483
6484 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006485 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006486 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6487 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07006488 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006489 connection_.GetAckAlarm()->Fire();
6490 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006491 padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006492 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006493 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006494 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6495 } else {
nharper55fa6132019-05-07 19:37:21 -07006496 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006497 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6498 }
6499 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006500 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006501
6502 // Wait 1 second and enesure the ack alarm is set to 1ms in the future.
6503 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
6504 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
6505 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6506 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6507
6508 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006509 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006510 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6511
6512 // Process enough packets to get into ack decimation behavior.
6513 // The ack time should be based on min_rtt/4, since it's less than the
6514 // default delayed ack time.
6515 ack_time = clock_.ApproximateNow() +
6516 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6517 uint64_t kFirstDecimatedPacket = 101;
6518 for (unsigned int i = 0; i < kFirstDecimatedPacket - 4; ++i) {
6519 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6520 ProcessDataPacketAtLevel(4 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6521 }
fayang9adfb532020-06-04 06:58:45 -07006522 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006523 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006524 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006525 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6526 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6527 ENCRYPTION_ZERO_RTT);
6528
6529 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006530 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006531 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6532
6533 // The 10th received packet causes an ack to be sent.
6534 for (int i = 0; i < 9; ++i) {
fayang9adfb532020-06-04 06:58:45 -07006535 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006536 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6537 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6538 ENCRYPTION_ZERO_RTT);
6539 }
6540 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07006541 padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006542 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07006543 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006544 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6545 } else {
nharperc32d8ab2019-10-09 11:09:06 -07006546 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006547 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6548 }
6549 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006550 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006551
6552 // Wait 1 second and enesure the ack alarm is set to 1ms in the future.
6553 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
6554 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
6555 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6556 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 10, !kHasStopWaiting,
6557 ENCRYPTION_ZERO_RTT);
6558
6559 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006560 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006561 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6562}
6563
6564TEST_P(QuicConnectionTest, SendDelayedAckDecimationUnlimitedAggregation) {
6565 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6566 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6567 QuicConfig config;
6568 QuicTagVector connection_options;
6569 connection_options.push_back(kACKD);
6570 // No limit on the number of packets received before sending an ack.
6571 connection_options.push_back(kAKDU);
6572 config.SetConnectionOptionsToSend(connection_options);
6573 connection_.SetFromConfig(config);
6574
6575 const size_t kMinRttMs = 40;
6576 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6577 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6578 QuicTime::Delta::Zero(), QuicTime::Zero());
6579 // The ack time should be based on min_rtt/4, since it's less than the
6580 // default delayed ack time.
6581 QuicTime ack_time = clock_.ApproximateNow() +
6582 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6583 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006584 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006585 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006586 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006587 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006588 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006589 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006590 // Process a packet from the non-crypto stream.
6591 frame1_.stream_id = 3;
6592
6593 // Process all the initial packets in order so there aren't missing packets.
6594 uint64_t kFirstDecimatedPacket = 101;
6595 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6596 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6597 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6598 }
fayang9adfb532020-06-04 06:58:45 -07006599 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006600 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006601 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006602 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6603 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6604 ENCRYPTION_ZERO_RTT);
6605
6606 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006607 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006608 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6609
6610 // 18 packets will not cause an ack to be sent. 19 will because when
6611 // stop waiting frames are in use, we ack every 20 packets no matter what.
6612 for (int i = 0; i < 18; ++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 // The delayed ack timer should still be set to the expected deadline.
fayang9adfb532020-06-04 06:58:45 -07006619 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006620 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6621}
6622
6623TEST_P(QuicConnectionTest, SendDelayedAckDecimationEighthRtt) {
6624 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6625 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION);
6626 QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
6627
6628 const size_t kMinRttMs = 40;
6629 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6630 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6631 QuicTime::Delta::Zero(), QuicTime::Zero());
6632 // The ack time should be based on min_rtt/8, since it's less than the
6633 // default delayed ack time.
6634 QuicTime ack_time = clock_.ApproximateNow() +
6635 QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
6636 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006637 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006638 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006639 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006640 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006641 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006642 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006643 // Process a packet from the non-crypto stream.
6644 frame1_.stream_id = 3;
6645
6646 // Process all the initial packets in order so there aren't missing packets.
6647 uint64_t kFirstDecimatedPacket = 101;
6648 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6649 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6650 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6651 }
fayang9adfb532020-06-04 06:58:45 -07006652 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006653 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006654 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006655 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6656 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6657 ENCRYPTION_ZERO_RTT);
6658
6659 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006660 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006661 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6662
6663 // The 10th received packet causes an ack to be sent.
6664 for (int i = 0; i < 9; ++i) {
fayang9adfb532020-06-04 06:58:45 -07006665 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006666 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6667 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6668 ENCRYPTION_ZERO_RTT);
6669 }
6670 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07006671 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006672 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07006673 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006674 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6675 } else {
nharperc32d8ab2019-10-09 11:09:06 -07006676 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006677 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6678 }
6679 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006680 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006681}
6682
6683TEST_P(QuicConnectionTest, SendDelayedAckDecimationWithReordering) {
6684 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6685 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6686
6687 const size_t kMinRttMs = 40;
6688 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6689 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6690 QuicTime::Delta::Zero(), QuicTime::Zero());
6691 // The ack time should be based on min_rtt/4, since it's less than the
6692 // default delayed ack time.
6693 QuicTime ack_time = clock_.ApproximateNow() +
6694 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6695 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006696 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006697 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006698 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006699 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006700 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006701 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006702 // Process a packet from the non-crypto stream.
6703 frame1_.stream_id = 3;
6704
6705 // Process all the initial packets in order so there aren't missing packets.
6706 uint64_t kFirstDecimatedPacket = 101;
6707 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6708 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6709 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6710 }
fayang9adfb532020-06-04 06:58:45 -07006711 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006712
6713 // Receive one packet out of order and then the rest in order.
6714 // The loop leaves a one packet gap between acks sent to simulate some loss.
6715 for (int j = 0; j < 3; ++j) {
6716 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6717 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6718 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 9 + (j * 11),
6719 !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6720 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
fayang9adfb532020-06-04 06:58:45 -07006721 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006722 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6723
6724 // The 10th received packet causes an ack to be sent.
6725 writer_->Reset();
6726 for (int i = 0; i < 9; ++i) {
fayang9adfb532020-06-04 06:58:45 -07006727 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006728 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6729 // The ACK shouldn't be sent until the 10th packet is processed.
6730 EXPECT_TRUE(writer_->ack_frames().empty());
6731 ProcessDataPacketAtLevel(kFirstDecimatedPacket + i + (j * 11),
6732 !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6733 }
6734 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07006735 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006736 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07006737 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006738 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6739 } else {
nharperc32d8ab2019-10-09 11:09:06 -07006740 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006741 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6742 }
6743 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006744 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006745 }
6746}
6747
6748TEST_P(QuicConnectionTest, SendDelayedAckDecimationWithLargeReordering) {
6749 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6750 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6751
6752 const size_t kMinRttMs = 40;
6753 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6754 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6755 QuicTime::Delta::Zero(), QuicTime::Zero());
6756 // The ack time should be based on min_rtt/4, since it's less than the
6757 // default delayed ack time.
6758 QuicTime ack_time = clock_.ApproximateNow() +
6759 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6760 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006761 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006762 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006763 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006764 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006765 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006766 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006767 // Process a packet from the non-crypto stream.
6768 frame1_.stream_id = 3;
6769
6770 // Process all the initial packets in order so there aren't missing packets.
6771 uint64_t kFirstDecimatedPacket = 101;
6772 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6773 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6774 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6775 }
fayang9adfb532020-06-04 06:58:45 -07006776 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006777 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006778 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006779 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6780 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6781 ENCRYPTION_ZERO_RTT);
6782
6783 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006784 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006785 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6786
6787 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6788 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6789 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 19, !kHasStopWaiting,
6790 ENCRYPTION_ZERO_RTT);
6791 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
fayang9adfb532020-06-04 06:58:45 -07006792 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006793 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6794
6795 // The 10th received packet causes an ack to be sent.
6796 for (int i = 0; i < 8; ++i) {
fayang9adfb532020-06-04 06:58:45 -07006797 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006798 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6799 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6800 ENCRYPTION_ZERO_RTT);
6801 }
6802 // Check that ack is sent and that delayed ack alarm is reset.
6803 if (GetParam().no_stop_waiting) {
fayang58f71072019-11-05 08:47:02 -08006804 EXPECT_EQ(writer_->padding_frames().size() + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006805 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6806 } else {
6807 EXPECT_EQ(2u, writer_->frame_count());
6808 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6809 }
6810 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006811 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006812
6813 // The next packet received in order will cause an immediate ack,
6814 // because it fills a hole.
fayang9adfb532020-06-04 06:58:45 -07006815 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006816 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6817 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 10, !kHasStopWaiting,
6818 ENCRYPTION_ZERO_RTT);
6819 // Check that ack is sent and that delayed ack alarm is reset.
6820 if (GetParam().no_stop_waiting) {
fayang58f71072019-11-05 08:47:02 -08006821 EXPECT_EQ(writer_->padding_frames().size() + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006822 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6823 } else {
6824 EXPECT_EQ(2u, writer_->frame_count());
6825 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6826 }
6827 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006828 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006829}
6830
6831TEST_P(QuicConnectionTest, SendDelayedAckDecimationWithReorderingEighthRtt) {
6832 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6833 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6834 QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
6835
6836 const size_t kMinRttMs = 40;
6837 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6838 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6839 QuicTime::Delta::Zero(), QuicTime::Zero());
6840 // The ack time should be based on min_rtt/8, since it's less than the
6841 // default delayed ack time.
6842 QuicTime ack_time = clock_.ApproximateNow() +
6843 QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
6844 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006845 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006846 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006847 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006848 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006849 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006850 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006851 // Process a packet from the non-crypto stream.
6852 frame1_.stream_id = 3;
6853
6854 // Process all the initial packets in order so there aren't missing packets.
6855 uint64_t kFirstDecimatedPacket = 101;
6856 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6857 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6858 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6859 }
fayang9adfb532020-06-04 06:58:45 -07006860 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006861 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006862 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006863 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6864 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6865 ENCRYPTION_ZERO_RTT);
6866
6867 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006868 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006869 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6870
6871 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6872 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6873 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 9, !kHasStopWaiting,
6874 ENCRYPTION_ZERO_RTT);
6875 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
fayang9adfb532020-06-04 06:58:45 -07006876 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006877 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6878
6879 // The 10th received packet causes an ack to be sent.
6880 for (int i = 0; i < 8; ++i) {
fayang9adfb532020-06-04 06:58:45 -07006881 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006882 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6883 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6884 ENCRYPTION_ZERO_RTT);
6885 }
6886 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07006887 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006888 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07006889 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006890 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6891 } else {
nharperc32d8ab2019-10-09 11:09:06 -07006892 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006893 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6894 }
6895 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006896 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006897}
6898
6899TEST_P(QuicConnectionTest,
6900 SendDelayedAckDecimationWithLargeReorderingEighthRtt) {
6901 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6902 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6903 QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
6904
6905 const size_t kMinRttMs = 40;
6906 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6907 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6908 QuicTime::Delta::Zero(), QuicTime::Zero());
6909 // The ack time should be based on min_rtt/8, since it's less than the
6910 // default delayed ack time.
6911 QuicTime ack_time = clock_.ApproximateNow() +
6912 QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
6913 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006914 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006915 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006916 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006917 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006918 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006919 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006920 // Process a packet from the non-crypto stream.
6921 frame1_.stream_id = 3;
6922
6923 // Process all the initial packets in order so there aren't missing packets.
6924 uint64_t kFirstDecimatedPacket = 101;
6925 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6926 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6927 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6928 }
fayang9adfb532020-06-04 06:58:45 -07006929 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006930 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006931 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006932 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6933 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6934 ENCRYPTION_ZERO_RTT);
6935
6936 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006937 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006938 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6939
6940 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6941 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6942 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 19, !kHasStopWaiting,
6943 ENCRYPTION_ZERO_RTT);
6944 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
fayang9adfb532020-06-04 06:58:45 -07006945 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006946 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6947
6948 // The 10th received packet causes an ack to be sent.
6949 for (int i = 0; i < 8; ++i) {
fayang9adfb532020-06-04 06:58:45 -07006950 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006951 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6952 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6953 ENCRYPTION_ZERO_RTT);
6954 }
6955 // Check that ack is sent and that delayed ack alarm is reset.
6956 if (GetParam().no_stop_waiting) {
fayang58f71072019-11-05 08:47:02 -08006957 EXPECT_EQ(writer_->padding_frames().size() + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006958 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6959 } else {
6960 EXPECT_EQ(2u, writer_->frame_count());
6961 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6962 }
6963 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006964 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006965
6966 // The next packet received in order will cause an immediate ack,
6967 // because it fills a hole.
fayang9adfb532020-06-04 06:58:45 -07006968 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006969 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6970 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 10, !kHasStopWaiting,
6971 ENCRYPTION_ZERO_RTT);
6972 // Check that ack is sent and that delayed ack alarm is reset.
6973 if (GetParam().no_stop_waiting) {
fayang58f71072019-11-05 08:47:02 -08006974 EXPECT_EQ(writer_->padding_frames().size() + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006975 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6976 } else {
6977 EXPECT_EQ(2u, writer_->frame_count());
6978 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6979 }
6980 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006981 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006982}
6983
6984TEST_P(QuicConnectionTest, SendDelayedAckOnHandshakeConfirmed) {
6985 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6986 ProcessPacket(1);
6987 // Check that ack is sent and that delayed ack alarm is set.
fayang9adfb532020-06-04 06:58:45 -07006988 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006989 QuicTime ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6990 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6991
6992 // Completing the handshake as the server does nothing.
6993 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_SERVER);
6994 connection_.OnHandshakeComplete();
fayang9adfb532020-06-04 06:58:45 -07006995 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006996 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6997
6998 // Complete the handshake as the client decreases the delayed ack time to 0ms.
6999 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_CLIENT);
7000 connection_.OnHandshakeComplete();
fayang9adfb532020-06-04 06:58:45 -07007001 EXPECT_TRUE(connection_.HasPendingAcks());
fayangb296fb82020-02-11 08:14:28 -08007002 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7003 EXPECT_EQ(clock_.ApproximateNow() + DefaultDelayedAckTime(),
7004 connection_.GetAckAlarm()->deadline());
7005 } else {
7006 EXPECT_EQ(clock_.ApproximateNow(), connection_.GetAckAlarm()->deadline());
7007 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007008}
7009
7010TEST_P(QuicConnectionTest, SendDelayedAckOnSecondPacket) {
7011 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7012 ProcessPacket(1);
7013 ProcessPacket(2);
7014 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07007015 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05007016 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07007017 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007018 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
7019 } else {
nharper55fa6132019-05-07 19:37:21 -07007020 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007021 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
7022 }
7023 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07007024 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007025}
7026
7027TEST_P(QuicConnectionTest, NoAckOnOldNacks) {
7028 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang6dba4902019-06-17 10:04:23 -07007029 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007030 ProcessPacket(2);
7031 size_t frames_per_ack = GetParam().no_stop_waiting ? 1 : 2;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007032
7033 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7034 ProcessPacket(3);
nharper55fa6132019-05-07 19:37:21 -07007035 size_t padding_frame_count = writer_->padding_frames().size();
7036 EXPECT_EQ(padding_frame_count + frames_per_ack, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007037 EXPECT_FALSE(writer_->ack_frames().empty());
7038 writer_->Reset();
7039
fayang6dba4902019-06-17 10:04:23 -07007040 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007041 ProcessPacket(4);
fayang6dba4902019-06-17 10:04:23 -07007042 EXPECT_EQ(0u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007043
7044 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7045 ProcessPacket(5);
nharper55fa6132019-05-07 19:37:21 -07007046 padding_frame_count = writer_->padding_frames().size();
7047 EXPECT_EQ(padding_frame_count + frames_per_ack, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007048 EXPECT_FALSE(writer_->ack_frames().empty());
7049 writer_->Reset();
7050
7051 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
7052 // Now only set the timer on the 6th packet, instead of sending another ack.
7053 ProcessPacket(6);
nharper55fa6132019-05-07 19:37:21 -07007054 padding_frame_count = writer_->padding_frames().size();
7055 EXPECT_EQ(padding_frame_count, writer_->frame_count());
fayang9adfb532020-06-04 06:58:45 -07007056 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007057}
7058
7059TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingPacket) {
7060 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
QUICHE team8c1daa22019-03-13 08:33:41 -07007061 EXPECT_CALL(visitor_, OnStreamFrame(_));
7062 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07007063 std::make_unique<TaggingEncrypter>(0x01));
zhongyi546cc452019-04-12 15:27:49 -07007064 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07007065 std::make_unique<StrictTaggingDecrypter>(0x01));
nharper2c9f02a2019-05-08 10:25:50 -07007066 ProcessDataPacket(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007067 connection_.SendStreamDataWithString(
7068 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
7069 0, NO_FIN);
7070 // Check that ack is bundled with outgoing data and that delayed ack
7071 // alarm is reset.
7072 if (GetParam().no_stop_waiting) {
7073 EXPECT_EQ(2u, writer_->frame_count());
7074 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
7075 } else {
7076 EXPECT_EQ(3u, writer_->frame_count());
7077 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
7078 }
7079 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07007080 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007081}
7082
7083TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingCryptoPacket) {
7084 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
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(1, ENCRYPTION_INITIAL);
nharper46833c32019-05-15 21:33:05 -07007091 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007092 // Check that ack is bundled with outgoing crypto data.
7093 if (GetParam().no_stop_waiting) {
7094 EXPECT_EQ(3u, writer_->frame_count());
7095 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
7096 } else {
7097 EXPECT_EQ(4u, writer_->frame_count());
7098 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
7099 }
fayang9adfb532020-06-04 06:58:45 -07007100 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007101}
7102
7103TEST_P(QuicConnectionTest, BlockAndBufferOnFirstCHLOPacketOfTwo) {
7104 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7105 ProcessPacket(1);
7106 BlockOnNextWrite();
7107 writer_->set_is_write_blocked_data_buffered(true);
fayang6a258412020-05-28 08:57:12 -07007108 if (GetQuicReloadableFlag(quic_move_amplification_limit) &&
7109 QuicVersionUsesCryptoFrames(connection_.transport_version())) {
7110 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7111 } else {
7112 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
7113 }
nharper46833c32019-05-15 21:33:05 -07007114 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007115 EXPECT_TRUE(writer_->IsWriteBlocked());
7116 EXPECT_FALSE(connection_.HasQueuedData());
nharper46833c32019-05-15 21:33:05 -07007117 connection_.SendCryptoDataWithString("bar", 3);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007118 EXPECT_TRUE(writer_->IsWriteBlocked());
fayang6a258412020-05-28 08:57:12 -07007119 if (GetQuicReloadableFlag(quic_move_amplification_limit) &&
7120 QuicVersionUsesCryptoFrames(connection_.transport_version())) {
7121 // CRYPTO frames are not flushed when writer is blocked.
7122 EXPECT_FALSE(connection_.HasQueuedData());
7123 } else {
7124 EXPECT_TRUE(connection_.HasQueuedData());
7125 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007126}
7127
7128TEST_P(QuicConnectionTest, BundleAckForSecondCHLO) {
7129 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07007130 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007131 EXPECT_CALL(visitor_, OnCanWrite())
7132 .WillOnce(IgnoreResult(InvokeWithoutArgs(
7133 &connection_, &TestConnection::SendCryptoStreamData)));
7134 // Process a packet from the crypto stream, which is frame1_'s default.
7135 // Receiving the CHLO as packet 2 first will cause the connection to
7136 // immediately send an ack, due to the packet gap.
fayangc31c9952019-06-05 13:54:48 -07007137 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
7138 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
7139 } else {
7140 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7141 }
7142 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007143 // Check that ack is sent and that delayed ack alarm is reset.
7144 if (GetParam().no_stop_waiting) {
7145 EXPECT_EQ(3u, writer_->frame_count());
7146 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
7147 } else {
7148 EXPECT_EQ(4u, writer_->frame_count());
7149 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
7150 }
QUICHE teamea740082019-03-11 17:58:43 -07007151 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007152 EXPECT_EQ(1u, writer_->stream_frames().size());
7153 } else {
7154 EXPECT_EQ(1u, writer_->crypto_frames().size());
7155 }
7156 EXPECT_EQ(1u, writer_->padding_frames().size());
7157 ASSERT_FALSE(writer_->ack_frames().empty());
7158 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(writer_->ack_frames().front()));
fayang9adfb532020-06-04 06:58:45 -07007159 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007160}
7161
7162TEST_P(QuicConnectionTest, BundleAckForSecondCHLOTwoPacketReject) {
7163 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07007164 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007165
7166 // Process two packets from the crypto stream, which is frame1_'s default,
7167 // simulating a 2 packet reject.
7168 {
fayangc31c9952019-06-05 13:54:48 -07007169 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
7170 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
7171 } else {
7172 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7173 }
7174 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007175 // Send the new CHLO when the REJ is processed.
fayangc31c9952019-06-05 13:54:48 -07007176 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
7177 EXPECT_CALL(visitor_, OnCryptoFrame(_))
7178 .WillOnce(IgnoreResult(InvokeWithoutArgs(
7179 &connection_, &TestConnection::SendCryptoStreamData)));
7180 } else {
7181 EXPECT_CALL(visitor_, OnStreamFrame(_))
7182 .WillOnce(IgnoreResult(InvokeWithoutArgs(
7183 &connection_, &TestConnection::SendCryptoStreamData)));
7184 }
7185 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007186 }
7187 // Check that ack is sent and that delayed ack alarm is reset.
7188 if (GetParam().no_stop_waiting) {
7189 EXPECT_EQ(3u, writer_->frame_count());
7190 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
7191 } else {
7192 EXPECT_EQ(4u, writer_->frame_count());
7193 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
7194 }
QUICHE teamea740082019-03-11 17:58:43 -07007195 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007196 EXPECT_EQ(1u, writer_->stream_frames().size());
7197 } else {
7198 EXPECT_EQ(1u, writer_->crypto_frames().size());
7199 }
7200 EXPECT_EQ(1u, writer_->padding_frames().size());
7201 ASSERT_FALSE(writer_->ack_frames().empty());
7202 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(writer_->ack_frames().front()));
fayang9adfb532020-06-04 06:58:45 -07007203 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007204}
7205
7206TEST_P(QuicConnectionTest, BundleAckWithDataOnIncomingAck) {
7207 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7208 connection_.SendStreamDataWithString(
7209 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
7210 0, NO_FIN);
7211 connection_.SendStreamDataWithString(
7212 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
7213 3, NO_FIN);
7214 // Ack the second packet, which will retransmit the first packet.
7215 QuicAckFrame ack = ConstructAckFrame(2, 1);
7216 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07007217 lost_packets.push_back(
7218 LostPacket(QuicPacketNumber(1), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007219 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07007220 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
7221 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007222 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7223 ProcessAckPacket(&ack);
nharper55fa6132019-05-07 19:37:21 -07007224 size_t padding_frame_count = writer_->padding_frames().size();
7225 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007226 EXPECT_EQ(1u, writer_->stream_frames().size());
7227 writer_->Reset();
7228
7229 // Now ack the retransmission, which will both raise the high water mark
7230 // and see if there is more data to send.
7231 ack = ConstructAckFrame(3, 1);
7232 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
7233 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7234 ProcessAckPacket(&ack);
7235
7236 // Check that no packet is sent and the ack alarm isn't set.
7237 EXPECT_EQ(0u, writer_->frame_count());
fayang9adfb532020-06-04 06:58:45 -07007238 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007239 writer_->Reset();
7240
7241 // Send the same ack, but send both data and an ack together.
7242 ack = ConstructAckFrame(3, 1);
7243 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
7244 EXPECT_CALL(visitor_, OnCanWrite())
7245 .WillOnce(IgnoreResult(InvokeWithoutArgs(
7246 &connection_, &TestConnection::EnsureWritableAndSendStreamData5)));
7247 ProcessAckPacket(&ack);
7248
7249 // Check that ack is bundled with outgoing data and the delayed ack
7250 // alarm is reset.
7251 if (GetParam().no_stop_waiting) {
fayang8a27b0f2019-11-04 11:27:40 -08007252 // Do not ACK acks.
7253 EXPECT_EQ(1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007254 } else {
7255 EXPECT_EQ(3u, writer_->frame_count());
7256 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
7257 }
fayang8a27b0f2019-11-04 11:27:40 -08007258 if (GetParam().no_stop_waiting) {
fayang03916692019-05-22 17:57:18 -07007259 EXPECT_TRUE(writer_->ack_frames().empty());
7260 } else {
7261 EXPECT_FALSE(writer_->ack_frames().empty());
7262 EXPECT_EQ(QuicPacketNumber(3u),
7263 LargestAcked(writer_->ack_frames().front()));
7264 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007265 EXPECT_EQ(1u, writer_->stream_frames().size());
fayang9adfb532020-06-04 06:58:45 -07007266 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007267}
7268
7269TEST_P(QuicConnectionTest, NoAckSentForClose) {
7270 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7271 ProcessPacket(1);
fkastenholz5d880a92019-06-21 09:01:56 -07007272 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
7273 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007274 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
7275 ProcessClosePacket(2);
fkastenholz5d880a92019-06-21 09:01:56 -07007276 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007277 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7278 IsError(QUIC_PEER_GOING_AWAY));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007279}
7280
7281TEST_P(QuicConnectionTest, SendWhenDisconnected) {
7282 EXPECT_TRUE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07007283 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7284 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007285 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
7286 ConnectionCloseBehavior::SILENT_CLOSE);
7287 EXPECT_FALSE(connection_.connected());
ianswettfc16a2b2020-05-18 16:05:49 -07007288 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
QUICHE team8c1daa22019-03-13 08:33:41 -07007289 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07007290 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007291 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
7292 .Times(0);
QUICHE team6987b4a2019-03-15 16:23:04 -07007293 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05007294 HAS_RETRANSMITTABLE_DATA, false, false);
fkastenholz5d880a92019-06-21 09:01:56 -07007295 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007296 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7297 IsError(QUIC_PEER_GOING_AWAY));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007298}
7299
7300TEST_P(QuicConnectionTest, SendConnectivityProbingWhenDisconnected) {
7301 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
fayangc31c9952019-06-05 13:54:48 -07007302 if (!IsDefaultTestConfiguration()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007303 return;
7304 }
7305
7306 EXPECT_TRUE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07007307 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7308 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007309 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
7310 ConnectionCloseBehavior::SILENT_CLOSE);
7311 EXPECT_FALSE(connection_.connected());
ianswettfc16a2b2020-05-18 16:05:49 -07007312 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007313
7314 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
7315 .Times(0);
7316
7317 EXPECT_QUIC_BUG(connection_.SendConnectivityProbingPacket(
7318 writer_.get(), connection_.peer_address()),
7319 "Not sending connectivity probing packet as connection is "
7320 "disconnected.");
fkastenholz5d880a92019-06-21 09:01:56 -07007321 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007322 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7323 IsError(QUIC_PEER_GOING_AWAY));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007324}
7325
7326TEST_P(QuicConnectionTest, WriteBlockedAfterClientSendsConnectivityProbe) {
7327 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
7328 TestPacketWriter probing_writer(version(), &clock_);
7329 // Block next write so that sending connectivity probe will encounter a
7330 // blocked write when send a connectivity probe to the peer.
7331 probing_writer.BlockOnNextWrite();
7332 // Connection will not be marked as write blocked as connectivity probe only
7333 // affects the probing_writer which is not the default.
7334 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
7335
7336 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
7337 .Times(1);
7338 connection_.SendConnectivityProbingPacket(&probing_writer,
7339 connection_.peer_address());
7340}
7341
7342TEST_P(QuicConnectionTest, WriterBlockedAfterServerSendsConnectivityProbe) {
7343 set_perspective(Perspective::IS_SERVER);
7344 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
7345
7346 // Block next write so that sending connectivity probe will encounter a
7347 // blocked write when send a connectivity probe to the peer.
7348 writer_->BlockOnNextWrite();
7349 // Connection will be marked as write blocked as server uses the default
7350 // writer to send connectivity probes.
7351 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
7352
7353 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
7354 .Times(1);
7355 connection_.SendConnectivityProbingPacket(writer_.get(),
7356 connection_.peer_address());
7357}
7358
7359TEST_P(QuicConnectionTest, WriterErrorWhenClientSendsConnectivityProbe) {
7360 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
7361 TestPacketWriter probing_writer(version(), &clock_);
7362 probing_writer.SetShouldWriteFail();
7363
7364 // Connection should not be closed if a connectivity probe is failed to be
7365 // sent.
fkastenholz5d880a92019-06-21 09:01:56 -07007366 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007367
7368 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
7369 .Times(0);
7370 connection_.SendConnectivityProbingPacket(&probing_writer,
7371 connection_.peer_address());
7372}
7373
7374TEST_P(QuicConnectionTest, WriterErrorWhenServerSendsConnectivityProbe) {
7375 set_perspective(Perspective::IS_SERVER);
7376 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
7377
7378 writer_->SetShouldWriteFail();
7379 // Connection should not be closed if a connectivity probe is failed to be
7380 // sent.
fkastenholz5d880a92019-06-21 09:01:56 -07007381 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007382
7383 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
7384 .Times(0);
7385 connection_.SendConnectivityProbingPacket(writer_.get(),
7386 connection_.peer_address());
7387}
7388
7389TEST_P(QuicConnectionTest, PublicReset) {
fayangc31c9952019-06-05 13:54:48 -07007390 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007391 return;
7392 }
7393 QuicPublicResetPacket header;
7394 // Public reset packet in only built by server.
7395 header.connection_id = connection_id_;
7396 std::unique_ptr<QuicEncryptedPacket> packet(
7397 framer_.BuildPublicResetPacket(header));
7398 std::unique_ptr<QuicReceivedPacket> received(
7399 ConstructReceivedPacket(*packet, QuicTime::Zero()));
fkastenholz5d880a92019-06-21 09:01:56 -07007400 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
7401 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007402 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
fkastenholz5d880a92019-06-21 09:01:56 -07007403 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007404 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7405 IsError(QUIC_PUBLIC_RESET));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007406}
7407
7408TEST_P(QuicConnectionTest, IetfStatelessReset) {
fayangc31c9952019-06-05 13:54:48 -07007409 if (!VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007410 return;
7411 }
7412 const QuicUint128 kTestStatelessResetToken = 1010101;
7413 QuicConfig config;
7414 QuicConfigPeer::SetReceivedStatelessResetToken(&config,
7415 kTestStatelessResetToken);
7416 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7417 connection_.SetFromConfig(config);
7418 std::unique_ptr<QuicEncryptedPacket> packet(
7419 QuicFramer::BuildIetfStatelessResetPacket(connection_id_,
7420 kTestStatelessResetToken));
7421 std::unique_ptr<QuicReceivedPacket> received(
7422 ConstructReceivedPacket(*packet, QuicTime::Zero()));
renjietang7f483b52020-05-20 14:30:47 -07007423 EXPECT_CALL(visitor_, ValidateStatelessReset(_, _)).WillOnce(Return(true));
fkastenholz5d880a92019-06-21 09:01:56 -07007424 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
7425 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007426 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
fkastenholz5d880a92019-06-21 09:01:56 -07007427 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007428 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7429 IsError(QUIC_PUBLIC_RESET));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007430}
7431
7432TEST_P(QuicConnectionTest, GoAway) {
fkastenholz305e1732019-06-18 05:01:22 -07007433 if (VersionHasIetfQuicFrames(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007434 // GoAway is not available in version 99.
7435 return;
7436 }
7437
7438 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7439
wub8a5dafa2020-05-13 12:30:17 -07007440 QuicGoAwayFrame* goaway = new QuicGoAwayFrame();
7441 goaway->last_good_stream_id = 1;
7442 goaway->error_code = QUIC_PEER_GOING_AWAY;
7443 goaway->reason_phrase = "Going away.";
QUICHE teama6ef0a62019-03-07 20:34:33 -05007444 EXPECT_CALL(visitor_, OnGoAway(_));
wub8a5dafa2020-05-13 12:30:17 -07007445 ProcessGoAwayPacket(goaway);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007446}
7447
7448TEST_P(QuicConnectionTest, WindowUpdate) {
7449 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7450
wub8a5dafa2020-05-13 12:30:17 -07007451 QuicWindowUpdateFrame* window_update = new QuicWindowUpdateFrame();
7452 window_update->stream_id = 3;
7453 window_update->max_data = 1234;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007454 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
wub8a5dafa2020-05-13 12:30:17 -07007455 ProcessFramePacket(QuicFrame(window_update));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007456}
7457
7458TEST_P(QuicConnectionTest, Blocked) {
7459 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7460
wub8a5dafa2020-05-13 12:30:17 -07007461 QuicBlockedFrame* blocked = new QuicBlockedFrame();
7462 blocked->stream_id = 3;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007463 EXPECT_CALL(visitor_, OnBlockedFrame(_));
wub8a5dafa2020-05-13 12:30:17 -07007464 ProcessFramePacket(QuicFrame(blocked));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007465 EXPECT_EQ(1u, connection_.GetStats().blocked_frames_received);
7466 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7467}
7468
7469TEST_P(QuicConnectionTest, ZeroBytePacket) {
7470 // Don't close the connection for zero byte packets.
fkastenholz5d880a92019-06-21 09:01:56 -07007471 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007472 QuicReceivedPacket encrypted(nullptr, 0, QuicTime::Zero());
7473 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, encrypted);
7474}
7475
7476TEST_P(QuicConnectionTest, MissingPacketsBeforeLeastUnacked) {
fayangd4291e42019-05-30 10:31:21 -07007477 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007478 return;
7479 }
7480 // Set the packet number of the ack packet to be least unacked (4).
7481 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 3);
7482 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7483 ProcessStopWaitingPacket(InitStopWaitingFrame(4));
fayangc31c9952019-06-05 13:54:48 -07007484 EXPECT_FALSE(connection_.ack_frame().packets.Empty());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007485}
7486
QUICHE teama6ef0a62019-03-07 20:34:33 -05007487TEST_P(QuicConnectionTest, ClientHandlesVersionNegotiation) {
dschinazi48ac9192019-07-31 00:07:26 -07007488 // All supported versions except the one the connection supports.
7489 ParsedQuicVersionVector versions;
7490 for (auto version : AllSupportedVersions()) {
7491 if (version != connection_.version()) {
7492 versions.push_back(version);
7493 }
7494 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007495
7496 // Send a version negotiation packet.
7497 std::unique_ptr<QuicEncryptedPacket> encrypted(
dschinazib417d602019-05-29 13:08:45 -07007498 QuicFramer::BuildVersionNegotiationPacket(
7499 connection_id_, EmptyQuicConnectionId(),
fayangd4291e42019-05-30 10:31:21 -07007500 VersionHasIetfInvariantHeader(connection_.transport_version()),
dschinazi48ac9192019-07-31 00:07:26 -07007501 connection_.version().HasLengthPrefixedConnectionIds(), versions));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007502 std::unique_ptr<QuicReceivedPacket> received(
7503 ConstructReceivedPacket(*encrypted, QuicTime::Zero()));
fkastenholz5d880a92019-06-21 09:01:56 -07007504 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7505 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
fayang95cef072019-10-10 12:44:14 -07007506 // Verify no connection close packet gets sent.
7507 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007508 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
fayang9ed391a2019-06-20 11:16:59 -07007509 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07007510 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007511 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7512 IsError(QUIC_INVALID_VERSION));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007513}
7514
7515TEST_P(QuicConnectionTest, BadVersionNegotiation) {
7516 // Send a version negotiation packet with the version the client started with.
7517 // It should be rejected.
fkastenholz5d880a92019-06-21 09:01:56 -07007518 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7519 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007520 std::unique_ptr<QuicEncryptedPacket> encrypted(
dschinazib417d602019-05-29 13:08:45 -07007521 QuicFramer::BuildVersionNegotiationPacket(
7522 connection_id_, EmptyQuicConnectionId(),
fayangd4291e42019-05-30 10:31:21 -07007523 VersionHasIetfInvariantHeader(connection_.transport_version()),
dschinazi48ac9192019-07-31 00:07:26 -07007524 connection_.version().HasLengthPrefixedConnectionIds(),
QUICHE teama6ef0a62019-03-07 20:34:33 -05007525 AllSupportedVersions()));
7526 std::unique_ptr<QuicReceivedPacket> received(
7527 ConstructReceivedPacket(*encrypted, QuicTime::Zero()));
7528 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
fkastenholz5d880a92019-06-21 09:01:56 -07007529 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007530 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7531 IsError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007532}
7533
7534TEST_P(QuicConnectionTest, CheckSendStats) {
fayang5f135052019-08-22 17:59:40 -07007535 if (connection_.PtoEnabled()) {
7536 return;
7537 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007538 connection_.SetMaxTailLossProbes(0);
7539
7540 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7541 connection_.SendStreamDataWithString(3, "first", 0, NO_FIN);
7542 size_t first_packet_size = writer_->last_packet_size();
7543
7544 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7545 connection_.SendStreamDataWithString(5, "second", 0, NO_FIN);
7546 size_t second_packet_size = writer_->last_packet_size();
7547
7548 // 2 retransmissions due to rto, 1 due to explicit nack.
7549 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
7550 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
7551
7552 // Retransmit due to RTO.
7553 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
7554 connection_.GetRetransmissionAlarm()->Fire();
7555
7556 // Retransmit due to explicit nacks.
7557 QuicAckFrame nack_three =
7558 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)},
7559 {QuicPacketNumber(4), QuicPacketNumber(5)}});
7560
7561 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07007562 lost_packets.push_back(
7563 LostPacket(QuicPacketNumber(1), kMaxOutgoingPacketSize));
7564 lost_packets.push_back(
7565 LostPacket(QuicPacketNumber(3), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007566 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07007567 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
7568 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007569 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007570 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7571 ProcessAckPacket(&nack_three);
7572
7573 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
7574 .WillOnce(Return(QuicBandwidth::Zero()));
7575
7576 const QuicConnectionStats& stats = connection_.GetStats();
7577 // For IETF QUIC, version is not included as the encryption level switches to
7578 // FORWARD_SECURE in SendStreamDataWithString.
7579 size_t save_on_version =
fayangd4291e42019-05-30 10:31:21 -07007580 VersionHasIetfInvariantHeader(GetParam().version.transport_version)
7581 ? 0
7582 : kQuicVersionSize;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007583 EXPECT_EQ(3 * first_packet_size + 2 * second_packet_size - save_on_version,
7584 stats.bytes_sent);
7585 EXPECT_EQ(5u, stats.packets_sent);
7586 EXPECT_EQ(2 * first_packet_size + second_packet_size - save_on_version,
7587 stats.bytes_retransmitted);
7588 EXPECT_EQ(3u, stats.packets_retransmitted);
7589 EXPECT_EQ(1u, stats.rto_count);
7590 EXPECT_EQ(kDefaultMaxPacketSize, stats.max_packet_size);
7591}
7592
7593TEST_P(QuicConnectionTest, ProcessFramesIfPacketClosedConnection) {
7594 // Construct a packet with stream frame and connection close frame.
7595 QuicPacketHeader header;
dschinazi5e1a7b22019-07-31 12:23:21 -07007596 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
QUICHE team2252b702019-05-14 23:55:14 -04007597 header.source_connection_id = connection_id_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007598 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
fayangd4291e42019-05-30 10:31:21 -07007599 if (!VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04007600 header.source_connection_id_included = CONNECTION_ID_PRESENT;
7601 }
7602 } else {
7603 header.destination_connection_id = connection_id_;
fayangd4291e42019-05-30 10:31:21 -07007604 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04007605 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
7606 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007607 }
7608 header.packet_number = QuicPacketNumber(1);
7609 header.version_flag = false;
7610
fkastenholz488a4622019-08-26 06:24:46 -07007611 QuicErrorCode kQuicErrorCode = QUIC_PEER_GOING_AWAY;
7612 // This QuicConnectionCloseFrame will default to being for a Google QUIC
7613 // close. If doing IETF QUIC then set fields appropriately for CC/T or CC/A,
7614 // depending on the mapping.
fkastenholz591814c2019-09-06 12:11:46 -07007615 QuicConnectionCloseFrame qccf(peer_framer_.transport_version(),
7616 kQuicErrorCode, "",
7617 /*transport_close_frame_type=*/0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007618 QuicFrames frames;
7619 frames.push_back(QuicFrame(frame1_));
7620 frames.push_back(QuicFrame(&qccf));
7621 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
7622 EXPECT_TRUE(nullptr != packet);
dschinazi66dea072019-04-09 11:41:06 -07007623 char buffer[kMaxOutgoingPacketSize];
nharperc6b99512019-09-19 11:13:48 -07007624 size_t encrypted_length = peer_framer_.EncryptPayload(
7625 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
7626 kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007627
fkastenholz5d880a92019-06-21 09:01:56 -07007628 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
7629 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007630 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7631 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7632
7633 connection_.ProcessUdpPacket(
7634 kSelfAddress, kPeerAddress,
7635 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
fkastenholz5d880a92019-06-21 09:01:56 -07007636 EXPECT_EQ(1, connection_close_frame_count_);
bnc77e77b82020-04-05 10:36:49 -07007637 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
bncf54082a2019-11-27 10:19:47 -08007638 IsError(QUIC_PEER_GOING_AWAY));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007639}
7640
7641TEST_P(QuicConnectionTest, SelectMutualVersion) {
7642 connection_.SetSupportedVersions(AllSupportedVersions());
7643 // Set the connection to speak the lowest quic version.
7644 connection_.set_version(QuicVersionMin());
7645 EXPECT_EQ(QuicVersionMin(), connection_.version());
7646
7647 // Pass in available versions which includes a higher mutually supported
7648 // version. The higher mutually supported version should be selected.
7649 ParsedQuicVersionVector supported_versions = AllSupportedVersions();
7650 EXPECT_TRUE(connection_.SelectMutualVersion(supported_versions));
7651 EXPECT_EQ(QuicVersionMax(), connection_.version());
7652
7653 // Expect that the lowest version is selected.
7654 // Ensure the lowest supported version is less than the max, unless they're
7655 // the same.
7656 ParsedQuicVersionVector lowest_version_vector;
7657 lowest_version_vector.push_back(QuicVersionMin());
7658 EXPECT_TRUE(connection_.SelectMutualVersion(lowest_version_vector));
7659 EXPECT_EQ(QuicVersionMin(), connection_.version());
7660
7661 // Shouldn't be able to find a mutually supported version.
7662 ParsedQuicVersionVector unsupported_version;
7663 unsupported_version.push_back(UnsupportedQuicVersion());
7664 EXPECT_FALSE(connection_.SelectMutualVersion(unsupported_version));
7665}
7666
7667TEST_P(QuicConnectionTest, ConnectionCloseWhenWritable) {
7668 EXPECT_FALSE(writer_->IsWriteBlocked());
7669
7670 // Send a packet.
7671 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7672 EXPECT_EQ(0u, connection_.NumQueuedPackets());
7673 EXPECT_EQ(1u, writer_->packets_write_attempts());
7674
7675 TriggerConnectionClose();
rch39c88ab2019-10-16 19:24:40 -07007676 EXPECT_LE(2u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007677}
7678
7679TEST_P(QuicConnectionTest, ConnectionCloseGettingWriteBlocked) {
7680 BlockOnNextWrite();
7681 TriggerConnectionClose();
7682 EXPECT_EQ(1u, writer_->packets_write_attempts());
7683 EXPECT_TRUE(writer_->IsWriteBlocked());
7684}
7685
7686TEST_P(QuicConnectionTest, ConnectionCloseWhenWriteBlocked) {
7687 BlockOnNextWrite();
7688 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7689 EXPECT_EQ(1u, connection_.NumQueuedPackets());
7690 EXPECT_EQ(1u, writer_->packets_write_attempts());
7691 EXPECT_TRUE(writer_->IsWriteBlocked());
7692 TriggerConnectionClose();
7693 EXPECT_EQ(1u, writer_->packets_write_attempts());
7694}
7695
7696TEST_P(QuicConnectionTest, OnPacketSentDebugVisitor) {
7697 MockQuicConnectionDebugVisitor debug_visitor;
7698 connection_.set_debug_visitor(&debug_visitor);
7699
fayangcff885a2019-10-22 07:39:04 -07007700 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007701 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7702
fayangcff885a2019-10-22 07:39:04 -07007703 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007704 connection_.SendConnectivityProbingPacket(writer_.get(),
7705 connection_.peer_address());
7706}
7707
7708TEST_P(QuicConnectionTest, OnPacketHeaderDebugVisitor) {
7709 QuicPacketHeader header;
7710 header.packet_number = QuicPacketNumber(1);
fayangd4291e42019-05-30 10:31:21 -07007711 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007712 header.form = IETF_QUIC_LONG_HEADER_PACKET;
7713 }
7714
7715 MockQuicConnectionDebugVisitor debug_visitor;
7716 connection_.set_debug_visitor(&debug_visitor);
7717 EXPECT_CALL(debug_visitor, OnPacketHeader(Ref(header))).Times(1);
7718 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(1);
7719 EXPECT_CALL(debug_visitor, OnSuccessfulVersionNegotiation(_)).Times(1);
7720 connection_.OnPacketHeader(header);
7721}
7722
7723TEST_P(QuicConnectionTest, Pacing) {
7724 TestConnection server(connection_id_, kSelfAddress, helper_.get(),
7725 alarm_factory_.get(), writer_.get(),
7726 Perspective::IS_SERVER, version());
7727 TestConnection client(connection_id_, kPeerAddress, helper_.get(),
7728 alarm_factory_.get(), writer_.get(),
7729 Perspective::IS_CLIENT, version());
7730 EXPECT_FALSE(QuicSentPacketManagerPeer::UsingPacing(
7731 static_cast<const QuicSentPacketManager*>(
7732 &client.sent_packet_manager())));
7733 EXPECT_FALSE(QuicSentPacketManagerPeer::UsingPacing(
7734 static_cast<const QuicSentPacketManager*>(
7735 &server.sent_packet_manager())));
7736}
7737
7738TEST_P(QuicConnectionTest, WindowUpdateInstigateAcks) {
7739 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7740
7741 // Send a WINDOW_UPDATE frame.
wub8a5dafa2020-05-13 12:30:17 -07007742 QuicWindowUpdateFrame* window_update = new QuicWindowUpdateFrame();
7743 window_update->stream_id = 3;
7744 window_update->max_data = 1234;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007745 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
wub8a5dafa2020-05-13 12:30:17 -07007746 ProcessFramePacket(QuicFrame(window_update));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007747
7748 // Ensure that this has caused the ACK alarm to be set.
fayang9adfb532020-06-04 06:58:45 -07007749 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007750}
7751
7752TEST_P(QuicConnectionTest, BlockedFrameInstigateAcks) {
7753 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7754
7755 // Send a BLOCKED frame.
wub8a5dafa2020-05-13 12:30:17 -07007756 QuicBlockedFrame* blocked = new QuicBlockedFrame();
7757 blocked->stream_id = 3;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007758 EXPECT_CALL(visitor_, OnBlockedFrame(_));
wub8a5dafa2020-05-13 12:30:17 -07007759 ProcessFramePacket(QuicFrame(blocked));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007760
7761 // Ensure that this has caused the ACK alarm to be set.
fayang9adfb532020-06-04 06:58:45 -07007762 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007763}
7764
7765TEST_P(QuicConnectionTest, ReevaluateTimeUntilSendOnAck) {
7766 // Enable pacing.
7767 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7768 QuicConfig config;
7769 connection_.SetFromConfig(config);
7770
7771 // Send two packets. One packet is not sufficient because if it gets acked,
7772 // there will be no packets in flight after that and the pacer will always
7773 // allow the next packet in that situation.
7774 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7775 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
7776 connection_.SendStreamDataWithString(
7777 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
7778 0, NO_FIN);
7779 connection_.SendStreamDataWithString(
7780 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "bar",
7781 3, NO_FIN);
7782 connection_.OnCanWrite();
7783
7784 // Schedule the next packet for a few milliseconds in future.
7785 QuicSentPacketManagerPeer::DisablePacerBursts(manager_);
7786 QuicTime scheduled_pacing_time =
7787 clock_.Now() + QuicTime::Delta::FromMilliseconds(5);
7788 QuicSentPacketManagerPeer::SetNextPacedPacketTime(manager_,
7789 scheduled_pacing_time);
7790
7791 // Send a packet and have it be blocked by congestion control.
7792 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(false));
7793 connection_.SendStreamDataWithString(
7794 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "baz",
7795 6, NO_FIN);
7796 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
7797
7798 // Process an ack and the send alarm will be set to the new 5ms delay.
7799 QuicAckFrame ack = InitAckFrame(1);
7800 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
7801 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7802 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
7803 ProcessAckPacket(&ack);
nharper55fa6132019-05-07 19:37:21 -07007804 size_t padding_frame_count = writer_->padding_frames().size();
7805 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007806 EXPECT_EQ(1u, writer_->stream_frames().size());
7807 EXPECT_TRUE(connection_.GetSendAlarm()->IsSet());
7808 EXPECT_EQ(scheduled_pacing_time, connection_.GetSendAlarm()->deadline());
7809 writer_->Reset();
7810}
7811
7812TEST_P(QuicConnectionTest, SendAcksImmediately) {
QUICHE teamcd098022019-03-22 18:49:55 -07007813 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7814 return;
7815 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007816 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7817 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7818 ProcessDataPacket(1);
7819 CongestionBlockWrites();
7820 SendAckPacketToPeer();
7821}
7822
7823TEST_P(QuicConnectionTest, SendPingImmediately) {
7824 MockQuicConnectionDebugVisitor debug_visitor;
7825 connection_.set_debug_visitor(&debug_visitor);
7826
7827 CongestionBlockWrites();
fayang93cc53a2019-08-22 12:47:30 -07007828 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007829 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
fayangcff885a2019-10-22 07:39:04 -07007830 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007831 EXPECT_CALL(debug_visitor, OnPingSent()).Times(1);
7832 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
7833 EXPECT_FALSE(connection_.HasQueuedData());
7834}
7835
7836TEST_P(QuicConnectionTest, SendBlockedImmediately) {
7837 MockQuicConnectionDebugVisitor debug_visitor;
7838 connection_.set_debug_visitor(&debug_visitor);
7839
fayang93cc53a2019-08-22 12:47:30 -07007840 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007841 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
fayangcff885a2019-10-22 07:39:04 -07007842 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007843 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7844 connection_.SendControlFrame(QuicFrame(new QuicBlockedFrame(1, 3)));
7845 EXPECT_EQ(1u, connection_.GetStats().blocked_frames_sent);
7846 EXPECT_FALSE(connection_.HasQueuedData());
7847}
7848
fayang93cc53a2019-08-22 12:47:30 -07007849TEST_P(QuicConnectionTest, FailedToSendBlockedFrames) {
7850 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
7851 return;
7852 }
7853 MockQuicConnectionDebugVisitor debug_visitor;
7854 connection_.set_debug_visitor(&debug_visitor);
7855 QuicBlockedFrame blocked(1, 3);
7856
7857 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
fayangcff885a2019-10-22 07:39:04 -07007858 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(0);
fayang93cc53a2019-08-22 12:47:30 -07007859 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7860 connection_.SendControlFrame(QuicFrame(&blocked));
7861 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7862 EXPECT_FALSE(connection_.HasQueuedData());
7863}
7864
QUICHE teama6ef0a62019-03-07 20:34:33 -05007865TEST_P(QuicConnectionTest, SendingUnencryptedStreamDataFails) {
7866 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
7867 if (!IsDefaultTestConfiguration()) {
7868 return;
7869 }
7870
fkastenholz5d880a92019-06-21 09:01:56 -07007871 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7872 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007873 struct iovec iov;
7874 MakeIOVector("", &iov);
7875 EXPECT_QUIC_BUG(connection_.SaveAndSendStreamData(3, &iov, 1, 0, 0, FIN),
fayang49523232019-05-03 06:28:22 -07007876 "Cannot send stream data with level: ENCRYPTION_INITIAL");
QUICHE teama6ef0a62019-03-07 20:34:33 -05007877 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07007878 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007879 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7880 IsError(QUIC_ATTEMPT_TO_SEND_UNENCRYPTED_STREAM_DATA));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007881}
7882
7883TEST_P(QuicConnectionTest, SetRetransmissionAlarmForCryptoPacket) {
7884 EXPECT_TRUE(connection_.connected());
7885 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
7886
7887 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7888 connection_.SendCryptoStreamData();
7889
7890 // Verify retransmission timer is correctly set after crypto packet has been
7891 // sent.
7892 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
7893 QuicTime retransmission_time =
7894 QuicConnectionPeer::GetSentPacketManager(&connection_)
7895 ->GetRetransmissionTime();
7896 EXPECT_NE(retransmission_time, clock_.ApproximateNow());
7897 EXPECT_EQ(retransmission_time,
7898 connection_.GetRetransmissionAlarm()->deadline());
7899
7900 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7901 connection_.GetRetransmissionAlarm()->Fire();
7902}
7903
7904TEST_P(QuicConnectionTest, PathDegradingAlarmForCryptoPacket) {
7905 EXPECT_TRUE(connection_.connected());
fayangb59c6f12020-03-23 15:06:14 -07007906 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007907 EXPECT_FALSE(connection_.IsPathDegrading());
7908
7909 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7910 connection_.SendCryptoStreamData();
7911
fayangb59c6f12020-03-23 15:06:14 -07007912 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007913 EXPECT_FALSE(connection_.IsPathDegrading());
7914 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7915 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07007916 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7917 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007918
7919 // Fire the path degrading alarm, path degrading signal should be sent to
7920 // the visitor.
7921 EXPECT_CALL(visitor_, OnPathDegrading());
7922 clock_.AdvanceTime(delay);
fayangb59c6f12020-03-23 15:06:14 -07007923 connection_.PathDegradingTimeout();
QUICHE teama6ef0a62019-03-07 20:34:33 -05007924 EXPECT_TRUE(connection_.IsPathDegrading());
fayangb59c6f12020-03-23 15:06:14 -07007925 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007926}
7927
vasilvv693d5b02019-04-09 21:58:56 -07007928// Includes regression test for b/69979024.
QUICHE teama6ef0a62019-03-07 20:34:33 -05007929TEST_P(QuicConnectionTest, PathDegradingAlarmForNonCryptoPackets) {
7930 EXPECT_TRUE(connection_.connected());
fayangb59c6f12020-03-23 15:06:14 -07007931 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007932 EXPECT_FALSE(connection_.IsPathDegrading());
7933
7934 const char data[] = "data";
7935 size_t data_size = strlen(data);
7936 QuicStreamOffset offset = 0;
7937
7938 for (int i = 0; i < 2; ++i) {
7939 // Send a packet. Now there's a retransmittable packet on the wire, so the
7940 // path degrading alarm should be set.
7941 connection_.SendStreamDataWithString(
7942 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
7943 offset, NO_FIN);
7944 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07007945 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007946 // Check the deadline of the path degrading alarm.
7947 QuicTime::Delta delay =
7948 QuicConnectionPeer::GetSentPacketManager(&connection_)
7949 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07007950 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7951 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007952
7953 // Send a second packet. The path degrading alarm's deadline should remain
7954 // the same.
vasilvv693d5b02019-04-09 21:58:56 -07007955 // Regression test for b/69979024.
QUICHE teama6ef0a62019-03-07 20:34:33 -05007956 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
fayang2205d952020-05-12 13:45:56 -07007957 QuicTime prev_deadline =
7958 connection_.GetBlackholeDetectorAlarm()->deadline();
QUICHE teama6ef0a62019-03-07 20:34:33 -05007959 connection_.SendStreamDataWithString(
7960 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
7961 offset, NO_FIN);
7962 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07007963 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
fayang2205d952020-05-12 13:45:56 -07007964 EXPECT_EQ(prev_deadline,
7965 connection_.GetBlackholeDetectorAlarm()->deadline());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007966
7967 // Now receive an ACK of the first packet. This should advance the path
7968 // degrading alarm's deadline since forward progress has been made.
7969 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7970 if (i == 0) {
7971 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7972 }
7973 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7974 QuicAckFrame frame = InitAckFrame(
7975 {{QuicPacketNumber(1u + 2u * i), QuicPacketNumber(2u + 2u * i)}});
7976 ProcessAckPacket(&frame);
fayangb59c6f12020-03-23 15:06:14 -07007977 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007978 // Check the deadline of the path degrading alarm.
7979 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7980 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07007981 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7982 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007983
7984 if (i == 0) {
7985 // Now receive an ACK of the second packet. Since there are no more
7986 // retransmittable packets on the wire, this should cancel the path
7987 // degrading alarm.
7988 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7989 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7990 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
7991 ProcessAckPacket(&frame);
fayangb59c6f12020-03-23 15:06:14 -07007992 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007993 } else {
7994 // Advance time to the path degrading alarm's deadline and simulate
7995 // firing the alarm.
7996 clock_.AdvanceTime(delay);
7997 EXPECT_CALL(visitor_, OnPathDegrading());
fayangb59c6f12020-03-23 15:06:14 -07007998 connection_.PathDegradingTimeout();
7999 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008000 }
8001 }
8002 EXPECT_TRUE(connection_.IsPathDegrading());
8003}
8004
8005TEST_P(QuicConnectionTest, RetransmittableOnWireSetsPingAlarm) {
8006 const QuicTime::Delta retransmittable_on_wire_timeout =
8007 QuicTime::Delta::FromMilliseconds(50);
zhongyi79ace162019-10-21 15:57:09 -07008008 connection_.set_initial_retransmittable_on_wire_timeout(
QUICHE teama6ef0a62019-03-07 20:34:33 -05008009 retransmittable_on_wire_timeout);
8010
8011 EXPECT_TRUE(connection_.connected());
8012 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8013 .WillRepeatedly(Return(true));
8014
fayangb59c6f12020-03-23 15:06:14 -07008015 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008016 EXPECT_FALSE(connection_.IsPathDegrading());
8017 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8018
8019 const char data[] = "data";
8020 size_t data_size = strlen(data);
8021 QuicStreamOffset offset = 0;
8022
8023 // Send a packet.
8024 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8025 offset += data_size;
8026 // Now there's a retransmittable packet on the wire, so the path degrading
8027 // alarm should be set.
8028 // The retransmittable-on-wire alarm should not be set.
fayangb59c6f12020-03-23 15:06:14 -07008029 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008030 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
8031 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07008032 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
8033 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008034 ASSERT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8035 // The ping alarm is set for the ping timeout, not the shorter
8036 // retransmittable_on_wire_timeout.
8037 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8038 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
zhongyieef848f2019-10-18 07:09:37 -07008039 EXPECT_EQ(ping_delay,
8040 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008041
8042 // Now receive an ACK of the packet.
8043 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8044 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8045 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8046 QuicAckFrame frame =
8047 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8048 ProcessAckPacket(&frame);
8049 // No more retransmittable packets on the wire, so the path degrading alarm
8050 // should be cancelled, and the ping alarm should be set to the
8051 // retransmittable_on_wire_timeout.
fayangb59c6f12020-03-23 15:06:14 -07008052 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008053 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07008054 EXPECT_EQ(retransmittable_on_wire_timeout,
8055 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008056
8057 // Simulate firing the ping alarm and sending a PING.
8058 clock_.AdvanceTime(retransmittable_on_wire_timeout);
8059 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8060 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
8061 }));
8062 connection_.GetPingAlarm()->Fire();
8063
8064 // Now there's a retransmittable packet (PING) on the wire, so the path
8065 // degrading alarm should be set.
fayangb59c6f12020-03-23 15:06:14 -07008066 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008067 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
8068 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07008069 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
8070 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008071}
8072
8073// This test verifies that the connection marks path as degrading and does not
8074// spin timer to detect path degrading when a new packet is sent on the
8075// degraded path.
8076TEST_P(QuicConnectionTest, NoPathDegradingAlarmIfPathIsDegrading) {
8077 EXPECT_TRUE(connection_.connected());
fayangb59c6f12020-03-23 15:06:14 -07008078 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008079 EXPECT_FALSE(connection_.IsPathDegrading());
8080
8081 const char data[] = "data";
8082 size_t data_size = strlen(data);
8083 QuicStreamOffset offset = 0;
8084
8085 // Send the first packet. Now there's a retransmittable packet on the wire, so
8086 // the path degrading alarm should be set.
8087 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8088 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07008089 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008090 // Check the deadline of the path degrading alarm.
8091 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
8092 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07008093 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
8094 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008095
8096 // Send a second packet. The path degrading alarm's deadline should remain
8097 // the same.
8098 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
fayang2205d952020-05-12 13:45:56 -07008099 QuicTime prev_deadline = connection_.GetBlackholeDetectorAlarm()->deadline();
QUICHE teama6ef0a62019-03-07 20:34:33 -05008100 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8101 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07008102 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
fayang2205d952020-05-12 13:45:56 -07008103 EXPECT_EQ(prev_deadline, connection_.GetBlackholeDetectorAlarm()->deadline());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008104
8105 // Now receive an ACK of the first packet. This should advance the path
8106 // degrading alarm's deadline since forward progress has been made.
8107 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8108 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8109 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8110 QuicAckFrame frame =
8111 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
8112 ProcessAckPacket(&frame);
fayangb59c6f12020-03-23 15:06:14 -07008113 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008114 // Check the deadline of the path degrading alarm.
8115 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
8116 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07008117 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
8118 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008119
8120 // Advance time to the path degrading alarm's deadline and simulate
8121 // firing the path degrading alarm. This path will be considered as
8122 // degrading.
8123 clock_.AdvanceTime(delay);
8124 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
fayangb59c6f12020-03-23 15:06:14 -07008125 connection_.PathDegradingTimeout();
8126 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008127 EXPECT_TRUE(connection_.IsPathDegrading());
8128
8129 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
fayangb59c6f12020-03-23 15:06:14 -07008130 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008131 // Send a third packet. The path degrading alarm is no longer set but path
8132 // should still be marked as degrading.
8133 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8134 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07008135 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008136 EXPECT_TRUE(connection_.IsPathDegrading());
8137}
8138
8139// This test verifies that the connection unmarks path as degrarding and spins
8140// the timer to detect future path degrading when forward progress is made
8141// after path has been marked degrading.
8142TEST_P(QuicConnectionTest, UnmarkPathDegradingOnForwardProgress) {
8143 EXPECT_TRUE(connection_.connected());
fayangb59c6f12020-03-23 15:06:14 -07008144 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008145 EXPECT_FALSE(connection_.IsPathDegrading());
8146
8147 const char data[] = "data";
8148 size_t data_size = strlen(data);
8149 QuicStreamOffset offset = 0;
8150
8151 // Send the first packet. Now there's a retransmittable packet on the wire, so
8152 // the path degrading alarm should be set.
8153 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8154 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07008155 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008156 // Check the deadline of the path degrading alarm.
8157 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
8158 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07008159 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
8160 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008161
8162 // Send a second packet. The path degrading alarm's deadline should remain
8163 // the same.
8164 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
fayang2205d952020-05-12 13:45:56 -07008165 QuicTime prev_deadline = connection_.GetBlackholeDetectorAlarm()->deadline();
QUICHE teama6ef0a62019-03-07 20:34:33 -05008166 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8167 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07008168 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
fayang2205d952020-05-12 13:45:56 -07008169 EXPECT_EQ(prev_deadline, connection_.GetBlackholeDetectorAlarm()->deadline());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008170
8171 // Now receive an ACK of the first packet. This should advance the path
8172 // degrading alarm's deadline since forward progress has been made.
8173 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8174 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8175 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8176 QuicAckFrame frame =
8177 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
8178 ProcessAckPacket(&frame);
fayangb59c6f12020-03-23 15:06:14 -07008179 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008180 // Check the deadline of the path degrading alarm.
8181 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
8182 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07008183 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
8184 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008185
8186 // Advance time to the path degrading alarm's deadline and simulate
8187 // firing the alarm.
8188 clock_.AdvanceTime(delay);
8189 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
fayangb59c6f12020-03-23 15:06:14 -07008190 connection_.PathDegradingTimeout();
8191 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008192 EXPECT_TRUE(connection_.IsPathDegrading());
8193
8194 // Send a third packet. The path degrading alarm is no longer set but path
8195 // should still be marked as degrading.
8196 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
fayangb59c6f12020-03-23 15:06:14 -07008197 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008198 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8199 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07008200 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008201 EXPECT_TRUE(connection_.IsPathDegrading());
8202
8203 // Now receive an ACK of the second packet. This should unmark the path as
8204 // degrading. And will set a timer to detect new path degrading.
8205 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8206 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
zhongyief1d6752020-06-11 16:19:28 -07008207 EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading()).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008208 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8209 ProcessAckPacket(&frame);
8210 EXPECT_FALSE(connection_.IsPathDegrading());
fayangb59c6f12020-03-23 15:06:14 -07008211 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008212}
8213
8214TEST_P(QuicConnectionTest, NoPathDegradingOnServer) {
QUICHE teamcd098022019-03-22 18:49:55 -07008215 if (connection_.SupportsMultiplePacketNumberSpaces()) {
8216 return;
8217 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008218 set_perspective(Perspective::IS_SERVER);
8219 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
8220
8221 EXPECT_FALSE(connection_.IsPathDegrading());
fayangb59c6f12020-03-23 15:06:14 -07008222 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008223
8224 // Send data.
8225 const char data[] = "data";
8226 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
8227 EXPECT_FALSE(connection_.IsPathDegrading());
fayangb59c6f12020-03-23 15:06:14 -07008228 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008229
8230 // Ack data.
8231 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
QUICHE teama6ef0a62019-03-07 20:34:33 -05008232 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8233 QuicAckFrame frame =
8234 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
8235 ProcessAckPacket(&frame);
8236 EXPECT_FALSE(connection_.IsPathDegrading());
fayangb59c6f12020-03-23 15:06:14 -07008237 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008238}
8239
8240TEST_P(QuicConnectionTest, NoPathDegradingAfterSendingAck) {
QUICHE teamcd098022019-03-22 18:49:55 -07008241 if (connection_.SupportsMultiplePacketNumberSpaces()) {
8242 return;
8243 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008244 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8245 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
8246 ProcessDataPacket(1);
8247 SendAckPacketToPeer();
8248 EXPECT_FALSE(connection_.sent_packet_manager().unacked_packets().empty());
8249 EXPECT_FALSE(connection_.sent_packet_manager().HasInFlightPackets());
8250 EXPECT_FALSE(connection_.IsPathDegrading());
fayangb59c6f12020-03-23 15:06:14 -07008251 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008252}
8253
8254TEST_P(QuicConnectionTest, MultipleCallsToCloseConnection) {
8255 // Verifies that multiple calls to CloseConnection do not
8256 // result in multiple attempts to close the connection - it will be marked as
8257 // disconnected after the first call.
fkastenholz5d880a92019-06-21 09:01:56 -07008258 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008259 connection_.CloseConnection(QUIC_NO_ERROR, "no reason",
8260 ConnectionCloseBehavior::SILENT_CLOSE);
8261 connection_.CloseConnection(QUIC_NO_ERROR, "no reason",
8262 ConnectionCloseBehavior::SILENT_CLOSE);
8263}
8264
8265TEST_P(QuicConnectionTest, ServerReceivesChloOnNonCryptoStream) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008266 set_perspective(Perspective::IS_SERVER);
8267 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
8268
8269 CryptoHandshakeMessage message;
8270 CryptoFramer framer;
8271 message.set_tag(kCHLO);
QUICHE team3fe6a8b2019-03-14 09:10:38 -07008272 std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008273 frame1_.stream_id = 10;
8274 frame1_.data_buffer = data->data();
8275 frame1_.data_length = data->length();
8276
fkastenholz5d880a92019-06-21 09:01:56 -07008277 EXPECT_CALL(visitor_,
8278 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05008279 ForceProcessFramePacket(QuicFrame(frame1_));
fkastenholz5d880a92019-06-21 09:01:56 -07008280 TestConnectionCloseQuicErrorCode(QUIC_MAYBE_CORRUPTED_MEMORY);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008281}
8282
8283TEST_P(QuicConnectionTest, ClientReceivesRejOnNonCryptoStream) {
8284 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8285
8286 CryptoHandshakeMessage message;
8287 CryptoFramer framer;
8288 message.set_tag(kREJ);
QUICHE team3fe6a8b2019-03-14 09:10:38 -07008289 std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008290 frame1_.stream_id = 10;
8291 frame1_.data_buffer = data->data();
8292 frame1_.data_length = data->length();
8293
fkastenholz5d880a92019-06-21 09:01:56 -07008294 EXPECT_CALL(visitor_,
8295 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05008296 ForceProcessFramePacket(QuicFrame(frame1_));
fkastenholz5d880a92019-06-21 09:01:56 -07008297 TestConnectionCloseQuicErrorCode(QUIC_MAYBE_CORRUPTED_MEMORY);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008298}
8299
8300TEST_P(QuicConnectionTest, CloseConnectionOnPacketTooLarge) {
8301 SimulateNextPacketTooLarge();
8302 // A connection close packet is sent
fkastenholz5d880a92019-06-21 09:01:56 -07008303 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
QUICHE teama6ef0a62019-03-07 20:34:33 -05008304 .Times(1);
8305 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
fkastenholz5d880a92019-06-21 09:01:56 -07008306 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008307}
8308
8309TEST_P(QuicConnectionTest, AlwaysGetPacketTooLarge) {
8310 // Test even we always get packet too large, we do not infinitely try to send
8311 // close packet.
8312 AlwaysGetPacketTooLarge();
fkastenholz5d880a92019-06-21 09:01:56 -07008313 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
QUICHE teama6ef0a62019-03-07 20:34:33 -05008314 .Times(1);
8315 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
fkastenholz5d880a92019-06-21 09:01:56 -07008316 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008317}
8318
nharperef468962019-07-02 14:15:38 -07008319TEST_P(QuicConnectionTest, CloseConnectionOnQueuedWriteError) {
nharperef468962019-07-02 14:15:38 -07008320 // Regression test for crbug.com/979507.
8321 //
8322 // If we get a write error when writing queued packets, we should attempt to
8323 // send a connection close packet, but if sending that fails, it shouldn't get
8324 // queued.
8325
8326 // Queue a packet to write.
8327 BlockOnNextWrite();
8328 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
8329 EXPECT_EQ(1u, connection_.NumQueuedPackets());
8330
8331 // Configure writer to always fail.
8332 AlwaysGetPacketTooLarge();
8333
8334 // Expect that we attempt to close the connection exactly once.
8335 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
8336 .Times(1);
8337
8338 // Unblock the writes and actually send.
8339 writer_->SetWritable();
8340 connection_.OnCanWrite();
8341 EXPECT_EQ(0u, connection_.NumQueuedPackets());
8342
8343 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
8344}
8345
QUICHE teama6ef0a62019-03-07 20:34:33 -05008346// Verify that if connection has no outstanding data, it notifies the send
8347// algorithm after the write.
8348TEST_P(QuicConnectionTest, SendDataAndBecomeApplicationLimited) {
8349 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
8350 {
8351 InSequence seq;
8352 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
8353 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
8354 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
8355 .WillRepeatedly(Return(false));
8356 }
8357
8358 connection_.SendStreamData3();
8359}
8360
8361// Verify that the connection does not become app-limited if there is
8362// outstanding data to send after the write.
8363TEST_P(QuicConnectionTest, NotBecomeApplicationLimitedIfMoreDataAvailable) {
8364 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
8365 {
8366 InSequence seq;
8367 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
8368 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
8369 }
8370
8371 connection_.SendStreamData3();
8372}
8373
8374// Verify that the connection does not become app-limited after blocked write
8375// even if there is outstanding data to send after the write.
8376TEST_P(QuicConnectionTest, NotBecomeApplicationLimitedDueToWriteBlock) {
8377 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
8378 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
8379 BlockOnNextWrite();
8380
fayange62e63c2019-12-04 07:16:25 -08008381 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008382 connection_.SendStreamData3();
8383
8384 // Now unblock the writer, become congestion control blocked,
8385 // and ensure we become app-limited after writing.
8386 writer_->SetWritable();
8387 CongestionBlockWrites();
8388 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(false));
fayange62e63c2019-12-04 07:16:25 -08008389 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
fayang2ce66082019-10-02 06:29:04 -07008390 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008391 connection_.OnCanWrite();
8392}
8393
8394// Test the mode in which the link is filled up with probing retransmissions if
8395// the connection becomes application-limited.
8396TEST_P(QuicConnectionTest, SendDataWhenApplicationLimited) {
8397 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8398 EXPECT_CALL(*send_algorithm_, ShouldSendProbingPacket())
8399 .WillRepeatedly(Return(true));
8400 {
8401 InSequence seq;
8402 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
8403 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
8404 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
8405 .WillRepeatedly(Return(false));
8406 }
QUICHE teamb8343252019-04-29 13:58:01 -07008407 EXPECT_CALL(visitor_, SendProbingData()).WillRepeatedly([this] {
8408 return connection_.sent_packet_manager().MaybeRetransmitOldestPacket(
8409 PROBING_RETRANSMISSION);
8410 });
QUICHE teama6ef0a62019-03-07 20:34:33 -05008411 // Fix congestion window to be 20,000 bytes.
8412 EXPECT_CALL(*send_algorithm_, CanSend(Ge(20000u)))
8413 .WillRepeatedly(Return(false));
8414 EXPECT_CALL(*send_algorithm_, CanSend(Lt(20000u)))
8415 .WillRepeatedly(Return(true));
8416
8417 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
8418 ASSERT_EQ(0u, connection_.GetStats().packets_sent);
8419 connection_.set_fill_up_link_during_probing(true);
fayangedf9ad52020-03-05 13:49:18 -08008420 EXPECT_CALL(visitor_, GetHandshakeState())
8421 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
QUICHE teama6ef0a62019-03-07 20:34:33 -05008422 connection_.OnHandshakeComplete();
8423 connection_.SendStreamData3();
8424
8425 // We expect a lot of packets from a 20 kbyte window.
8426 EXPECT_GT(connection_.GetStats().packets_sent, 10u);
8427 // Ensure that the packets are padded.
8428 QuicByteCount average_packet_size =
8429 connection_.GetStats().bytes_sent / connection_.GetStats().packets_sent;
8430 EXPECT_GT(average_packet_size, 1000u);
8431
8432 // Acknowledge all packets sent, except for the last one.
8433 QuicAckFrame ack = InitAckFrame(
8434 connection_.sent_packet_manager().GetLargestSentPacket() - 1);
8435 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
8436 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8437
8438 // Ensure that since we no longer have retransmittable bytes in flight, this
8439 // will not cause any responses to be sent.
8440 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8441 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
8442 ProcessAckPacket(&ack);
8443}
8444
rchd672c6d2019-11-27 15:30:54 -08008445TEST_P(QuicConnectionTest, DoNotForceSendingAckOnPacketTooLarge) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008446 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8447 // Send an ack by simulating delayed ack alarm firing.
8448 ProcessPacket(1);
fayang9adfb532020-06-04 06:58:45 -07008449 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008450 connection_.GetAckAlarm()->Fire();
8451 // Simulate data packet causes write error.
fkastenholz5d880a92019-06-21 09:01:56 -07008452 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05008453 SimulateNextPacketTooLarge();
8454 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
rchd672c6d2019-11-27 15:30:54 -08008455 EXPECT_EQ(1u, writer_->connection_close_frames().size());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008456 // Ack frame is not bundled in connection close packet.
8457 EXPECT_TRUE(writer_->ack_frames().empty());
rchd672c6d2019-11-27 15:30:54 -08008458 if (writer_->padding_frames().empty()) {
8459 EXPECT_EQ(1u, writer_->frame_count());
8460 } else {
8461 EXPECT_EQ(2u, writer_->frame_count());
8462 }
8463
fkastenholz5d880a92019-06-21 09:01:56 -07008464 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008465}
8466
rchd672c6d2019-11-27 15:30:54 -08008467TEST_P(QuicConnectionTest, CloseConnectionAllLevels) {
fayangc303bfd2020-02-11 09:19:54 -08008468 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8469 return;
8470 }
rchd672c6d2019-11-27 15:30:54 -08008471
8472 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
8473 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
8474 connection_.CloseConnection(
8475 kQuicErrorCode, "Some random error message",
8476 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
8477
8478 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
8479
8480 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
8481 EXPECT_EQ(1u, writer_->connection_close_frames().size());
8482
8483 if (!connection_.version().CanSendCoalescedPackets()) {
8484 // Each connection close packet should be sent in distinct UDP packets.
8485 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
8486 writer_->connection_close_packets());
8487 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
8488 writer_->packets_write_attempts());
8489 return;
8490 }
8491
8492 // A single UDP packet should be sent with multiple connection close packets
8493 // coalesced together.
8494 EXPECT_EQ(1u, writer_->packets_write_attempts());
8495
8496 // Only the first packet has been processed yet.
8497 EXPECT_EQ(1u, writer_->connection_close_packets());
8498
8499 // ProcessPacket resets the visitor and frees the coalesced packet.
8500 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
8501 auto packet = writer_->coalesced_packet()->Clone();
8502 writer_->framer()->ProcessPacket(*packet);
8503 EXPECT_EQ(1u, writer_->connection_close_packets());
8504 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
8505}
8506
8507TEST_P(QuicConnectionTest, CloseConnectionOneLevel) {
fayangc303bfd2020-02-11 09:19:54 -08008508 if (connection_.SupportsMultiplePacketNumberSpaces()) {
8509 return;
8510 }
rchd672c6d2019-11-27 15:30:54 -08008511
8512 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
8513 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
8514 connection_.CloseConnection(
8515 kQuicErrorCode, "Some random error message",
8516 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
8517
8518 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
8519
8520 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
8521 EXPECT_EQ(1u, writer_->connection_close_frames().size());
8522 EXPECT_EQ(1u, writer_->connection_close_packets());
8523 EXPECT_EQ(1u, writer_->packets_write_attempts());
8524 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
8525}
8526
fayang9abdfec2020-02-13 12:34:58 -08008527TEST_P(QuicConnectionTest, DoNotPadServerInitialConnectionClose) {
8528 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8529 return;
8530 }
8531 set_perspective(Perspective::IS_SERVER);
8532
8533 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
8534 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
8535 connection_.CloseConnection(
8536 kQuicErrorCode, "Some random error message",
8537 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
8538
8539 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
8540
8541 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
8542 EXPECT_EQ(1u, writer_->connection_close_frames().size());
8543 EXPECT_TRUE(writer_->padding_frames().empty());
8544 EXPECT_EQ(ENCRYPTION_INITIAL, writer_->framer()->last_decrypted_level());
8545}
8546
QUICHE teama6ef0a62019-03-07 20:34:33 -05008547// Regression test for b/63620844.
8548TEST_P(QuicConnectionTest, FailedToWriteHandshakePacket) {
8549 SimulateNextPacketTooLarge();
fkastenholz5d880a92019-06-21 09:01:56 -07008550 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
QUICHE teama6ef0a62019-03-07 20:34:33 -05008551 .Times(1);
fkastenholz5d880a92019-06-21 09:01:56 -07008552
QUICHE teama6ef0a62019-03-07 20:34:33 -05008553 connection_.SendCryptoStreamData();
fkastenholz5d880a92019-06-21 09:01:56 -07008554 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008555}
8556
8557TEST_P(QuicConnectionTest, MaxPacingRate) {
8558 EXPECT_EQ(0, connection_.MaxPacingRate().ToBytesPerSecond());
8559 connection_.SetMaxPacingRate(QuicBandwidth::FromBytesPerSecond(100));
8560 EXPECT_EQ(100, connection_.MaxPacingRate().ToBytesPerSecond());
8561}
8562
8563TEST_P(QuicConnectionTest, ClientAlwaysSendConnectionId) {
8564 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
8565 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8566 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
8567 EXPECT_EQ(CONNECTION_ID_PRESENT,
8568 writer_->last_packet_header().destination_connection_id_included);
8569
8570 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8571 QuicConfig config;
8572 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
8573 connection_.SetFromConfig(config);
8574
8575 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8576 connection_.SendStreamDataWithString(3, "bar", 3, NO_FIN);
8577 // Verify connection id is still sent in the packet.
8578 EXPECT_EQ(CONNECTION_ID_PRESENT,
8579 writer_->last_packet_header().destination_connection_id_included);
8580}
8581
8582TEST_P(QuicConnectionTest, SendProbingRetransmissions) {
8583 MockQuicConnectionDebugVisitor debug_visitor;
8584 connection_.set_debug_visitor(&debug_visitor);
8585
8586 const QuicStreamId stream_id = 2;
8587 QuicPacketNumber last_packet;
8588 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
8589 SendStreamDataToPeer(stream_id, "bar", 3, NO_FIN, &last_packet);
8590 SendStreamDataToPeer(stream_id, "test", 6, NO_FIN, &last_packet);
8591
8592 const QuicByteCount old_bytes_in_flight =
8593 connection_.sent_packet_manager().GetBytesInFlight();
8594
8595 // Allow 9 probing retransmissions to be sent.
8596 {
8597 InSequence seq;
8598 EXPECT_CALL(*send_algorithm_, CanSend(_))
8599 .Times(9 * 2)
8600 .WillRepeatedly(Return(true));
8601 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(Return(false));
8602 }
8603 // Expect them retransmitted in cyclic order (foo, bar, test, foo, bar...).
8604 QuicPacketCount sent_count = 0;
fayangcff885a2019-10-22 07:39:04 -07008605 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _))
QUICHE teama6ef0a62019-03-07 20:34:33 -05008606 .WillRepeatedly(Invoke([this, &sent_count](const SerializedPacket&,
QUICHE teama6ef0a62019-03-07 20:34:33 -05008607 TransmissionType, QuicTime) {
8608 ASSERT_EQ(1u, writer_->stream_frames().size());
fayang58f71072019-11-05 08:47:02 -08008609 if (connection_.version().CanSendCoalescedPackets()) {
8610 // There is a delay of sending coalesced packet, so (6, 0, 3, 6,
8611 // 0...).
8612 EXPECT_EQ(3 * ((sent_count + 2) % 3),
8613 writer_->stream_frames()[0]->offset);
8614 } else {
8615 // Identify the frames by stream offset (0, 3, 6, 0, 3...).
8616 EXPECT_EQ(3 * (sent_count % 3), writer_->stream_frames()[0]->offset);
8617 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008618 sent_count++;
8619 }));
8620 EXPECT_CALL(*send_algorithm_, ShouldSendProbingPacket())
8621 .WillRepeatedly(Return(true));
QUICHE teamb8343252019-04-29 13:58:01 -07008622 EXPECT_CALL(visitor_, SendProbingData()).WillRepeatedly([this] {
8623 return connection_.sent_packet_manager().MaybeRetransmitOldestPacket(
8624 PROBING_RETRANSMISSION);
8625 });
QUICHE teama6ef0a62019-03-07 20:34:33 -05008626
8627 connection_.SendProbingRetransmissions();
8628
8629 // Ensure that the in-flight has increased.
8630 const QuicByteCount new_bytes_in_flight =
8631 connection_.sent_packet_manager().GetBytesInFlight();
8632 EXPECT_GT(new_bytes_in_flight, old_bytes_in_flight);
8633}
8634
8635// Ensure that SendProbingRetransmissions() does not retransmit anything when
8636// there are no outstanding packets.
8637TEST_P(QuicConnectionTest,
8638 SendProbingRetransmissionsFailsWhenNothingToRetransmit) {
8639 ASSERT_TRUE(connection_.sent_packet_manager().unacked_packets().empty());
8640
8641 MockQuicConnectionDebugVisitor debug_visitor;
8642 connection_.set_debug_visitor(&debug_visitor);
fayangcff885a2019-10-22 07:39:04 -07008643 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008644 EXPECT_CALL(*send_algorithm_, ShouldSendProbingPacket())
8645 .WillRepeatedly(Return(true));
QUICHE teamb8343252019-04-29 13:58:01 -07008646 EXPECT_CALL(visitor_, SendProbingData()).WillRepeatedly([this] {
8647 return connection_.sent_packet_manager().MaybeRetransmitOldestPacket(
8648 PROBING_RETRANSMISSION);
8649 });
QUICHE teama6ef0a62019-03-07 20:34:33 -05008650
8651 connection_.SendProbingRetransmissions();
8652}
8653
8654TEST_P(QuicConnectionTest, PingAfterLastRetransmittablePacketAcked) {
8655 const QuicTime::Delta retransmittable_on_wire_timeout =
8656 QuicTime::Delta::FromMilliseconds(50);
zhongyi79ace162019-10-21 15:57:09 -07008657 connection_.set_initial_retransmittable_on_wire_timeout(
QUICHE teama6ef0a62019-03-07 20:34:33 -05008658 retransmittable_on_wire_timeout);
8659
8660 EXPECT_TRUE(connection_.connected());
8661 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8662 .WillRepeatedly(Return(true));
8663
8664 const char data[] = "data";
8665 size_t data_size = strlen(data);
8666 QuicStreamOffset offset = 0;
8667
8668 // Advance 5ms, send a retransmittable packet to the peer.
8669 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8670 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8671 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8672 offset += data_size;
8673 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8674 // The ping alarm is set for the ping timeout, not the shorter
8675 // retransmittable_on_wire_timeout.
8676 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8677 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
zhongyieef848f2019-10-18 07:09:37 -07008678 EXPECT_EQ(ping_delay,
8679 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008680
8681 // Advance 5ms, send a second retransmittable packet to the peer.
8682 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8683 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8684 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8685 offset += data_size;
8686 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8687
8688 // Now receive an ACK of the first packet. This should not set the
8689 // retransmittable-on-wire alarm since packet 2 is still on the wire.
8690 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8691 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8692 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8693 QuicAckFrame frame =
8694 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8695 ProcessAckPacket(&frame);
8696 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8697 // The ping alarm is set for the ping timeout, not the shorter
8698 // retransmittable_on_wire_timeout.
8699 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8700 // The ping alarm has a 1 second granularity, and the clock has been advanced
8701 // 10ms since it was originally set.
zhongyieef848f2019-10-18 07:09:37 -07008702 EXPECT_EQ(ping_delay - QuicTime::Delta::FromMilliseconds(10),
8703 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008704
8705 // Now receive an ACK of the second packet. This should set the
8706 // retransmittable-on-wire alarm now that no retransmittable packets are on
8707 // the wire.
8708 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8709 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8710 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8711 ProcessAckPacket(&frame);
8712 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07008713 EXPECT_EQ(retransmittable_on_wire_timeout,
8714 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008715
8716 // Now receive a duplicate ACK of the second packet. This should not update
8717 // the ping alarm.
8718 QuicTime prev_deadline = connection_.GetPingAlarm()->deadline();
8719 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8720 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8721 ProcessAckPacket(&frame);
8722 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8723 EXPECT_EQ(prev_deadline, connection_.GetPingAlarm()->deadline());
8724
8725 // Now receive a non-ACK packet. This should not update the ping alarm.
8726 prev_deadline = connection_.GetPingAlarm()->deadline();
8727 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8728 ProcessPacket(4);
8729 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8730 EXPECT_EQ(prev_deadline, connection_.GetPingAlarm()->deadline());
8731
8732 // Simulate the alarm firing and check that a PING is sent.
8733 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8734 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
8735 }));
8736 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07008737 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05008738 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07008739 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008740 } else {
nharper55fa6132019-05-07 19:37:21 -07008741 EXPECT_EQ(padding_frame_count + 3u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008742 }
8743 ASSERT_EQ(1u, writer_->ping_frames().size());
8744}
8745
8746TEST_P(QuicConnectionTest, NoPingIfRetransmittablePacketSent) {
8747 const QuicTime::Delta retransmittable_on_wire_timeout =
8748 QuicTime::Delta::FromMilliseconds(50);
zhongyi79ace162019-10-21 15:57:09 -07008749 connection_.set_initial_retransmittable_on_wire_timeout(
QUICHE teama6ef0a62019-03-07 20:34:33 -05008750 retransmittable_on_wire_timeout);
8751
8752 EXPECT_TRUE(connection_.connected());
8753 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8754 .WillRepeatedly(Return(true));
8755
8756 const char data[] = "data";
8757 size_t data_size = strlen(data);
8758 QuicStreamOffset offset = 0;
8759
8760 // Advance 5ms, send a retransmittable packet to the peer.
8761 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8762 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8763 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8764 offset += data_size;
8765 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8766 // The ping alarm is set for the ping timeout, not the shorter
8767 // retransmittable_on_wire_timeout.
8768 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8769 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
zhongyieef848f2019-10-18 07:09:37 -07008770 EXPECT_EQ(ping_delay,
8771 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008772
8773 // Now receive an ACK of the first packet. This should set the
8774 // retransmittable-on-wire alarm now that no retransmittable packets are on
8775 // the wire.
8776 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8777 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8778 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8779 QuicAckFrame frame =
8780 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8781 ProcessAckPacket(&frame);
8782 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07008783 EXPECT_EQ(retransmittable_on_wire_timeout,
8784 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008785
8786 // Before the alarm fires, send another retransmittable packet. This should
8787 // cancel the retransmittable-on-wire alarm since now there's a
8788 // retransmittable packet on the wire.
8789 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8790 offset += data_size;
8791 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8792
8793 // Now receive an ACK of the second packet. This should set the
8794 // retransmittable-on-wire alarm now that no retransmittable packets are on
8795 // the wire.
8796 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8797 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8798 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8799 ProcessAckPacket(&frame);
8800 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07008801 EXPECT_EQ(retransmittable_on_wire_timeout,
8802 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008803
8804 // Simulate the alarm firing and check that a PING is sent.
8805 writer_->Reset();
8806 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8807 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
8808 }));
8809 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07008810 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05008811 if (GetParam().no_stop_waiting) {
fayang8a27b0f2019-11-04 11:27:40 -08008812 // Do not ACK acks.
8813 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008814 } else {
nharper55fa6132019-05-07 19:37:21 -07008815 EXPECT_EQ(padding_frame_count + 3u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008816 }
8817 ASSERT_EQ(1u, writer_->ping_frames().size());
8818}
8819
zhongyi79ace162019-10-21 15:57:09 -07008820// When there is no stream data received but are open streams, send the
8821// first few consecutive pings with aggressive retransmittable-on-wire
8822// timeout. Exponentially back off the retransmittable-on-wire ping timeout
8823// afterwards until it exceeds the default ping timeout.
8824TEST_P(QuicConnectionTest, BackOffRetransmittableOnWireTimeout) {
8825 int max_aggressive_retransmittable_on_wire_ping_count = 5;
8826 SetQuicFlag(FLAGS_quic_max_aggressive_retransmittable_on_wire_ping_count,
8827 max_aggressive_retransmittable_on_wire_ping_count);
8828 const QuicTime::Delta initial_retransmittable_on_wire_timeout =
8829 QuicTime::Delta::FromMilliseconds(200);
8830 connection_.set_initial_retransmittable_on_wire_timeout(
8831 initial_retransmittable_on_wire_timeout);
8832
8833 EXPECT_TRUE(connection_.connected());
8834 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8835 .WillRepeatedly(Return(true));
8836
8837 const char data[] = "data";
8838 // Advance 5ms, send a retransmittable data packet to the peer.
8839 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8840 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8841 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
8842 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8843 // The ping alarm is set for the ping timeout, not the shorter
8844 // retransmittable_on_wire_timeout.
8845 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8846 EXPECT_EQ(connection_.ping_timeout(),
8847 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8848
8849 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
8850 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
8851 .Times(AnyNumber());
8852
8853 // Verify that the first few consecutive retransmittable on wire pings are
8854 // sent with aggressive timeout.
8855 for (int i = 0; i <= max_aggressive_retransmittable_on_wire_ping_count; i++) {
8856 // Receive an ACK of the previous packet. This should set the ping alarm
8857 // with the initial retransmittable-on-wire timeout.
8858 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8859 QuicPacketNumber ack_num = creator_->packet_number();
8860 QuicAckFrame frame = InitAckFrame(
8861 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8862 ProcessAckPacket(&frame);
8863 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8864 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8865 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8866 // Simulate the alarm firing and check that a PING is sent.
8867 writer_->Reset();
8868 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8869 SendPing();
8870 }));
8871 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8872 connection_.GetPingAlarm()->Fire();
8873 }
8874
8875 QuicTime::Delta retransmittable_on_wire_timeout =
8876 initial_retransmittable_on_wire_timeout;
8877
8878 // Verify subsequent pings are sent with timeout that is exponentially backed
8879 // off.
8880 while (retransmittable_on_wire_timeout * 2 < connection_.ping_timeout()) {
8881 // Receive an ACK for the previous PING. This should set the
8882 // ping alarm with backed off retransmittable-on-wire timeout.
8883 retransmittable_on_wire_timeout = retransmittable_on_wire_timeout * 2;
8884 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8885 QuicPacketNumber ack_num = creator_->packet_number();
8886 QuicAckFrame frame = InitAckFrame(
8887 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8888 ProcessAckPacket(&frame);
8889 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8890 EXPECT_EQ(retransmittable_on_wire_timeout,
8891 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8892
8893 // Simulate the alarm firing and check that a PING is sent.
8894 writer_->Reset();
8895 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8896 SendPing();
8897 }));
8898 clock_.AdvanceTime(retransmittable_on_wire_timeout);
8899 connection_.GetPingAlarm()->Fire();
8900 }
8901
8902 // The ping alarm is set with default ping timeout.
8903 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8904 EXPECT_EQ(connection_.ping_timeout(),
8905 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8906
8907 // Receive an ACK for the previous PING. The ping alarm is set with an
8908 // earlier deadline.
8909 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8910 QuicPacketNumber ack_num = creator_->packet_number();
8911 QuicAckFrame frame = InitAckFrame(
8912 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8913 ProcessAckPacket(&frame);
8914 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8915 EXPECT_EQ(connection_.ping_timeout() - QuicTime::Delta::FromMilliseconds(5),
8916 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8917}
8918
8919// This test verify that the count of consecutive aggressive pings is reset
8920// when new data is received. And it also verifies the connection resets
8921// the exponential back-off of the retransmittable-on-wire ping timeout
8922// after receiving new stream data.
8923TEST_P(QuicConnectionTest, ResetBackOffRetransmitableOnWireTimeout) {
8924 int max_aggressive_retransmittable_on_wire_ping_count = 3;
8925 SetQuicFlag(FLAGS_quic_max_aggressive_retransmittable_on_wire_ping_count, 3);
8926 const QuicTime::Delta initial_retransmittable_on_wire_timeout =
8927 QuicTime::Delta::FromMilliseconds(200);
8928 connection_.set_initial_retransmittable_on_wire_timeout(
8929 initial_retransmittable_on_wire_timeout);
8930
8931 EXPECT_TRUE(connection_.connected());
8932 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8933 .WillRepeatedly(Return(true));
8934 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
8935 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
8936 .Times(AnyNumber());
8937
8938 const char data[] = "data";
8939 // Advance 5ms, send a retransmittable data packet to the peer.
8940 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8941 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8942 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
8943 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8944 // The ping alarm is set for the ping timeout, not the shorter
8945 // retransmittable_on_wire_timeout.
8946 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8947 EXPECT_EQ(connection_.ping_timeout(),
8948 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8949
8950 // Receive an ACK of the first packet. This should set the ping alarm with
8951 // initial retransmittable-on-wire timeout since there is no retransmittable
8952 // packet on the wire.
8953 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8954 QuicAckFrame frame =
8955 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8956 ProcessAckPacket(&frame);
8957 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8958 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8959 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8960
8961 // Simulate the alarm firing and check that a PING is sent.
8962 writer_->Reset();
8963 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
8964 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8965 connection_.GetPingAlarm()->Fire();
8966
8967 // Receive an ACK for the previous PING. Ping alarm will be set with
8968 // aggressive timeout.
8969 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8970 QuicPacketNumber ack_num = creator_->packet_number();
8971 frame = InitAckFrame(
8972 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8973 ProcessAckPacket(&frame);
8974 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8975 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8976 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8977
8978 // Process a data packet.
8979 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
8980 ProcessDataPacket(peer_creator_.packet_number() + 1);
8981 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_,
8982 peer_creator_.packet_number() + 1);
8983 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8984 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8985
8986 // Verify the count of consecutive aggressive pings is reset.
8987 for (int i = 0; i < max_aggressive_retransmittable_on_wire_ping_count; i++) {
8988 // Receive an ACK of the previous packet. This should set the ping alarm
8989 // with the initial retransmittable-on-wire timeout.
8990 QuicPacketNumber ack_num = creator_->packet_number();
8991 QuicAckFrame frame = InitAckFrame(
8992 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8993 ProcessAckPacket(&frame);
8994 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8995 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8996 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8997 // Simulate the alarm firing and check that a PING is sent.
8998 writer_->Reset();
8999 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
9000 SendPing();
9001 }));
9002 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
9003 connection_.GetPingAlarm()->Fire();
9004 // Advance 5ms to receive next packet.
9005 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
9006 }
9007
9008 // Receive another ACK for the previous PING. This should set the
9009 // ping alarm with backed off retransmittable-on-wire timeout.
9010 ack_num = creator_->packet_number();
9011 frame = InitAckFrame(
9012 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
9013 ProcessAckPacket(&frame);
9014 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
9015 EXPECT_EQ(initial_retransmittable_on_wire_timeout * 2,
9016 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
9017
9018 writer_->Reset();
9019 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
9020 clock_.AdvanceTime(2 * initial_retransmittable_on_wire_timeout);
9021 connection_.GetPingAlarm()->Fire();
9022
9023 // Process another data packet and a new ACK packet. The ping alarm is set
9024 // with aggressive ping timeout again.
9025 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
9026 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
9027 ProcessDataPacket(peer_creator_.packet_number() + 1);
9028 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_,
9029 peer_creator_.packet_number() + 1);
9030 ack_num = creator_->packet_number();
9031 frame = InitAckFrame(
9032 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
9033 ProcessAckPacket(&frame);
9034 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
9035 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
9036 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
9037}
9038
QUICHE teama6ef0a62019-03-07 20:34:33 -05009039TEST_P(QuicConnectionTest, ValidStatelessResetToken) {
9040 const QuicUint128 kTestToken = 1010101;
9041 const QuicUint128 kWrongTestToken = 1010100;
9042 QuicConfig config;
9043 // No token has been received.
9044 EXPECT_FALSE(connection_.IsValidStatelessResetToken(kTestToken));
9045
9046 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(2);
9047 // Token is different from received token.
9048 QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestToken);
9049 connection_.SetFromConfig(config);
9050 EXPECT_FALSE(connection_.IsValidStatelessResetToken(kWrongTestToken));
9051
9052 QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestToken);
9053 connection_.SetFromConfig(config);
9054 EXPECT_TRUE(connection_.IsValidStatelessResetToken(kTestToken));
9055}
9056
9057TEST_P(QuicConnectionTest, WriteBlockedWithInvalidAck) {
9058 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayange62e63c2019-12-04 07:16:25 -08009059 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05009060 BlockOnNextWrite();
fayange62e63c2019-12-04 07:16:25 -08009061 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05009062 connection_.SendStreamDataWithString(5, "foo", 0, FIN);
9063 // This causes connection to be closed because packet 1 has not been sent yet.
9064 QuicAckFrame frame = InitAckFrame(1);
fayange62e63c2019-12-04 07:16:25 -08009065 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05009066 ProcessAckPacket(1, &frame);
fayange62e63c2019-12-04 07:16:25 -08009067 EXPECT_EQ(0, connection_close_frame_count_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05009068}
9069
9070TEST_P(QuicConnectionTest, SendMessage) {
fayangc31c9952019-06-05 13:54:48 -07009071 if (!VersionSupportsMessageFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05009072 return;
9073 }
dschinazied459c02020-05-07 16:12:23 -07009074 if (connection_.version().UsesTls()) {
9075 QuicConfig config;
9076 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
9077 &config, kMaxAcceptedDatagramFrameSize);
9078 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9079 connection_.SetFromConfig(config);
9080 }
ianswettb239f862019-04-05 09:15:06 -07009081 std::string message(connection_.GetCurrentLargestMessagePayload() * 2, 'a');
dmcardlecf0bfcf2019-12-13 08:08:21 -08009082 quiche::QuicheStringPiece message_data(message);
QUICHE teama6ef0a62019-03-07 20:34:33 -05009083 QuicMemSliceStorage storage(nullptr, 0, nullptr, 0);
9084 {
fayanga4b37b22019-06-18 13:37:47 -07009085 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05009086 connection_.SendStreamData3();
9087 // Send a message which cannot fit into current open packet, and 2 packets
9088 // get sent, one contains stream frame, and the other only contains the
9089 // message frame.
9090 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
QUICHE team350e9e62019-11-19 13:16:24 -08009091 EXPECT_EQ(MESSAGE_STATUS_SUCCESS,
9092 connection_.SendMessage(
9093 1,
9094 MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(),
dmcardlecf0bfcf2019-12-13 08:08:21 -08009095 quiche::QuicheStringPiece(
QUICHE team350e9e62019-11-19 13:16:24 -08009096 message_data.data(),
9097 connection_.GetCurrentLargestMessagePayload()),
9098 &storage),
9099 false));
QUICHE teama6ef0a62019-03-07 20:34:33 -05009100 }
9101 // Fail to send a message if connection is congestion control blocked.
9102 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(Return(false));
QUICHE team350e9e62019-11-19 13:16:24 -08009103 EXPECT_EQ(MESSAGE_STATUS_BLOCKED,
9104 connection_.SendMessage(
9105 2,
9106 MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(),
9107 "message", &storage),
9108 false));
QUICHE teama6ef0a62019-03-07 20:34:33 -05009109
9110 // Always fail to send a message which cannot fit into one packet.
9111 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE team350e9e62019-11-19 13:16:24 -08009112 EXPECT_EQ(MESSAGE_STATUS_TOO_LARGE,
9113 connection_.SendMessage(
9114 3,
9115 MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(),
dmcardlecf0bfcf2019-12-13 08:08:21 -08009116 quiche::QuicheStringPiece(
QUICHE team350e9e62019-11-19 13:16:24 -08009117 message_data.data(),
9118 connection_.GetCurrentLargestMessagePayload() + 1),
9119 &storage),
9120 false));
QUICHE teama6ef0a62019-03-07 20:34:33 -05009121}
9122
dschinazied459c02020-05-07 16:12:23 -07009123TEST_P(QuicConnectionTest, GetCurrentLargestMessagePayload) {
9124 if (!connection_.version().SupportsMessageFrames()) {
9125 return;
9126 }
9127 // Force use of this encrypter to simplify test expectations by making sure
9128 // that the encryption overhead is constant across versions.
9129 connection_.SetEncrypter(ENCRYPTION_INITIAL,
9130 std::make_unique<TaggingEncrypter>(0x00));
9131 QuicPacketLength expected_largest_payload = 1319;
9132 if (connection_.version().SendsVariableLengthPacketNumberInLongHeader()) {
9133 expected_largest_payload += 3;
9134 }
9135 if (connection_.version().HasLongHeaderLengths()) {
9136 expected_largest_payload -= 2;
9137 }
9138 if (connection_.version().HasLengthPrefixedConnectionIds()) {
9139 expected_largest_payload -= 1;
9140 }
9141 if (connection_.version().UsesTls()) {
9142 // QUIC+TLS disallows DATAGRAM/MESSAGE frames before the handshake.
9143 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), 0);
9144 QuicConfig config;
9145 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
9146 &config, kMaxAcceptedDatagramFrameSize);
9147 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9148 connection_.SetFromConfig(config);
9149 // Verify the value post-handshake.
9150 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(),
9151 expected_largest_payload);
9152 } else {
9153 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(),
9154 expected_largest_payload);
9155 }
9156}
9157
9158TEST_P(QuicConnectionTest, GetGuaranteedLargestMessagePayload) {
9159 if (!connection_.version().SupportsMessageFrames()) {
9160 return;
9161 }
9162 // Force use of this encrypter to simplify test expectations by making sure
9163 // that the encryption overhead is constant across versions.
9164 connection_.SetEncrypter(ENCRYPTION_INITIAL,
9165 std::make_unique<TaggingEncrypter>(0x00));
9166 QuicPacketLength expected_largest_payload = 1319;
9167 if (connection_.version().HasLongHeaderLengths()) {
9168 expected_largest_payload -= 2;
9169 }
9170 if (connection_.version().HasLengthPrefixedConnectionIds()) {
9171 expected_largest_payload -= 1;
9172 }
9173 if (connection_.version().UsesTls()) {
9174 // QUIC+TLS disallows DATAGRAM/MESSAGE frames before the handshake.
9175 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(), 0);
9176 QuicConfig config;
9177 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
9178 &config, kMaxAcceptedDatagramFrameSize);
9179 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9180 connection_.SetFromConfig(config);
9181 // Verify the value post-handshake.
9182 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(),
9183 expected_largest_payload);
9184 } else {
9185 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(),
9186 expected_largest_payload);
9187 }
9188}
9189
9190TEST_P(QuicConnectionTest, LimitedLargestMessagePayload) {
9191 if (!connection_.version().SupportsMessageFrames() ||
9192 !connection_.version().UsesTls()) {
9193 return;
9194 }
9195 constexpr QuicPacketLength kFrameSizeLimit = 1000;
9196 constexpr QuicPacketLength kPayloadSizeLimit =
9197 kFrameSizeLimit - kQuicFrameTypeSize;
9198 // QUIC+TLS disallows DATAGRAM/MESSAGE frames before the handshake.
9199 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), 0);
9200 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(), 0);
9201 QuicConfig config;
9202 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(&config, kFrameSizeLimit);
9203 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9204 connection_.SetFromConfig(config);
9205 // Verify the value post-handshake.
9206 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), kPayloadSizeLimit);
9207 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(),
9208 kPayloadSizeLimit);
9209}
9210
QUICHE teama6ef0a62019-03-07 20:34:33 -05009211// Test to check that the path challenge/path response logic works
9212// correctly. This test is only for version-99
9213TEST_P(QuicConnectionTest, PathChallengeResponse) {
fkastenholz305e1732019-06-18 05:01:22 -07009214 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05009215 return;
9216 }
9217 // First check if we can probe from server to client and back
9218 set_perspective(Perspective::IS_SERVER);
9219 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
9220
9221 // Create and send the probe request (PATH_CHALLENGE frame).
9222 // SendConnectivityProbingPacket ends up calling
9223 // TestPacketWriter::WritePacket() which in turns receives and parses the
9224 // packet by calling framer_.ProcessPacket() -- which in turn calls
9225 // SimpleQuicFramer::OnPathChallengeFrame(). SimpleQuicFramer saves
9226 // the packet in writer_->path_challenge_frames()
9227 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9228 connection_.SendConnectivityProbingPacket(writer_.get(),
9229 connection_.peer_address());
9230 // Save the random contents of the challenge for later comparison to the
9231 // response.
nharper55fa6132019-05-07 19:37:21 -07009232 ASSERT_GE(writer_->path_challenge_frames().size(), 1u);
QUICHE teama6ef0a62019-03-07 20:34:33 -05009233 QuicPathFrameBuffer challenge_data =
9234 writer_->path_challenge_frames().front().data_buffer;
9235
9236 // Normally, QuicConnection::OnPathChallengeFrame and OnPaddingFrame would be
9237 // called and it will perform actions to ensure that the rest of the protocol
9238 // is performed (specifically, call UpdatePacketContent to say that this is a
9239 // path challenge so that when QuicConnection::OnPacketComplete is called
9240 // (again, out of the framer), the response is generated). Simulate those
9241 // calls so that the right internal state is set up for generating
9242 // the response.
9243 EXPECT_TRUE(connection_.OnPathChallengeFrame(
9244 writer_->path_challenge_frames().front()));
9245 EXPECT_TRUE(connection_.OnPaddingFrame(writer_->padding_frames().front()));
9246 // Cause the response to be created and sent. Result is that the response
9247 // should be stashed in writer's path_response_frames.
9248 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9249 connection_.SendConnectivityProbingResponsePacket(connection_.peer_address());
9250
9251 // The final check is to ensure that the random data in the response matches
9252 // the random data from the challenge.
9253 EXPECT_EQ(0, memcmp(&challenge_data,
9254 &(writer_->path_response_frames().front().data_buffer),
9255 sizeof(challenge_data)));
9256}
9257
9258// Regression test for b/110259444
9259TEST_P(QuicConnectionTest, DoNotScheduleSpuriousAckAlarm) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05009260 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9261 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
9262 writer_->SetWriteBlocked();
9263
9264 ProcessPacket(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05009265 // Verify ack alarm is set.
fayang9adfb532020-06-04 06:58:45 -07009266 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05009267 // Fire the ack alarm, verify no packet is sent because the writer is blocked.
9268 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9269 connection_.GetAckAlarm()->Fire();
9270
9271 writer_->SetWritable();
9272 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9273 ProcessPacket(2);
9274 // Verify ack alarm is not set.
fayang9adfb532020-06-04 06:58:45 -07009275 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05009276}
9277
9278TEST_P(QuicConnectionTest, DisablePacingOffloadConnectionOptions) {
9279 EXPECT_FALSE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
9280 writer_->set_supports_release_time(true);
9281 QuicConfig config;
9282 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9283 connection_.SetFromConfig(config);
9284 EXPECT_TRUE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
9285
9286 QuicTagVector connection_options;
9287 connection_options.push_back(kNPCO);
9288 config.SetConnectionOptionsToSend(connection_options);
9289 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9290 connection_.SetFromConfig(config);
9291 // Verify pacing offload is disabled.
9292 EXPECT_FALSE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
9293}
9294
9295// Regression test for b/110259444
9296// Get a path response without having issued a path challenge...
9297TEST_P(QuicConnectionTest, OrphanPathResponse) {
9298 QuicPathFrameBuffer data = {{0, 1, 2, 3, 4, 5, 6, 7}};
9299
9300 QuicPathResponseFrame frame(99, data);
9301 EXPECT_TRUE(connection_.OnPathResponseFrame(frame));
9302 // If PATH_RESPONSE was accepted (payload matches the payload saved
9303 // in QuicConnection::transmitted_connectivity_probe_payload_) then
9304 // current_packet_content_ would be set to FIRST_FRAME_IS_PING.
9305 // Since this PATH_RESPONSE does not match, current_packet_content_
9306 // must not be FIRST_FRAME_IS_PING.
9307 EXPECT_NE(QuicConnection::FIRST_FRAME_IS_PING,
9308 QuicConnectionPeer::GetCurrentPacketContent(&connection_));
9309}
9310
9311// Regression test for b/120791670
9312TEST_P(QuicConnectionTest, StopProcessingGQuicPacketInIetfQuicConnection) {
9313 // This test mimics a problematic scenario where an IETF QUIC connection
9314 // receives a Google QUIC packet and continue processing it using Google QUIC
9315 // wire format.
fayangd4291e42019-05-30 10:31:21 -07009316 if (!VersionHasIetfInvariantHeader(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05009317 return;
9318 }
9319 set_perspective(Perspective::IS_SERVER);
nharper46833c32019-05-15 21:33:05 -07009320 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07009321 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
9322 } else {
nharper46833c32019-05-15 21:33:05 -07009323 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
9324 }
wub8a5dafa2020-05-13 12:30:17 -07009325 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
9326 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05009327
9328 // Let connection process a Google QUIC packet.
9329 peer_framer_.set_version_for_tests(
9330 ParsedQuicVersion(PROTOCOL_QUIC_CRYPTO, QUIC_VERSION_43));
QUICHE team8c1daa22019-03-13 08:33:41 -07009331 std::unique_ptr<QuicPacket> packet(
QUICHE team6987b4a2019-03-15 16:23:04 -07009332 ConstructDataPacket(2, !kHasStopWaiting, ENCRYPTION_INITIAL));
dschinazi66dea072019-04-09 11:41:06 -07009333 char buffer[kMaxOutgoingPacketSize];
9334 size_t encrypted_length =
9335 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(2),
9336 *packet, buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05009337 // Make sure no stream frame is processed.
9338 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(0);
9339 connection_.ProcessUdpPacket(
9340 kSelfAddress, kPeerAddress,
9341 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
9342
9343 EXPECT_EQ(2u, connection_.GetStats().packets_received);
9344 EXPECT_EQ(1u, connection_.GetStats().packets_processed);
9345}
9346
9347TEST_P(QuicConnectionTest, AcceptPacketNumberZero) {
fkastenholz305e1732019-06-18 05:01:22 -07009348 if (!VersionHasIetfQuicFrames(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05009349 return;
9350 }
9351 // Set first_sending_packet_number to be 0 to allow successfully processing
9352 // acks which ack packet number 0.
9353 QuicFramerPeer::SetFirstSendingPacketNumber(writer_->framer()->framer(), 0);
9354 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9355
9356 ProcessPacket(0);
fayangc31c9952019-06-05 13:54:48 -07009357 EXPECT_EQ(QuicPacketNumber(0), LargestAcked(connection_.ack_frame()));
9358 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05009359
9360 ProcessPacket(1);
fayangc31c9952019-06-05 13:54:48 -07009361 EXPECT_EQ(QuicPacketNumber(1), LargestAcked(connection_.ack_frame()));
9362 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05009363
9364 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07009365 EXPECT_EQ(QuicPacketNumber(2), LargestAcked(connection_.ack_frame()));
9366 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05009367}
9368
QUICHE teamcd098022019-03-22 18:49:55 -07009369TEST_P(QuicConnectionTest, MultiplePacketNumberSpacesBasicSending) {
9370 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
9371 return;
9372 }
9373 use_tagging_decrypter();
9374 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07009375 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teamcd098022019-03-22 18:49:55 -07009376
9377 connection_.SendCryptoStreamData();
9378 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9379 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
9380 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
9381 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9382 QuicAckFrame frame1 = InitAckFrame(1);
9383 // Received ACK for packet 1.
9384 ProcessFramePacketAtLevel(30, QuicFrame(&frame1), ENCRYPTION_INITIAL);
9385
9386 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(4);
9387 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
9388 NO_FIN);
9389 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 4,
9390 NO_FIN);
9391 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
9392 8, NO_FIN);
9393 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
9394 12, FIN);
9395 // Received ACK for packets 2, 4, 5.
9396 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
9397 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
9398 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9399 QuicAckFrame frame2 =
9400 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)},
9401 {QuicPacketNumber(4), QuicPacketNumber(6)}});
9402 // Make sure although the same packet number is used, but they are in
9403 // different packet number spaces.
9404 ProcessFramePacketAtLevel(30, QuicFrame(&frame2), ENCRYPTION_FORWARD_SECURE);
9405}
9406
9407TEST_P(QuicConnectionTest, PeerAcksPacketsInWrongPacketNumberSpace) {
9408 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
9409 return;
9410 }
9411 use_tagging_decrypter();
9412 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07009413 std::make_unique<TaggingEncrypter>(0x01));
rch39c88ab2019-10-16 19:24:40 -07009414 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
9415 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teamcd098022019-03-22 18:49:55 -07009416
9417 connection_.SendCryptoStreamData();
9418 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9419 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
9420 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
9421 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9422 QuicAckFrame frame1 = InitAckFrame(1);
9423 // Received ACK for packet 1.
9424 ProcessFramePacketAtLevel(30, QuicFrame(&frame1), ENCRYPTION_INITIAL);
9425
9426 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
9427 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
9428 NO_FIN);
9429 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 4,
9430 NO_FIN);
9431
9432 // Received ACK for packets 2 and 3 in wrong packet number space.
9433 QuicAckFrame invalid_ack =
9434 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(4)}});
fkastenholz5d880a92019-06-21 09:01:56 -07009435 EXPECT_CALL(visitor_,
9436 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07009437 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teamcd098022019-03-22 18:49:55 -07009438 ProcessFramePacketAtLevel(300, QuicFrame(&invalid_ack), ENCRYPTION_INITIAL);
fkastenholz5d880a92019-06-21 09:01:56 -07009439 TestConnectionCloseQuicErrorCode(QUIC_INVALID_ACK_DATA);
QUICHE teamcd098022019-03-22 18:49:55 -07009440}
9441
9442TEST_P(QuicConnectionTest, MultiplePacketNumberSpacesBasicReceiving) {
9443 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
9444 return;
9445 }
9446 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
nharper46833c32019-05-15 21:33:05 -07009447 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9448 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9449 }
QUICHE teamcd098022019-03-22 18:49:55 -07009450 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
9451 use_tagging_decrypter();
9452 // Receives packet 1000 in initial data.
nharper46833c32019-05-15 21:33:05 -07009453 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
fayang9adfb532020-06-04 06:58:45 -07009454 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teamcd098022019-03-22 18:49:55 -07009455 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07009456 std::make_unique<TaggingEncrypter>(0x02));
zhongyi546cc452019-04-12 15:27:49 -07009457 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07009458 std::make_unique<StrictTaggingDecrypter>(0x02));
QUICHE teamcd098022019-03-22 18:49:55 -07009459 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07009460 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teamcd098022019-03-22 18:49:55 -07009461 // Receives packet 1000 in application data.
9462 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
fayang9adfb532020-06-04 06:58:45 -07009463 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teamcd098022019-03-22 18:49:55 -07009464 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
9465 NO_FIN);
9466 // Verify application data ACK gets bundled with outgoing data.
9467 EXPECT_EQ(2u, writer_->frame_count());
9468 // Make sure ACK alarm is still set because initial data is not ACKed.
fayang9adfb532020-06-04 06:58:45 -07009469 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teamcd098022019-03-22 18:49:55 -07009470 // Receive packet 1001 in application data.
9471 ProcessDataPacketAtLevel(1001, false, ENCRYPTION_ZERO_RTT);
9472 clock_.AdvanceTime(DefaultRetransmissionTime());
9473 // Simulates ACK alarm fires and verify two ACKs are flushed.
9474 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
9475 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07009476 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teamcd098022019-03-22 18:49:55 -07009477 connection_.GetAckAlarm()->Fire();
fayang9adfb532020-06-04 06:58:45 -07009478 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teamcd098022019-03-22 18:49:55 -07009479 // Receives more packets in application data.
9480 ProcessDataPacketAtLevel(1002, false, ENCRYPTION_ZERO_RTT);
fayang9adfb532020-06-04 06:58:45 -07009481 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teamcd098022019-03-22 18:49:55 -07009482
9483 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07009484 std::make_unique<TaggingEncrypter>(0x02));
zhongyi546cc452019-04-12 15:27:49 -07009485 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07009486 std::make_unique<StrictTaggingDecrypter>(0x02));
QUICHE teamcd098022019-03-22 18:49:55 -07009487 // Verify zero rtt and forward secure packets get acked in the same packet.
9488 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
nharper2c9f02a2019-05-08 10:25:50 -07009489 ProcessDataPacket(1003);
fayang9adfb532020-06-04 06:58:45 -07009490 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teamcd098022019-03-22 18:49:55 -07009491}
9492
QUICHE team552f71f2019-03-23 15:37:59 -07009493TEST_P(QuicConnectionTest, CancelAckAlarmOnWriteBlocked) {
9494 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
9495 return;
9496 }
9497 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
nharper46833c32019-05-15 21:33:05 -07009498 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9499 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9500 }
QUICHE team552f71f2019-03-23 15:37:59 -07009501 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
9502 use_tagging_decrypter();
9503 // Receives packet 1000 in initial data.
nharper46833c32019-05-15 21:33:05 -07009504 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
fayang9adfb532020-06-04 06:58:45 -07009505 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE team552f71f2019-03-23 15:37:59 -07009506 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07009507 std::make_unique<TaggingEncrypter>(0x02));
zhongyi546cc452019-04-12 15:27:49 -07009508 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07009509 std::make_unique<StrictTaggingDecrypter>(0x02));
QUICHE team552f71f2019-03-23 15:37:59 -07009510 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07009511 std::make_unique<TaggingEncrypter>(0x02));
QUICHE team552f71f2019-03-23 15:37:59 -07009512 // Receives packet 1000 in application data.
9513 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
fayang9adfb532020-06-04 06:58:45 -07009514 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE team552f71f2019-03-23 15:37:59 -07009515
9516 writer_->SetWriteBlocked();
9517 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AnyNumber());
9518 // Simulates ACK alarm fires and verify no ACK is flushed because of write
9519 // blocked.
9520 clock_.AdvanceTime(DefaultDelayedAckTime());
9521 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9522 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07009523 std::make_unique<TaggingEncrypter>(0x02));
QUICHE team552f71f2019-03-23 15:37:59 -07009524 connection_.GetAckAlarm()->Fire();
9525 // Verify ACK alarm is not set.
fayang9adfb532020-06-04 06:58:45 -07009526 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE team552f71f2019-03-23 15:37:59 -07009527
9528 writer_->SetWritable();
9529 // Verify 2 ACKs are sent when connection gets unblocked.
9530 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
9531 connection_.OnCanWrite();
fayang9adfb532020-06-04 06:58:45 -07009532 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE team552f71f2019-03-23 15:37:59 -07009533}
9534
dschinazi346b7ce2019-06-05 01:38:18 -07009535// Make sure a packet received with the right client connection ID is processed.
9536TEST_P(QuicConnectionTest, ValidClientConnectionId) {
dschinazi346b7ce2019-06-05 01:38:18 -07009537 if (!framer_.version().SupportsClientConnectionIds()) {
9538 return;
9539 }
9540 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9541 connection_.set_client_connection_id(TestConnectionId(0x33));
9542 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_FORWARD_SECURE);
9543 header.destination_connection_id = TestConnectionId(0x33);
9544 header.destination_connection_id_included = CONNECTION_ID_PRESENT;
9545 header.source_connection_id_included = CONNECTION_ID_ABSENT;
9546 QuicFrames frames;
9547 QuicPingFrame ping_frame;
9548 QuicPaddingFrame padding_frame;
9549 frames.push_back(QuicFrame(ping_frame));
9550 frames.push_back(QuicFrame(padding_frame));
9551 std::unique_ptr<QuicPacket> packet =
9552 BuildUnsizedDataPacket(&framer_, header, frames);
9553 char buffer[kMaxOutgoingPacketSize];
9554 size_t encrypted_length = peer_framer_.EncryptPayload(
9555 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
9556 kMaxOutgoingPacketSize);
9557 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9558 false);
9559 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9560 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9561 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9562}
9563
9564// Make sure a packet received with a different client connection ID is dropped.
9565TEST_P(QuicConnectionTest, InvalidClientConnectionId) {
dschinazi346b7ce2019-06-05 01:38:18 -07009566 if (!framer_.version().SupportsClientConnectionIds()) {
9567 return;
9568 }
9569 connection_.set_client_connection_id(TestConnectionId(0x33));
9570 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_FORWARD_SECURE);
9571 header.destination_connection_id = TestConnectionId(0xbad);
9572 header.destination_connection_id_included = CONNECTION_ID_PRESENT;
9573 header.source_connection_id_included = CONNECTION_ID_ABSENT;
9574 QuicFrames frames;
9575 QuicPingFrame ping_frame;
9576 QuicPaddingFrame padding_frame;
9577 frames.push_back(QuicFrame(ping_frame));
9578 frames.push_back(QuicFrame(padding_frame));
9579 std::unique_ptr<QuicPacket> packet =
9580 BuildUnsizedDataPacket(&framer_, header, frames);
9581 char buffer[kMaxOutgoingPacketSize];
9582 size_t encrypted_length = peer_framer_.EncryptPayload(
9583 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
9584 kMaxOutgoingPacketSize);
9585 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9586 false);
9587 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9588 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9589 EXPECT_EQ(1u, connection_.GetStats().packets_dropped);
9590}
9591
9592// Make sure the first packet received with a different client connection ID on
9593// the server is processed and it changes the client connection ID.
9594TEST_P(QuicConnectionTest, UpdateClientConnectionIdFromFirstPacket) {
dschinazi346b7ce2019-06-05 01:38:18 -07009595 if (!framer_.version().SupportsClientConnectionIds()) {
9596 return;
9597 }
dschinazi346b7ce2019-06-05 01:38:18 -07009598 set_perspective(Perspective::IS_SERVER);
9599 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_INITIAL);
9600 header.source_connection_id = TestConnectionId(0x33);
9601 header.source_connection_id_included = CONNECTION_ID_PRESENT;
9602 QuicFrames frames;
9603 QuicPingFrame ping_frame;
9604 QuicPaddingFrame padding_frame;
9605 frames.push_back(QuicFrame(ping_frame));
9606 frames.push_back(QuicFrame(padding_frame));
9607 std::unique_ptr<QuicPacket> packet =
9608 BuildUnsizedDataPacket(&framer_, header, frames);
9609 char buffer[kMaxOutgoingPacketSize];
nharperc6b99512019-09-19 11:13:48 -07009610 size_t encrypted_length =
9611 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(1),
9612 *packet, buffer, kMaxOutgoingPacketSize);
dschinazi346b7ce2019-06-05 01:38:18 -07009613 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9614 false);
9615 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9616 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9617 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9618 EXPECT_EQ(TestConnectionId(0x33), connection_.client_connection_id());
9619}
9620
fayang40ec3ac2019-06-05 09:07:54 -07009621// Regression test for b/134416344.
9622TEST_P(QuicConnectionTest, CheckConnectedBeforeFlush) {
9623 // This test mimics a scenario where a connection processes 2 packets and the
9624 // 2nd packet contains connection close frame. When the 2nd flusher goes out
9625 // of scope, a delayed ACK is pending, and ACK alarm should not be scheduled
9626 // because connection is disconnected.
9627 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fkastenholz5d880a92019-06-21 09:01:56 -07009628 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
fayang40ec3ac2019-06-05 09:07:54 -07009629 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
fkastenholz88d08f42019-09-06 07:38:04 -07009630 const QuicErrorCode kErrorCode = QUIC_INTERNAL_ERROR;
fayang40ec3ac2019-06-05 09:07:54 -07009631 std::unique_ptr<QuicConnectionCloseFrame> connection_close_frame(
fkastenholz591814c2019-09-06 12:11:46 -07009632 new QuicConnectionCloseFrame(connection_.transport_version(), kErrorCode,
9633 "",
9634 /*transport_close_frame_type=*/0));
9635
fayang40ec3ac2019-06-05 09:07:54 -07009636 // Received 2 packets.
fayang40ec3ac2019-06-05 09:07:54 -07009637 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
fayang40ec3ac2019-06-05 09:07:54 -07009638 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9639 } else {
fayang40ec3ac2019-06-05 09:07:54 -07009640 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
9641 }
wub8a5dafa2020-05-13 12:30:17 -07009642 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
9643 kPeerAddress);
fayang9adfb532020-06-04 06:58:45 -07009644 EXPECT_TRUE(connection_.HasPendingAcks());
wub8a5dafa2020-05-13 12:30:17 -07009645 ProcessFramePacketWithAddresses(QuicFrame(connection_close_frame.release()),
fayang40ec3ac2019-06-05 09:07:54 -07009646 kSelfAddress, kPeerAddress);
fayang0f0c4e62019-07-16 08:55:54 -07009647 // Verify ack alarm is not set.
fayang9adfb532020-06-04 06:58:45 -07009648 EXPECT_FALSE(connection_.HasPendingAcks());
fayang40ec3ac2019-06-05 09:07:54 -07009649}
9650
dschinazi8d551132019-08-02 19:17:16 -07009651// Verify that a packet containing three coalesced packets is parsed correctly.
9652TEST_P(QuicConnectionTest, CoalescedPacket) {
9653 if (!QuicVersionHasLongHeaderLengths(connection_.transport_version())) {
9654 // Coalesced packets can only be encoded using long header lengths.
9655 return;
9656 }
9657 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9658 EXPECT_TRUE(connection_.connected());
9659 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9660 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(3);
9661 } else {
9662 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(3);
9663 }
9664
9665 uint64_t packet_numbers[3] = {1, 2, 3};
9666 EncryptionLevel encryption_levels[3] = {
9667 ENCRYPTION_INITIAL, ENCRYPTION_INITIAL, ENCRYPTION_FORWARD_SECURE};
9668 char buffer[kMaxOutgoingPacketSize] = {};
9669 size_t total_encrypted_length = 0;
9670 for (int i = 0; i < 3; i++) {
9671 QuicPacketHeader header =
9672 ConstructPacketHeader(packet_numbers[i], encryption_levels[i]);
9673 QuicFrames frames;
9674 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9675 frames.push_back(QuicFrame(&crypto_frame_));
9676 } else {
9677 frames.push_back(QuicFrame(frame1_));
9678 }
9679 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
9680 peer_creator_.set_encryption_level(encryption_levels[i]);
9681 size_t encrypted_length = peer_framer_.EncryptPayload(
9682 encryption_levels[i], QuicPacketNumber(packet_numbers[i]), *packet,
9683 buffer + total_encrypted_length,
9684 sizeof(buffer) - total_encrypted_length);
9685 EXPECT_GT(encrypted_length, 0u);
9686 total_encrypted_length += encrypted_length;
9687 }
9688 connection_.ProcessUdpPacket(
9689 kSelfAddress, kPeerAddress,
9690 QuicReceivedPacket(buffer, total_encrypted_length, clock_.Now(), false));
9691 if (connection_.GetSendAlarm()->IsSet()) {
9692 connection_.GetSendAlarm()->Fire();
9693 }
9694
9695 EXPECT_TRUE(connection_.connected());
9696}
9697
dschinazi66fc0242019-08-16 10:00:25 -07009698// Regression test for crbug.com/992831.
9699TEST_P(QuicConnectionTest, CoalescedPacketThatSavesFrames) {
9700 if (!QuicVersionHasLongHeaderLengths(connection_.transport_version())) {
9701 // Coalesced packets can only be encoded using long header lengths.
9702 return;
9703 }
9704 if (connection_.SupportsMultiplePacketNumberSpaces()) {
9705 // TODO(b/129151114) Enable this test with multiple packet number spaces.
9706 return;
9707 }
9708 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9709 EXPECT_TRUE(connection_.connected());
9710 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9711 EXPECT_CALL(visitor_, OnCryptoFrame(_))
9712 .Times(3)
9713 .WillRepeatedly([this](const QuicCryptoFrame& /*frame*/) {
9714 // QuicFrame takes ownership of the QuicBlockedFrame.
9715 connection_.SendControlFrame(QuicFrame(new QuicBlockedFrame(1, 3)));
9716 });
9717 } else {
9718 EXPECT_CALL(visitor_, OnStreamFrame(_))
9719 .Times(3)
9720 .WillRepeatedly([this](const QuicStreamFrame& /*frame*/) {
9721 // QuicFrame takes ownership of the QuicBlockedFrame.
9722 connection_.SendControlFrame(QuicFrame(new QuicBlockedFrame(1, 3)));
9723 });
9724 }
9725
9726 uint64_t packet_numbers[3] = {1, 2, 3};
9727 EncryptionLevel encryption_levels[3] = {
9728 ENCRYPTION_INITIAL, ENCRYPTION_INITIAL, ENCRYPTION_FORWARD_SECURE};
9729 char buffer[kMaxOutgoingPacketSize] = {};
9730 size_t total_encrypted_length = 0;
9731 for (int i = 0; i < 3; i++) {
9732 QuicPacketHeader header =
9733 ConstructPacketHeader(packet_numbers[i], encryption_levels[i]);
9734 QuicFrames frames;
9735 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9736 frames.push_back(QuicFrame(&crypto_frame_));
9737 } else {
9738 frames.push_back(QuicFrame(frame1_));
9739 }
9740 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
9741 peer_creator_.set_encryption_level(encryption_levels[i]);
9742 size_t encrypted_length = peer_framer_.EncryptPayload(
9743 encryption_levels[i], QuicPacketNumber(packet_numbers[i]), *packet,
9744 buffer + total_encrypted_length,
9745 sizeof(buffer) - total_encrypted_length);
9746 EXPECT_GT(encrypted_length, 0u);
9747 total_encrypted_length += encrypted_length;
9748 }
9749 connection_.ProcessUdpPacket(
9750 kSelfAddress, kPeerAddress,
9751 QuicReceivedPacket(buffer, total_encrypted_length, clock_.Now(), false));
9752 if (connection_.GetSendAlarm()->IsSet()) {
9753 connection_.GetSendAlarm()->Fire();
9754 }
9755
9756 EXPECT_TRUE(connection_.connected());
9757
9758 SendAckPacketToPeer();
9759}
9760
fayangd3016832019-08-08 07:24:45 -07009761// Regresstion test for b/138962304.
9762TEST_P(QuicConnectionTest, RtoAndWriteBlocked) {
fayangd3016832019-08-08 07:24:45 -07009763 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9764
9765 QuicStreamId stream_id = 2;
9766 QuicPacketNumber last_data_packet;
9767 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
9768 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9769
9770 // Writer gets blocked.
9771 writer_->SetWriteBlocked();
9772
9773 // Cancel the stream.
9774 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9775 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
fayang67f82272019-08-14 16:08:45 -07009776 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
9777 .WillRepeatedly(
9778 Invoke(&notifier_, &SimpleSessionNotifier::WillingToWrite));
fayangd3016832019-08-08 07:24:45 -07009779 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9780
9781 // Retransmission timer fires in RTO mode.
9782 connection_.GetRetransmissionAlarm()->Fire();
9783 // Verify no packets get flushed when writer is blocked.
9784 EXPECT_EQ(0u, connection_.NumQueuedPackets());
9785}
9786
9787// Regresstion test for b/138962304.
9788TEST_P(QuicConnectionTest, TlpAndWriteBlocked) {
fayangd3016832019-08-08 07:24:45 -07009789 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9790 connection_.SetMaxTailLossProbes(1);
9791
9792 QuicStreamId stream_id = 2;
9793 QuicPacketNumber last_data_packet;
9794 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
9795 SendStreamDataToPeer(4, "foo", 0, NO_FIN, &last_data_packet);
9796 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9797
9798 // Writer gets blocked.
9799 writer_->SetWriteBlocked();
9800
9801 // Cancel stream 2.
9802 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9803 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
9804 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9805
fayange62e63c2019-12-04 07:16:25 -08009806 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
fayangd3016832019-08-08 07:24:45 -07009807 // Retransmission timer fires in TLP mode.
9808 connection_.GetRetransmissionAlarm()->Fire();
9809 // Verify one packets is forced flushed when writer is blocked.
9810 EXPECT_EQ(1u, connection_.NumQueuedPackets());
9811}
9812
fayang67f82272019-08-14 16:08:45 -07009813// Regresstion test for b/139375344.
9814TEST_P(QuicConnectionTest, RtoForcesSendingPing) {
fayangcff885a2019-10-22 07:39:04 -07009815 if (connection_.PtoEnabled()) {
fayang67f82272019-08-14 16:08:45 -07009816 return;
9817 }
9818 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9819 connection_.SetMaxTailLossProbes(2);
9820 EXPECT_EQ(0u, connection_.GetStats().tlp_count);
9821 EXPECT_EQ(0u, connection_.GetStats().rto_count);
9822
9823 SendStreamDataToPeer(2, "foo", 0, NO_FIN, nullptr);
9824 QuicTime retransmission_time =
9825 connection_.GetRetransmissionAlarm()->deadline();
9826 EXPECT_NE(QuicTime::Zero(), retransmission_time);
9827 // TLP fires.
9828 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
9829 clock_.AdvanceTime(retransmission_time - clock_.Now());
9830 connection_.GetRetransmissionAlarm()->Fire();
9831 EXPECT_EQ(1u, connection_.GetStats().tlp_count);
9832 EXPECT_EQ(0u, connection_.GetStats().rto_count);
9833 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9834
9835 // Packet 1 gets acked.
9836 QuicAckFrame frame = InitAckFrame(1);
9837 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
9838 ProcessAckPacket(1, &frame);
9839 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9840 retransmission_time = connection_.GetRetransmissionAlarm()->deadline();
9841
9842 // RTO fires, verify a PING packet gets sent because there is no data to send.
9843 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(3), _, _));
9844 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
9845 clock_.AdvanceTime(retransmission_time - clock_.Now());
9846 connection_.GetRetransmissionAlarm()->Fire();
9847 EXPECT_EQ(1u, connection_.GetStats().tlp_count);
9848 EXPECT_EQ(1u, connection_.GetStats().rto_count);
9849 EXPECT_EQ(1u, writer_->ping_frames().size());
9850}
9851
fayangce0a3162019-08-15 09:05:36 -07009852TEST_P(QuicConnectionTest, ProbeTimeout) {
fayangce0a3162019-08-15 09:05:36 -07009853 QuicConfig config;
9854 QuicTagVector connection_options;
9855 connection_options.push_back(k2PTO);
9856 config.SetConnectionOptionsToSend(connection_options);
9857 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9858 connection_.SetFromConfig(config);
9859 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9860
9861 QuicStreamId stream_id = 2;
9862 QuicPacketNumber last_packet;
9863 SendStreamDataToPeer(stream_id, "foooooo", 0, NO_FIN, &last_packet);
9864 SendStreamDataToPeer(stream_id, "foooooo", 7, NO_FIN, &last_packet);
9865 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9866
9867 // Reset stream.
9868 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9869 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9870
9871 // Fire the PTO and verify only the RST_STREAM is resent, not stream data.
9872 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9873 connection_.GetRetransmissionAlarm()->Fire();
9874 EXPECT_EQ(0u, writer_->stream_frames().size());
9875 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
9876 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9877}
9878
fayang97ce41e2019-10-07 08:37:29 -07009879TEST_P(QuicConnectionTest, CloseConnectionAfter6ClientPTOs) {
fayang97ce41e2019-10-07 08:37:29 -07009880 QuicConfig config;
9881 QuicTagVector connection_options;
9882 connection_options.push_back(k1PTO);
9883 connection_options.push_back(k6PTO);
9884 config.SetConnectionOptionsToSend(connection_options);
dschinazif7c6a912020-05-05 11:39:53 -07009885 QuicConfigPeer::SetNegotiated(&config, true);
dschinazie7c38a52020-05-29 15:25:45 -07009886 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
9887 QuicConfigPeer::SetReceivedOriginalConnectionId(
9888 &config, connection_.connection_id());
9889 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
9890 &config, connection_.connection_id());
9891 }
fayang97ce41e2019-10-07 08:37:29 -07009892 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9893 connection_.SetFromConfig(config);
fayang656cbb52020-06-09 13:29:35 -07009894 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangaa4f3f22020-06-05 16:22:00 -07009895 EXPECT_CALL(visitor_, GetHandshakeState())
9896 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
9897 }
fayang97ce41e2019-10-07 08:37:29 -07009898 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9899
9900 // Send stream data.
9901 SendStreamDataToPeer(
9902 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
9903 0, FIN, nullptr);
9904
fayang97ce41e2019-10-07 08:37:29 -07009905 // Fire the retransmission alarm 5 times.
9906 for (int i = 0; i < 5; ++i) {
ianswett825b48b2020-05-11 06:25:04 -07009907 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
fayang97ce41e2019-10-07 08:37:29 -07009908 connection_.GetRetransmissionAlarm()->Fire();
9909 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
9910 EXPECT_TRUE(connection_.connected());
9911 }
fayang2205d952020-05-12 13:45:56 -07009912 EXPECT_CALL(visitor_, OnPathDegrading());
9913 connection_.PathDegradingTimeout();
fayang97ce41e2019-10-07 08:37:29 -07009914
9915 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveTlpCount());
9916 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveRtoCount());
9917 EXPECT_EQ(5u, connection_.sent_packet_manager().GetConsecutivePtoCount());
9918 // Closes connection on 6th PTO.
ianswett825b48b2020-05-11 06:25:04 -07009919 // May send multiple connecction close packets with multiple PN spaces.
9920 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
fayang97ce41e2019-10-07 08:37:29 -07009921 EXPECT_CALL(visitor_,
9922 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
fayang2205d952020-05-12 13:45:56 -07009923 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
9924 connection_.GetBlackholeDetectorAlarm()->Fire();
fayang97ce41e2019-10-07 08:37:29 -07009925 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
9926 EXPECT_FALSE(connection_.connected());
9927 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
9928}
9929
fayangce0a3162019-08-15 09:05:36 -07009930TEST_P(QuicConnectionTest, CloseConnectionAfter7ClientPTOs) {
fayangce0a3162019-08-15 09:05:36 -07009931 QuicConfig config;
9932 QuicTagVector connection_options;
9933 connection_options.push_back(k2PTO);
9934 connection_options.push_back(k7PTO);
9935 config.SetConnectionOptionsToSend(connection_options);
dschinazif7c6a912020-05-05 11:39:53 -07009936 QuicConfigPeer::SetNegotiated(&config, true);
dschinazie7c38a52020-05-29 15:25:45 -07009937 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
9938 QuicConfigPeer::SetReceivedOriginalConnectionId(
9939 &config, connection_.connection_id());
9940 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
9941 &config, connection_.connection_id());
9942 }
fayangce0a3162019-08-15 09:05:36 -07009943 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9944 connection_.SetFromConfig(config);
fayang656cbb52020-06-09 13:29:35 -07009945 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangaa4f3f22020-06-05 16:22:00 -07009946 EXPECT_CALL(visitor_, GetHandshakeState())
9947 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
9948 }
fayangce0a3162019-08-15 09:05:36 -07009949 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9950
9951 // Send stream data.
9952 SendStreamDataToPeer(
9953 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
9954 0, FIN, nullptr);
9955
9956 // Fire the retransmission alarm 6 times.
9957 for (int i = 0; i < 6; ++i) {
9958 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
9959 connection_.GetRetransmissionAlarm()->Fire();
9960 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
9961 EXPECT_TRUE(connection_.connected());
9962 }
fayang2205d952020-05-12 13:45:56 -07009963 EXPECT_CALL(visitor_, OnPathDegrading());
9964 connection_.PathDegradingTimeout();
fayangce0a3162019-08-15 09:05:36 -07009965
9966 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveTlpCount());
9967 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveRtoCount());
9968 EXPECT_EQ(6u, connection_.sent_packet_manager().GetConsecutivePtoCount());
9969 // Closes connection on 7th PTO.
9970 EXPECT_CALL(visitor_,
9971 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07009972 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
fayang2205d952020-05-12 13:45:56 -07009973 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
9974 connection_.GetBlackholeDetectorAlarm()->Fire();
fayangce0a3162019-08-15 09:05:36 -07009975 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
9976 EXPECT_FALSE(connection_.connected());
9977 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
9978}
9979
9980TEST_P(QuicConnectionTest, CloseConnectionAfter8ClientPTOs) {
fayangce0a3162019-08-15 09:05:36 -07009981 QuicConfig config;
9982 QuicTagVector connection_options;
9983 connection_options.push_back(k2PTO);
9984 connection_options.push_back(k8PTO);
dschinazif7c6a912020-05-05 11:39:53 -07009985 QuicConfigPeer::SetNegotiated(&config, true);
dschinazie7c38a52020-05-29 15:25:45 -07009986 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
9987 QuicConfigPeer::SetReceivedOriginalConnectionId(
9988 &config, connection_.connection_id());
9989 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
9990 &config, connection_.connection_id());
9991 }
fayangce0a3162019-08-15 09:05:36 -07009992 config.SetConnectionOptionsToSend(connection_options);
9993 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9994 connection_.SetFromConfig(config);
fayang656cbb52020-06-09 13:29:35 -07009995 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangaa4f3f22020-06-05 16:22:00 -07009996 EXPECT_CALL(visitor_, GetHandshakeState())
9997 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
9998 }
fayangce0a3162019-08-15 09:05:36 -07009999 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
10000
10001 // Send stream data.
10002 SendStreamDataToPeer(
10003 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
10004 0, FIN, nullptr);
10005
10006 // Fire the retransmission alarm 7 times.
10007 for (int i = 0; i < 7; ++i) {
10008 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
10009 connection_.GetRetransmissionAlarm()->Fire();
10010 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
10011 EXPECT_TRUE(connection_.connected());
10012 }
fayang2205d952020-05-12 13:45:56 -070010013 EXPECT_CALL(visitor_, OnPathDegrading());
10014 connection_.PathDegradingTimeout();
fayangce0a3162019-08-15 09:05:36 -070010015
10016 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveTlpCount());
10017 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveRtoCount());
10018 EXPECT_EQ(7u, connection_.sent_packet_manager().GetConsecutivePtoCount());
10019 // Closes connection on 8th PTO.
10020 EXPECT_CALL(visitor_,
10021 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -070010022 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
fayang2205d952020-05-12 13:45:56 -070010023 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
10024 connection_.GetBlackholeDetectorAlarm()->Fire();
fayangce0a3162019-08-15 09:05:36 -070010025 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
10026 EXPECT_FALSE(connection_.connected());
10027 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
10028}
10029
fayang5f135052019-08-22 17:59:40 -070010030TEST_P(QuicConnectionTest, DeprecateHandshakeMode) {
10031 if (!connection_.version().SupportsAntiAmplificationLimit()) {
10032 return;
10033 }
10034 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10035 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
10036
10037 // Send CHLO.
10038 connection_.SendCryptoStreamData();
10039 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
10040
10041 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
10042 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
10043 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
10044 QuicAckFrame frame1 = InitAckFrame(1);
10045 // Received ACK for packet 1.
10046 ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL);
10047
10048 // Verify retransmission alarm is still set because handshake is not
10049 // confirmed although there is nothing in flight.
10050 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
10051 EXPECT_EQ(0u, connection_.GetStats().pto_count);
10052 EXPECT_EQ(0u, connection_.GetStats().crypto_retransmit_count);
10053
10054 // PTO fires, verify a PING packet gets sent because there is no data to send.
fayang5d011982020-05-13 14:14:38 -070010055 EXPECT_CALL(*send_algorithm_,
10056 OnPacketSent(_, _,
10057 GetQuicReloadableFlag(quic_default_on_pto)
10058 ? QuicPacketNumber(2)
10059 : QuicPacketNumber(3),
10060 _, _));
fayang5f135052019-08-22 17:59:40 -070010061 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
10062 connection_.GetRetransmissionAlarm()->Fire();
10063 EXPECT_EQ(1u, connection_.GetStats().pto_count);
fayangaf9903b2020-05-14 14:34:28 -070010064 EXPECT_EQ(1u, connection_.GetStats().crypto_retransmit_count);
fayang5f135052019-08-22 17:59:40 -070010065 EXPECT_EQ(1u, writer_->ping_frames().size());
10066}
10067
10068TEST_P(QuicConnectionTest, AntiAmplificationLimit) {
10069 if (!connection_.version().SupportsAntiAmplificationLimit()) {
10070 return;
10071 }
fayang5f135052019-08-22 17:59:40 -070010072 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10073
10074 set_perspective(Perspective::IS_SERVER);
10075 // Verify no data can be sent at the beginning because bytes received is 0.
10076 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
10077 connection_.SendCryptoDataWithString("foo", 0);
fayang6a258412020-05-28 08:57:12 -070010078 if (GetQuicReloadableFlag(quic_move_amplification_limit)) {
10079 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
10080 EXPECT_FALSE(connection_.CanWrite(NO_RETRANSMITTABLE_DATA));
10081 }
fayang5f135052019-08-22 17:59:40 -070010082 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
10083
10084 // Receives packet 1.
10085 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
10086
10087 const size_t anti_amplification_factor =
fayang6a258412020-05-28 08:57:12 -070010088 connection_.anti_amplification_factor();
fayang5f135052019-08-22 17:59:40 -070010089 // Verify now packets can be sent.
10090 for (size_t i = 0; i < anti_amplification_factor; ++i) {
10091 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10092 connection_.SendCryptoDataWithString("foo", i * 3);
10093 // Verify retransmission alarm is not set if throttled by anti-amplification
10094 // limit.
10095 EXPECT_EQ(i != anti_amplification_factor - 1,
10096 connection_.GetRetransmissionAlarm()->IsSet());
10097 }
10098 // Verify server is throttled by anti-amplification limit.
10099 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
10100 connection_.SendCryptoDataWithString("foo", anti_amplification_factor * 3);
10101
10102 // Receives packet 2.
10103 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
10104 // Verify more packets can be sent.
10105 for (size_t i = anti_amplification_factor; i < anti_amplification_factor * 2;
10106 ++i) {
10107 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10108 connection_.SendCryptoDataWithString("foo", i * 3);
10109 }
10110 // Verify server is throttled by anti-amplification limit.
10111 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
10112 connection_.SendCryptoDataWithString("foo",
10113 2 * anti_amplification_factor * 3);
10114
10115 ProcessPacket(3);
10116 // Verify anti-amplification limit is gone after address validation.
10117 for (size_t i = 0; i < 100; ++i) {
10118 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10119 connection_.SendStreamDataWithString(3, "first", i * 0, NO_FIN);
10120 }
10121}
10122
fayang6a258412020-05-28 08:57:12 -070010123TEST_P(QuicConnectionTest, AckPendingWithAmplificationLimited) {
10124 if (!connection_.version().SupportsAntiAmplificationLimit() ||
10125 !GetQuicReloadableFlag(quic_move_amplification_limit)) {
10126 return;
10127 }
10128 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10129 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(AnyNumber());
10130 set_perspective(Perspective::IS_SERVER);
10131 use_tagging_decrypter();
10132 connection_.SetEncrypter(ENCRYPTION_INITIAL,
10133 std::make_unique<TaggingEncrypter>(0x01));
10134 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10135 // Receives packet 1.
10136 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
10137 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10138 std::make_unique<TaggingEncrypter>(0x02));
10139 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
fayang9adfb532020-06-04 06:58:45 -070010140 EXPECT_TRUE(connection_.HasPendingAcks());
fayang6a258412020-05-28 08:57:12 -070010141 // Send response in different encryption level and cause amplification factor
10142 // throttled.
10143 size_t i = 0;
10144 while (connection_.CanWrite(HAS_RETRANSMITTABLE_DATA)) {
10145 connection_.SendCryptoDataWithString(std::string(1024, 'a'), i * 1024,
10146 ENCRYPTION_HANDSHAKE);
10147 ++i;
10148 }
10149 // Verify ACK is still pending.
fayang9adfb532020-06-04 06:58:45 -070010150 EXPECT_TRUE(connection_.HasPendingAcks());
fayang6a258412020-05-28 08:57:12 -070010151
10152 // Fire ACK alarm and verify ACK cannot be sent due to amplification factor.
10153 clock_.AdvanceTime(connection_.GetAckAlarm()->deadline() - clock_.Now());
10154 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
10155 connection_.GetAckAlarm()->Fire();
10156 // Verify ACK alarm is cancelled.
fayang9adfb532020-06-04 06:58:45 -070010157 EXPECT_FALSE(connection_.HasPendingAcks());
fayang6a258412020-05-28 08:57:12 -070010158
10159 // Receives packet 2 and verify ACK gets flushed.
10160 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10161 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
10162 EXPECT_FALSE(writer_->ack_frames().empty());
10163}
10164
fkastenholza3660102019-08-28 05:19:24 -070010165TEST_P(QuicConnectionTest, ConnectionCloseFrameType) {
10166 if (!VersionHasIetfQuicFrames(version().transport_version)) {
10167 // Test relevent only for IETF QUIC.
10168 return;
10169 }
10170 const QuicErrorCode kQuicErrorCode = IETF_QUIC_PROTOCOL_VIOLATION;
10171 // Use the (unknown) frame type of 9999 to avoid triggering any logic
10172 // which might be associated with the processing of a known frame type.
10173 const uint64_t kTransportCloseFrameType = 9999u;
10174 QuicFramerPeer::set_current_received_frame_type(
10175 QuicConnectionPeer::GetFramer(&connection_), kTransportCloseFrameType);
10176 // Do a transport connection close
10177 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10178 connection_.CloseConnection(
10179 kQuicErrorCode, "Some random error message",
10180 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10181 const std::vector<QuicConnectionCloseFrame>& connection_close_frames =
10182 writer_->connection_close_frames();
10183 ASSERT_EQ(1u, connection_close_frames.size());
10184 EXPECT_EQ(IETF_QUIC_TRANSPORT_CONNECTION_CLOSE,
10185 connection_close_frames[0].close_type);
bnc77e77b82020-04-05 10:36:49 -070010186 EXPECT_EQ(kQuicErrorCode, connection_close_frames[0].quic_error_code);
fkastenholza3660102019-08-28 05:19:24 -070010187 EXPECT_EQ(kTransportCloseFrameType,
10188 connection_close_frames[0].transport_close_frame_type);
10189}
10190
fayang0fcbf352019-08-30 11:15:58 -070010191// Regression test for b/137401387 and b/138962304.
10192TEST_P(QuicConnectionTest, RtoPacketAsTwo) {
fayangcff885a2019-10-22 07:39:04 -070010193 if (connection_.PtoEnabled()) {
fayang0fcbf352019-08-30 11:15:58 -070010194 return;
10195 }
10196 connection_.SetMaxTailLossProbes(1);
10197 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10198 std::string stream_data(3000, 's');
10199 // Send packets 1 - 66 and exhaust cwnd.
10200 for (size_t i = 0; i < 22; ++i) {
10201 // 3 packets for each stream, the first 2 are guaranteed to be full packets.
10202 SendStreamDataToPeer(i + 2, stream_data, 0, FIN, nullptr);
10203 }
10204 CongestionBlockWrites();
10205
10206 // Fires TLP. Please note, this tail loss probe has 1 byte less stream data
10207 // compared to packet 1 because packet number length increases.
10208 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(67), _, _));
10209 connection_.GetRetransmissionAlarm()->Fire();
10210 // Fires RTO. Please note, although packets 2 and 3 *should* be RTOed, but
10211 // packet 2 gets RTOed to two packets because packet number length increases.
10212 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(68), _, _));
10213 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(69), _, _));
10214 connection_.GetRetransmissionAlarm()->Fire();
10215
10216 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10217 // Resets all streams except 2 and ack packets 1 and 2. Now, packet 3 is the
10218 // only one containing retransmittable frames.
10219 for (size_t i = 1; i < 22; ++i) {
10220 notifier_.OnStreamReset(i + 2, QUIC_STREAM_CANCELLED);
10221 }
10222 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
10223 QuicAckFrame frame =
10224 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(3)}});
10225 ProcessAckPacket(1, &frame);
10226 CongestionUnblockWrites();
10227
10228 // Fires TLP, verify a PING gets sent because packet 3 is marked
10229 // RTO_RETRANSMITTED.
10230 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(70), _, _));
10231 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
10232 connection_.GetRetransmissionAlarm()->Fire();
10233}
10234
fayang4c1c2362019-09-13 07:20:01 -070010235TEST_P(QuicConnectionTest, PtoSkipsPacketNumber) {
fayang4c1c2362019-09-13 07:20:01 -070010236 QuicConfig config;
10237 QuicTagVector connection_options;
10238 connection_options.push_back(k1PTO);
10239 connection_options.push_back(kPTOS);
10240 config.SetConnectionOptionsToSend(connection_options);
10241 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10242 connection_.SetFromConfig(config);
10243 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
10244
10245 QuicStreamId stream_id = 2;
10246 QuicPacketNumber last_packet;
10247 SendStreamDataToPeer(stream_id, "foooooo", 0, NO_FIN, &last_packet);
10248 SendStreamDataToPeer(stream_id, "foooooo", 7, NO_FIN, &last_packet);
10249 EXPECT_EQ(QuicPacketNumber(2), last_packet);
10250 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
10251
10252 // Fire PTO and verify the PTO retransmission skips one packet number.
10253 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10254 connection_.GetRetransmissionAlarm()->Fire();
10255 EXPECT_EQ(1u, writer_->stream_frames().size());
10256 EXPECT_EQ(QuicPacketNumber(4), writer_->last_packet_header().packet_number);
10257 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
10258}
10259
fayang58f71072019-11-05 08:47:02 -080010260TEST_P(QuicConnectionTest, SendCoalescedPackets) {
10261 if (!connection_.version().CanSendCoalescedPackets()) {
10262 return;
10263 }
fayang6100ab72020-03-18 13:16:25 -070010264 MockQuicConnectionDebugVisitor debug_visitor;
10265 connection_.set_debug_visitor(&debug_visitor);
10266 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(3);
10267 EXPECT_CALL(debug_visitor, OnCoalescedPacketSent(_, _)).Times(1);
fayang44ae4e92020-04-28 13:09:42 -070010268 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
fayang58f71072019-11-05 08:47:02 -080010269 {
10270 QuicConnection::ScopedPacketFlusher flusher(&connection_);
10271 use_tagging_decrypter();
10272 connection_.SetEncrypter(ENCRYPTION_INITIAL,
10273 std::make_unique<TaggingEncrypter>(0x01));
10274 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10275 connection_.SendCryptoDataWithString("foo", 0);
10276 // Verify this packet is on hold.
10277 EXPECT_EQ(0u, writer_->packets_write_attempts());
10278
10279 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10280 std::make_unique<TaggingEncrypter>(0x02));
10281 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10282 connection_.SendCryptoDataWithString("bar", 3);
10283 EXPECT_EQ(0u, writer_->packets_write_attempts());
10284
10285 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
10286 std::make_unique<TaggingEncrypter>(0x03));
10287 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10288 SendStreamDataToPeer(2, "baz", 3, NO_FIN, nullptr);
10289 }
10290 // Verify all 3 packets are coalesced in the same UDP datagram.
10291 EXPECT_EQ(1u, writer_->packets_write_attempts());
10292 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
10293 // Verify the packet is padded to full.
10294 EXPECT_EQ(connection_.max_packet_length(), writer_->last_packet_size());
10295
10296 // Verify packet process.
10297 EXPECT_EQ(1u, writer_->crypto_frames().size());
10298 EXPECT_EQ(0u, writer_->stream_frames().size());
10299 // Verify there is coalesced packet.
10300 EXPECT_NE(nullptr, writer_->coalesced_packet());
10301}
10302
fayang01062942020-01-22 07:23:23 -080010303TEST_P(QuicConnectionTest, ClientReceivedHandshakeDone) {
10304 if (!connection_.version().HasHandshakeDone()) {
10305 return;
10306 }
10307 EXPECT_CALL(visitor_, OnHandshakeDoneReceived());
10308 QuicFrames frames;
10309 frames.push_back(QuicFrame(QuicHandshakeDoneFrame()));
10310 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10311 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10312}
10313
10314TEST_P(QuicConnectionTest, ServerReceivedHandshakeDone) {
10315 if (!connection_.version().HasHandshakeDone()) {
10316 return;
10317 }
10318 set_perspective(Perspective::IS_SERVER);
10319 EXPECT_CALL(visitor_, OnHandshakeDoneReceived()).Times(0);
10320 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10321 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
10322 QuicFrames frames;
10323 frames.push_back(QuicFrame(QuicHandshakeDoneFrame()));
10324 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10325 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10326 EXPECT_EQ(1, connection_close_frame_count_);
10327 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
10328 IsError(IETF_QUIC_PROTOCOL_VIOLATION));
10329}
10330
fayang18ff23b2020-01-28 09:19:00 -080010331TEST_P(QuicConnectionTest, MultiplePacketNumberSpacePto) {
10332 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10333 return;
10334 }
10335 use_tagging_decrypter();
10336 // Send handshake packet.
10337 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10338 std::make_unique<TaggingEncrypter>(0x02));
10339 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
fayang44ae4e92020-04-28 13:09:42 -070010340 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
fayang18ff23b2020-01-28 09:19:00 -080010341 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
10342 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
10343
10344 // Send application data.
10345 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
10346 0, NO_FIN);
10347 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
10348 QuicTime retransmission_time =
10349 connection_.GetRetransmissionAlarm()->deadline();
10350 EXPECT_NE(QuicTime::Zero(), retransmission_time);
10351
10352 // Retransmit handshake data.
10353 clock_.AdvanceTime(retransmission_time - clock_.Now());
fayang5d011982020-05-13 14:14:38 -070010354 EXPECT_CALL(*send_algorithm_,
10355 OnPacketSent(_, _,
10356 GetQuicReloadableFlag(quic_default_on_pto)
10357 ? QuicPacketNumber(3)
10358 : QuicPacketNumber(4),
10359 _, _));
fayang44ae4e92020-04-28 13:09:42 -070010360 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
fayang18ff23b2020-01-28 09:19:00 -080010361 connection_.GetRetransmissionAlarm()->Fire();
10362 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
10363
10364 // Send application data.
10365 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
10366 4, NO_FIN);
10367 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
10368 retransmission_time = connection_.GetRetransmissionAlarm()->deadline();
10369 EXPECT_NE(QuicTime::Zero(), retransmission_time);
10370
10371 // Retransmit handshake data again.
10372 clock_.AdvanceTime(retransmission_time - clock_.Now());
fayang5d011982020-05-13 14:14:38 -070010373 EXPECT_CALL(*send_algorithm_,
10374 OnPacketSent(_, _,
10375 GetQuicReloadableFlag(quic_default_on_pto)
10376 ? QuicPacketNumber(5)
10377 : QuicPacketNumber(7),
10378 _, _));
fayang44ae4e92020-04-28 13:09:42 -070010379 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
fayang18ff23b2020-01-28 09:19:00 -080010380 connection_.GetRetransmissionAlarm()->Fire();
10381 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
10382
10383 // Discard handshake key.
10384 connection_.OnHandshakeComplete();
10385 retransmission_time = connection_.GetRetransmissionAlarm()->deadline();
10386 EXPECT_NE(QuicTime::Zero(), retransmission_time);
10387
10388 // Retransmit application data.
10389 clock_.AdvanceTime(retransmission_time - clock_.Now());
fayang5d011982020-05-13 14:14:38 -070010390 EXPECT_CALL(*send_algorithm_,
10391 OnPacketSent(_, _,
10392 GetQuicReloadableFlag(quic_default_on_pto)
10393 ? QuicPacketNumber(6)
10394 : QuicPacketNumber(9),
10395 _, _));
fayang18ff23b2020-01-28 09:19:00 -080010396 connection_.GetRetransmissionAlarm()->Fire();
10397 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
10398}
10399
dschinazie7c38a52020-05-29 15:25:45 -070010400void QuicConnectionTest::TestClientRetryHandling(
10401 bool invalid_retry_tag,
10402 bool missing_original_id_in_config,
10403 bool wrong_original_id_in_config,
10404 bool missing_retry_id_in_config,
10405 bool wrong_retry_id_in_config) {
dschinazi39e5e552020-05-06 13:55:24 -070010406 if (invalid_retry_tag) {
dschinazie7c38a52020-05-29 15:25:45 -070010407 ASSERT_FALSE(missing_original_id_in_config);
10408 ASSERT_FALSE(wrong_original_id_in_config);
10409 ASSERT_FALSE(missing_retry_id_in_config);
10410 ASSERT_FALSE(wrong_retry_id_in_config);
dschinazi39e5e552020-05-06 13:55:24 -070010411 } else {
dschinazie7c38a52020-05-29 15:25:45 -070010412 ASSERT_FALSE(missing_original_id_in_config && wrong_original_id_in_config);
10413 ASSERT_FALSE(missing_retry_id_in_config && wrong_retry_id_in_config);
dschinazi39e5e552020-05-06 13:55:24 -070010414 }
dschinazi278efae2020-01-28 17:03:09 -080010415 if (!version().HasRetryIntegrityTag()) {
10416 return;
10417 }
dschinazi39e5e552020-05-06 13:55:24 -070010418
10419 // These values come from draft-ietf-quic-tls Appendix A.4.
10420 char retry_packet25[] = {
10421 0xff, 0xff, 0x00, 0x00, 0x19, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a,
10422 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x1e, 0x5e, 0xc5, 0xb0,
10423 0x14, 0xcb, 0xb1, 0xf0, 0xfd, 0x93, 0xdf, 0x40, 0x48, 0xc4, 0x46, 0xa6};
10424 char retry_packet27[] = {
10425 0xff, 0xff, 0x00, 0x00, 0x1b, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a,
10426 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0xa5, 0x23, 0xcb, 0x5b,
10427 0xa5, 0x24, 0x69, 0x5f, 0x65, 0x69, 0xf2, 0x93, 0xa1, 0x35, 0x9d, 0x8e};
dschinazi2c78aac2020-05-21 17:21:58 -070010428 char retry_packet28[] = {
10429 0xff, 0xff, 0x00, 0x00, 0x1c, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a,
10430 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0xf7, 0x1a, 0x5f, 0x12,
10431 0xaf, 0xe3, 0xec, 0xf8, 0x00, 0x1a, 0x92, 0x0e, 0x6f, 0xdf, 0x1d, 0x63};
dschinazib3fed9e2020-06-11 11:59:33 -070010432 char retry_packet29[] = {
10433 0xff, 0xff, 0x00, 0x00, 0x1d, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a,
10434 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0xd1, 0x69, 0x26, 0xd8,
10435 0x1f, 0x6f, 0x9c, 0xa2, 0x95, 0x3a, 0x8a, 0xa4, 0x57, 0x5e, 0x1e, 0x49};
dschinazi39e5e552020-05-06 13:55:24 -070010436
10437 char* retry_packet;
10438 size_t retry_packet_length;
dschinazib3fed9e2020-06-11 11:59:33 -070010439 if (version() == ParsedQuicVersion::Draft29()) {
10440 retry_packet = retry_packet29;
10441 retry_packet_length = QUICHE_ARRAYSIZE(retry_packet29);
10442 } else if (version() == ParsedQuicVersion::Draft28()) {
dschinazi2c78aac2020-05-21 17:21:58 -070010443 retry_packet = retry_packet28;
10444 retry_packet_length = QUICHE_ARRAYSIZE(retry_packet28);
dschinazib3fed9e2020-06-11 11:59:33 -070010445 } else if (version() == ParsedQuicVersion::Draft27()) {
dschinazi39e5e552020-05-06 13:55:24 -070010446 retry_packet = retry_packet27;
10447 retry_packet_length = QUICHE_ARRAYSIZE(retry_packet27);
dschinazib3fed9e2020-06-11 11:59:33 -070010448 } else if (version() == ParsedQuicVersion::Draft25()) {
dschinazi39e5e552020-05-06 13:55:24 -070010449 retry_packet = retry_packet25;
10450 retry_packet_length = QUICHE_ARRAYSIZE(retry_packet25);
10451 } else {
dschinazi278efae2020-01-28 17:03:09 -080010452 // TODO(dschinazi) generate retry packets for all versions once we have
10453 // server-side support for generating these programmatically.
10454 return;
10455 }
10456
dschinazi278efae2020-01-28 17:03:09 -080010457 char original_connection_id_bytes[] = {0x83, 0x94, 0xc8, 0xf0,
10458 0x3e, 0x51, 0x57, 0x08};
10459 char new_connection_id_bytes[] = {0xf0, 0x67, 0xa5, 0x50,
10460 0x2a, 0x42, 0x62, 0xb5};
10461 char retry_token_bytes[] = {0x74, 0x6f, 0x6b, 0x65, 0x6e};
10462
10463 QuicConnectionId original_connection_id(
10464 original_connection_id_bytes,
10465 QUICHE_ARRAYSIZE(original_connection_id_bytes));
10466 QuicConnectionId new_connection_id(new_connection_id_bytes,
10467 QUICHE_ARRAYSIZE(new_connection_id_bytes));
10468
10469 std::string retry_token(retry_token_bytes,
10470 QUICHE_ARRAYSIZE(retry_token_bytes));
10471
dschinazi39e5e552020-05-06 13:55:24 -070010472 if (invalid_retry_tag) {
10473 // Flip the last bit of the retry packet to prevent the integrity tag
10474 // from validating correctly.
10475 retry_packet[retry_packet_length - 1] ^= 1;
dschinazi278efae2020-01-28 17:03:09 -080010476 }
10477
dschinazi39e5e552020-05-06 13:55:24 -070010478 QuicConnectionId config_original_connection_id = original_connection_id;
dschinazie7c38a52020-05-29 15:25:45 -070010479 if (wrong_original_id_in_config) {
dschinazi39e5e552020-05-06 13:55:24 -070010480 // Flip the first bit of the connection ID.
10481 ASSERT_FALSE(config_original_connection_id.IsEmpty());
10482 config_original_connection_id.mutable_data()[0] ^= 0x80;
10483 }
dschinazie7c38a52020-05-29 15:25:45 -070010484 QuicConnectionId config_retry_source_connection_id = new_connection_id;
10485 if (wrong_retry_id_in_config) {
10486 // Flip the first bit of the connection ID.
10487 ASSERT_FALSE(config_retry_source_connection_id.IsEmpty());
10488 config_retry_source_connection_id.mutable_data()[0] ^= 0x80;
10489 }
dschinazi278efae2020-01-28 17:03:09 -080010490
dschinazi39e5e552020-05-06 13:55:24 -070010491 // Make sure the connection uses the connection ID from the test vectors,
10492 QuicConnectionPeer::SetServerConnectionId(&connection_,
10493 original_connection_id);
dschinazi278efae2020-01-28 17:03:09 -080010494
dschinazi39e5e552020-05-06 13:55:24 -070010495 // Process the RETRY packet.
10496 connection_.ProcessUdpPacket(
10497 kSelfAddress, kPeerAddress,
10498 QuicReceivedPacket(retry_packet, retry_packet_length, clock_.Now()));
10499
10500 if (invalid_retry_tag) {
10501 // Make sure we refuse to process a RETRY with invalid tag.
10502 EXPECT_FALSE(connection_.GetStats().retry_packet_processed);
10503 EXPECT_EQ(connection_.connection_id(), original_connection_id);
dschinazi278efae2020-01-28 17:03:09 -080010504 EXPECT_TRUE(QuicPacketCreatorPeer::GetRetryToken(
dschinazi39e5e552020-05-06 13:55:24 -070010505 QuicConnectionPeer::GetPacketCreator(&connection_))
dschinazi278efae2020-01-28 17:03:09 -080010506 .empty());
dschinazi39e5e552020-05-06 13:55:24 -070010507 return;
dschinazi278efae2020-01-28 17:03:09 -080010508 }
dschinazi39e5e552020-05-06 13:55:24 -070010509
10510 // Make sure we correctly parsed the RETRY.
10511 EXPECT_TRUE(connection_.GetStats().retry_packet_processed);
10512 EXPECT_EQ(connection_.connection_id(), new_connection_id);
10513 EXPECT_EQ(QuicPacketCreatorPeer::GetRetryToken(
10514 QuicConnectionPeer::GetPacketCreator(&connection_)),
10515 retry_token);
10516 // Make sure our fake framer has the new post-retry INITIAL keys.
10517 writer_->framer()->framer()->SetInitialObfuscators(new_connection_id);
10518
10519 // Test validating the original_connection_id from the config.
10520 QuicConfig received_config;
10521 QuicConfigPeer::SetNegotiated(&received_config, true);
dschinazie7c38a52020-05-29 15:25:45 -070010522 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
10523 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
10524 &received_config, connection_.connection_id());
10525 if (!missing_retry_id_in_config) {
10526 QuicConfigPeer::SetReceivedRetrySourceConnectionId(
10527 &received_config, config_retry_source_connection_id);
10528 }
10529 }
10530 if (!missing_original_id_in_config) {
dschinazi39e5e552020-05-06 13:55:24 -070010531 QuicConfigPeer::SetReceivedOriginalConnectionId(
10532 &received_config, config_original_connection_id);
10533 }
dschinazie7c38a52020-05-29 15:25:45 -070010534
10535 if (missing_original_id_in_config || wrong_original_id_in_config ||
10536 missing_retry_id_in_config || wrong_retry_id_in_config) {
dschinazi39e5e552020-05-06 13:55:24 -070010537 EXPECT_CALL(visitor_,
10538 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10539 .Times(1);
10540 } else {
10541 EXPECT_CALL(visitor_,
10542 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10543 .Times(0);
10544 }
10545 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
10546 connection_.SetFromConfig(received_config);
dschinazie7c38a52020-05-29 15:25:45 -070010547 if (missing_original_id_in_config || wrong_original_id_in_config ||
10548 missing_retry_id_in_config || wrong_retry_id_in_config) {
10549 ASSERT_FALSE(connection_.connected());
dschinazi39e5e552020-05-06 13:55:24 -070010550 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
10551 } else {
10552 EXPECT_TRUE(connection_.connected());
10553 }
10554}
10555
10556TEST_P(QuicConnectionTest, ClientParsesRetry) {
10557 TestClientRetryHandling(/*invalid_retry_tag=*/false,
dschinazie7c38a52020-05-29 15:25:45 -070010558 /*missing_original_id_in_config=*/false,
10559 /*wrong_original_id_in_config=*/false,
10560 /*missing_retry_id_in_config=*/false,
10561 /*wrong_retry_id_in_config=*/false);
dschinazi39e5e552020-05-06 13:55:24 -070010562}
10563
dschinazie7c38a52020-05-29 15:25:45 -070010564TEST_P(QuicConnectionTest, ClientParsesRetryInvalidTag) {
dschinazi39e5e552020-05-06 13:55:24 -070010565 TestClientRetryHandling(/*invalid_retry_tag=*/true,
dschinazie7c38a52020-05-29 15:25:45 -070010566 /*missing_original_id_in_config=*/false,
10567 /*wrong_original_id_in_config=*/false,
10568 /*missing_retry_id_in_config=*/false,
10569 /*wrong_retry_id_in_config=*/false);
dschinazi39e5e552020-05-06 13:55:24 -070010570}
10571
dschinazie7c38a52020-05-29 15:25:45 -070010572TEST_P(QuicConnectionTest, ClientParsesRetryMissingOriginalId) {
dschinazi39e5e552020-05-06 13:55:24 -070010573 TestClientRetryHandling(/*invalid_retry_tag=*/false,
dschinazie7c38a52020-05-29 15:25:45 -070010574 /*missing_original_id_in_config=*/true,
10575 /*wrong_original_id_in_config=*/false,
10576 /*missing_retry_id_in_config=*/false,
10577 /*wrong_retry_id_in_config=*/false);
dschinazi39e5e552020-05-06 13:55:24 -070010578}
10579
dschinazie7c38a52020-05-29 15:25:45 -070010580TEST_P(QuicConnectionTest, ClientParsesRetryWrongOriginalId) {
dschinazi39e5e552020-05-06 13:55:24 -070010581 TestClientRetryHandling(/*invalid_retry_tag=*/false,
dschinazie7c38a52020-05-29 15:25:45 -070010582 /*missing_original_id_in_config=*/false,
10583 /*wrong_original_id_in_config=*/true,
10584 /*missing_retry_id_in_config=*/false,
10585 /*wrong_retry_id_in_config=*/false);
10586}
10587
10588TEST_P(QuicConnectionTest, ClientParsesRetryMissingRetryId) {
10589 if (!connection_.version().AuthenticatesHandshakeConnectionIds()) {
10590 // Versions that do not authenticate connection IDs never send the
10591 // retry_source_connection_id transport parameter.
10592 return;
10593 }
10594 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10595 /*missing_original_id_in_config=*/false,
10596 /*wrong_original_id_in_config=*/false,
10597 /*missing_retry_id_in_config=*/true,
10598 /*wrong_retry_id_in_config=*/false);
10599}
10600
10601TEST_P(QuicConnectionTest, ClientParsesRetryWrongRetryId) {
10602 if (!connection_.version().AuthenticatesHandshakeConnectionIds()) {
10603 // Versions that do not authenticate connection IDs never send the
10604 // retry_source_connection_id transport parameter.
10605 return;
10606 }
10607 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10608 /*missing_original_id_in_config=*/false,
10609 /*wrong_original_id_in_config=*/false,
10610 /*missing_retry_id_in_config=*/false,
10611 /*wrong_retry_id_in_config=*/true);
dschinazi39e5e552020-05-06 13:55:24 -070010612}
10613
10614TEST_P(QuicConnectionTest, ClientReceivesOriginalConnectionIdWithoutRetry) {
dschinazie7c38a52020-05-29 15:25:45 -070010615 if (!connection_.version().UsesTls()) {
10616 // QUIC+TLS is required to transmit connection ID transport parameters.
10617 return;
10618 }
10619 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
10620 // Versions that authenticate connection IDs always send the
10621 // original_destination_connection_id transport parameter.
10622 return;
10623 }
10624 // Make sure that receiving the original_destination_connection_id transport
10625 // parameter fails the handshake when no RETRY packet was received before it.
dschinazi39e5e552020-05-06 13:55:24 -070010626 QuicConfig received_config;
10627 QuicConfigPeer::SetNegotiated(&received_config, true);
10628 QuicConfigPeer::SetReceivedOriginalConnectionId(&received_config,
10629 TestConnectionId(0x12345));
10630 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
10631 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10632 .Times(1);
10633 connection_.SetFromConfig(received_config);
10634 EXPECT_FALSE(connection_.connected());
10635 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
dschinazi278efae2020-01-28 17:03:09 -080010636}
10637
dschinazie7c38a52020-05-29 15:25:45 -070010638TEST_P(QuicConnectionTest, ClientReceivesRetrySourceConnectionIdWithoutRetry) {
10639 if (!connection_.version().AuthenticatesHandshakeConnectionIds()) {
10640 // Versions that do not authenticate connection IDs never send the
10641 // retry_source_connection_id transport parameter.
10642 return;
10643 }
10644 // Make sure that receiving the retry_source_connection_id transport parameter
10645 // fails the handshake when no RETRY packet was received before it.
10646 QuicConfig received_config;
10647 QuicConfigPeer::SetNegotiated(&received_config, true);
10648 QuicConfigPeer::SetReceivedRetrySourceConnectionId(&received_config,
10649 TestConnectionId(0x12345));
10650 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
10651 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10652 .Times(1);
10653 connection_.SetFromConfig(received_config);
10654 EXPECT_FALSE(connection_.connected());
10655 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
10656}
10657
fayang0e3035e2020-02-03 13:30:36 -080010658// Regression test for http://crbug/1047977
10659TEST_P(QuicConnectionTest, MaxStreamsFrameCausesConnectionClose) {
10660 if (!VersionHasIetfQuicFrames(connection_.transport_version())) {
10661 return;
10662 }
10663 // Received frame causes connection close.
10664 EXPECT_CALL(visitor_, OnMaxStreamsFrame(_))
10665 .WillOnce(InvokeWithoutArgs([this]() {
10666 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10667 connection_.CloseConnection(
10668 QUIC_TOO_MANY_BUFFERED_CONTROL_FRAMES, "error",
10669 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10670 return true;
10671 }));
10672 QuicFrames frames;
10673 frames.push_back(QuicFrame(QuicMaxStreamsFrame()));
10674 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10675 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10676}
10677
10678TEST_P(QuicConnectionTest, StreamsBlockedFrameCausesConnectionClose) {
10679 if (!VersionHasIetfQuicFrames(connection_.transport_version())) {
10680 return;
10681 }
10682 // Received frame causes connection close.
10683 EXPECT_CALL(visitor_, OnStreamsBlockedFrame(_))
10684 .WillOnce(InvokeWithoutArgs([this]() {
10685 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10686 connection_.CloseConnection(
10687 QUIC_TOO_MANY_BUFFERED_CONTROL_FRAMES, "error",
10688 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10689 return true;
10690 }));
10691 QuicFrames frames;
10692 frames.push_back(
10693 QuicFrame(QuicStreamsBlockedFrame(kInvalidControlFrameId, 10, false)));
10694 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10695 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10696}
10697
fayang79400d52020-02-13 10:13:05 -080010698TEST_P(QuicConnectionTest,
10699 BundleAckWithConnectionCloseMultiplePacketNumberSpace) {
10700 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10701 return;
10702 }
10703 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10704 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10705 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
10706 // Receives packet 1000 in initial data.
10707 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
10708 // Receives packet 2000 in application data.
10709 ProcessDataPacketAtLevel(2000, false, ENCRYPTION_FORWARD_SECURE);
10710 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10711 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
10712 connection_.CloseConnection(
10713 kQuicErrorCode, "Some random error message",
10714 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10715
10716 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
10717
10718 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
10719 EXPECT_EQ(1u, writer_->connection_close_frames().size());
10720 // Verify ack is bundled.
10721 EXPECT_EQ(1u, writer_->ack_frames().size());
10722
10723 if (!connection_.version().CanSendCoalescedPackets()) {
10724 // Each connection close packet should be sent in distinct UDP packets.
10725 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
10726 writer_->connection_close_packets());
10727 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
10728 writer_->packets_write_attempts());
10729 return;
10730 }
10731
10732 // A single UDP packet should be sent with multiple connection close packets
10733 // coalesced together.
10734 EXPECT_EQ(1u, writer_->packets_write_attempts());
10735
10736 // Only the first packet has been processed yet.
10737 EXPECT_EQ(1u, writer_->connection_close_packets());
10738
10739 // ProcessPacket resets the visitor and frees the coalesced packet.
10740 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
10741 auto packet = writer_->coalesced_packet()->Clone();
10742 writer_->framer()->ProcessPacket(*packet);
10743 EXPECT_EQ(1u, writer_->connection_close_packets());
10744 EXPECT_EQ(1u, writer_->connection_close_frames().size());
10745 // Verify ack is bundled.
10746 EXPECT_EQ(1u, writer_->ack_frames().size());
10747 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
10748}
10749
fayang61453cb2020-03-11 11:32:26 -070010750// Regression test for b/151220135.
10751TEST_P(QuicConnectionTest, SendPingWhenSkipPacketNumberForPto) {
10752 if (!VersionSupportsMessageFrames(connection_.transport_version())) {
10753 return;
10754 }
10755 QuicConfig config;
10756 QuicTagVector connection_options;
10757 connection_options.push_back(kPTOS);
10758 connection_options.push_back(k1PTO);
10759 config.SetConnectionOptionsToSend(connection_options);
dschinazied459c02020-05-07 16:12:23 -070010760 if (connection_.version().UsesTls()) {
10761 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
10762 &config, kMaxAcceptedDatagramFrameSize);
10763 }
fayang61453cb2020-03-11 11:32:26 -070010764 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10765 connection_.SetFromConfig(config);
10766 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
10767
10768 EXPECT_EQ(MESSAGE_STATUS_SUCCESS, SendMessage("message"));
10769 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
10770
fayang80f9cc62020-04-22 08:08:20 -070010771 // PTO fires, verify a PING packet gets sent because there is no data to
10772 // send.
10773 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(3), _, _));
10774 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
fayang61453cb2020-03-11 11:32:26 -070010775 connection_.GetRetransmissionAlarm()->Fire();
fayang80f9cc62020-04-22 08:08:20 -070010776 EXPECT_EQ(1u, connection_.GetStats().pto_count);
10777 EXPECT_EQ(0u, connection_.GetStats().crypto_retransmit_count);
10778 EXPECT_EQ(1u, writer_->ping_frames().size());
fayang61453cb2020-03-11 11:32:26 -070010779}
10780
fayangcc210e72020-05-05 14:41:34 -070010781// Regression test for b/155757133
10782TEST_P(QuicConnectionTest, DonotChangeQueuedAcks) {
10783 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10784 return;
10785 }
10786 const size_t kMinRttMs = 40;
10787 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
10788 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
10789 QuicTime::Delta::Zero(), QuicTime::Zero());
10790 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10791 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
10792 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10793
10794 ProcessPacket(2);
10795 ProcessPacket(3);
10796 ProcessPacket(4);
10797 // Process a packet containing stream frame followed by ACK of packets 1.
10798 QuicFrames frames;
10799 frames.push_back(QuicFrame(QuicStreamFrame(
10800 QuicUtils::GetFirstBidirectionalStreamId(
10801 connection_.version().transport_version, Perspective::IS_CLIENT),
10802 false, 0u, quiche::QuicheStringPiece())));
10803 QuicAckFrame ack_frame = InitAckFrame(1);
10804 frames.push_back(QuicFrame(&ack_frame));
10805 // Receiving stream frame causes something to send.
10806 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([this]() {
10807 connection_.SendControlFrame(QuicFrame(new QuicWindowUpdateFrame(1, 0, 0)));
10808 // Verify now the queued ACK contains packet number 2.
10809 EXPECT_TRUE(QuicPacketCreatorPeer::QueuedFrames(
10810 QuicConnectionPeer::GetPacketCreator(&connection_))[0]
10811 .ack_frame->packets.Contains(QuicPacketNumber(2)));
10812 }));
10813 ProcessFramesPacketAtLevel(9, frames, ENCRYPTION_FORWARD_SECURE);
10814 if (GetQuicReloadableFlag(quic_donot_change_queued_ack)) {
10815 EXPECT_TRUE(writer_->ack_frames()[0].packets.Contains(QuicPacketNumber(2)));
10816 } else {
10817 // ACK frame changes mid packet serialiation!
10818 EXPECT_FALSE(
10819 writer_->ack_frames()[0].packets.Contains(QuicPacketNumber(2)));
10820 }
10821}
10822
fayange9304002020-05-07 11:57:48 -070010823TEST_P(QuicConnectionTest, DonotExtendIdleTimeOnUndecryptablePackets) {
10824 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10825 QuicConfig config;
10826 connection_.SetFromConfig(config);
10827 // Subtract a second from the idle timeout on the client side.
10828 QuicTime initial_deadline =
10829 clock_.ApproximateNow() +
10830 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
10831 EXPECT_EQ(initial_deadline, connection_.GetTimeoutAlarm()->deadline());
10832
10833 // Received an undecryptable packet.
10834 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
10835 const uint8_t tag = 0x07;
10836 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
10837 std::make_unique<TaggingEncrypter>(tag));
10838 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
fayang2205d952020-05-12 13:45:56 -070010839 if (GetQuicReloadableFlag(quic_extend_idle_time_on_decryptable_packets)) {
fayange9304002020-05-07 11:57:48 -070010840 // Verify deadline does not get extended.
10841 EXPECT_EQ(initial_deadline, connection_.GetTimeoutAlarm()->deadline());
10842 }
10843 if (GetQuicReloadableFlag(quic_extend_idle_time_on_decryptable_packets)) {
10844 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
10845 } else {
10846 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
10847 }
10848 QuicTime::Delta delay = initial_deadline - clock_.ApproximateNow();
10849 clock_.AdvanceTime(delay);
fayang2205d952020-05-12 13:45:56 -070010850 if (GetQuicReloadableFlag(quic_extend_idle_time_on_decryptable_packets)) {
fayange9304002020-05-07 11:57:48 -070010851 connection_.GetTimeoutAlarm()->Fire();
10852 }
10853 if (GetQuicReloadableFlag(quic_extend_idle_time_on_decryptable_packets)) {
10854 // Verify connection gets closed.
10855 EXPECT_FALSE(connection_.connected());
10856 } else {
10857 // Verify the timeout alarm deadline is updated.
10858 EXPECT_TRUE(connection_.connected());
10859 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
10860 }
10861}
10862
fayang9f430a52020-05-08 07:28:33 -070010863TEST_P(QuicConnectionTest, BundleAckWithImmediateResponse) {
10864 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10865 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10866
10867 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([this]() {
10868 connection_.SendControlFrame(QuicFrame(new QuicWindowUpdateFrame(1, 0, 0)));
10869 }));
10870 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10871 ProcessDataPacket(1);
fayang9f430a52020-05-08 07:28:33 -070010872 if (GetQuicReloadableFlag(quic_advance_ack_timeout_update)) {
10873 // Verify ACK is bundled with WINDOW_UPDATE.
10874 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -070010875 EXPECT_FALSE(connection_.HasPendingAcks());
fayang9f430a52020-05-08 07:28:33 -070010876 } else {
10877 // ACK is pending.
10878 EXPECT_TRUE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -070010879 EXPECT_TRUE(connection_.HasPendingAcks());
fayang9f430a52020-05-08 07:28:33 -070010880 }
10881}
10882
fayangf44a6672020-05-27 12:51:45 -070010883TEST_P(QuicConnectionTest, AckAlarmFiresEarly) {
10884 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10885 return;
10886 }
10887 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10888 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
10889 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10890 }
10891 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
10892 use_tagging_decrypter();
10893 // Receives packet 1000 in initial data.
10894 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
fayang9adfb532020-06-04 06:58:45 -070010895 EXPECT_TRUE(connection_.HasPendingAcks());
fayangf44a6672020-05-27 12:51:45 -070010896
10897 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
10898 std::make_unique<TaggingEncrypter>(0x02));
10899 SetDecrypter(ENCRYPTION_ZERO_RTT,
10900 std::make_unique<StrictTaggingDecrypter>(0x02));
10901 connection_.SetEncrypter(ENCRYPTION_INITIAL,
10902 std::make_unique<TaggingEncrypter>(0x02));
10903 // Receives packet 1000 in application data.
10904 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
fayang9adfb532020-06-04 06:58:45 -070010905 EXPECT_TRUE(connection_.HasPendingAcks());
fayangf44a6672020-05-27 12:51:45 -070010906 // Verify ACK deadline does not change.
10907 EXPECT_EQ(clock_.ApproximateNow() + kAlarmGranularity,
10908 connection_.GetAckAlarm()->deadline());
10909
10910 // Ack alarm fires early.
10911 if (GetQuicReloadableFlag(quic_always_send_earliest_ack)) {
10912 // Verify the earliest ACK is flushed.
10913 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10914 } else {
10915 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
10916 }
10917 connection_.GetAckAlarm()->Fire();
fayang9adfb532020-06-04 06:58:45 -070010918 EXPECT_TRUE(connection_.HasPendingAcks());
fayangf44a6672020-05-27 12:51:45 -070010919 if (GetQuicReloadableFlag(quic_always_send_earliest_ack)) {
10920 EXPECT_EQ(clock_.ApproximateNow() + DefaultDelayedAckTime(),
10921 connection_.GetAckAlarm()->deadline());
10922 } else {
10923 // No forward progress has been made.
10924 EXPECT_EQ(clock_.ApproximateNow() + kAlarmGranularity,
10925 connection_.GetAckAlarm()->deadline());
10926 }
10927}
10928
fayangf78b6932020-06-08 08:36:45 -070010929TEST_P(QuicConnectionTest, ClientOnlyBlackholeDetectionClient) {
fayang656cbb52020-06-09 13:29:35 -070010930 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangf78b6932020-06-08 08:36:45 -070010931 return;
10932 }
10933 QuicConfig config;
10934 QuicTagVector connection_options;
10935 connection_options.push_back(kCBHD);
10936 config.SetConnectionOptionsToSend(connection_options);
10937 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10938 connection_.SetFromConfig(config);
10939 EXPECT_CALL(visitor_, GetHandshakeState())
10940 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
10941 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
10942 // Send stream data.
10943 SendStreamDataToPeer(
10944 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
10945 0, FIN, nullptr);
10946 // Verify blackhole detection is in progress.
10947 EXPECT_TRUE(connection_.GetBlackholeDetectorAlarm()->IsSet());
10948}
10949
10950TEST_P(QuicConnectionTest, ClientOnlyBlackholeDetectionServer) {
fayang656cbb52020-06-09 13:29:35 -070010951 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangf78b6932020-06-08 08:36:45 -070010952 return;
10953 }
10954 set_perspective(Perspective::IS_SERVER);
10955 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
10956 if (version().SupportsAntiAmplificationLimit()) {
10957 QuicConnectionPeer::SetAddressValidated(&connection_);
10958 }
10959 QuicConfig config;
10960 QuicTagVector connection_options;
10961 connection_options.push_back(kCBHD);
10962 config.SetInitialReceivedConnectionOptions(connection_options);
10963 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10964 connection_.SetFromConfig(config);
10965 EXPECT_CALL(visitor_, GetHandshakeState())
10966 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
10967 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
10968 // Send stream data.
10969 SendStreamDataToPeer(
10970 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
10971 0, FIN, nullptr);
10972 // Verify blackhole detection is disabled.
10973 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
10974}
10975
10976TEST_P(QuicConnectionTest, 2RtoBlackholeDetection) {
fayang656cbb52020-06-09 13:29:35 -070010977 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangf78b6932020-06-08 08:36:45 -070010978 return;
10979 }
10980 QuicConfig config;
10981 QuicTagVector connection_options;
10982 connection_options.push_back(k2RTO);
10983 config.SetConnectionOptionsToSend(connection_options);
10984 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10985 connection_.SetFromConfig(config);
10986 const size_t kMinRttMs = 40;
10987 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
10988 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
10989 QuicTime::Delta::Zero(), QuicTime::Zero());
10990 EXPECT_CALL(visitor_, GetHandshakeState())
10991 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
10992 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
10993 // Send stream data.
10994 SendStreamDataToPeer(
10995 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
10996 0, FIN, nullptr);
10997 // Verify blackhole delay is expected.
10998 EXPECT_EQ(clock_.Now() +
10999 connection_.sent_packet_manager().GetNetworkBlackholeDelay(2),
11000 QuicConnectionPeer::GetBlackholeDetectionDeadline(&connection_));
11001}
11002
11003TEST_P(QuicConnectionTest, 3RtoBlackholeDetection) {
fayang656cbb52020-06-09 13:29:35 -070011004 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangf78b6932020-06-08 08:36:45 -070011005 return;
11006 }
11007 QuicConfig config;
11008 QuicTagVector connection_options;
11009 connection_options.push_back(k3RTO);
11010 config.SetConnectionOptionsToSend(connection_options);
11011 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11012 connection_.SetFromConfig(config);
11013 const size_t kMinRttMs = 40;
11014 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
11015 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
11016 QuicTime::Delta::Zero(), QuicTime::Zero());
11017 EXPECT_CALL(visitor_, GetHandshakeState())
11018 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
11019 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
11020 // Send stream data.
11021 SendStreamDataToPeer(
11022 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
11023 0, FIN, nullptr);
11024 // Verify blackhole delay is expected.
11025 EXPECT_EQ(clock_.Now() +
11026 connection_.sent_packet_manager().GetNetworkBlackholeDelay(3),
11027 QuicConnectionPeer::GetBlackholeDetectionDeadline(&connection_));
11028}
11029
11030TEST_P(QuicConnectionTest, 4RtoBlackholeDetection) {
fayang656cbb52020-06-09 13:29:35 -070011031 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangf78b6932020-06-08 08:36:45 -070011032 return;
11033 }
11034 QuicConfig config;
11035 QuicTagVector connection_options;
11036 connection_options.push_back(k4RTO);
11037 config.SetConnectionOptionsToSend(connection_options);
11038 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11039 connection_.SetFromConfig(config);
11040 const size_t kMinRttMs = 40;
11041 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
11042 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
11043 QuicTime::Delta::Zero(), QuicTime::Zero());
11044 EXPECT_CALL(visitor_, GetHandshakeState())
11045 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
11046 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
11047 // Send stream data.
11048 SendStreamDataToPeer(
11049 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
11050 0, FIN, nullptr);
11051 // Verify blackhole delay is expected.
11052 EXPECT_EQ(clock_.Now() +
11053 connection_.sent_packet_manager().GetNetworkBlackholeDelay(4),
11054 QuicConnectionPeer::GetBlackholeDetectionDeadline(&connection_));
11055}
11056
11057TEST_P(QuicConnectionTest, 6RtoBlackholeDetection) {
fayang656cbb52020-06-09 13:29:35 -070011058 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangf78b6932020-06-08 08:36:45 -070011059 return;
11060 }
11061 QuicConfig config;
11062 QuicTagVector connection_options;
11063 connection_options.push_back(k6RTO);
11064 config.SetConnectionOptionsToSend(connection_options);
11065 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11066 connection_.SetFromConfig(config);
11067 const size_t kMinRttMs = 40;
11068 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
11069 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
11070 QuicTime::Delta::Zero(), QuicTime::Zero());
11071 EXPECT_CALL(visitor_, GetHandshakeState())
11072 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
11073 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
11074 // Send stream data.
11075 SendStreamDataToPeer(
11076 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
11077 0, FIN, nullptr);
11078 // Verify blackhole delay is expected.
11079 EXPECT_EQ(clock_.Now() +
11080 connection_.sent_packet_manager().GetNetworkBlackholeDelay(6),
11081 QuicConnectionPeer::GetBlackholeDetectionDeadline(&connection_));
11082}
11083
fayang656cbb52020-06-09 13:29:35 -070011084// Regresstion test for b/158491591.
11085TEST_P(QuicConnectionTest, MadeForwardProgressOnDiscardingKeys) {
11086 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
11087 return;
11088 }
11089 use_tagging_decrypter();
11090 // Send handshake packet.
11091 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
11092 std::make_unique<TaggingEncrypter>(0x02));
11093 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11094 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
11095 QuicConfig config;
11096 QuicTagVector connection_options;
11097 connection_options.push_back(k5RTO);
11098 config.SetConnectionOptionsToSend(connection_options);
11099 QuicConfigPeer::SetNegotiated(&config, true);
11100 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
11101 EXPECT_CALL(visitor_, GetHandshakeState())
11102 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
11103 }
11104 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
11105 QuicConfigPeer::SetReceivedOriginalConnectionId(
11106 &config, connection_.connection_id());
11107 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
11108 &config, connection_.connection_id());
11109 }
11110 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11111 connection_.SetFromConfig(config);
11112
11113 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
11114 EXPECT_TRUE(connection_.BlackholeDetectionInProgress());
11115 // Discard handshake keys.
11116 connection_.OnHandshakeComplete();
11117 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
11118 // Verify blackhole detection stops.
11119 EXPECT_FALSE(connection_.BlackholeDetectionInProgress());
11120 } else {
11121 // Problematic: although there is nothing in flight, blackhole detection is
11122 // still in progress.
11123 EXPECT_TRUE(connection_.BlackholeDetectionInProgress());
11124 }
11125}
11126
QUICHE teama6ef0a62019-03-07 20:34:33 -050011127} // namespace
11128} // namespace test
11129} // namespace quic