blob: 8d096ebe4f833cad3f0b06b56e9086a18a51eeb1 [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());
QUICHE teama6ef0a62019-03-07 20:34:33 -05001159 EXPECT_CALL(visitor_, OnForwardProgressConfirmed()).Times(AnyNumber());
wub256b2d62019-11-25 08:46:55 -08001160 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
fayang2f2915d2020-01-24 06:47:15 -08001161 EXPECT_CALL(visitor_, OnOneRttPacketAcknowledged())
1162 .Times(testing::AtMost(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001163 EXPECT_CALL(*loss_algorithm_, GetLossTimeout())
1164 .WillRepeatedly(Return(QuicTime::Zero()));
1165 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
1166 .Times(AnyNumber());
fayang5014e922020-01-22 12:28:11 -08001167 EXPECT_CALL(visitor_, GetHandshakeState())
1168 .WillRepeatedly(Return(HANDSHAKE_START));
zhongyi546cc452019-04-12 15:27:49 -07001169 if (connection_.version().KnowsWhichDecrypterToUse()) {
1170 connection_.InstallDecrypter(
1171 ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07001172 std::make_unique<NullDecrypter>(Perspective::IS_CLIENT));
zhongyi546cc452019-04-12 15:27:49 -07001173 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001174 }
1175
1176 QuicConnectionTest(const QuicConnectionTest&) = delete;
1177 QuicConnectionTest& operator=(const QuicConnectionTest&) = delete;
1178
1179 ParsedQuicVersion version() { return GetParam().version; }
1180
QUICHE teama6ef0a62019-03-07 20:34:33 -05001181 QuicStopWaitingFrame* stop_waiting() {
1182 QuicConnectionPeer::PopulateStopWaitingFrame(&connection_, &stop_waiting_);
1183 return &stop_waiting_;
1184 }
1185
1186 QuicPacketNumber least_unacked() {
1187 if (writer_->stop_waiting_frames().empty()) {
1188 return QuicPacketNumber();
1189 }
1190 return writer_->stop_waiting_frames()[0].least_unacked;
1191 }
1192
1193 void use_tagging_decrypter() { writer_->use_tagging_decrypter(); }
1194
zhongyi546cc452019-04-12 15:27:49 -07001195 void SetDecrypter(EncryptionLevel level,
1196 std::unique_ptr<QuicDecrypter> decrypter) {
1197 if (connection_.version().KnowsWhichDecrypterToUse()) {
1198 connection_.InstallDecrypter(level, std::move(decrypter));
1199 connection_.RemoveDecrypter(ENCRYPTION_INITIAL);
1200 } else {
1201 connection_.SetDecrypter(level, std::move(decrypter));
1202 }
1203 }
1204
QUICHE teama6ef0a62019-03-07 20:34:33 -05001205 void ProcessPacket(uint64_t number) {
1206 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
1207 ProcessDataPacket(number);
1208 if (connection_.GetSendAlarm()->IsSet()) {
1209 connection_.GetSendAlarm()->Fire();
1210 }
1211 }
1212
1213 void ProcessReceivedPacket(const QuicSocketAddress& self_address,
1214 const QuicSocketAddress& peer_address,
1215 const QuicReceivedPacket& packet) {
1216 connection_.ProcessUdpPacket(self_address, peer_address, packet);
1217 if (connection_.GetSendAlarm()->IsSet()) {
1218 connection_.GetSendAlarm()->Fire();
1219 }
1220 }
1221
wub8a5dafa2020-05-13 12:30:17 -07001222 QuicFrame MakeCryptoFrame() const {
1223 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1224 return QuicFrame(new QuicCryptoFrame(crypto_frame_));
1225 }
1226 return QuicFrame(QuicStreamFrame(
1227 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
1228 0u, quiche::QuicheStringPiece()));
1229 }
1230
QUICHE teama6ef0a62019-03-07 20:34:33 -05001231 void ProcessFramePacket(QuicFrame frame) {
1232 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
1233 }
1234
1235 void ProcessFramePacketWithAddresses(QuicFrame frame,
1236 QuicSocketAddress self_address,
1237 QuicSocketAddress peer_address) {
1238 QuicFrames frames;
1239 frames.push_back(QuicFrame(frame));
zhongyif06ca342020-02-24 14:11:13 -08001240 return ProcessFramesPacketWithAddresses(frames, self_address, peer_address);
1241 }
1242
1243 void ProcessFramesPacketWithAddresses(QuicFrames frames,
1244 QuicSocketAddress self_address,
1245 QuicSocketAddress peer_address) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001246 QuicPacketCreatorPeer::SetSendVersionInPacket(
wub031d47c2019-11-21 08:04:07 -08001247 &peer_creator_,
1248 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_) <
1249 ENCRYPTION_FORWARD_SECURE &&
1250 connection_.perspective() == Perspective::IS_SERVER);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001251
dschinazi66dea072019-04-09 11:41:06 -07001252 char buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05001253 SerializedPacket serialized_packet =
dschinazi66dea072019-04-09 11:41:06 -07001254 QuicPacketCreatorPeer::SerializeAllFrames(
1255 &peer_creator_, frames, buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001256 connection_.ProcessUdpPacket(
1257 self_address, peer_address,
1258 QuicReceivedPacket(serialized_packet.encrypted_buffer,
1259 serialized_packet.encrypted_length, clock_.Now()));
1260 if (connection_.GetSendAlarm()->IsSet()) {
1261 connection_.GetSendAlarm()->Fire();
1262 }
1263 }
1264
1265 // Bypassing the packet creator is unrealistic, but allows us to process
1266 // packets the QuicPacketCreator won't allow us to create.
1267 void ForceProcessFramePacket(QuicFrame frame) {
1268 QuicFrames frames;
1269 frames.push_back(QuicFrame(frame));
zhongyi546cc452019-04-12 15:27:49 -07001270 bool send_version = connection_.perspective() == Perspective::IS_SERVER;
1271 if (connection_.version().KnowsWhichDecrypterToUse()) {
1272 send_version = true;
1273 }
1274 QuicPacketCreatorPeer::SetSendVersionInPacket(&peer_creator_, send_version);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001275 QuicPacketHeader header;
1276 QuicPacketCreatorPeer::FillPacketHeader(&peer_creator_, &header);
dschinazi66dea072019-04-09 11:41:06 -07001277 char encrypted_buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05001278 size_t length = peer_framer_.BuildDataPacket(
dschinazi66dea072019-04-09 11:41:06 -07001279 header, frames, encrypted_buffer, kMaxOutgoingPacketSize,
1280 ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001281 DCHECK_GT(length, 0u);
1282
1283 const size_t encrypted_length = peer_framer_.EncryptInPlace(
QUICHE team6987b4a2019-03-15 16:23:04 -07001284 ENCRYPTION_INITIAL, header.packet_number,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001285 GetStartOfEncryptedData(peer_framer_.version().transport_version,
1286 header),
dschinazi66dea072019-04-09 11:41:06 -07001287 length, kMaxOutgoingPacketSize, encrypted_buffer);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001288 DCHECK_GT(encrypted_length, 0u);
1289
1290 connection_.ProcessUdpPacket(
1291 kSelfAddress, kPeerAddress,
1292 QuicReceivedPacket(encrypted_buffer, encrypted_length, clock_.Now()));
1293 }
1294
1295 size_t ProcessFramePacketAtLevel(uint64_t number,
1296 QuicFrame frame,
1297 EncryptionLevel level) {
fayang01062942020-01-22 07:23:23 -08001298 QuicFrames frames;
1299 frames.push_back(frame);
1300 return ProcessFramesPacketAtLevel(number, frames, level);
1301 }
1302
1303 size_t ProcessFramesPacketAtLevel(uint64_t number,
1304 const QuicFrames& frames,
1305 EncryptionLevel level) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001306 QuicPacketHeader header;
1307 header.destination_connection_id = connection_id_;
1308 header.packet_number_length = packet_number_length_;
1309 header.destination_connection_id_included = connection_id_included_;
dschinazi5e1a7b22019-07-31 12:23:21 -07001310 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001311 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1312 }
zhongyi546cc452019-04-12 15:27:49 -07001313 if (level == ENCRYPTION_INITIAL &&
1314 peer_framer_.version().KnowsWhichDecrypterToUse()) {
1315 header.version_flag = true;
nharperd43f1d62019-07-01 15:18:20 -07001316 if (QuicVersionHasLongHeaderLengths(peer_framer_.transport_version())) {
1317 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
1318 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
1319 }
QUICHE team2252b702019-05-14 23:55:14 -04001320 }
dschinazi5e1a7b22019-07-31 12:23:21 -07001321 if (header.version_flag &&
QUICHE team2252b702019-05-14 23:55:14 -04001322 peer_framer_.perspective() == Perspective::IS_SERVER) {
1323 header.source_connection_id = connection_id_;
1324 header.source_connection_id_included = CONNECTION_ID_PRESENT;
zhongyi546cc452019-04-12 15:27:49 -07001325 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001326 header.packet_number = QuicPacketNumber(number);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001327 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
QUICHE teamcd098022019-03-22 18:49:55 -07001328 // Set the correct encryption level and encrypter on peer_creator and
1329 // peer_framer, respectively.
1330 peer_creator_.set_encryption_level(level);
1331 if (QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_) >
1332 ENCRYPTION_INITIAL) {
1333 peer_framer_.SetEncrypter(
1334 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
vasilvv0fc587f2019-09-06 13:33:08 -07001335 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teamcd098022019-03-22 18:49:55 -07001336 // Set the corresponding decrypter.
zhongyi546cc452019-04-12 15:27:49 -07001337 if (connection_.version().KnowsWhichDecrypterToUse()) {
1338 connection_.InstallDecrypter(
1339 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
vasilvv0fc587f2019-09-06 13:33:08 -07001340 std::make_unique<StrictTaggingDecrypter>(0x01));
zhongyi546cc452019-04-12 15:27:49 -07001341 connection_.RemoveDecrypter(ENCRYPTION_INITIAL);
1342 } else {
1343 connection_.SetDecrypter(
1344 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
vasilvv0fc587f2019-09-06 13:33:08 -07001345 std::make_unique<StrictTaggingDecrypter>(0x01));
zhongyi546cc452019-04-12 15:27:49 -07001346 }
QUICHE teamcd098022019-03-22 18:49:55 -07001347 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001348
dschinazi66dea072019-04-09 11:41:06 -07001349 char buffer[kMaxOutgoingPacketSize];
1350 size_t encrypted_length =
1351 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
1352 buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001353 connection_.ProcessUdpPacket(
1354 kSelfAddress, kPeerAddress,
QUICHE teamcd098022019-03-22 18:49:55 -07001355 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1356 if (connection_.GetSendAlarm()->IsSet()) {
1357 connection_.GetSendAlarm()->Fire();
1358 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001359 return encrypted_length;
1360 }
1361
1362 size_t ProcessDataPacket(uint64_t number) {
nharper2c9f02a2019-05-08 10:25:50 -07001363 return ProcessDataPacketAtLevel(number, false, ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001364 }
1365
1366 size_t ProcessDataPacket(QuicPacketNumber packet_number) {
nharper2c9f02a2019-05-08 10:25:50 -07001367 return ProcessDataPacketAtLevel(packet_number, false,
1368 ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001369 }
1370
1371 size_t ProcessDataPacketAtLevel(QuicPacketNumber packet_number,
1372 bool has_stop_waiting,
1373 EncryptionLevel level) {
1374 return ProcessDataPacketAtLevel(packet_number.ToUint64(), has_stop_waiting,
1375 level);
1376 }
1377
dschinazi17d42422019-06-18 16:35:07 -07001378 size_t ProcessCryptoPacketAtLevel(uint64_t number,
1379 EncryptionLevel /*level*/) {
fayangc31c9952019-06-05 13:54:48 -07001380 QuicPacketHeader header = ConstructPacketHeader(number, ENCRYPTION_INITIAL);
nharper46833c32019-05-15 21:33:05 -07001381 QuicFrames frames;
1382 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1383 frames.push_back(QuicFrame(&crypto_frame_));
1384 } else {
1385 frames.push_back(QuicFrame(frame1_));
1386 }
fayang5f135052019-08-22 17:59:40 -07001387 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
nharper46833c32019-05-15 21:33:05 -07001388 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
1389 char buffer[kMaxOutgoingPacketSize];
1390 peer_creator_.set_encryption_level(ENCRYPTION_INITIAL);
fayangc31c9952019-06-05 13:54:48 -07001391 size_t encrypted_length = peer_framer_.EncryptPayload(
1392 ENCRYPTION_INITIAL, QuicPacketNumber(number), *packet, buffer,
1393 kMaxOutgoingPacketSize);
nharper46833c32019-05-15 21:33:05 -07001394 connection_.ProcessUdpPacket(
1395 kSelfAddress, kPeerAddress,
1396 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1397 if (connection_.GetSendAlarm()->IsSet()) {
1398 connection_.GetSendAlarm()->Fire();
1399 }
1400 return encrypted_length;
1401 }
1402
QUICHE teama6ef0a62019-03-07 20:34:33 -05001403 size_t ProcessDataPacketAtLevel(uint64_t number,
1404 bool has_stop_waiting,
1405 EncryptionLevel level) {
1406 std::unique_ptr<QuicPacket> packet(
QUICHE team8c1daa22019-03-13 08:33:41 -07001407 ConstructDataPacket(number, has_stop_waiting, level));
dschinazi66dea072019-04-09 11:41:06 -07001408 char buffer[kMaxOutgoingPacketSize];
QUICHE teamcd098022019-03-22 18:49:55 -07001409 peer_creator_.set_encryption_level(level);
dschinazi66dea072019-04-09 11:41:06 -07001410 size_t encrypted_length =
1411 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
1412 buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001413 connection_.ProcessUdpPacket(
1414 kSelfAddress, kPeerAddress,
1415 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1416 if (connection_.GetSendAlarm()->IsSet()) {
1417 connection_.GetSendAlarm()->Fire();
1418 }
1419 return encrypted_length;
1420 }
1421
1422 void ProcessClosePacket(uint64_t number) {
1423 std::unique_ptr<QuicPacket> packet(ConstructClosePacket(number));
dschinazi66dea072019-04-09 11:41:06 -07001424 char buffer[kMaxOutgoingPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07001425 size_t encrypted_length = peer_framer_.EncryptPayload(
nharperc6b99512019-09-19 11:13:48 -07001426 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(number), *packet, buffer,
dschinazi66dea072019-04-09 11:41:06 -07001427 kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001428 connection_.ProcessUdpPacket(
1429 kSelfAddress, kPeerAddress,
1430 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
1431 }
1432
1433 QuicByteCount SendStreamDataToPeer(QuicStreamId id,
dmcardlecf0bfcf2019-12-13 08:08:21 -08001434 quiche::QuicheStringPiece data,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001435 QuicStreamOffset offset,
1436 StreamSendingState state,
1437 QuicPacketNumber* last_packet) {
1438 QuicByteCount packet_size;
fayang0fcbf352019-08-30 11:15:58 -07001439 // Save the last packet's size.
QUICHE teama6ef0a62019-03-07 20:34:33 -05001440 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
fayang0fcbf352019-08-30 11:15:58 -07001441 .Times(AnyNumber())
1442 .WillRepeatedly(SaveArg<3>(&packet_size));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001443 connection_.SendStreamDataWithString(id, data, offset, state);
1444 if (last_packet != nullptr) {
1445 *last_packet = creator_->packet_number();
1446 }
1447 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1448 .Times(AnyNumber());
1449 return packet_size;
1450 }
1451
1452 void SendAckPacketToPeer() {
1453 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1454 {
fayanga4b37b22019-06-18 13:37:47 -07001455 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001456 connection_.SendAck();
1457 }
1458 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1459 .Times(AnyNumber());
1460 }
1461
1462 void SendRstStream(QuicStreamId id,
1463 QuicRstStreamErrorCode error,
1464 QuicStreamOffset bytes_written) {
fayangcff885a2019-10-22 07:39:04 -07001465 notifier_.WriteOrBufferRstStream(id, error, bytes_written);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001466 connection_.OnStreamReset(id, error);
1467 }
1468
fayangcff885a2019-10-22 07:39:04 -07001469 void SendPing() { notifier_.WriteOrBufferPing(); }
zhongyifbb25772019-04-10 16:54:08 -07001470
fayang61453cb2020-03-11 11:32:26 -07001471 MessageStatus SendMessage(quiche::QuicheStringPiece message) {
1472 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1473 QuicMemSliceStorage storage(nullptr, 0, nullptr, 0);
1474 return connection_.SendMessage(
1475 1,
1476 MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(), message,
1477 &storage),
1478 false);
1479 }
1480
QUICHE teama6ef0a62019-03-07 20:34:33 -05001481 void ProcessAckPacket(uint64_t packet_number, QuicAckFrame* frame) {
1482 if (packet_number > 1) {
1483 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, packet_number - 1);
1484 } else {
1485 QuicPacketCreatorPeer::ClearPacketNumber(&peer_creator_);
1486 }
1487 ProcessFramePacket(QuicFrame(frame));
1488 }
1489
1490 void ProcessAckPacket(QuicAckFrame* frame) {
1491 ProcessFramePacket(QuicFrame(frame));
1492 }
1493
1494 void ProcessStopWaitingPacket(QuicStopWaitingFrame frame) {
1495 ProcessFramePacket(QuicFrame(frame));
1496 }
1497
1498 size_t ProcessStopWaitingPacketAtLevel(uint64_t number,
1499 QuicStopWaitingFrame frame,
dschinazi17d42422019-06-18 16:35:07 -07001500 EncryptionLevel /*level*/) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001501 return ProcessFramePacketAtLevel(number, QuicFrame(frame),
1502 ENCRYPTION_ZERO_RTT);
1503 }
1504
1505 void ProcessGoAwayPacket(QuicGoAwayFrame* frame) {
1506 ProcessFramePacket(QuicFrame(frame));
1507 }
1508
1509 bool IsMissing(uint64_t number) {
fayangc31c9952019-06-05 13:54:48 -07001510 return IsAwaitingPacket(connection_.ack_frame(), QuicPacketNumber(number),
QUICHE teama6ef0a62019-03-07 20:34:33 -05001511 QuicPacketNumber());
1512 }
1513
1514 std::unique_ptr<QuicPacket> ConstructPacket(const QuicPacketHeader& header,
1515 const QuicFrames& frames) {
1516 auto packet = BuildUnsizedDataPacket(&peer_framer_, header, frames);
1517 EXPECT_NE(nullptr, packet.get());
1518 return packet;
1519 }
1520
nharper46833c32019-05-15 21:33:05 -07001521 QuicPacketHeader ConstructPacketHeader(uint64_t number,
1522 EncryptionLevel level) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001523 QuicPacketHeader header;
fayangd4291e42019-05-30 10:31:21 -07001524 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version()) &&
QUICHE team8c1daa22019-03-13 08:33:41 -07001525 level < ENCRYPTION_FORWARD_SECURE) {
1526 // Set long header type accordingly.
1527 header.version_flag = true;
nharperc6b99512019-09-19 11:13:48 -07001528 header.form = IETF_QUIC_LONG_HEADER_PACKET;
QUICHE team8c1daa22019-03-13 08:33:41 -07001529 header.long_packet_type = EncryptionlevelToLongHeaderType(level);
1530 if (QuicVersionHasLongHeaderLengths(
1531 peer_framer_.version().transport_version)) {
1532 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
1533 if (header.long_packet_type == INITIAL) {
1534 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
1535 }
1536 }
1537 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001538 // Set connection_id to peer's in memory representation as this data packet
1539 // is created by peer_framer.
dschinazi5e1a7b22019-07-31 12:23:21 -07001540 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
QUICHE team2252b702019-05-14 23:55:14 -04001541 header.source_connection_id = connection_id_;
1542 header.source_connection_id_included = connection_id_included_;
1543 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1544 } else {
1545 header.destination_connection_id = connection_id_;
1546 header.destination_connection_id_included = connection_id_included_;
1547 }
fayangd4291e42019-05-30 10:31:21 -07001548 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version()) &&
QUICHE teama6ef0a62019-03-07 20:34:33 -05001549 peer_framer_.perspective() == Perspective::IS_SERVER) {
1550 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
QUICHE team8c1daa22019-03-13 08:33:41 -07001551 if (header.version_flag) {
1552 header.source_connection_id = connection_id_;
1553 header.source_connection_id_included = CONNECTION_ID_PRESENT;
1554 if (GetParam().version.handshake_protocol == PROTOCOL_QUIC_CRYPTO &&
1555 header.long_packet_type == ZERO_RTT_PROTECTED) {
QUICHE team548d51b2019-03-14 10:06:54 -07001556 header.nonce = &kTestDiversificationNonce;
QUICHE team8c1daa22019-03-13 08:33:41 -07001557 }
1558 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001559 }
QUICHE team2252b702019-05-14 23:55:14 -04001560 header.packet_number_length = packet_number_length_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001561 header.packet_number = QuicPacketNumber(number);
nharper46833c32019-05-15 21:33:05 -07001562 return header;
1563 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001564
nharper46833c32019-05-15 21:33:05 -07001565 std::unique_ptr<QuicPacket> ConstructDataPacket(uint64_t number,
1566 bool has_stop_waiting,
1567 EncryptionLevel level) {
1568 QuicPacketHeader header = ConstructPacketHeader(number, level);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001569 QuicFrames frames;
1570 frames.push_back(QuicFrame(frame1_));
1571 if (has_stop_waiting) {
1572 frames.push_back(QuicFrame(stop_waiting_));
1573 }
1574 return ConstructPacket(header, frames);
1575 }
1576
wub8a5dafa2020-05-13 12:30:17 -07001577 std::unique_ptr<SerializedPacket> ConstructProbingPacket() {
fkastenholz305e1732019-06-18 05:01:22 -07001578 if (VersionHasIetfQuicFrames(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001579 QuicPathFrameBuffer payload = {
1580 {0xde, 0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xfe}};
1581 return QuicPacketCreatorPeer::
1582 SerializePathChallengeConnectivityProbingPacket(&peer_creator_,
1583 &payload);
1584 }
1585 return QuicPacketCreatorPeer::SerializeConnectivityProbingPacket(
1586 &peer_creator_);
1587 }
1588
1589 std::unique_ptr<QuicPacket> ConstructClosePacket(uint64_t number) {
1590 QuicPacketHeader header;
1591 // Set connection_id to peer's in memory representation as this connection
1592 // close packet is created by peer_framer.
dschinazi5e1a7b22019-07-31 12:23:21 -07001593 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
QUICHE team2252b702019-05-14 23:55:14 -04001594 header.source_connection_id = connection_id_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001595 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
fayangd4291e42019-05-30 10:31:21 -07001596 if (!VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04001597 header.source_connection_id_included = CONNECTION_ID_PRESENT;
1598 }
1599 } else {
1600 header.destination_connection_id = connection_id_;
fayangd4291e42019-05-30 10:31:21 -07001601 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04001602 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1603 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001604 }
1605
QUICHE team2252b702019-05-14 23:55:14 -04001606 header.packet_number = QuicPacketNumber(number);
1607
fkastenholz0d6554a2019-08-05 12:20:35 -07001608 QuicErrorCode kQuicErrorCode = QUIC_PEER_GOING_AWAY;
fkastenholz591814c2019-09-06 12:11:46 -07001609 QuicConnectionCloseFrame qccf(peer_framer_.transport_version(),
1610 kQuicErrorCode, "",
1611 /*transport_close_frame_type=*/0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001612 QuicFrames frames;
1613 frames.push_back(QuicFrame(&qccf));
1614 return ConstructPacket(header, frames);
1615 }
1616
1617 QuicTime::Delta DefaultRetransmissionTime() {
1618 return QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
1619 }
1620
1621 QuicTime::Delta DefaultDelayedAckTime() {
1622 return QuicTime::Delta::FromMilliseconds(kDefaultDelayedAckTimeMs);
1623 }
1624
1625 const QuicStopWaitingFrame InitStopWaitingFrame(uint64_t least_unacked) {
1626 QuicStopWaitingFrame frame;
1627 frame.least_unacked = QuicPacketNumber(least_unacked);
1628 return frame;
1629 }
1630
1631 // Construct a ack_frame that acks all packet numbers between 1 and
1632 // |largest_acked|, except |missing|.
1633 // REQUIRES: 1 <= |missing| < |largest_acked|
1634 QuicAckFrame ConstructAckFrame(uint64_t largest_acked, uint64_t missing) {
1635 return ConstructAckFrame(QuicPacketNumber(largest_acked),
1636 QuicPacketNumber(missing));
1637 }
1638
1639 QuicAckFrame ConstructAckFrame(QuicPacketNumber largest_acked,
1640 QuicPacketNumber missing) {
1641 if (missing == QuicPacketNumber(1)) {
1642 return InitAckFrame({{missing + 1, largest_acked + 1}});
1643 }
1644 return InitAckFrame(
1645 {{QuicPacketNumber(1), missing}, {missing + 1, largest_acked + 1}});
1646 }
1647
1648 // Undo nacking a packet within the frame.
1649 void AckPacket(QuicPacketNumber arrived, QuicAckFrame* frame) {
1650 EXPECT_FALSE(frame->packets.Contains(arrived));
1651 frame->packets.Add(arrived);
1652 }
1653
1654 void TriggerConnectionClose() {
1655 // Send an erroneous packet to close the connection.
fkastenholz5d880a92019-06-21 09:01:56 -07001656 EXPECT_CALL(visitor_,
1657 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
1658 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
1659
QUICHE teamcd098022019-03-22 18:49:55 -07001660 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1661 // Triggers a connection by receiving ACK of unsent packet.
1662 QuicAckFrame frame = InitAckFrame(10000);
1663 ProcessAckPacket(1, &frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001664 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1665 nullptr);
fkastenholz5d880a92019-06-21 09:01:56 -07001666 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08001667 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
1668 IsError(QUIC_INVALID_ACK_DATA));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001669 }
1670
1671 void BlockOnNextWrite() {
1672 writer_->BlockOnNextWrite();
1673 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
1674 }
1675
1676 void SimulateNextPacketTooLarge() { writer_->SimulateNextPacketTooLarge(); }
1677
1678 void AlwaysGetPacketTooLarge() { writer_->AlwaysGetPacketTooLarge(); }
1679
1680 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
1681 writer_->SetWritePauseTimeDelta(delta);
1682 }
1683
1684 void CongestionBlockWrites() {
1685 EXPECT_CALL(*send_algorithm_, CanSend(_))
1686 .WillRepeatedly(testing::Return(false));
1687 }
1688
1689 void CongestionUnblockWrites() {
1690 EXPECT_CALL(*send_algorithm_, CanSend(_))
1691 .WillRepeatedly(testing::Return(true));
1692 }
1693
1694 void set_perspective(Perspective perspective) {
1695 connection_.set_perspective(perspective);
1696 if (perspective == Perspective::IS_SERVER) {
1697 connection_.set_can_truncate_connection_ids(true);
wub256b2d62019-11-25 08:46:55 -08001698 QuicConnectionPeer::SetNegotiatedVersion(&connection_);
wubbea386e2020-01-27 09:04:51 -08001699 connection_.OnSuccessfulVersionNegotiation();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001700 }
1701 QuicFramerPeer::SetPerspective(&peer_framer_,
nharper4eba09b2019-06-26 20:17:25 -07001702 QuicUtils::InvertPerspective(perspective));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001703 }
1704
1705 void set_packets_between_probes_base(
1706 const QuicPacketCount packets_between_probes_base) {
wub173916e2019-11-27 14:36:24 -08001707 QuicConnectionPeer::ReInitializeMtuDiscoverer(
1708 &connection_, packets_between_probes_base,
1709 QuicPacketNumber(packets_between_probes_base));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001710 }
1711
1712 bool IsDefaultTestConfiguration() {
1713 TestParams p = GetParam();
1714 return p.ack_response == AckResponse::kImmediate &&
1715 p.version == AllSupportedVersions()[0] && p.no_stop_waiting;
1716 }
1717
fkastenholz5d880a92019-06-21 09:01:56 -07001718 void TestConnectionCloseQuicErrorCode(QuicErrorCode expected_code) {
1719 // Not strictly needed for this test, but is commonly done.
1720 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1721 nullptr);
1722 const std::vector<QuicConnectionCloseFrame>& connection_close_frames =
1723 writer_->connection_close_frames();
1724 ASSERT_EQ(1u, connection_close_frames.size());
bnc77e77b82020-04-05 10:36:49 -07001725
dschinazi39e5e552020-05-06 13:55:24 -07001726 EXPECT_THAT(connection_close_frames[0].quic_error_code,
1727 IsError(expected_code));
bnc77e77b82020-04-05 10:36:49 -07001728
fkastenholz0d6554a2019-08-05 12:20:35 -07001729 if (!VersionHasIetfQuicFrames(version().transport_version)) {
dschinazi39e5e552020-05-06 13:55:24 -07001730 EXPECT_THAT(connection_close_frames[0].wire_error_code,
1731 IsError(expected_code));
fkastenholz0d6554a2019-08-05 12:20:35 -07001732 EXPECT_EQ(GOOGLE_QUIC_CONNECTION_CLOSE,
1733 connection_close_frames[0].close_type);
1734 return;
1735 }
1736
1737 QuicErrorCodeToIetfMapping mapping =
1738 QuicErrorCodeToTransportErrorCode(expected_code);
1739
bnc0054cc62020-04-09 18:22:57 -07001740 if (mapping.is_transport_close) {
fkastenholz0d6554a2019-08-05 12:20:35 -07001741 // This Google QUIC Error Code maps to a transport close,
1742 EXPECT_EQ(IETF_QUIC_TRANSPORT_CONNECTION_CLOSE,
1743 connection_close_frames[0].close_type);
fkastenholz0d6554a2019-08-05 12:20:35 -07001744 } else {
1745 // This maps to an application close.
fkastenholz0d6554a2019-08-05 12:20:35 -07001746 EXPECT_EQ(IETF_QUIC_APPLICATION_CONNECTION_CLOSE,
1747 connection_close_frames[0].close_type);
fkastenholz0d6554a2019-08-05 12:20:35 -07001748 }
bnc0054cc62020-04-09 18:22:57 -07001749 EXPECT_EQ(mapping.error_code, connection_close_frames[0].wire_error_code);
fkastenholz5d880a92019-06-21 09:01:56 -07001750 }
1751
wub031d47c2019-11-21 08:04:07 -08001752 void MtuDiscoveryTestInit() {
1753 set_perspective(Perspective::IS_SERVER);
wub031d47c2019-11-21 08:04:07 -08001754 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
fayang6a258412020-05-28 08:57:12 -07001755 if (version().SupportsAntiAmplificationLimit()) {
1756 QuicConnectionPeer::SetAddressValidated(&connection_);
1757 }
wub031d47c2019-11-21 08:04:07 -08001758 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1759 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
1760 // QuicFramer::GetMaxPlaintextSize uses the smallest max plaintext size
1761 // across all encrypters. The initial encrypter used with IETF QUIC has a
1762 // 16-byte overhead, while the NullEncrypter used throughout this test has a
1763 // 12-byte overhead. This test tests behavior that relies on computing the
1764 // packet size correctly, so by unsetting the initial encrypter, we avoid
1765 // having a mismatch between the overheads for the encrypters used. In
1766 // non-test scenarios all encrypters used for a given connection have the
1767 // same overhead, either 12 bytes for ones using Google QUIC crypto, or 16
1768 // bytes for ones using TLS.
1769 connection_.SetEncrypter(ENCRYPTION_INITIAL, nullptr);
wubecb643f2020-03-19 08:58:46 -07001770 // Prevent packets from being coalesced.
1771 EXPECT_CALL(visitor_, GetHandshakeState())
1772 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
wub031d47c2019-11-21 08:04:07 -08001773 EXPECT_TRUE(connection_.connected());
1774 }
1775
dschinazi39e5e552020-05-06 13:55:24 -07001776 void TestClientRetryHandling(bool invalid_retry_tag,
dschinazie7c38a52020-05-29 15:25:45 -07001777 bool missing_original_id_in_config,
1778 bool wrong_original_id_in_config,
1779 bool missing_retry_id_in_config,
1780 bool wrong_retry_id_in_config);
dschinazi39e5e552020-05-06 13:55:24 -07001781
QUICHE teama6ef0a62019-03-07 20:34:33 -05001782 QuicConnectionId connection_id_;
1783 QuicFramer framer_;
1784
1785 MockSendAlgorithm* send_algorithm_;
1786 std::unique_ptr<MockLossAlgorithm> loss_algorithm_;
1787 MockClock clock_;
1788 MockRandom random_generator_;
1789 SimpleBufferAllocator buffer_allocator_;
1790 std::unique_ptr<TestConnectionHelper> helper_;
1791 std::unique_ptr<TestAlarmFactory> alarm_factory_;
1792 QuicFramer peer_framer_;
1793 QuicPacketCreator peer_creator_;
1794 std::unique_ptr<TestPacketWriter> writer_;
1795 TestConnection connection_;
1796 QuicPacketCreator* creator_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001797 QuicSentPacketManager* manager_;
1798 StrictMock<MockQuicConnectionVisitor> visitor_;
1799
1800 QuicStreamFrame frame1_;
1801 QuicStreamFrame frame2_;
nharper46833c32019-05-15 21:33:05 -07001802 QuicCryptoFrame crypto_frame_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001803 QuicAckFrame ack_;
1804 QuicStopWaitingFrame stop_waiting_;
1805 QuicPacketNumberLength packet_number_length_;
1806 QuicConnectionIdIncluded connection_id_included_;
1807
1808 SimpleSessionNotifier notifier_;
fkastenholz5d880a92019-06-21 09:01:56 -07001809
1810 QuicConnectionCloseFrame saved_connection_close_frame_;
1811 int connection_close_frame_count_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001812};
1813
1814// Run all end to end tests with all supported versions.
dschinazi39e5e552020-05-06 13:55:24 -07001815INSTANTIATE_TEST_SUITE_P(QuicConnectionTests,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001816 QuicConnectionTest,
dschinazi142051a2019-09-18 18:17:29 -07001817 ::testing::ValuesIn(GetTestParams()),
1818 ::testing::PrintToStringParamName());
QUICHE teama6ef0a62019-03-07 20:34:33 -05001819
fkastenholz0d6554a2019-08-05 12:20:35 -07001820// These two tests ensure that the QuicErrorCode mapping works correctly.
1821// Both tests expect to see a Google QUIC close if not running IETF QUIC.
1822// If running IETF QUIC, the first will generate a transport connection
1823// close, the second an application connection close.
1824// The connection close codes for the two tests are manually chosen;
1825// they are expected to always map to transport- and application-
dschinazi39e5e552020-05-06 13:55:24 -07001826// closes, respectively. If that changes, new codes should be chosen.
fkastenholz0d6554a2019-08-05 12:20:35 -07001827TEST_P(QuicConnectionTest, CloseErrorCodeTestTransport) {
1828 EXPECT_TRUE(connection_.connected());
1829 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
1830 connection_.CloseConnection(
1831 IETF_QUIC_PROTOCOL_VIOLATION, "Should be transport close",
1832 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1833 EXPECT_FALSE(connection_.connected());
1834 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
1835}
1836
1837// Test that the IETF QUIC Error code mapping function works
1838// properly for application connection close codes.
1839TEST_P(QuicConnectionTest, CloseErrorCodeTestApplication) {
1840 EXPECT_TRUE(connection_.connected());
1841 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
1842 connection_.CloseConnection(
1843 QUIC_HEADERS_STREAM_DATA_DECOMPRESS_FAILURE,
1844 "Should be application close",
1845 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1846 EXPECT_FALSE(connection_.connected());
1847 TestConnectionCloseQuicErrorCode(QUIC_HEADERS_STREAM_DATA_DECOMPRESS_FAILURE);
1848}
1849
QUICHE teama6ef0a62019-03-07 20:34:33 -05001850TEST_P(QuicConnectionTest, SelfAddressChangeAtClient) {
1851 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1852
1853 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
1854 EXPECT_TRUE(connection_.connected());
1855
nharper46833c32019-05-15 21:33:05 -07001856 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07001857 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1858 } else {
nharper46833c32019-05-15 21:33:05 -07001859 EXPECT_CALL(visitor_, OnStreamFrame(_));
1860 }
wub8a5dafa2020-05-13 12:30:17 -07001861 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
1862 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001863 // Cause change in self_address.
1864 QuicIpAddress host;
1865 host.FromString("1.1.1.1");
1866 QuicSocketAddress self_address(host, 123);
nharper46833c32019-05-15 21:33:05 -07001867 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1868 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1869 } else {
1870 EXPECT_CALL(visitor_, OnStreamFrame(_));
1871 }
wub8a5dafa2020-05-13 12:30:17 -07001872 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address,
1873 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001874 EXPECT_TRUE(connection_.connected());
1875}
1876
1877TEST_P(QuicConnectionTest, SelfAddressChangeAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001878 set_perspective(Perspective::IS_SERVER);
1879 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1880
1881 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1882 EXPECT_TRUE(connection_.connected());
1883
nharper46833c32019-05-15 21:33:05 -07001884 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07001885 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1886 } else {
nharper46833c32019-05-15 21:33:05 -07001887 EXPECT_CALL(visitor_, OnStreamFrame(_));
1888 }
wub8a5dafa2020-05-13 12:30:17 -07001889 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
1890 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001891 // Cause change in self_address.
1892 QuicIpAddress host;
1893 host.FromString("1.1.1.1");
1894 QuicSocketAddress self_address(host, 123);
1895 EXPECT_CALL(visitor_, AllowSelfAddressChange()).WillOnce(Return(false));
fkastenholz5d880a92019-06-21 09:01:56 -07001896 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
wub8a5dafa2020-05-13 12:30:17 -07001897 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address,
1898 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001899 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07001900 TestConnectionCloseQuicErrorCode(QUIC_ERROR_MIGRATING_ADDRESS);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001901}
1902
1903TEST_P(QuicConnectionTest, AllowSelfAddressChangeToMappedIpv4AddressAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001904 set_perspective(Perspective::IS_SERVER);
1905 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1906
1907 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1908 EXPECT_TRUE(connection_.connected());
1909
nharper46833c32019-05-15 21:33:05 -07001910 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07001911 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(3);
1912 } else {
nharper46833c32019-05-15 21:33:05 -07001913 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(3);
1914 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001915 QuicIpAddress host;
1916 host.FromString("1.1.1.1");
1917 QuicSocketAddress self_address1(host, 443);
wub8a5dafa2020-05-13 12:30:17 -07001918 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address1,
1919 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001920 // Cause self_address change to mapped Ipv4 address.
1921 QuicIpAddress host2;
dmcardlecf0bfcf2019-12-13 08:08:21 -08001922 host2.FromString(quiche::QuicheStrCat(
1923 "::ffff:", connection_.self_address().host().ToString()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001924 QuicSocketAddress self_address2(host2, connection_.self_address().port());
wub8a5dafa2020-05-13 12:30:17 -07001925 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address2,
1926 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001927 EXPECT_TRUE(connection_.connected());
1928 // self_address change back to Ipv4 address.
wub8a5dafa2020-05-13 12:30:17 -07001929 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address1,
1930 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001931 EXPECT_TRUE(connection_.connected());
1932}
1933
1934TEST_P(QuicConnectionTest, ClientAddressChangeAndPacketReordered) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001935 set_perspective(Perspective::IS_SERVER);
1936 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1937
1938 // Clear direct_peer_address.
1939 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1940 // Clear effective_peer_address, it is the same as direct_peer_address for
1941 // this test.
1942 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1943 QuicSocketAddress());
1944
nharper46833c32019-05-15 21:33:05 -07001945 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07001946 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1947 } else {
nharper46833c32019-05-15 21:33:05 -07001948 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1949 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001950 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001951 const QuicSocketAddress kNewPeerAddress =
1952 QuicSocketAddress(QuicIpAddress::Loopback6(),
1953 /*port=*/23456);
wub8a5dafa2020-05-13 12:30:17 -07001954 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
1955 kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001956 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1957 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1958
1959 // Decrease packet number to simulate out-of-order packets.
1960 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 4);
1961 // This is an old packet, do not migrate.
1962 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
wub8a5dafa2020-05-13 12:30:17 -07001963 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
1964 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001965 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1966 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1967}
1968
1969TEST_P(QuicConnectionTest, PeerAddressChangeAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001970 set_perspective(Perspective::IS_SERVER);
1971 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1972 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1973
1974 // Clear direct_peer_address.
1975 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1976 // Clear effective_peer_address, it is the same as direct_peer_address for
1977 // this test.
1978 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1979 QuicSocketAddress());
1980 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1981
nharper46833c32019-05-15 21:33:05 -07001982 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07001983 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1984 } else {
nharper46833c32019-05-15 21:33:05 -07001985 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1986 }
wub8a5dafa2020-05-13 12:30:17 -07001987 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
1988 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001989 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1990 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1991
1992 // Process another packet with a different peer address on server side will
1993 // start connection migration.
1994 const QuicSocketAddress kNewPeerAddress =
1995 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
1996 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
wub8a5dafa2020-05-13 12:30:17 -07001997 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
1998 kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001999 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2000 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2001}
2002
2003TEST_P(QuicConnectionTest, EffectivePeerAddressChangeAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002004 set_perspective(Perspective::IS_SERVER);
2005 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2006 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
fayang6a258412020-05-28 08:57:12 -07002007 if (version().SupportsAntiAmplificationLimit()) {
2008 QuicConnectionPeer::SetAddressValidated(&connection_);
2009 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002010
2011 // Clear direct_peer_address.
2012 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2013 // Clear effective_peer_address, it is different from direct_peer_address for
2014 // this test.
2015 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2016 QuicSocketAddress());
2017 const QuicSocketAddress kEffectivePeerAddress =
2018 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/43210);
2019 connection_.ReturnEffectivePeerAddressForNextPacket(kEffectivePeerAddress);
2020
nharper46833c32019-05-15 21:33:05 -07002021 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07002022 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2023 } else {
nharper46833c32019-05-15 21:33:05 -07002024 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2025 }
wub8a5dafa2020-05-13 12:30:17 -07002026 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2027 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002028 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2029 EXPECT_EQ(kEffectivePeerAddress, connection_.effective_peer_address());
2030
2031 // Process another packet with the same direct peer address and different
2032 // effective peer address on server side will start connection migration.
2033 const QuicSocketAddress kNewEffectivePeerAddress =
2034 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/54321);
2035 connection_.ReturnEffectivePeerAddressForNextPacket(kNewEffectivePeerAddress);
2036 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
wub8a5dafa2020-05-13 12:30:17 -07002037 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2038 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002039 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2040 EXPECT_EQ(kNewEffectivePeerAddress, connection_.effective_peer_address());
2041
2042 // Process another packet with a different direct peer address and the same
2043 // effective peer address on server side will not start connection migration.
2044 const QuicSocketAddress kNewPeerAddress =
2045 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2046 connection_.ReturnEffectivePeerAddressForNextPacket(kNewEffectivePeerAddress);
2047 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2048 // ack_frame is used to complete the migration started by the last packet, we
2049 // need to make sure a new migration does not start after the previous one is
2050 // completed.
2051 QuicAckFrame ack_frame = InitAckFrame(1);
2052 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
2053 ProcessFramePacketWithAddresses(QuicFrame(&ack_frame), kSelfAddress,
2054 kNewPeerAddress);
2055 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2056 EXPECT_EQ(kNewEffectivePeerAddress, connection_.effective_peer_address());
2057
2058 // Process another packet with different direct peer address and different
2059 // effective peer address on server side will start connection migration.
2060 const QuicSocketAddress kNewerEffectivePeerAddress =
2061 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/65432);
2062 const QuicSocketAddress kFinalPeerAddress =
2063 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/34567);
2064 connection_.ReturnEffectivePeerAddressForNextPacket(
2065 kNewerEffectivePeerAddress);
2066 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
wub8a5dafa2020-05-13 12:30:17 -07002067 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2068 kFinalPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002069 EXPECT_EQ(kFinalPeerAddress, connection_.peer_address());
2070 EXPECT_EQ(kNewerEffectivePeerAddress, connection_.effective_peer_address());
2071 EXPECT_EQ(PORT_CHANGE, connection_.active_effective_peer_migration_type());
2072
2073 // While the previous migration is ongoing, process another packet with the
2074 // same direct peer address and different effective peer address on server
2075 // side will start a new connection migration.
2076 const QuicSocketAddress kNewestEffectivePeerAddress =
2077 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/65430);
2078 connection_.ReturnEffectivePeerAddressForNextPacket(
2079 kNewestEffectivePeerAddress);
2080 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
2081 EXPECT_CALL(*send_algorithm_, OnConnectionMigration()).Times(1);
wub8a5dafa2020-05-13 12:30:17 -07002082 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2083 kFinalPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002084 EXPECT_EQ(kFinalPeerAddress, connection_.peer_address());
2085 EXPECT_EQ(kNewestEffectivePeerAddress, connection_.effective_peer_address());
2086 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
2087 connection_.active_effective_peer_migration_type());
2088}
2089
zhongyif06ca342020-02-24 14:11:13 -08002090TEST_P(QuicConnectionTest, ReceivePathProbeWithNoAddressChangeAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002091 set_perspective(Perspective::IS_SERVER);
2092 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2093 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2094
2095 // Clear direct_peer_address.
2096 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2097 // Clear effective_peer_address, it is the same as direct_peer_address for
2098 // this test.
2099 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2100 QuicSocketAddress());
2101 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2102
nharper46833c32019-05-15 21:33:05 -07002103 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07002104 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2105 } else {
nharper46833c32019-05-15 21:33:05 -07002106 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2107 }
wub8a5dafa2020-05-13 12:30:17 -07002108 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2109 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002110 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2111 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2112
2113 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyi83161e42019-08-19 09:06:25 -07002114 EXPECT_CALL(visitor_, OnPacketReceived(_, _, false)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002115
2116 // Process a padded PING or PATH CHALLENGE packet with no peer address change
2117 // on server side will be ignored.
wub8a5dafa2020-05-13 12:30:17 -07002118 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
zhongyif06ca342020-02-24 14:11:13 -08002119
QUICHE teama6ef0a62019-03-07 20:34:33 -05002120 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2121 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2122 probing_packet->encrypted_length),
2123 clock_.Now()));
2124
2125 uint64_t num_probing_received =
2126 connection_.GetStats().num_connectivity_probing_received;
2127 ProcessReceivedPacket(kSelfAddress, kPeerAddress, *received);
2128
2129 EXPECT_EQ(num_probing_received,
2130 connection_.GetStats().num_connectivity_probing_received);
2131 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2132 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2133}
2134
wub54bd5bf2020-05-13 13:02:16 -07002135// Regression test for b/150161358.
2136TEST_P(QuicConnectionTest, BufferedMtuPacketTooBig) {
wub54bd5bf2020-05-13 13:02:16 -07002137 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
2138 writer_->SetWriteBlocked();
2139
2140 // Send a MTU packet while blocked. It should be buffered.
2141 connection_.SendMtuDiscoveryPacket(kMaxOutgoingPacketSize);
2142 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2143 EXPECT_TRUE(writer_->IsWriteBlocked());
2144
2145 writer_->AlwaysGetPacketTooLarge();
2146 writer_->SetWritable();
2147 connection_.OnCanWrite();
2148}
2149
QUICHE teama6ef0a62019-03-07 20:34:33 -05002150TEST_P(QuicConnectionTest, WriteOutOfOrderQueuedPackets) {
2151 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
fayangc31c9952019-06-05 13:54:48 -07002152 if (!IsDefaultTestConfiguration()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002153 return;
2154 }
2155
2156 set_perspective(Perspective::IS_CLIENT);
2157
2158 BlockOnNextWrite();
2159
2160 QuicStreamId stream_id = 2;
2161 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
2162
2163 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2164
2165 writer_->SetWritable();
2166 connection_.SendConnectivityProbingPacket(writer_.get(),
2167 connection_.peer_address());
fayange62e63c2019-12-04 07:16:25 -08002168 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
2169 connection_.OnCanWrite();
QUICHE teama6ef0a62019-03-07 20:34:33 -05002170}
2171
2172TEST_P(QuicConnectionTest, DiscardQueuedPacketsAfterConnectionClose) {
2173 // Regression test for b/74073386.
2174 {
2175 InSequence seq;
rch39c88ab2019-10-16 19:24:40 -07002176 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2177 .Times(AtLeast(1));
2178 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002179 }
2180
2181 set_perspective(Perspective::IS_CLIENT);
2182
2183 writer_->SimulateNextPacketTooLarge();
2184
2185 // This packet write should fail, which should cause the connection to close
2186 // after sending a connection close packet, then the failed packet should be
2187 // queued.
2188 connection_.SendStreamDataWithString(/*id=*/2, "foo", 0, NO_FIN);
2189
2190 EXPECT_FALSE(connection_.connected());
fayange62e63c2019-12-04 07:16:25 -08002191 // No need to buffer packets.
2192 EXPECT_EQ(0u, connection_.NumQueuedPackets());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002193
2194 EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
2195 connection_.OnCanWrite();
fayang0f0c4e62019-07-16 08:55:54 -07002196 EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002197}
2198
zhongyif06ca342020-02-24 14:11:13 -08002199// Receive a path probe request at the server side, i.e.,
2200// in non-IETF version: receive a padded PING packet with a peer addess change;
2201// in IETF version: receive a packet contains PATH CHALLENGE with peer address
2202// change.
2203TEST_P(QuicConnectionTest, ReceivePathProbingAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002204 set_perspective(Perspective::IS_SERVER);
2205 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2206 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2207
2208 // Clear direct_peer_address.
2209 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2210 // Clear effective_peer_address, it is the same as direct_peer_address for
2211 // this test.
2212 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2213 QuicSocketAddress());
2214 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2215
nharper46833c32019-05-15 21:33:05 -07002216 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07002217 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2218 } else {
nharper46833c32019-05-15 21:33:05 -07002219 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2220 }
wub8a5dafa2020-05-13 12:30:17 -07002221 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2222 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002223 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2224 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2225
2226 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyif06ca342020-02-24 14:11:13 -08002227 if (!GetParam().version.HasIetfQuicFrames()) {
2228 EXPECT_CALL(visitor_,
2229 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2230 .Times(1);
2231 } else {
2232 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2233 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002234 // Process a padded PING packet from a new peer address on server side
2235 // is effectively receiving a connectivity probing.
2236 const QuicSocketAddress kNewPeerAddress =
2237 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2238
wub8a5dafa2020-05-13 12:30:17 -07002239 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
QUICHE teama6ef0a62019-03-07 20:34:33 -05002240 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2241 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2242 probing_packet->encrypted_length),
2243 clock_.Now()));
2244
2245 uint64_t num_probing_received =
2246 connection_.GetStats().num_connectivity_probing_received;
2247 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2248
2249 EXPECT_EQ(num_probing_received + 1,
2250 connection_.GetStats().num_connectivity_probing_received);
2251 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2252 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2253
2254 // Process another packet with the old peer address on server side will not
2255 // start peer migration.
2256 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
wub8a5dafa2020-05-13 12:30:17 -07002257 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2258 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002259 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2260 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2261}
2262
zhongyif06ca342020-02-24 14:11:13 -08002263// Receive a padded PING packet with a port change on server side.
2264TEST_P(QuicConnectionTest, ReceivePaddedPingWithPortChangeAtServer) {
2265 set_perspective(Perspective::IS_SERVER);
2266 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2267 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2268
2269 // Clear direct_peer_address.
2270 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2271 // Clear effective_peer_address, it is the same as direct_peer_address for
2272 // this test.
2273 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2274 QuicSocketAddress());
2275 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2276
zhongyif06ca342020-02-24 14:11:13 -08002277 if (GetParam().version.UsesCryptoFrames()) {
zhongyif06ca342020-02-24 14:11:13 -08002278 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2279 } else {
zhongyif06ca342020-02-24 14:11:13 -08002280 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2281 }
wub8a5dafa2020-05-13 12:30:17 -07002282 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2283 kPeerAddress);
zhongyif06ca342020-02-24 14:11:13 -08002284 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2285 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2286
2287 if (GetParam().version.HasIetfQuicFrames()) {
2288 // In IETF version, a padded PING packet with port change is not taken as
2289 // connectivity probe.
2290 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2291 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2292 } else {
2293 // In non-IETF version, process a padded PING packet from a new peer
2294 // address on server side is effectively receiving a connectivity probing.
2295 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2296 EXPECT_CALL(visitor_,
2297 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2298 .Times(1);
2299 }
2300 const QuicSocketAddress kNewPeerAddress =
2301 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2302
2303 QuicFrames frames;
2304 // Write a PING frame, which has no data payload.
2305 QuicPingFrame ping_frame;
2306 frames.push_back(QuicFrame(ping_frame));
2307
2308 // Add padding to the rest of the packet.
2309 QuicPaddingFrame padding_frame;
2310 frames.push_back(QuicFrame(padding_frame));
2311
2312 uint64_t num_probing_received =
2313 connection_.GetStats().num_connectivity_probing_received;
2314
2315 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress);
2316
2317 if (GetParam().version.HasIetfQuicFrames()) {
2318 // Padded PING with port changen is not considered as connectivity probe but
2319 // a PORT CHANGE.
2320 EXPECT_EQ(num_probing_received,
2321 connection_.GetStats().num_connectivity_probing_received);
2322 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2323 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2324 } else {
2325 EXPECT_EQ(num_probing_received + 1,
2326 connection_.GetStats().num_connectivity_probing_received);
2327 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2328 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2329 }
2330
2331 // Process another packet with the old peer address on server side.
2332 if (GetParam().version.HasIetfQuicFrames()) {
2333 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2334 } else {
2335 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2336 }
wub8a5dafa2020-05-13 12:30:17 -07002337 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2338 kPeerAddress);
zhongyif06ca342020-02-24 14:11:13 -08002339 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2340 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2341}
2342
2343TEST_P(QuicConnectionTest, ReceiveReorderedPathProbingAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002344 set_perspective(Perspective::IS_SERVER);
2345 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2346 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2347
2348 // Clear direct_peer_address.
2349 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2350 // Clear effective_peer_address, it is the same as direct_peer_address for
2351 // this test.
2352 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2353 QuicSocketAddress());
2354 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2355
nharper46833c32019-05-15 21:33:05 -07002356 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07002357 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2358 } else {
nharper46833c32019-05-15 21:33:05 -07002359 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2360 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002361 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
wub8a5dafa2020-05-13 12:30:17 -07002362 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2363 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002364 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2365 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2366
2367 // Decrease packet number to simulate out-of-order packets.
2368 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 4);
2369
2370 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyif06ca342020-02-24 14:11:13 -08002371 if (!GetParam().version.HasIetfQuicFrames()) {
2372 EXPECT_CALL(visitor_,
2373 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2374 .Times(1);
2375 } else {
2376 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2377 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002378
2379 // Process a padded PING packet from a new peer address on server side
2380 // is effectively receiving a connectivity probing, even if a newer packet has
2381 // been received before this one.
2382 const QuicSocketAddress kNewPeerAddress =
2383 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2384
wub8a5dafa2020-05-13 12:30:17 -07002385 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
QUICHE teama6ef0a62019-03-07 20:34:33 -05002386 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2387 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2388 probing_packet->encrypted_length),
2389 clock_.Now()));
2390
2391 uint64_t num_probing_received =
2392 connection_.GetStats().num_connectivity_probing_received;
2393 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2394
2395 EXPECT_EQ(num_probing_received + 1,
2396 connection_.GetStats().num_connectivity_probing_received);
2397 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2398 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2399}
2400
2401TEST_P(QuicConnectionTest, MigrateAfterProbingAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002402 set_perspective(Perspective::IS_SERVER);
2403 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2404 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2405
2406 // Clear direct_peer_address.
2407 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2408 // Clear effective_peer_address, it is the same as direct_peer_address for
2409 // this test.
2410 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2411 QuicSocketAddress());
2412 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2413
nharper46833c32019-05-15 21:33:05 -07002414 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07002415 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2416 } else {
nharper46833c32019-05-15 21:33:05 -07002417 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2418 }
wub8a5dafa2020-05-13 12:30:17 -07002419 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2420 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002421 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2422 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2423
2424 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyif06ca342020-02-24 14:11:13 -08002425 if (!GetParam().version.HasIetfQuicFrames()) {
2426 EXPECT_CALL(visitor_,
2427 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2428 .Times(1);
2429 } else {
2430 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2431 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002432
2433 // Process a padded PING packet from a new peer address on server side
2434 // is effectively receiving a connectivity probing.
2435 const QuicSocketAddress kNewPeerAddress =
2436 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2437
wub8a5dafa2020-05-13 12:30:17 -07002438 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
QUICHE teama6ef0a62019-03-07 20:34:33 -05002439 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2440 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2441 probing_packet->encrypted_length),
2442 clock_.Now()));
2443 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2444 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2445 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2446
2447 // Process another non-probing packet with the new peer address on server
2448 // side will start peer migration.
2449 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2450
wub8a5dafa2020-05-13 12:30:17 -07002451 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2452 kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002453 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2454 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2455}
2456
2457TEST_P(QuicConnectionTest, ReceivePaddedPingAtClient) {
2458 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2459 set_perspective(Perspective::IS_CLIENT);
2460 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2461
2462 // Clear direct_peer_address.
2463 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2464 // Clear effective_peer_address, it is the same as direct_peer_address for
2465 // this test.
2466 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2467 QuicSocketAddress());
2468 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2469
nharper46833c32019-05-15 21:33:05 -07002470 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07002471 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2472 } else {
nharper46833c32019-05-15 21:33:05 -07002473 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2474 }
wub8a5dafa2020-05-13 12:30:17 -07002475 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2476 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002477 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2478 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2479
2480 // Client takes all padded PING packet as speculative connectivity
2481 // probing packet, and reports to visitor.
2482 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyi83161e42019-08-19 09:06:25 -07002483 EXPECT_CALL(visitor_, OnPacketReceived(_, _, false)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002484
wub8a5dafa2020-05-13 12:30:17 -07002485 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
QUICHE teama6ef0a62019-03-07 20:34:33 -05002486 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2487 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2488 probing_packet->encrypted_length),
2489 clock_.Now()));
2490 uint64_t num_probing_received =
2491 connection_.GetStats().num_connectivity_probing_received;
2492 ProcessReceivedPacket(kSelfAddress, kPeerAddress, *received);
2493
2494 EXPECT_EQ(num_probing_received,
2495 connection_.GetStats().num_connectivity_probing_received);
2496 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2497 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2498}
2499
zhongyif06ca342020-02-24 14:11:13 -08002500TEST_P(QuicConnectionTest, ReceiveConnectivityProbingResponseAtClient) {
2501 // TODO(b/150095484): add test coverage for IETF to verify that client takes
2502 // PATH RESPONSE with peer address change as correct validation on the new
2503 // path.
2504 if (GetParam().version.HasIetfQuicFrames()) {
2505 return;
2506 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002507 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2508 set_perspective(Perspective::IS_CLIENT);
2509 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2510
2511 // Clear direct_peer_address.
2512 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2513 // Clear effective_peer_address, it is the same as direct_peer_address for
2514 // this test.
2515 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2516 QuicSocketAddress());
2517 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2518
nharper46833c32019-05-15 21:33:05 -07002519 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07002520 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2521 } else {
nharper46833c32019-05-15 21:33:05 -07002522 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2523 }
wub8a5dafa2020-05-13 12:30:17 -07002524 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2525 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002526 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2527 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2528
2529 // Process a padded PING packet with a different self address on client side
2530 // is effectively receiving a connectivity probing.
2531 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyif06ca342020-02-24 14:11:13 -08002532 if (!GetParam().version.HasIetfQuicFrames()) {
2533 EXPECT_CALL(visitor_,
2534 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2535 .Times(1);
2536 } else {
2537 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2538 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002539
2540 const QuicSocketAddress kNewSelfAddress =
2541 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2542
wub8a5dafa2020-05-13 12:30:17 -07002543 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
QUICHE teama6ef0a62019-03-07 20:34:33 -05002544 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2545 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2546 probing_packet->encrypted_length),
2547 clock_.Now()));
2548 uint64_t num_probing_received =
2549 connection_.GetStats().num_connectivity_probing_received;
2550 ProcessReceivedPacket(kNewSelfAddress, kPeerAddress, *received);
2551
2552 EXPECT_EQ(num_probing_received + 1,
2553 connection_.GetStats().num_connectivity_probing_received);
2554 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2555 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2556}
2557
2558TEST_P(QuicConnectionTest, PeerAddressChangeAtClient) {
2559 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2560 set_perspective(Perspective::IS_CLIENT);
2561 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2562
2563 // Clear direct_peer_address.
2564 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2565 // Clear effective_peer_address, it is the same as direct_peer_address for
2566 // this test.
2567 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2568 QuicSocketAddress());
2569 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2570
nharper46833c32019-05-15 21:33:05 -07002571 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07002572 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2573 } else {
nharper46833c32019-05-15 21:33:05 -07002574 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2575 }
wub8a5dafa2020-05-13 12:30:17 -07002576 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2577 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002578 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2579 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2580
2581 // Process another packet with a different peer address on client side will
2582 // only update peer address.
2583 const QuicSocketAddress kNewPeerAddress =
2584 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2585 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
wub8a5dafa2020-05-13 12:30:17 -07002586 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2587 kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002588 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2589 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2590}
2591
2592TEST_P(QuicConnectionTest, MaxPacketSize) {
2593 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2594 EXPECT_EQ(1350u, connection_.max_packet_length());
2595}
2596
dschinazi4ad1f462020-01-16 11:56:52 -08002597TEST_P(QuicConnectionTest, PeerLowersMaxPacketSize) {
2598 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2599
2600 // SetFromConfig is always called after construction from InitializeSession.
2601 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
2602 constexpr uint32_t kTestMaxPacketSize = 1233u;
2603 QuicConfig config;
2604 QuicConfigPeer::SetReceivedMaxPacketSize(&config, kTestMaxPacketSize);
2605 connection_.SetFromConfig(config);
2606
2607 EXPECT_EQ(kTestMaxPacketSize, connection_.max_packet_length());
2608}
2609
vasilvvebc5d0c2020-01-16 15:19:21 -08002610TEST_P(QuicConnectionTest, PeerCannotRaiseMaxPacketSize) {
2611 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2612
2613 // SetFromConfig is always called after construction from InitializeSession.
2614 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
2615 constexpr uint32_t kTestMaxPacketSize = 1450u;
2616 QuicConfig config;
2617 QuicConfigPeer::SetReceivedMaxPacketSize(&config, kTestMaxPacketSize);
2618 connection_.SetFromConfig(config);
2619
2620 EXPECT_EQ(kDefaultMaxPacketSize, connection_.max_packet_length());
2621}
2622
QUICHE teama6ef0a62019-03-07 20:34:33 -05002623TEST_P(QuicConnectionTest, SmallerServerMaxPacketSize) {
2624 TestConnection connection(TestConnectionId(), kPeerAddress, helper_.get(),
2625 alarm_factory_.get(), writer_.get(),
2626 Perspective::IS_SERVER, version());
2627 EXPECT_EQ(Perspective::IS_SERVER, connection.perspective());
2628 EXPECT_EQ(1000u, connection.max_packet_length());
2629}
2630
2631TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSize) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002632 set_perspective(Perspective::IS_SERVER);
2633 connection_.SetMaxPacketLength(1000);
2634
2635 QuicPacketHeader header;
2636 header.destination_connection_id = connection_id_;
2637 header.version_flag = true;
nharper21af28e2019-06-17 15:54:34 -07002638 header.packet_number = QuicPacketNumber(12);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002639
2640 if (QuicVersionHasLongHeaderLengths(
2641 peer_framer_.version().transport_version)) {
2642 header.long_packet_type = INITIAL;
2643 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
2644 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
2645 }
2646
2647 QuicFrames frames;
2648 QuicPaddingFrame padding;
nharper46833c32019-05-15 21:33:05 -07002649 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2650 frames.push_back(QuicFrame(&crypto_frame_));
2651 } else {
2652 frames.push_back(QuicFrame(frame1_));
2653 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002654 frames.push_back(QuicFrame(padding));
2655 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
dschinazi66dea072019-04-09 11:41:06 -07002656 char buffer[kMaxOutgoingPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07002657 size_t encrypted_length =
2658 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12),
dschinazi66dea072019-04-09 11:41:06 -07002659 *packet, buffer, kMaxOutgoingPacketSize);
2660 EXPECT_EQ(kMaxOutgoingPacketSize, encrypted_length);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002661
2662 framer_.set_version(version());
nharper46833c32019-05-15 21:33:05 -07002663 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2664 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
2665 } else {
2666 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2667 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002668 connection_.ProcessUdpPacket(
2669 kSelfAddress, kPeerAddress,
2670 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
2671
dschinazi66dea072019-04-09 11:41:06 -07002672 EXPECT_EQ(kMaxOutgoingPacketSize, connection_.max_packet_length());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002673}
2674
2675TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSizeWhileWriterLimited) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002676 const QuicByteCount lower_max_packet_size = 1240;
2677 writer_->set_max_packet_size(lower_max_packet_size);
2678 set_perspective(Perspective::IS_SERVER);
2679 connection_.SetMaxPacketLength(1000);
2680 EXPECT_EQ(1000u, connection_.max_packet_length());
2681
2682 QuicPacketHeader header;
2683 header.destination_connection_id = connection_id_;
2684 header.version_flag = true;
nharper21af28e2019-06-17 15:54:34 -07002685 header.packet_number = QuicPacketNumber(12);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002686
2687 if (QuicVersionHasLongHeaderLengths(
2688 peer_framer_.version().transport_version)) {
2689 header.long_packet_type = INITIAL;
2690 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
2691 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
2692 }
2693
2694 QuicFrames frames;
2695 QuicPaddingFrame padding;
nharper46833c32019-05-15 21:33:05 -07002696 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2697 frames.push_back(QuicFrame(&crypto_frame_));
2698 } else {
2699 frames.push_back(QuicFrame(frame1_));
2700 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002701 frames.push_back(QuicFrame(padding));
2702 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
dschinazi66dea072019-04-09 11:41:06 -07002703 char buffer[kMaxOutgoingPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07002704 size_t encrypted_length =
2705 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12),
dschinazi66dea072019-04-09 11:41:06 -07002706 *packet, buffer, kMaxOutgoingPacketSize);
2707 EXPECT_EQ(kMaxOutgoingPacketSize, encrypted_length);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002708
2709 framer_.set_version(version());
nharper46833c32019-05-15 21:33:05 -07002710 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2711 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
2712 } else {
2713 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2714 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002715 connection_.ProcessUdpPacket(
2716 kSelfAddress, kPeerAddress,
2717 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
2718
2719 // Here, the limit imposed by the writer is lower than the size of the packet
2720 // received, so the writer max packet size is used.
2721 EXPECT_EQ(lower_max_packet_size, connection_.max_packet_length());
2722}
2723
2724TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriter) {
2725 const QuicByteCount lower_max_packet_size = 1240;
2726 writer_->set_max_packet_size(lower_max_packet_size);
2727
2728 static_assert(lower_max_packet_size < kDefaultMaxPacketSize,
2729 "Default maximum packet size is too low");
2730 connection_.SetMaxPacketLength(kDefaultMaxPacketSize);
2731
2732 EXPECT_EQ(lower_max_packet_size, connection_.max_packet_length());
2733}
2734
2735TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriterForNewConnection) {
2736 const QuicConnectionId connection_id = TestConnectionId(17);
2737 const QuicByteCount lower_max_packet_size = 1240;
2738 writer_->set_max_packet_size(lower_max_packet_size);
2739 TestConnection connection(connection_id, kPeerAddress, helper_.get(),
2740 alarm_factory_.get(), writer_.get(),
2741 Perspective::IS_CLIENT, version());
2742 EXPECT_EQ(Perspective::IS_CLIENT, connection.perspective());
2743 EXPECT_EQ(lower_max_packet_size, connection.max_packet_length());
2744}
2745
2746TEST_P(QuicConnectionTest, PacketsInOrder) {
2747 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2748
2749 ProcessPacket(1);
fayangc31c9952019-06-05 13:54:48 -07002750 EXPECT_EQ(QuicPacketNumber(1u), LargestAcked(connection_.ack_frame()));
2751 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002752
2753 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07002754 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(connection_.ack_frame()));
2755 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002756
2757 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002758 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
2759 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002760}
2761
2762TEST_P(QuicConnectionTest, PacketsOutOfOrder) {
2763 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2764
2765 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002766 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002767 EXPECT_TRUE(IsMissing(2));
2768 EXPECT_TRUE(IsMissing(1));
2769
2770 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07002771 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002772 EXPECT_FALSE(IsMissing(2));
2773 EXPECT_TRUE(IsMissing(1));
2774
2775 ProcessPacket(1);
fayangc31c9952019-06-05 13:54:48 -07002776 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002777 EXPECT_FALSE(IsMissing(2));
2778 EXPECT_FALSE(IsMissing(1));
2779}
2780
2781TEST_P(QuicConnectionTest, DuplicatePacket) {
2782 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2783
2784 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002785 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002786 EXPECT_TRUE(IsMissing(2));
2787 EXPECT_TRUE(IsMissing(1));
2788
2789 // Send packet 3 again, but do not set the expectation that
2790 // the visitor OnStreamFrame() will be called.
2791 ProcessDataPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002792 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002793 EXPECT_TRUE(IsMissing(2));
2794 EXPECT_TRUE(IsMissing(1));
2795}
2796
2797TEST_P(QuicConnectionTest, PacketsOutOfOrderWithAdditionsAndLeastAwaiting) {
QUICHE teamcd098022019-03-22 18:49:55 -07002798 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2799 return;
2800 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002801 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2802
2803 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002804 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002805 EXPECT_TRUE(IsMissing(2));
2806 EXPECT_TRUE(IsMissing(1));
2807
2808 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07002809 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002810 EXPECT_TRUE(IsMissing(1));
2811
2812 ProcessPacket(5);
fayangc31c9952019-06-05 13:54:48 -07002813 EXPECT_EQ(QuicPacketNumber(5u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002814 EXPECT_TRUE(IsMissing(1));
2815 EXPECT_TRUE(IsMissing(4));
2816
2817 // Pretend at this point the client has gotten acks for 2 and 3 and 1 is a
2818 // packet the peer will not retransmit. It indicates this by sending 'least
2819 // awaiting' is 4. The connection should then realize 1 will not be
2820 // retransmitted, and will remove it from the missing list.
2821 QuicAckFrame frame = InitAckFrame(1);
2822 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
2823 ProcessAckPacket(6, &frame);
2824
2825 // Force an ack to be sent.
2826 SendAckPacketToPeer();
2827 EXPECT_TRUE(IsMissing(4));
2828}
2829
QUICHE teama6ef0a62019-03-07 20:34:33 -05002830TEST_P(QuicConnectionTest, RejectUnencryptedStreamData) {
2831 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
2832 if (!IsDefaultTestConfiguration()) {
2833 return;
2834 }
2835
2836 // Process an unencrypted packet from the non-crypto stream.
2837 frame1_.stream_id = 3;
2838 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fkastenholz5d880a92019-06-21 09:01:56 -07002839 EXPECT_CALL(visitor_,
2840 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
nharper2c9f02a2019-05-08 10:25:50 -07002841 EXPECT_QUIC_PEER_BUG(ProcessDataPacketAtLevel(1, false, ENCRYPTION_INITIAL),
2842 "");
fkastenholz5d880a92019-06-21 09:01:56 -07002843 TestConnectionCloseQuicErrorCode(QUIC_UNENCRYPTED_STREAM_DATA);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002844}
2845
2846TEST_P(QuicConnectionTest, OutOfOrderReceiptCausesAckSend) {
2847 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2848
2849 ProcessPacket(3);
fayang6dba4902019-06-17 10:04:23 -07002850 // Should not cause an ack.
2851 EXPECT_EQ(0u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002852
2853 ProcessPacket(2);
fayang6dba4902019-06-17 10:04:23 -07002854 // Should ack immediately, since this fills the last hole.
2855 EXPECT_EQ(1u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002856
2857 ProcessPacket(1);
2858 // Should ack immediately, since this fills the last hole.
fayang6dba4902019-06-17 10:04:23 -07002859 EXPECT_EQ(2u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002860
2861 ProcessPacket(4);
2862 // Should not cause an ack.
fayang6dba4902019-06-17 10:04:23 -07002863 EXPECT_EQ(2u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002864}
2865
2866TEST_P(QuicConnectionTest, OutOfOrderAckReceiptCausesNoAck) {
2867 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2868
2869 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
2870 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
2871 EXPECT_EQ(2u, writer_->packets_write_attempts());
2872
2873 QuicAckFrame ack1 = InitAckFrame(1);
2874 QuicAckFrame ack2 = InitAckFrame(2);
2875 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
fayang2f2915d2020-01-24 06:47:15 -08002876 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2877 EXPECT_CALL(visitor_, OnOneRttPacketAcknowledged()).Times(1);
2878 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002879 ProcessAckPacket(2, &ack2);
2880 // Should ack immediately since we have missing packets.
2881 EXPECT_EQ(2u, writer_->packets_write_attempts());
2882
fayang2f2915d2020-01-24 06:47:15 -08002883 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2884 EXPECT_CALL(visitor_, OnOneRttPacketAcknowledged()).Times(0);
2885 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002886 ProcessAckPacket(1, &ack1);
2887 // Should not ack an ack filling a missing packet.
2888 EXPECT_EQ(2u, writer_->packets_write_attempts());
2889}
2890
2891TEST_P(QuicConnectionTest, AckReceiptCausesAckSend) {
2892 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2893 QuicPacketNumber original, second;
2894
2895 QuicByteCount packet_size =
2896 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &original); // 1st packet.
2897 SendStreamDataToPeer(3, "bar", 3, NO_FIN, &second); // 2nd packet.
2898
2899 QuicAckFrame frame = InitAckFrame({{second, second + 1}});
2900 // First nack triggers early retransmit.
2901 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07002902 lost_packets.push_back(LostPacket(original, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002903 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07002904 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
2905 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002906 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2907 QuicPacketNumber retransmission;
2908 // Packet 1 is short header for IETF QUIC because the encryption level
2909 // switched to ENCRYPTION_FORWARD_SECURE in SendStreamDataToPeer.
fayangd4291e42019-05-30 10:31:21 -07002910 EXPECT_CALL(*send_algorithm_,
2911 OnPacketSent(_, _, _,
2912 VersionHasIetfInvariantHeader(
2913 GetParam().version.transport_version)
2914 ? packet_size
2915 : packet_size - kQuicVersionSize,
2916 _))
QUICHE teama6ef0a62019-03-07 20:34:33 -05002917 .WillOnce(SaveArg<2>(&retransmission));
2918
2919 ProcessAckPacket(&frame);
2920
2921 QuicAckFrame frame2 = ConstructAckFrame(retransmission, original);
2922 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2923 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
2924 ProcessAckPacket(&frame2);
2925
2926 // Now if the peer sends an ack which still reports the retransmitted packet
2927 // as missing, that will bundle an ack with data after two acks in a row
2928 // indicate the high water mark needs to be raised.
2929 EXPECT_CALL(*send_algorithm_,
2930 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA));
2931 connection_.SendStreamDataWithString(3, "foo", 6, NO_FIN);
2932 // No ack sent.
nharper55fa6132019-05-07 19:37:21 -07002933 size_t padding_frame_count = writer_->padding_frames().size();
2934 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002935 EXPECT_EQ(1u, writer_->stream_frames().size());
2936
2937 // No more packet loss for the rest of the test.
2938 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
2939 .Times(AnyNumber());
2940 ProcessAckPacket(&frame2);
2941 EXPECT_CALL(*send_algorithm_,
2942 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA));
fayang03916692019-05-22 17:57:18 -07002943 connection_.SendStreamDataWithString(3, "foofoofoo", 9, NO_FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002944 // Ack bundled.
2945 if (GetParam().no_stop_waiting) {
fayang8a27b0f2019-11-04 11:27:40 -08002946 // Do not ACK acks.
2947 EXPECT_EQ(1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002948 } else {
2949 EXPECT_EQ(3u, writer_->frame_count());
2950 }
2951 EXPECT_EQ(1u, writer_->stream_frames().size());
fayang8a27b0f2019-11-04 11:27:40 -08002952 if (GetParam().no_stop_waiting) {
fayang03916692019-05-22 17:57:18 -07002953 EXPECT_TRUE(writer_->ack_frames().empty());
2954 } else {
2955 EXPECT_FALSE(writer_->ack_frames().empty());
2956 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002957
2958 // But an ack with no missing packets will not send an ack.
2959 AckPacket(original, &frame2);
2960 ProcessAckPacket(&frame2);
2961 ProcessAckPacket(&frame2);
2962}
2963
2964TEST_P(QuicConnectionTest, AckSentEveryNthPacket) {
2965 connection_.set_ack_frequency_before_ack_decimation(3);
2966
2967 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2968 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(39);
2969
2970 // Expect 13 acks, every 3rd packet.
2971 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(13);
2972 // Receives packets 1 - 39.
2973 for (size_t i = 1; i <= 39; ++i) {
2974 ProcessDataPacket(i);
2975 }
2976}
2977
2978TEST_P(QuicConnectionTest, AckDecimationReducesAcks) {
2979 const size_t kMinRttMs = 40;
2980 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
2981 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
2982 QuicTime::Delta::Zero(), QuicTime::Zero());
2983 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
2984
2985 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
2986
2987 // Start ack decimation from 10th packet.
2988 connection_.set_min_received_before_ack_decimation(10);
2989
2990 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2991 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(30);
2992
2993 // Expect 6 acks: 5 acks between packets 1-10, and ack at 20.
2994 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(6);
2995 // Receives packets 1 - 29.
2996 for (size_t i = 1; i <= 29; ++i) {
2997 ProcessDataPacket(i);
2998 }
2999
3000 // We now receive the 30th packet, and so we send an ack.
3001 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3002 ProcessDataPacket(30);
3003}
3004
3005TEST_P(QuicConnectionTest, AckNeedsRetransmittableFrames) {
ianswett68cf0042019-05-09 08:37:58 -07003006 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003007 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3008 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(99);
3009
3010 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(19);
3011 // Receives packets 1 - 39.
3012 for (size_t i = 1; i <= 39; ++i) {
3013 ProcessDataPacket(i);
3014 }
3015 // Receiving Packet 40 causes 20th ack to send. Session is informed and adds
3016 // WINDOW_UPDATE.
3017 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
3018 .WillOnce(Invoke([this]() {
3019 connection_.SendControlFrame(
3020 QuicFrame(new QuicWindowUpdateFrame(1, 0, 0)));
3021 }));
3022 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3023 EXPECT_EQ(0u, writer_->window_update_frames().size());
3024 ProcessDataPacket(40);
3025 EXPECT_EQ(1u, writer_->window_update_frames().size());
3026
3027 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(9);
3028 // Receives packets 41 - 59.
3029 for (size_t i = 41; i <= 59; ++i) {
3030 ProcessDataPacket(i);
3031 }
3032 // Send a packet containing stream frame.
QUICHE team8c1daa22019-03-13 08:33:41 -07003033 SendStreamDataToPeer(
nharper46833c32019-05-15 21:33:05 -07003034 QuicUtils::GetFirstBidirectionalStreamId(
3035 connection_.version().transport_version, Perspective::IS_CLIENT),
QUICHE team8c1daa22019-03-13 08:33:41 -07003036 "bar", 0, NO_FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003037
3038 // Session will not be informed until receiving another 20 packets.
3039 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(19);
3040 for (size_t i = 60; i <= 98; ++i) {
3041 ProcessDataPacket(i);
3042 EXPECT_EQ(0u, writer_->window_update_frames().size());
3043 }
3044 // Session does not add a retransmittable frame.
3045 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
3046 .WillOnce(Invoke([this]() {
3047 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
3048 }));
3049 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3050 EXPECT_EQ(0u, writer_->ping_frames().size());
3051 ProcessDataPacket(99);
3052 EXPECT_EQ(0u, writer_->window_update_frames().size());
3053 // A ping frame will be added.
3054 EXPECT_EQ(1u, writer_->ping_frames().size());
3055}
3056
ianswett6083a102020-02-09 12:04:04 -08003057TEST_P(QuicConnectionTest, AckNeedsRetransmittableFramesAfterPto) {
ianswett6083a102020-02-09 12:04:04 -08003058 // Disable TLP so the RTO fires immediately.
3059 connection_.SetMaxTailLossProbes(0);
3060 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3061 QuicConfig config;
3062 QuicTagVector connection_options;
3063 connection_options.push_back(kEACK);
3064 config.SetConnectionOptionsToSend(connection_options);
3065 connection_.SetFromConfig(config);
3066
3067 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3068 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3069 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(10);
3070
3071 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(4);
3072 // Receive packets 1 - 9.
3073 for (size_t i = 1; i <= 9; ++i) {
3074 ProcessDataPacket(i);
3075 }
3076
3077 // Send a ping and fire the retransmission alarm.
3078 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3079 SendPing();
3080 QuicTime retransmission_time =
3081 connection_.GetRetransmissionAlarm()->deadline();
3082 clock_.AdvanceTime(retransmission_time - clock_.Now());
3083 connection_.GetRetransmissionAlarm()->Fire();
3084 ASSERT_TRUE(manager_->GetConsecutiveRtoCount() > 0 ||
3085 manager_->GetConsecutivePtoCount() > 0);
3086
3087 // Process a packet, which requests a retransmittable frame be bundled
3088 // with the ACK.
3089 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
3090 .WillOnce(Invoke([this]() {
3091 connection_.SendControlFrame(
3092 QuicFrame(new QuicWindowUpdateFrame(1, 0, 0)));
3093 }));
3094 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3095 ProcessDataPacket(11);
3096 EXPECT_EQ(1u, writer_->window_update_frames().size());
3097}
3098
QUICHE teama6ef0a62019-03-07 20:34:33 -05003099TEST_P(QuicConnectionTest, LeastUnackedLower) {
fayangc31c9952019-06-05 13:54:48 -07003100 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003101 return;
3102 }
3103 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3104
3105 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
3106 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
3107 SendStreamDataToPeer(1, "eep", 6, NO_FIN, nullptr);
3108
3109 // Start out saying the least unacked is 2.
3110 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
3111 ProcessStopWaitingPacket(InitStopWaitingFrame(2));
3112
3113 // Change it to 1, but lower the packet number to fake out-of-order packets.
3114 // This should be fine.
3115 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 1);
3116 // The scheduler will not process out of order acks, but all packet processing
3117 // causes the connection to try to write.
3118 if (!GetParam().no_stop_waiting) {
3119 EXPECT_CALL(visitor_, OnCanWrite());
3120 }
3121 ProcessStopWaitingPacket(InitStopWaitingFrame(1));
3122
3123 // Now claim it's one, but set the ordering so it was sent "after" the first
3124 // one. This should cause a connection error.
3125 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 7);
3126 if (!GetParam().no_stop_waiting) {
rch39c88ab2019-10-16 19:24:40 -07003127 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3128 .Times(AtLeast(1));
fkastenholz5d880a92019-06-21 09:01:56 -07003129 EXPECT_CALL(visitor_,
rch39c88ab2019-10-16 19:24:40 -07003130 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
3131 .Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003132 }
3133 ProcessStopWaitingPacket(InitStopWaitingFrame(1));
fkastenholz5d880a92019-06-21 09:01:56 -07003134 if (!GetParam().no_stop_waiting) {
3135 TestConnectionCloseQuicErrorCode(QUIC_INVALID_STOP_WAITING_DATA);
3136 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003137}
3138
3139TEST_P(QuicConnectionTest, TooManySentPackets) {
3140 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3141
3142 QuicPacketCount max_tracked_packets = 50;
3143 QuicConnectionPeer::SetMaxTrackedPackets(&connection_, max_tracked_packets);
3144
3145 const int num_packets = max_tracked_packets + 5;
3146
3147 for (int i = 0; i < num_packets; ++i) {
3148 SendStreamDataToPeer(1, "foo", 3 * i, NO_FIN, nullptr);
3149 }
3150
3151 // Ack packet 1, which leaves more than the limit outstanding.
3152 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3153 EXPECT_CALL(visitor_,
fkastenholz5d880a92019-06-21 09:01:56 -07003154 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003155
3156 // Nack the first packet and ack the rest, leaving a huge gap.
3157 QuicAckFrame frame1 = ConstructAckFrame(num_packets, 1);
3158 ProcessAckPacket(&frame1);
fkastenholz5d880a92019-06-21 09:01:56 -07003159 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003160}
3161
3162TEST_P(QuicConnectionTest, LargestObservedLower) {
3163 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3164
3165 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
3166 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
3167 SendStreamDataToPeer(1, "eep", 6, NO_FIN, nullptr);
3168 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3169
3170 // Start out saying the largest observed is 2.
3171 QuicAckFrame frame1 = InitAckFrame(1);
3172 QuicAckFrame frame2 = InitAckFrame(2);
3173 ProcessAckPacket(&frame2);
3174
fayang745c93a2019-06-21 13:43:04 -07003175 EXPECT_CALL(visitor_, OnCanWrite());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003176 ProcessAckPacket(&frame1);
3177}
3178
3179TEST_P(QuicConnectionTest, AckUnsentData) {
3180 // Ack a packet which has not been sent.
fkastenholz5d880a92019-06-21 09:01:56 -07003181 EXPECT_CALL(visitor_,
3182 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003183 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
rch39c88ab2019-10-16 19:24:40 -07003184 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003185 QuicAckFrame frame = InitAckFrame(1);
3186 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
3187 ProcessAckPacket(&frame);
fkastenholz5d880a92019-06-21 09:01:56 -07003188 TestConnectionCloseQuicErrorCode(QUIC_INVALID_ACK_DATA);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003189}
3190
3191TEST_P(QuicConnectionTest, BasicSending) {
QUICHE teamcd098022019-03-22 18:49:55 -07003192 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3193 return;
3194 }
fayang643c7dd2020-05-18 07:11:27 -07003195 const QuicConnectionStats& stats = connection_.GetStats();
3196 EXPECT_FALSE(stats.first_decrypted_packet.IsInitialized());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003197 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3198 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3199 ProcessDataPacket(1);
fayang643c7dd2020-05-18 07:11:27 -07003200 EXPECT_EQ(QuicPacketNumber(1), stats.first_decrypted_packet);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003201 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
3202 QuicPacketNumber last_packet;
3203 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
3204 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
3205 SendAckPacketToPeer(); // Packet 2
3206
3207 if (GetParam().no_stop_waiting) {
3208 // Expect no stop waiting frame is sent.
3209 EXPECT_FALSE(least_unacked().IsInitialized());
3210 } else {
3211 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
3212 }
3213
3214 SendAckPacketToPeer(); // Packet 3
3215 if (GetParam().no_stop_waiting) {
3216 // Expect no stop waiting frame is sent.
3217 EXPECT_FALSE(least_unacked().IsInitialized());
3218 } else {
3219 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
3220 }
3221
3222 SendStreamDataToPeer(1, "bar", 3, NO_FIN, &last_packet); // Packet 4
3223 EXPECT_EQ(QuicPacketNumber(4u), last_packet);
3224 SendAckPacketToPeer(); // Packet 5
3225 if (GetParam().no_stop_waiting) {
3226 // Expect no stop waiting frame is sent.
3227 EXPECT_FALSE(least_unacked().IsInitialized());
3228 } else {
3229 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
3230 }
3231
3232 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3233
3234 // Peer acks up to packet 3.
3235 QuicAckFrame frame = InitAckFrame(3);
3236 ProcessAckPacket(&frame);
3237 SendAckPacketToPeer(); // Packet 6
3238
3239 // As soon as we've acked one, we skip ack packets 2 and 3 and note lack of
3240 // ack for 4.
3241 if (GetParam().no_stop_waiting) {
3242 // Expect no stop waiting frame is sent.
3243 EXPECT_FALSE(least_unacked().IsInitialized());
3244 } else {
3245 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
3246 }
3247
3248 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3249
3250 // Peer acks up to packet 4, the last packet.
3251 QuicAckFrame frame2 = InitAckFrame(6);
3252 ProcessAckPacket(&frame2); // Acks don't instigate acks.
3253
3254 // Verify that we did not send an ack.
3255 EXPECT_EQ(QuicPacketNumber(6u), writer_->header().packet_number);
3256
3257 // So the last ack has not changed.
3258 if (GetParam().no_stop_waiting) {
3259 // Expect no stop waiting frame is sent.
3260 EXPECT_FALSE(least_unacked().IsInitialized());
3261 } else {
3262 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
3263 }
3264
3265 // If we force an ack, we shouldn't change our retransmit state.
3266 SendAckPacketToPeer(); // Packet 7
3267 if (GetParam().no_stop_waiting) {
3268 // Expect no stop waiting frame is sent.
3269 EXPECT_FALSE(least_unacked().IsInitialized());
3270 } else {
3271 EXPECT_EQ(QuicPacketNumber(7u), least_unacked());
3272 }
3273
3274 // But if we send more data it should.
3275 SendStreamDataToPeer(1, "eep", 6, NO_FIN, &last_packet); // Packet 8
3276 EXPECT_EQ(QuicPacketNumber(8u), last_packet);
3277 SendAckPacketToPeer(); // Packet 9
3278 if (GetParam().no_stop_waiting) {
3279 // Expect no stop waiting frame is sent.
3280 EXPECT_FALSE(least_unacked().IsInitialized());
3281 } else {
3282 EXPECT_EQ(QuicPacketNumber(7u), least_unacked());
3283 }
fayang643c7dd2020-05-18 07:11:27 -07003284 EXPECT_EQ(QuicPacketNumber(1), stats.first_decrypted_packet);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003285}
3286
3287// QuicConnection should record the packet sent-time prior to sending the
3288// packet.
3289TEST_P(QuicConnectionTest, RecordSentTimeBeforePacketSent) {
3290 // We're using a MockClock for the tests, so we have complete control over the
3291 // time.
3292 // Our recorded timestamp for the last packet sent time will be passed in to
3293 // the send_algorithm. Make sure that it is set to the correct value.
3294 QuicTime actual_recorded_send_time = QuicTime::Zero();
3295 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3296 .WillOnce(SaveArg<0>(&actual_recorded_send_time));
3297
3298 // First send without any pause and check the result.
3299 QuicTime expected_recorded_send_time = clock_.Now();
3300 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3301 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
3302 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
3303 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
3304
3305 // Now pause during the write, and check the results.
3306 actual_recorded_send_time = QuicTime::Zero();
3307 const QuicTime::Delta write_pause_time_delta =
3308 QuicTime::Delta::FromMilliseconds(5000);
3309 SetWritePauseTimeDelta(write_pause_time_delta);
3310 expected_recorded_send_time = clock_.Now();
3311
3312 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3313 .WillOnce(SaveArg<0>(&actual_recorded_send_time));
3314 connection_.SendStreamDataWithString(2, "baz", 0, NO_FIN);
3315 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
3316 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
3317 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
3318}
3319
3320TEST_P(QuicConnectionTest, FramePacking) {
3321 // Send two stream frames in 1 packet by queueing them.
3322 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3323 {
fayanga4b37b22019-06-18 13:37:47 -07003324 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003325 connection_.SendStreamData3();
3326 connection_.SendStreamData5();
3327 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3328 }
3329 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3330 EXPECT_FALSE(connection_.HasQueuedData());
3331
3332 // Parse the last packet and ensure it's an ack and two stream frames from
3333 // two different streams.
3334 if (GetParam().no_stop_waiting) {
3335 EXPECT_EQ(2u, writer_->frame_count());
3336 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
3337 } else {
3338 EXPECT_EQ(2u, writer_->frame_count());
3339 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
3340 }
3341
3342 EXPECT_TRUE(writer_->ack_frames().empty());
3343
3344 ASSERT_EQ(2u, writer_->stream_frames().size());
3345 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3346 writer_->stream_frames()[0]->stream_id);
3347 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3348 writer_->stream_frames()[1]->stream_id);
3349}
3350
3351TEST_P(QuicConnectionTest, FramePackingNonCryptoThenCrypto) {
3352 // Send two stream frames (one non-crypto, then one crypto) in 2 packets by
3353 // queueing them.
3354 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3355 {
3356 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
fayanga4b37b22019-06-18 13:37:47 -07003357 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003358 connection_.SendStreamData3();
fayang58f71072019-11-05 08:47:02 -08003359 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003360 connection_.SendCryptoStreamData();
fayang58f71072019-11-05 08:47:02 -08003361 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003362 }
3363 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3364 EXPECT_FALSE(connection_.HasQueuedData());
3365
3366 // Parse the last packet and ensure it's the crypto stream frame.
3367 EXPECT_EQ(2u, writer_->frame_count());
3368 ASSERT_EQ(1u, writer_->padding_frames().size());
QUICHE teamea740082019-03-11 17:58:43 -07003369 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003370 ASSERT_EQ(1u, writer_->stream_frames().size());
3371 EXPECT_EQ(QuicUtils::GetCryptoStreamId(connection_.transport_version()),
3372 writer_->stream_frames()[0]->stream_id);
3373 } else {
3374 EXPECT_EQ(1u, writer_->crypto_frames().size());
3375 }
3376}
3377
3378TEST_P(QuicConnectionTest, FramePackingCryptoThenNonCrypto) {
3379 // Send two stream frames (one crypto, then one non-crypto) in 2 packets by
3380 // queueing them.
3381 {
3382 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3383 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
fayanga4b37b22019-06-18 13:37:47 -07003384 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003385 connection_.SendCryptoStreamData();
3386 connection_.SendStreamData3();
3387 }
3388 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3389 EXPECT_FALSE(connection_.HasQueuedData());
3390
3391 // Parse the last packet and ensure it's the stream frame from stream 3.
nharper55fa6132019-05-07 19:37:21 -07003392 size_t padding_frame_count = writer_->padding_frames().size();
3393 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003394 ASSERT_EQ(1u, writer_->stream_frames().size());
3395 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3396 writer_->stream_frames()[0]->stream_id);
3397}
3398
3399TEST_P(QuicConnectionTest, FramePackingAckResponse) {
3400 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3401 // Process a data packet to queue up a pending ack.
fayang3451f6e2019-06-11 08:18:12 -07003402 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3403 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
3404 } else {
3405 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3406 }
3407 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
3408
QUICHE teama6ef0a62019-03-07 20:34:33 -05003409 QuicPacketNumber last_packet;
nharper46833c32019-05-15 21:33:05 -07003410 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3411 connection_.SendCryptoDataWithString("foo", 0);
3412 } else {
3413 SendStreamDataToPeer(
3414 QuicUtils::GetCryptoStreamId(connection_.transport_version()), "foo", 0,
3415 NO_FIN, &last_packet);
3416 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003417 // Verify ack is bundled with outging packet.
3418 EXPECT_FALSE(writer_->ack_frames().empty());
3419
3420 EXPECT_CALL(visitor_, OnCanWrite())
3421 .WillOnce(DoAll(IgnoreResult(InvokeWithoutArgs(
3422 &connection_, &TestConnection::SendStreamData3)),
3423 IgnoreResult(InvokeWithoutArgs(
3424 &connection_, &TestConnection::SendStreamData5))));
3425
3426 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3427
3428 // Process a data packet to cause the visitor's OnCanWrite to be invoked.
3429 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
QUICHE team8c1daa22019-03-13 08:33:41 -07003430 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07003431 std::make_unique<TaggingEncrypter>(0x01));
zhongyi546cc452019-04-12 15:27:49 -07003432 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07003433 std::make_unique<StrictTaggingDecrypter>(0x01));
nharper2c9f02a2019-05-08 10:25:50 -07003434 ProcessDataPacket(2);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003435
3436 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3437 EXPECT_FALSE(connection_.HasQueuedData());
3438
3439 // Parse the last packet and ensure it's an ack and two stream frames from
3440 // two different streams.
3441 if (GetParam().no_stop_waiting) {
3442 EXPECT_EQ(3u, writer_->frame_count());
3443 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
3444 } else {
3445 EXPECT_EQ(4u, writer_->frame_count());
3446 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3447 }
3448 EXPECT_FALSE(writer_->ack_frames().empty());
3449 ASSERT_EQ(2u, writer_->stream_frames().size());
3450 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3451 writer_->stream_frames()[0]->stream_id);
3452 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3453 writer_->stream_frames()[1]->stream_id);
3454}
3455
3456TEST_P(QuicConnectionTest, FramePackingSendv) {
nharper46833c32019-05-15 21:33:05 -07003457 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003458 // Send data in 1 packet by writing multiple blocks in a single iovector
3459 // using writev.
3460 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3461
3462 char data[] = "ABCDEF";
3463 struct iovec iov[2];
3464 iov[0].iov_base = data;
3465 iov[0].iov_len = 4;
3466 iov[1].iov_base = data + 4;
3467 iov[1].iov_len = 2;
nharper46833c32019-05-15 21:33:05 -07003468 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
3469 connection_.transport_version(), Perspective::IS_CLIENT);
3470 connection_.SaveAndSendStreamData(stream_id, iov, 2, 6, 0, NO_FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003471
3472 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3473 EXPECT_FALSE(connection_.HasQueuedData());
3474
3475 // Parse the last packet and ensure multiple iovector blocks have
3476 // been packed into a single stream frame from one stream.
nharper46833c32019-05-15 21:33:05 -07003477 EXPECT_EQ(1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003478 EXPECT_EQ(1u, writer_->stream_frames().size());
nharper46833c32019-05-15 21:33:05 -07003479 EXPECT_EQ(0u, writer_->padding_frames().size());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003480 QuicStreamFrame* frame = writer_->stream_frames()[0].get();
nharper46833c32019-05-15 21:33:05 -07003481 EXPECT_EQ(stream_id, frame->stream_id);
dmcardlecf0bfcf2019-12-13 08:08:21 -08003482 EXPECT_EQ("ABCDEF",
3483 quiche::QuicheStringPiece(frame->data_buffer, frame->data_length));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003484}
3485
3486TEST_P(QuicConnectionTest, FramePackingSendvQueued) {
nharper46833c32019-05-15 21:33:05 -07003487 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003488 // Try to send two stream frames in 1 packet by using writev.
3489 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3490
3491 BlockOnNextWrite();
3492 char data[] = "ABCDEF";
3493 struct iovec iov[2];
3494 iov[0].iov_base = data;
3495 iov[0].iov_len = 4;
3496 iov[1].iov_base = data + 4;
3497 iov[1].iov_len = 2;
nharper46833c32019-05-15 21:33:05 -07003498 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
3499 connection_.transport_version(), Perspective::IS_CLIENT);
3500 connection_.SaveAndSendStreamData(stream_id, iov, 2, 6, 0, NO_FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003501
3502 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3503 EXPECT_TRUE(connection_.HasQueuedData());
3504
3505 // Unblock the writes and actually send.
3506 writer_->SetWritable();
3507 connection_.OnCanWrite();
3508 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3509
3510 // Parse the last packet and ensure it's one stream frame from one stream.
nharper46833c32019-05-15 21:33:05 -07003511 EXPECT_EQ(1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003512 EXPECT_EQ(1u, writer_->stream_frames().size());
nharper46833c32019-05-15 21:33:05 -07003513 EXPECT_EQ(0u, writer_->padding_frames().size());
3514 EXPECT_EQ(stream_id, writer_->stream_frames()[0]->stream_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003515}
3516
3517TEST_P(QuicConnectionTest, SendingZeroBytes) {
3518 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3519 // Send a zero byte write with a fin using writev.
3520 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
nharper46833c32019-05-15 21:33:05 -07003521 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
3522 connection_.transport_version(), Perspective::IS_CLIENT);
3523 connection_.SaveAndSendStreamData(stream_id, nullptr, 0, 0, 0, FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003524
3525 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3526 EXPECT_FALSE(connection_.HasQueuedData());
3527
nharper55fa6132019-05-07 19:37:21 -07003528 // Padding frames are added by v99 to ensure a minimum packet size.
3529 size_t extra_padding_frames = 0;
3530 if (GetParam().version.HasHeaderProtection()) {
3531 extra_padding_frames = 1;
3532 }
3533
QUICHE teama6ef0a62019-03-07 20:34:33 -05003534 // Parse the last packet and ensure it's one stream frame from one stream.
nharper55fa6132019-05-07 19:37:21 -07003535 EXPECT_EQ(1u + extra_padding_frames, writer_->frame_count());
3536 EXPECT_EQ(extra_padding_frames, writer_->padding_frames().size());
3537 ASSERT_EQ(1u, writer_->stream_frames().size());
nharper46833c32019-05-15 21:33:05 -07003538 EXPECT_EQ(stream_id, writer_->stream_frames()[0]->stream_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003539 EXPECT_TRUE(writer_->stream_frames()[0]->fin);
3540}
3541
3542TEST_P(QuicConnectionTest, LargeSendWithPendingAck) {
3543 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3544 // Set the ack alarm by processing a ping frame.
3545 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3546
3547 // Processs a PING frame.
3548 ProcessFramePacket(QuicFrame(QuicPingFrame()));
3549 // Ensure that this has caused the ACK alarm to be set.
fayang9adfb532020-06-04 06:58:45 -07003550 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003551
3552 // Send data and ensure the ack is bundled.
3553 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(8);
3554 size_t len = 10000;
3555 std::unique_ptr<char[]> data_array(new char[len]);
3556 memset(data_array.get(), '?', len);
3557 struct iovec iov;
3558 iov.iov_base = data_array.get();
3559 iov.iov_len = len;
3560 QuicConsumedData consumed = connection_.SaveAndSendStreamData(
dschinazi552accc2019-06-17 17:07:34 -07003561 GetNthClientInitiatedStreamId(0, connection_.transport_version()), &iov,
3562 1, len, 0, FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003563 EXPECT_EQ(len, consumed.bytes_consumed);
3564 EXPECT_TRUE(consumed.fin_consumed);
3565 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3566 EXPECT_FALSE(connection_.HasQueuedData());
3567
3568 // Parse the last packet and ensure it's one stream frame with a fin.
3569 EXPECT_EQ(1u, writer_->frame_count());
nharper55fa6132019-05-07 19:37:21 -07003570 ASSERT_EQ(1u, writer_->stream_frames().size());
dschinazi552accc2019-06-17 17:07:34 -07003571 EXPECT_EQ(GetNthClientInitiatedStreamId(0, connection_.transport_version()),
QUICHE teama6ef0a62019-03-07 20:34:33 -05003572 writer_->stream_frames()[0]->stream_id);
3573 EXPECT_TRUE(writer_->stream_frames()[0]->fin);
3574 // Ensure the ack alarm was cancelled when the ack was sent.
fayang9adfb532020-06-04 06:58:45 -07003575 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003576}
3577
3578TEST_P(QuicConnectionTest, OnCanWrite) {
3579 // Visitor's OnCanWrite will send data, but will have more pending writes.
3580 EXPECT_CALL(visitor_, OnCanWrite())
3581 .WillOnce(DoAll(IgnoreResult(InvokeWithoutArgs(
3582 &connection_, &TestConnection::SendStreamData3)),
3583 IgnoreResult(InvokeWithoutArgs(
3584 &connection_, &TestConnection::SendStreamData5))));
3585 {
3586 InSequence seq;
3587 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillOnce(Return(true));
3588 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
3589 .WillRepeatedly(Return(false));
3590 }
3591
3592 EXPECT_CALL(*send_algorithm_, CanSend(_))
3593 .WillRepeatedly(testing::Return(true));
3594
3595 connection_.OnCanWrite();
3596
3597 // Parse the last packet and ensure it's the two stream frames from
3598 // two different streams.
3599 EXPECT_EQ(2u, writer_->frame_count());
3600 EXPECT_EQ(2u, writer_->stream_frames().size());
3601 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3602 writer_->stream_frames()[0]->stream_id);
3603 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3604 writer_->stream_frames()[1]->stream_id);
3605}
3606
3607TEST_P(QuicConnectionTest, RetransmitOnNack) {
3608 QuicPacketNumber last_packet;
3609 QuicByteCount second_packet_size;
3610 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet); // Packet 1
3611 second_packet_size =
3612 SendStreamDataToPeer(3, "foos", 3, NO_FIN, &last_packet); // Packet 2
3613 SendStreamDataToPeer(3, "fooos", 7, NO_FIN, &last_packet); // Packet 3
3614
3615 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3616
3617 // Don't lose a packet on an ack, and nothing is retransmitted.
3618 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3619 QuicAckFrame ack_one = InitAckFrame(1);
3620 ProcessAckPacket(&ack_one);
3621
3622 // Lose a packet and ensure it triggers retransmission.
3623 QuicAckFrame nack_two = ConstructAckFrame(3, 2);
3624 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003625 lost_packets.push_back(
3626 LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003627 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07003628 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
3629 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003630 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3631 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3632 EXPECT_FALSE(QuicPacketCreatorPeer::SendVersionInPacket(creator_));
3633 ProcessAckPacket(&nack_two);
3634}
3635
3636TEST_P(QuicConnectionTest, DoNotSendQueuedPacketForResetStream) {
3637 // Block the connection to queue the packet.
3638 BlockOnNextWrite();
3639
3640 QuicStreamId stream_id = 2;
3641 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
3642
3643 // Now that there is a queued packet, reset the stream.
3644 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
3645
3646 // Unblock the connection and verify that only the RST_STREAM is sent.
3647 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3648 writer_->SetWritable();
3649 connection_.OnCanWrite();
nharper55fa6132019-05-07 19:37:21 -07003650 size_t padding_frame_count = writer_->padding_frames().size();
3651 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003652 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3653}
3654
3655TEST_P(QuicConnectionTest, SendQueuedPacketForQuicRstStreamNoError) {
3656 // Block the connection to queue the packet.
3657 BlockOnNextWrite();
3658
3659 QuicStreamId stream_id = 2;
fayange62e63c2019-12-04 07:16:25 -08003660 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003661 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
3662
3663 // Now that there is a queued packet, reset the stream.
3664 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 3);
3665
3666 // Unblock the connection and verify that the RST_STREAM is sent and the data
3667 // packet is sent.
fayange62e63c2019-12-04 07:16:25 -08003668 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003669 writer_->SetWritable();
3670 connection_.OnCanWrite();
nharper55fa6132019-05-07 19:37:21 -07003671 size_t padding_frame_count = writer_->padding_frames().size();
3672 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003673 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3674}
3675
3676TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnNack) {
3677 QuicStreamId stream_id = 2;
3678 QuicPacketNumber last_packet;
3679 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3680 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3681 SendStreamDataToPeer(stream_id, "fooos", 7, NO_FIN, &last_packet);
3682
3683 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3684 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 12);
3685
3686 // Lose a packet and ensure it does not trigger retransmission.
3687 QuicAckFrame nack_two = ConstructAckFrame(last_packet, last_packet - 1);
3688 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3689 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3690 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3691 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3692 ProcessAckPacket(&nack_two);
3693}
3694
3695TEST_P(QuicConnectionTest, RetransmitForQuicRstStreamNoErrorOnNack) {
3696 QuicStreamId stream_id = 2;
3697 QuicPacketNumber last_packet;
3698 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3699 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3700 SendStreamDataToPeer(stream_id, "fooos", 7, NO_FIN, &last_packet);
3701
3702 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3703 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 12);
3704
3705 // Lose a packet, ensure it triggers retransmission.
3706 QuicAckFrame nack_two = ConstructAckFrame(last_packet, last_packet - 1);
3707 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3708 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003709 lost_packets.push_back(LostPacket(last_packet - 1, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003710 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07003711 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
3712 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003713 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3714 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
3715 ProcessAckPacket(&nack_two);
3716}
3717
3718TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnRTO) {
3719 QuicStreamId stream_id = 2;
3720 QuicPacketNumber last_packet;
3721 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3722
3723 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3724 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
3725
3726 // Fire the RTO and verify that the RST_STREAM is resent, not stream data.
3727 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3728 clock_.AdvanceTime(DefaultRetransmissionTime());
3729 connection_.GetRetransmissionAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07003730 size_t padding_frame_count = writer_->padding_frames().size();
3731 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003732 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3733 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
3734}
3735
3736// Ensure that if the only data in flight is non-retransmittable, the
3737// retransmission alarm is not set.
3738TEST_P(QuicConnectionTest, CancelRetransmissionAlarmAfterResetStream) {
3739 QuicStreamId stream_id = 2;
3740 QuicPacketNumber last_data_packet;
3741 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
3742
3743 // Cancel the stream.
3744 const QuicPacketNumber rst_packet = last_data_packet + 1;
3745 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, rst_packet, _, _)).Times(1);
3746 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
3747
3748 // Ack the RST_STREAM frame (since it's retransmittable), but not the data
3749 // packet, which is no longer retransmittable since the stream was cancelled.
3750 QuicAckFrame nack_stream_data =
3751 ConstructAckFrame(rst_packet, last_data_packet);
3752 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3753 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3754 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3755 ProcessAckPacket(&nack_stream_data);
3756
3757 // Ensure that the data is still in flight, but the retransmission alarm is no
3758 // longer set.
ianswett9f459cb2019-04-21 06:39:59 -07003759 EXPECT_GT(manager_->GetBytesInFlight(), 0u);
fayangcff885a2019-10-22 07:39:04 -07003760 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003761}
3762
3763TEST_P(QuicConnectionTest, RetransmitForQuicRstStreamNoErrorOnRTO) {
3764 connection_.SetMaxTailLossProbes(0);
3765
3766 QuicStreamId stream_id = 2;
3767 QuicPacketNumber last_packet;
3768 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3769
3770 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3771 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 3);
3772
3773 // Fire the RTO and verify that the RST_STREAM is resent, the stream data
3774 // is sent.
fayang1c2d1ab2020-03-11 12:08:41 -07003775 const size_t num_retransmissions =
3776 connection_.SupportsMultiplePacketNumberSpaces() ? 1 : 2;
3777 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3778 .Times(AtLeast(num_retransmissions));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003779 clock_.AdvanceTime(DefaultRetransmissionTime());
3780 connection_.GetRetransmissionAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07003781 size_t padding_frame_count = writer_->padding_frames().size();
3782 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
fayang1c2d1ab2020-03-11 12:08:41 -07003783 if (num_retransmissions == 2) {
3784 ASSERT_EQ(1u, writer_->rst_stream_frames().size());
3785 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
3786 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003787}
3788
3789TEST_P(QuicConnectionTest, DoNotSendPendingRetransmissionForResetStream) {
3790 QuicStreamId stream_id = 2;
3791 QuicPacketNumber last_packet;
3792 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3793 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3794 BlockOnNextWrite();
3795 connection_.SendStreamDataWithString(stream_id, "fooos", 7, NO_FIN);
3796
3797 // Lose a packet which will trigger a pending retransmission.
3798 QuicAckFrame ack = ConstructAckFrame(last_packet, last_packet - 1);
3799 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3800 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3801 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3802 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3803 ProcessAckPacket(&ack);
3804
3805 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 12);
3806
3807 // Unblock the connection and verify that the RST_STREAM is sent but not the
3808 // second data packet nor a retransmit.
3809 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3810 writer_->SetWritable();
3811 connection_.OnCanWrite();
nharper55fa6132019-05-07 19:37:21 -07003812 size_t padding_frame_count = writer_->padding_frames().size();
3813 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
zhongyi546cc452019-04-12 15:27:49 -07003814 ASSERT_EQ(1u, writer_->rst_stream_frames().size());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003815 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
3816}
3817
3818TEST_P(QuicConnectionTest, SendPendingRetransmissionForQuicRstStreamNoError) {
3819 QuicStreamId stream_id = 2;
3820 QuicPacketNumber last_packet;
3821 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3822 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3823 BlockOnNextWrite();
3824 connection_.SendStreamDataWithString(stream_id, "fooos", 7, NO_FIN);
3825
3826 // Lose a packet which will trigger a pending retransmission.
3827 QuicAckFrame ack = ConstructAckFrame(last_packet, last_packet - 1);
3828 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3829 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003830 lost_packets.push_back(LostPacket(last_packet - 1, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003831 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07003832 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
3833 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003834 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3835 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3836 ProcessAckPacket(&ack);
3837
3838 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 12);
3839
3840 // Unblock the connection and verify that the RST_STREAM is sent and the
3841 // second data packet or a retransmit is sent.
3842 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(2));
3843 writer_->SetWritable();
3844 connection_.OnCanWrite();
3845 // The RST_STREAM_FRAME is sent after queued packets and pending
3846 // retransmission.
3847 connection_.SendControlFrame(QuicFrame(
3848 new QuicRstStreamFrame(1, stream_id, QUIC_STREAM_NO_ERROR, 14)));
nharper55fa6132019-05-07 19:37:21 -07003849 size_t padding_frame_count = writer_->padding_frames().size();
3850 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003851 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3852}
3853
3854TEST_P(QuicConnectionTest, RetransmitAckedPacket) {
3855 QuicPacketNumber last_packet;
3856 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
3857 SendStreamDataToPeer(1, "foos", 3, NO_FIN, &last_packet); // Packet 2
3858 SendStreamDataToPeer(1, "fooos", 7, NO_FIN, &last_packet); // Packet 3
3859
3860 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3861
3862 // Instigate a loss with an ack.
3863 QuicAckFrame nack_two = ConstructAckFrame(3, 2);
3864 // The first nack should trigger a fast retransmission, but we'll be
3865 // write blocked, so the packet will be queued.
3866 BlockOnNextWrite();
3867
3868 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003869 lost_packets.push_back(
3870 LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003871 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07003872 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
3873 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003874 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
fayange62e63c2019-12-04 07:16:25 -08003875 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _))
3876 .Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003877 ProcessAckPacket(&nack_two);
3878 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3879
3880 // Now, ack the previous transmission.
3881 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3882 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(false, _, _, _, _));
3883 QuicAckFrame ack_all = InitAckFrame(3);
3884 ProcessAckPacket(&ack_all);
3885
fayange62e63c2019-12-04 07:16:25 -08003886 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _))
3887 .Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003888
3889 writer_->SetWritable();
3890 connection_.OnCanWrite();
3891
3892 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3893 // We do not store retransmittable frames of this retransmission.
3894 EXPECT_FALSE(QuicConnectionPeer::HasRetransmittableFrames(&connection_, 4));
3895}
3896
3897TEST_P(QuicConnectionTest, RetransmitNackedLargestObserved) {
3898 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3899 QuicPacketNumber original, second;
3900
3901 QuicByteCount packet_size =
3902 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &original); // 1st packet.
3903 SendStreamDataToPeer(3, "bar", 3, NO_FIN, &second); // 2nd packet.
3904
3905 QuicAckFrame frame = InitAckFrame({{second, second + 1}});
3906 // The first nack should retransmit the largest observed packet.
3907 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003908 lost_packets.push_back(LostPacket(original, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003909 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07003910 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
3911 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003912 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3913 // Packet 1 is short header for IETF QUIC because the encryption level
3914 // switched to ENCRYPTION_FORWARD_SECURE in SendStreamDataToPeer.
fayangd4291e42019-05-30 10:31:21 -07003915 EXPECT_CALL(*send_algorithm_,
3916 OnPacketSent(_, _, _,
3917 VersionHasIetfInvariantHeader(
3918 GetParam().version.transport_version)
3919 ? packet_size
3920 : packet_size - kQuicVersionSize,
3921 _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003922 ProcessAckPacket(&frame);
3923}
3924
3925TEST_P(QuicConnectionTest, QueueAfterTwoRTOs) {
fayangcff885a2019-10-22 07:39:04 -07003926 if (connection_.PtoEnabled()) {
fayang5f135052019-08-22 17:59:40 -07003927 return;
3928 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003929 connection_.SetMaxTailLossProbes(0);
3930
3931 for (int i = 0; i < 10; ++i) {
3932 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3933 connection_.SendStreamDataWithString(3, "foo", i * 3, NO_FIN);
3934 }
3935
3936 // Block the writer and ensure they're queued.
3937 BlockOnNextWrite();
3938 clock_.AdvanceTime(DefaultRetransmissionTime());
fayange62e63c2019-12-04 07:16:25 -08003939 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003940 connection_.GetRetransmissionAlarm()->Fire();
3941 EXPECT_TRUE(connection_.HasQueuedData());
3942
3943 // Unblock the writer.
3944 writer_->SetWritable();
3945 clock_.AdvanceTime(QuicTime::Delta::FromMicroseconds(
3946 2 * DefaultRetransmissionTime().ToMicroseconds()));
fayange62e63c2019-12-04 07:16:25 -08003947 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003948 connection_.GetRetransmissionAlarm()->Fire();
3949 connection_.OnCanWrite();
3950}
3951
3952TEST_P(QuicConnectionTest, WriteBlockedBufferedThenSent) {
3953 BlockOnNextWrite();
3954 writer_->set_is_write_blocked_data_buffered(true);
3955 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3956 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3957 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3958
3959 writer_->SetWritable();
3960 connection_.OnCanWrite();
3961 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3962}
3963
3964TEST_P(QuicConnectionTest, WriteBlockedThenSent) {
3965 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3966 BlockOnNextWrite();
fayange62e63c2019-12-04 07:16:25 -08003967 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003968 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
fayange62e63c2019-12-04 07:16:25 -08003969 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003970 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3971
3972 // The second packet should also be queued, in order to ensure packets are
3973 // never sent out of order.
3974 writer_->SetWritable();
fayange62e63c2019-12-04 07:16:25 -08003975 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003976 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3977 EXPECT_EQ(2u, connection_.NumQueuedPackets());
3978
3979 // Now both are sent in order when we unblock.
fayange62e63c2019-12-04 07:16:25 -08003980 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003981 connection_.OnCanWrite();
3982 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
fayang2ce66082019-10-02 06:29:04 -07003983 EXPECT_EQ(0u, connection_.NumQueuedPackets());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003984}
3985
3986TEST_P(QuicConnectionTest, RetransmitWriteBlockedAckedOriginalThenSent) {
3987 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3988 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
3989 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3990
3991 BlockOnNextWrite();
3992 writer_->set_is_write_blocked_data_buffered(true);
3993 // Simulate the retransmission alarm firing.
3994 clock_.AdvanceTime(DefaultRetransmissionTime());
3995 connection_.GetRetransmissionAlarm()->Fire();
3996
3997 // Ack the sent packet before the callback returns, which happens in
3998 // rare circumstances with write blocked sockets.
3999 QuicAckFrame ack = InitAckFrame(1);
4000 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4001 ProcessAckPacket(&ack);
4002
4003 writer_->SetWritable();
4004 connection_.OnCanWrite();
fayangcff885a2019-10-22 07:39:04 -07004005 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
fayang5d011982020-05-13 14:14:38 -07004006 uint64_t retransmission = connection_.SupportsMultiplePacketNumberSpaces() &&
4007 !GetQuicReloadableFlag(quic_default_on_pto)
4008 ? 3
4009 : 2;
fayang1c2d1ab2020-03-11 12:08:41 -07004010 EXPECT_FALSE(QuicConnectionPeer::HasRetransmittableFrames(&connection_,
4011 retransmission));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004012}
4013
4014TEST_P(QuicConnectionTest, AlarmsWhenWriteBlocked) {
4015 // Block the connection.
4016 BlockOnNextWrite();
4017 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
4018 EXPECT_EQ(1u, writer_->packets_write_attempts());
4019 EXPECT_TRUE(writer_->IsWriteBlocked());
4020
4021 // Set the send alarm. Fire the alarm and ensure it doesn't attempt to write.
4022 connection_.GetSendAlarm()->Set(clock_.ApproximateNow());
4023 connection_.GetSendAlarm()->Fire();
4024 EXPECT_TRUE(writer_->IsWriteBlocked());
4025 EXPECT_EQ(1u, writer_->packets_write_attempts());
4026}
4027
4028TEST_P(QuicConnectionTest, NoSendAlarmAfterProcessPacketWhenWriteBlocked) {
4029 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4030
4031 // Block the connection.
4032 BlockOnNextWrite();
4033 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
4034 EXPECT_TRUE(writer_->IsWriteBlocked());
4035 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4036 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4037
4038 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4039 // Process packet number 1. Can not call ProcessPacket or ProcessDataPacket
4040 // here, because they will fire the alarm after QuicConnection::ProcessPacket
4041 // is returned.
4042 const uint64_t received_packet_num = 1;
4043 const bool has_stop_waiting = false;
nharperc6b99512019-09-19 11:13:48 -07004044 const EncryptionLevel level = ENCRYPTION_FORWARD_SECURE;
4045 std::unique_ptr<QuicPacket> packet(
4046 ConstructDataPacket(received_packet_num, has_stop_waiting, level));
dschinazi66dea072019-04-09 11:41:06 -07004047 char buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05004048 size_t encrypted_length =
4049 peer_framer_.EncryptPayload(level, QuicPacketNumber(received_packet_num),
dschinazi66dea072019-04-09 11:41:06 -07004050 *packet, buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004051 connection_.ProcessUdpPacket(
4052 kSelfAddress, kPeerAddress,
4053 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
4054
4055 EXPECT_TRUE(writer_->IsWriteBlocked());
4056 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4057}
4058
4059TEST_P(QuicConnectionTest, AddToWriteBlockedListIfWriterBlockedWhenProcessing) {
4060 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4061 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
4062
4063 // Simulate the case where a shared writer gets blocked by another connection.
4064 writer_->SetWriteBlocked();
4065
4066 // Process an ACK, make sure the connection calls visitor_->OnWriteBlocked().
4067 QuicAckFrame ack1 = InitAckFrame(1);
4068 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
4069 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
4070 ProcessAckPacket(1, &ack1);
4071}
4072
4073TEST_P(QuicConnectionTest, DoNotAddToWriteBlockedListAfterDisconnect) {
4074 writer_->SetBatchMode(true);
4075 EXPECT_TRUE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07004076 // Have to explicitly grab the OnConnectionClosed frame and check
4077 // its parameters because this is a silent connection close and the
4078 // frame is not also transmitted to the peer.
4079 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
4080 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004081
4082 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
4083
4084 {
fayanga4b37b22019-06-18 13:37:47 -07004085 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004086 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
4087 ConnectionCloseBehavior::SILENT_CLOSE);
4088
4089 EXPECT_FALSE(connection_.connected());
4090 writer_->SetWriteBlocked();
4091 }
fkastenholz5d880a92019-06-21 09:01:56 -07004092 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08004093 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
4094 IsError(QUIC_PEER_GOING_AWAY));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004095}
4096
4097TEST_P(QuicConnectionTest, AddToWriteBlockedListIfBlockedOnFlushPackets) {
4098 writer_->SetBatchMode(true);
4099 writer_->BlockOnNextFlush();
4100
4101 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
4102 {
fayanga4b37b22019-06-18 13:37:47 -07004103 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004104 // flusher's destructor will call connection_.FlushPackets, which should add
4105 // the connection to the write blocked list.
4106 }
4107}
4108
4109TEST_P(QuicConnectionTest, NoLimitPacketsPerNack) {
4110 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4111 int offset = 0;
4112 // Send packets 1 to 15.
4113 for (int i = 0; i < 15; ++i) {
4114 SendStreamDataToPeer(1, "foo", offset, NO_FIN, nullptr);
4115 offset += 3;
4116 }
4117
4118 // Ack 15, nack 1-14.
4119
4120 QuicAckFrame nack =
4121 InitAckFrame({{QuicPacketNumber(15), QuicPacketNumber(16)}});
4122
4123 // 14 packets have been NACK'd and lost.
4124 LostPacketVector lost_packets;
4125 for (int i = 1; i < 15; ++i) {
dschinazi66dea072019-04-09 11:41:06 -07004126 lost_packets.push_back(
4127 LostPacket(QuicPacketNumber(i), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004128 }
4129 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07004130 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
4131 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004132 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
fayangcff885a2019-10-22 07:39:04 -07004133 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004134 ProcessAckPacket(&nack);
4135}
4136
4137// Test sending multiple acks from the connection to the session.
4138TEST_P(QuicConnectionTest, MultipleAcks) {
QUICHE teamcd098022019-03-22 18:49:55 -07004139 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4140 return;
4141 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004142 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4143 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4144 ProcessDataPacket(1);
4145 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
4146 QuicPacketNumber last_packet;
4147 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
4148 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4149 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet); // Packet 2
4150 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
4151 SendAckPacketToPeer(); // Packet 3
4152 SendStreamDataToPeer(5, "foo", 0, NO_FIN, &last_packet); // Packet 4
4153 EXPECT_EQ(QuicPacketNumber(4u), last_packet);
4154 SendStreamDataToPeer(1, "foo", 3, NO_FIN, &last_packet); // Packet 5
4155 EXPECT_EQ(QuicPacketNumber(5u), last_packet);
4156 SendStreamDataToPeer(3, "foo", 3, NO_FIN, &last_packet); // Packet 6
4157 EXPECT_EQ(QuicPacketNumber(6u), last_packet);
4158
4159 // Client will ack packets 1, 2, [!3], 4, 5.
4160 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4161 QuicAckFrame frame1 = ConstructAckFrame(5, 3);
4162 ProcessAckPacket(&frame1);
4163
4164 // Now the client implicitly acks 3, and explicitly acks 6.
4165 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4166 QuicAckFrame frame2 = InitAckFrame(6);
4167 ProcessAckPacket(&frame2);
4168}
4169
4170TEST_P(QuicConnectionTest, DontLatchUnackedPacket) {
QUICHE teamcd098022019-03-22 18:49:55 -07004171 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4172 return;
4173 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004174 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4175 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4176 ProcessDataPacket(1);
4177 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
4178 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr); // Packet 1;
4179 // From now on, we send acks, so the send algorithm won't mark them pending.
4180 SendAckPacketToPeer(); // Packet 2
4181
4182 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4183 QuicAckFrame frame = InitAckFrame(1);
4184 ProcessAckPacket(&frame);
4185
4186 // Verify that our internal state has least-unacked as 2, because we're still
4187 // waiting for a potential ack for 2.
4188
4189 EXPECT_EQ(QuicPacketNumber(2u), stop_waiting()->least_unacked);
4190
4191 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4192 frame = InitAckFrame(2);
4193 ProcessAckPacket(&frame);
4194 EXPECT_EQ(QuicPacketNumber(3u), stop_waiting()->least_unacked);
4195
4196 // When we send an ack, we make sure our least-unacked makes sense. In this
4197 // case since we're not waiting on an ack for 2 and all packets are acked, we
4198 // set it to 3.
4199 SendAckPacketToPeer(); // Packet 3
4200 // Least_unacked remains at 3 until another ack is received.
4201 EXPECT_EQ(QuicPacketNumber(3u), stop_waiting()->least_unacked);
4202 if (GetParam().no_stop_waiting) {
4203 // Expect no stop waiting frame is sent.
4204 EXPECT_FALSE(least_unacked().IsInitialized());
4205 } else {
4206 // Check that the outgoing ack had its packet number as least_unacked.
4207 EXPECT_EQ(QuicPacketNumber(3u), least_unacked());
4208 }
4209
4210 // Ack the ack, which updates the rtt and raises the least unacked.
4211 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4212 frame = InitAckFrame(3);
4213 ProcessAckPacket(&frame);
4214
4215 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr); // Packet 4
4216 EXPECT_EQ(QuicPacketNumber(4u), stop_waiting()->least_unacked);
4217 SendAckPacketToPeer(); // Packet 5
4218 if (GetParam().no_stop_waiting) {
4219 // Expect no stop waiting frame is sent.
4220 EXPECT_FALSE(least_unacked().IsInitialized());
4221 } else {
4222 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
4223 }
4224
4225 // Send two data packets at the end, and ensure if the last one is acked,
4226 // the least unacked is raised above the ack packets.
4227 SendStreamDataToPeer(1, "bar", 6, NO_FIN, nullptr); // Packet 6
4228 SendStreamDataToPeer(1, "bar", 9, NO_FIN, nullptr); // Packet 7
4229
4230 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4231 frame = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(5)},
4232 {QuicPacketNumber(7), QuicPacketNumber(8)}});
4233 ProcessAckPacket(&frame);
4234
4235 EXPECT_EQ(QuicPacketNumber(6u), stop_waiting()->least_unacked);
4236}
4237
4238TEST_P(QuicConnectionTest, TLP) {
fayang5d011982020-05-13 14:14:38 -07004239 if (connection_.PtoEnabled()) {
4240 return;
4241 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004242 connection_.SetMaxTailLossProbes(1);
4243
4244 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
4245 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4246 QuicTime retransmission_time =
4247 connection_.GetRetransmissionAlarm()->deadline();
4248 EXPECT_NE(QuicTime::Zero(), retransmission_time);
4249
4250 EXPECT_EQ(QuicPacketNumber(1u), writer_->header().packet_number);
4251 // Simulate the retransmission alarm firing and sending a tlp,
4252 // so send algorithm's OnRetransmissionTimeout is not called.
4253 clock_.AdvanceTime(retransmission_time - clock_.Now());
fayang1c2d1ab2020-03-11 12:08:41 -07004254 const QuicPacketNumber retransmission(
4255 connection_.SupportsMultiplePacketNumberSpaces() ? 3 : 2);
4256 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, retransmission, _, _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004257 connection_.GetRetransmissionAlarm()->Fire();
fayang1c2d1ab2020-03-11 12:08:41 -07004258 EXPECT_EQ(retransmission, writer_->header().packet_number);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004259 // We do not raise the high water mark yet.
4260 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4261}
4262
zhongyifbb25772019-04-10 16:54:08 -07004263TEST_P(QuicConnectionTest, TailLossProbeDelayForStreamDataInTLPR) {
fayangcff885a2019-10-22 07:39:04 -07004264 if (connection_.PtoEnabled()) {
zhongyi1b2f7832019-06-14 13:31:34 -07004265 return;
4266 }
4267
zhongyifbb25772019-04-10 16:54:08 -07004268 // Set TLPR from QuicConfig.
4269 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4270 QuicConfig config;
4271 QuicTagVector options;
4272 options.push_back(kTLPR);
4273 config.SetConnectionOptionsToSend(options);
4274 connection_.SetFromConfig(config);
4275 connection_.SetMaxTailLossProbes(1);
4276
4277 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
4278 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4279
4280 QuicTime retransmission_time =
4281 connection_.GetRetransmissionAlarm()->deadline();
4282 EXPECT_NE(QuicTime::Zero(), retransmission_time);
4283 QuicTime::Delta expected_tlp_delay =
4284 0.5 * manager_->GetRttStats()->SmoothedOrInitialRtt();
4285 EXPECT_EQ(expected_tlp_delay, retransmission_time - clock_.Now());
4286
4287 EXPECT_EQ(QuicPacketNumber(1u), writer_->header().packet_number);
4288 // Simulate firing of the retransmission alarm and retransmit the packet.
4289 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
4290 clock_.AdvanceTime(retransmission_time - clock_.Now());
4291 connection_.GetRetransmissionAlarm()->Fire();
4292 EXPECT_EQ(QuicPacketNumber(2u), writer_->header().packet_number);
4293
4294 // We do not raise the high water mark yet.
4295 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4296}
4297
4298TEST_P(QuicConnectionTest, TailLossProbeDelayForNonStreamDataInTLPR) {
fayangcff885a2019-10-22 07:39:04 -07004299 if (connection_.PtoEnabled()) {
zhongyi1b2f7832019-06-14 13:31:34 -07004300 return;
4301 }
4302
zhongyifbb25772019-04-10 16:54:08 -07004303 // Set TLPR from QuicConfig.
4304 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4305 QuicConfig config;
4306 QuicTagVector options;
4307 options.push_back(kTLPR);
4308 config.SetConnectionOptionsToSend(options);
dschinazif7c6a912020-05-05 11:39:53 -07004309 QuicConfigPeer::SetNegotiated(&config, true);
dschinazie7c38a52020-05-29 15:25:45 -07004310 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
4311 QuicConfigPeer::SetReceivedOriginalConnectionId(
4312 &config, connection_.connection_id());
4313 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
4314 &config, connection_.connection_id());
4315 }
zhongyifbb25772019-04-10 16:54:08 -07004316 connection_.SetFromConfig(config);
4317 connection_.SetMaxTailLossProbes(1);
4318
4319 // Sets retransmittable on wire.
4320 const QuicTime::Delta retransmittable_on_wire_timeout =
4321 QuicTime::Delta::FromMilliseconds(50);
zhongyi79ace162019-10-21 15:57:09 -07004322 connection_.set_initial_retransmittable_on_wire_timeout(
zhongyifbb25772019-04-10 16:54:08 -07004323 retransmittable_on_wire_timeout);
4324
4325 EXPECT_TRUE(connection_.connected());
4326 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4327 .WillRepeatedly(Return(true));
fayangb59c6f12020-03-23 15:06:14 -07004328 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
zhongyifbb25772019-04-10 16:54:08 -07004329 EXPECT_FALSE(connection_.IsPathDegrading());
4330 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4331
4332 const char data[] = "data";
4333 size_t data_size = strlen(data);
4334 QuicStreamOffset offset = 0;
4335
4336 // Send a data packet.
4337 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
4338 offset += data_size;
4339
4340 // Path degrading alarm should be set when there is a retransmittable packet
4341 // on the wire.
fayangb59c6f12020-03-23 15:06:14 -07004342 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
zhongyifbb25772019-04-10 16:54:08 -07004343
4344 // Verify the path degrading delay.
4345 // First TLP with stream data.
4346 QuicTime::Delta srtt = manager_->GetRttStats()->SmoothedOrInitialRtt();
4347 QuicTime::Delta expected_delay = 0.5 * srtt;
4348 // Add 1st RTO.
4349 QuicTime::Delta retransmission_delay =
4350 QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
4351 expected_delay = expected_delay + retransmission_delay;
4352 // Add 2nd RTO.
4353 expected_delay = expected_delay + retransmission_delay * 2;
4354 EXPECT_EQ(expected_delay,
4355 QuicConnectionPeer::GetSentPacketManager(&connection_)
4356 ->GetPathDegradingDelay());
4357 ASSERT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
4358
4359 // The ping alarm is set for the ping timeout, not the shorter
4360 // retransmittable_on_wire_timeout.
4361 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004362 EXPECT_EQ(connection_.ping_timeout(),
zhongyifbb25772019-04-10 16:54:08 -07004363 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
4364
4365 // Receive an ACK for the data packet.
4366 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4367 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4368 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4369 QuicAckFrame frame =
4370 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
4371 ProcessAckPacket(&frame);
4372
4373 // Path degrading alarm should be cancelled as there is no more
4374 // reretransmittable packets on the wire.
fayangb59c6f12020-03-23 15:06:14 -07004375 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
zhongyifbb25772019-04-10 16:54:08 -07004376 // The ping alarm should be set to the retransmittable_on_wire_timeout.
4377 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4378 EXPECT_EQ(retransmittable_on_wire_timeout,
4379 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
4380
4381 // Simulate firing of the retransmittable on wire and send a PING.
4382 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
4383 clock_.AdvanceTime(retransmittable_on_wire_timeout);
4384 connection_.GetPingAlarm()->Fire();
4385
4386 // The retransmission alarm and the path degrading alarm should be set as
4387 // there is a retransmittable packet (PING) on the wire,
4388 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
fayangb59c6f12020-03-23 15:06:14 -07004389 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
zhongyifbb25772019-04-10 16:54:08 -07004390
4391 // Verify the retransmission delay.
4392 QuicTime::Delta min_rto_timeout =
4393 QuicTime::Delta::FromMilliseconds(kMinRetransmissionTimeMs);
4394 srtt = manager_->GetRttStats()->SmoothedOrInitialRtt();
zhongyi9fa2be32019-09-10 12:39:01 -07004395
4396 // First TLP without unacked stream data will no longer use TLPR.
4397 expected_delay = std::max(2 * srtt, 1.5 * srtt + 0.5 * min_rto_timeout);
zhongyifbb25772019-04-10 16:54:08 -07004398 EXPECT_EQ(expected_delay,
4399 connection_.GetRetransmissionAlarm()->deadline() - clock_.Now());
4400
zhongyi1b2f7832019-06-14 13:31:34 -07004401 // Verify the path degrading delay = TLP delay + 1st RTO + 2nd RTO.
zhongyifbb25772019-04-10 16:54:08 -07004402 // Add 1st RTO.
4403 retransmission_delay =
4404 std::max(manager_->GetRttStats()->smoothed_rtt() +
4405 4 * manager_->GetRttStats()->mean_deviation(),
4406 min_rto_timeout);
4407 expected_delay = expected_delay + retransmission_delay;
4408 // Add 2nd RTO.
4409 expected_delay = expected_delay + retransmission_delay * 2;
4410 EXPECT_EQ(expected_delay,
4411 QuicConnectionPeer::GetSentPacketManager(&connection_)
4412 ->GetPathDegradingDelay());
4413
4414 // The ping alarm is set for the ping timeout, not the shorter
4415 // retransmittable_on_wire_timeout.
4416 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004417 EXPECT_EQ(connection_.ping_timeout(),
zhongyifbb25772019-04-10 16:54:08 -07004418 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
zhongyi1b2f7832019-06-14 13:31:34 -07004419
4420 // Advance a small period of time: 5ms. And receive a retransmitted ACK.
4421 // This will update the retransmission alarm, verify the retransmission delay
4422 // is correct.
4423 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4424 QuicAckFrame ack = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
4425 ProcessAckPacket(&ack);
4426
4427 // Verify the retransmission delay.
zhongyi9fa2be32019-09-10 12:39:01 -07004428 // First TLP without unacked stream data will no longer use TLPR.
4429 expected_delay = std::max(2 * srtt, 1.5 * srtt + 0.5 * min_rto_timeout);
zhongyi1b2f7832019-06-14 13:31:34 -07004430 expected_delay = expected_delay - QuicTime::Delta::FromMilliseconds(5);
4431 EXPECT_EQ(expected_delay,
4432 connection_.GetRetransmissionAlarm()->deadline() - clock_.Now());
zhongyifbb25772019-04-10 16:54:08 -07004433}
4434
QUICHE teama6ef0a62019-03-07 20:34:33 -05004435TEST_P(QuicConnectionTest, RTO) {
fayang5f135052019-08-22 17:59:40 -07004436 if (connection_.PtoEnabled()) {
4437 return;
4438 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004439 connection_.SetMaxTailLossProbes(0);
4440
4441 QuicTime default_retransmission_time =
4442 clock_.ApproximateNow() + DefaultRetransmissionTime();
4443 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
4444 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4445
4446 EXPECT_EQ(QuicPacketNumber(1u), writer_->header().packet_number);
4447 EXPECT_EQ(default_retransmission_time,
4448 connection_.GetRetransmissionAlarm()->deadline());
4449 // Simulate the retransmission alarm firing.
4450 clock_.AdvanceTime(DefaultRetransmissionTime());
4451 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
4452 connection_.GetRetransmissionAlarm()->Fire();
4453 EXPECT_EQ(QuicPacketNumber(2u), writer_->header().packet_number);
4454 // We do not raise the high water mark yet.
4455 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4456}
4457
fayanga29eb242019-07-16 12:25:38 -07004458// Regression test of b/133771183.
4459TEST_P(QuicConnectionTest, RtoWithNoDataToRetransmit) {
fayangcff885a2019-10-22 07:39:04 -07004460 if (connection_.PtoEnabled()) {
fayanga29eb242019-07-16 12:25:38 -07004461 return;
4462 }
4463 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4464 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4465 connection_.SetMaxTailLossProbes(0);
4466
4467 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
4468 // Connection is cwnd limited.
4469 CongestionBlockWrites();
4470 // Stream gets reset.
4471 SendRstStream(3, QUIC_ERROR_PROCESSING_STREAM, 3);
4472 // Simulate the retransmission alarm firing.
4473 clock_.AdvanceTime(DefaultRetransmissionTime());
4474 // RTO fires, but there is no packet to be RTOed.
fayange861aee2019-10-16 13:40:39 -07004475 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
fayanga29eb242019-07-16 12:25:38 -07004476 connection_.GetRetransmissionAlarm()->Fire();
fayange861aee2019-10-16 13:40:39 -07004477 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
fayanga29eb242019-07-16 12:25:38 -07004478
4479 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(40);
4480 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(20);
fayange861aee2019-10-16 13:40:39 -07004481 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(false));
4482 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(1);
fayanga29eb242019-07-16 12:25:38 -07004483 // Receives packets 1 - 40.
4484 for (size_t i = 1; i <= 40; ++i) {
4485 ProcessDataPacket(i);
4486 }
4487}
4488
QUICHE teama6ef0a62019-03-07 20:34:33 -05004489TEST_P(QuicConnectionTest, SendHandshakeMessages) {
4490 use_tagging_decrypter();
4491 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
4492 // the end of the packet. We can test this to check which encrypter was used.
QUICHE team6987b4a2019-03-15 16:23:04 -07004493 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07004494 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004495
4496 // Attempt to send a handshake message and have the socket block.
4497 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
4498 BlockOnNextWrite();
nharper46833c32019-05-15 21:33:05 -07004499 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004500 // The packet should be serialized, but not queued.
4501 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4502
4503 // Switch to the new encrypter.
4504 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004505 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004506 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4507
4508 // Now become writeable and flush the packets.
4509 writer_->SetWritable();
4510 EXPECT_CALL(visitor_, OnCanWrite());
4511 connection_.OnCanWrite();
4512 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4513
4514 // Verify that the handshake packet went out at the null encryption.
4515 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
4516}
4517
4518TEST_P(QuicConnectionTest,
4519 DropRetransmitsForNullEncryptedPacketAfterForwardSecure) {
4520 use_tagging_decrypter();
QUICHE team6987b4a2019-03-15 16:23:04 -07004521 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07004522 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004523 connection_.SendCryptoStreamData();
4524
4525 // Simulate the retransmission alarm firing and the socket blocking.
4526 BlockOnNextWrite();
4527 clock_.AdvanceTime(DefaultRetransmissionTime());
fayange62e63c2019-12-04 07:16:25 -08004528 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004529 connection_.GetRetransmissionAlarm()->Fire();
fayang2ce66082019-10-02 06:29:04 -07004530 EXPECT_EQ(1u, connection_.NumQueuedPackets());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004531
4532 // Go forward secure.
4533 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07004534 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004535 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4536 notifier_.NeuterUnencryptedData();
4537 connection_.NeuterUnencryptedPackets();
fayang2ce66082019-10-02 06:29:04 -07004538 connection_.OnHandshakeComplete();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004539
4540 EXPECT_EQ(QuicTime::Zero(), connection_.GetRetransmissionAlarm()->deadline());
4541 // Unblock the socket and ensure that no packets are sent.
4542 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4543 writer_->SetWritable();
4544 connection_.OnCanWrite();
4545}
4546
4547TEST_P(QuicConnectionTest, RetransmitPacketsWithInitialEncryption) {
4548 use_tagging_decrypter();
QUICHE team6987b4a2019-03-15 16:23:04 -07004549 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07004550 std::make_unique<TaggingEncrypter>(0x01));
QUICHE team6987b4a2019-03-15 16:23:04 -07004551 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004552
nharper46833c32019-05-15 21:33:05 -07004553 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004554
4555 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004556 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004557 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4558
4559 SendStreamDataToPeer(2, "bar", 0, NO_FIN, nullptr);
4560 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4561
renjietangc0080082020-05-26 18:35:19 -07004562 connection_.RetransmitZeroRttPackets();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004563}
4564
4565TEST_P(QuicConnectionTest, BufferNonDecryptablePackets) {
QUICHE teamcd098022019-03-22 18:49:55 -07004566 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4567 return;
4568 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004569 // SetFromConfig is always called after construction from InitializeSession.
4570 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4571 QuicConfig config;
4572 connection_.SetFromConfig(config);
4573 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4574 use_tagging_decrypter();
4575
4576 const uint8_t tag = 0x07;
4577 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004578 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004579
4580 // Process an encrypted packet which can not yet be decrypted which should
4581 // result in the packet being buffered.
4582 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4583
4584 // Transition to the new encryption state and process another encrypted packet
4585 // which should result in the original packet being processed.
zhongyi546cc452019-04-12 15:27:49 -07004586 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004587 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004588 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4589 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004590 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004591 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(2);
4592 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4593
4594 // Finally, process a third packet and note that we do not reprocess the
4595 // buffered packet.
4596 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4597 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4598}
4599
4600TEST_P(QuicConnectionTest, TestRetransmitOrder) {
fayang5f135052019-08-22 17:59:40 -07004601 if (connection_.PtoEnabled()) {
4602 return;
4603 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004604 connection_.SetMaxTailLossProbes(0);
4605
4606 QuicByteCount first_packet_size;
4607 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4608 .WillOnce(SaveArg<3>(&first_packet_size));
4609
4610 connection_.SendStreamDataWithString(3, "first_packet", 0, NO_FIN);
4611 QuicByteCount second_packet_size;
4612 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4613 .WillOnce(SaveArg<3>(&second_packet_size));
4614 connection_.SendStreamDataWithString(3, "second_packet", 12, NO_FIN);
4615 EXPECT_NE(first_packet_size, second_packet_size);
4616 // Advance the clock by huge time to make sure packets will be retransmitted.
4617 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
4618 {
4619 InSequence s;
4620 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, first_packet_size, _));
4621 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, second_packet_size, _));
4622 }
4623 connection_.GetRetransmissionAlarm()->Fire();
4624
4625 // Advance again and expect the packets to be sent again in the same order.
4626 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(20));
4627 {
4628 InSequence s;
4629 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, first_packet_size, _));
4630 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, second_packet_size, _));
4631 }
4632 connection_.GetRetransmissionAlarm()->Fire();
4633}
4634
4635TEST_P(QuicConnectionTest, Buffer100NonDecryptablePacketsThenKeyChange) {
QUICHE teamcd098022019-03-22 18:49:55 -07004636 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4637 return;
4638 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004639 // SetFromConfig is always called after construction from InitializeSession.
4640 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4641 QuicConfig config;
4642 config.set_max_undecryptable_packets(100);
4643 connection_.SetFromConfig(config);
4644 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4645 use_tagging_decrypter();
4646
4647 const uint8_t tag = 0x07;
4648 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004649 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004650
4651 // Process an encrypted packet which can not yet be decrypted which should
4652 // result in the packet being buffered.
4653 for (uint64_t i = 1; i <= 100; ++i) {
4654 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4655 }
4656
4657 // Transition to the new encryption state and process another encrypted packet
4658 // which should result in the original packets being processed.
4659 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
zhongyi546cc452019-04-12 15:27:49 -07004660 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004661 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004662 EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
4663 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4664 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004665 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004666
4667 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(100);
4668 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
4669
4670 // Finally, process a third packet and note that we do not reprocess the
4671 // buffered packet.
4672 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4673 ProcessDataPacketAtLevel(102, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4674}
4675
4676TEST_P(QuicConnectionTest, SetRTOAfterWritingToSocket) {
4677 BlockOnNextWrite();
fayange62e63c2019-12-04 07:16:25 -08004678 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004679 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
fayange62e63c2019-12-04 07:16:25 -08004680 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004681
4682 // Test that RTO is started once we write to the socket.
4683 writer_->SetWritable();
fayange62e63c2019-12-04 07:16:25 -08004684 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004685 connection_.OnCanWrite();
4686 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4687}
4688
4689TEST_P(QuicConnectionTest, DelayRTOWithAckReceipt) {
fayang5f135052019-08-22 17:59:40 -07004690 if (connection_.PtoEnabled()) {
4691 return;
4692 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004693 connection_.SetMaxTailLossProbes(0);
4694
4695 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4696 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
4697 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
4698 connection_.SendStreamDataWithString(3, "bar", 0, NO_FIN);
4699 QuicAlarm* retransmission_alarm = connection_.GetRetransmissionAlarm();
4700 EXPECT_TRUE(retransmission_alarm->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004701 EXPECT_EQ(DefaultRetransmissionTime(),
4702 retransmission_alarm->deadline() - clock_.Now());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004703
4704 // Advance the time right before the RTO, then receive an ack for the first
4705 // packet to delay the RTO.
4706 clock_.AdvanceTime(DefaultRetransmissionTime());
4707 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4708 QuicAckFrame ack = InitAckFrame(1);
4709 ProcessAckPacket(&ack);
4710 // Now we have an RTT sample of DefaultRetransmissionTime(500ms),
4711 // so the RTO has increased to 2 * SRTT.
4712 EXPECT_TRUE(retransmission_alarm->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004713 EXPECT_EQ(retransmission_alarm->deadline() - clock_.Now(),
4714 2 * DefaultRetransmissionTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004715
4716 // Move forward past the original RTO and ensure the RTO is still pending.
4717 clock_.AdvanceTime(2 * DefaultRetransmissionTime());
4718
4719 // Ensure the second packet gets retransmitted when it finally fires.
4720 EXPECT_TRUE(retransmission_alarm->IsSet());
4721 EXPECT_EQ(retransmission_alarm->deadline(), clock_.ApproximateNow());
4722 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4723 // Manually cancel the alarm to simulate a real test.
4724 connection_.GetRetransmissionAlarm()->Fire();
4725
4726 // The new retransmitted packet number should set the RTO to a larger value
4727 // than previously.
4728 EXPECT_TRUE(retransmission_alarm->IsSet());
4729 QuicTime next_rto_time = retransmission_alarm->deadline();
4730 QuicTime expected_rto_time =
4731 connection_.sent_packet_manager().GetRetransmissionTime();
4732 EXPECT_EQ(next_rto_time, expected_rto_time);
4733}
4734
4735TEST_P(QuicConnectionTest, TestQueued) {
4736 connection_.SetMaxTailLossProbes(0);
4737
4738 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4739 BlockOnNextWrite();
4740 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4741 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4742
4743 // Unblock the writes and actually send.
4744 writer_->SetWritable();
4745 connection_.OnCanWrite();
4746 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4747}
4748
4749TEST_P(QuicConnectionTest, InitialTimeout) {
4750 EXPECT_TRUE(connection_.connected());
4751 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4752 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4753
4754 // SetFromConfig sets the initial timeouts before negotiation.
4755 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4756 QuicConfig config;
4757 connection_.SetFromConfig(config);
4758 // Subtract a second from the idle timeout on the client side.
4759 QuicTime default_timeout =
4760 clock_.ApproximateNow() +
4761 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4762 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
4763
fkastenholz5d880a92019-06-21 09:01:56 -07004764 EXPECT_CALL(visitor_,
4765 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004766 // Simulate the timeout alarm firing.
4767 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1));
4768 connection_.GetTimeoutAlarm()->Fire();
4769
4770 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4771 EXPECT_FALSE(connection_.connected());
4772
fayang9adfb532020-06-04 06:58:45 -07004773 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004774 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4775 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4776 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4777 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
renjietang11e4a3d2019-05-03 11:27:26 -07004778 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07004779 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004780}
4781
4782TEST_P(QuicConnectionTest, IdleTimeoutAfterFirstSentPacket) {
4783 EXPECT_TRUE(connection_.connected());
4784 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4785 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4786
4787 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4788 QuicConfig config;
4789 connection_.SetFromConfig(config);
4790 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4791 QuicTime initial_ddl =
4792 clock_.ApproximateNow() +
4793 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4794 EXPECT_EQ(initial_ddl, connection_.GetTimeoutAlarm()->deadline());
4795 EXPECT_TRUE(connection_.connected());
4796
4797 // Advance the time and send the first packet to the peer.
fayangb9c88442020-03-26 07:03:57 -07004798 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004799 QuicPacketNumber last_packet;
4800 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4801 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4802 // This will be the updated deadline for the connection to idle time out.
4803 QuicTime new_ddl = clock_.ApproximateNow() +
4804 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4805
4806 // Simulate the timeout alarm firing, the connection should not be closed as
4807 // a new packet has been sent.
fkastenholz5d880a92019-06-21 09:01:56 -07004808 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004809 QuicTime::Delta delay = initial_ddl - clock_.ApproximateNow();
4810 clock_.AdvanceTime(delay);
fayang2205d952020-05-12 13:45:56 -07004811 if (!GetQuicReloadableFlag(quic_use_idle_network_detector)) {
fayangb9c88442020-03-26 07:03:57 -07004812 connection_.GetTimeoutAlarm()->Fire();
4813 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004814 // Verify the timeout alarm deadline is updated.
4815 EXPECT_TRUE(connection_.connected());
4816 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4817 EXPECT_EQ(new_ddl, connection_.GetTimeoutAlarm()->deadline());
4818
4819 // Simulate the timeout alarm firing again, the connection now should be
4820 // closed.
fkastenholz5d880a92019-06-21 09:01:56 -07004821 EXPECT_CALL(visitor_,
4822 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004823 clock_.AdvanceTime(new_ddl - clock_.ApproximateNow());
4824 connection_.GetTimeoutAlarm()->Fire();
4825 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4826 EXPECT_FALSE(connection_.connected());
4827
fayang9adfb532020-06-04 06:58:45 -07004828 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004829 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4830 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4831 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4832 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07004833 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004834}
4835
4836TEST_P(QuicConnectionTest, IdleTimeoutAfterSendTwoPackets) {
4837 EXPECT_TRUE(connection_.connected());
4838 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4839 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4840
4841 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4842 QuicConfig config;
4843 connection_.SetFromConfig(config);
4844 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4845 QuicTime initial_ddl =
4846 clock_.ApproximateNow() +
4847 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4848 EXPECT_EQ(initial_ddl, connection_.GetTimeoutAlarm()->deadline());
4849 EXPECT_TRUE(connection_.connected());
4850
4851 // Immediately send the first packet, this is a rare case but test code will
4852 // hit this issue often as MockClock used for tests doesn't move with code
4853 // execution until manually adjusted.
4854 QuicPacketNumber last_packet;
4855 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4856 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4857
4858 // Advance the time and send the second packet to the peer.
4859 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
4860 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4861 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
4862
zhongyic1cab062019-06-19 12:02:24 -07004863 // Simulate the timeout alarm firing, the connection will be closed.
fkastenholz5d880a92019-06-21 09:01:56 -07004864 EXPECT_CALL(visitor_,
4865 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
zhongyic1cab062019-06-19 12:02:24 -07004866 clock_.AdvanceTime(initial_ddl - clock_.ApproximateNow());
4867 connection_.GetTimeoutAlarm()->Fire();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004868
4869 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4870 EXPECT_FALSE(connection_.connected());
4871
fayang9adfb532020-06-04 06:58:45 -07004872 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004873 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4874 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4875 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4876 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07004877 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004878}
4879
4880TEST_P(QuicConnectionTest, HandshakeTimeout) {
4881 // Use a shorter handshake timeout than idle timeout for this test.
4882 const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(5);
4883 connection_.SetNetworkTimeouts(timeout, timeout);
4884 EXPECT_TRUE(connection_.connected());
4885 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4886
4887 QuicTime handshake_timeout =
4888 clock_.ApproximateNow() + timeout - QuicTime::Delta::FromSeconds(1);
4889 EXPECT_EQ(handshake_timeout, connection_.GetTimeoutAlarm()->deadline());
4890 EXPECT_TRUE(connection_.connected());
4891
4892 // Send and ack new data 3 seconds later to lengthen the idle timeout.
4893 SendStreamDataToPeer(
dschinazi552accc2019-06-17 17:07:34 -07004894 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
4895 "GET /", 0, FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004896 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(3));
4897 QuicAckFrame frame = InitAckFrame(1);
4898 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4899 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4900 ProcessAckPacket(&frame);
4901
fayang2205d952020-05-12 13:45:56 -07004902 if (!GetQuicReloadableFlag(quic_use_idle_network_detector)) {
fayangb9c88442020-03-26 07:03:57 -07004903 // Fire early to verify it wouldn't timeout yet.
4904 connection_.GetTimeoutAlarm()->Fire();
4905 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004906 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4907 EXPECT_TRUE(connection_.connected());
4908
4909 clock_.AdvanceTime(timeout - QuicTime::Delta::FromSeconds(2));
4910
fkastenholz5d880a92019-06-21 09:01:56 -07004911 EXPECT_CALL(visitor_,
4912 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004913 // Simulate the timeout alarm firing.
4914 connection_.GetTimeoutAlarm()->Fire();
4915
4916 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4917 EXPECT_FALSE(connection_.connected());
4918
fayang9adfb532020-06-04 06:58:45 -07004919 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004920 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4921 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4922 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07004923 TestConnectionCloseQuicErrorCode(QUIC_HANDSHAKE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004924}
4925
4926TEST_P(QuicConnectionTest, PingAfterSend) {
QUICHE teamcd098022019-03-22 18:49:55 -07004927 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4928 return;
4929 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004930 EXPECT_TRUE(connection_.connected());
4931 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4932 .WillRepeatedly(Return(true));
4933 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4934
4935 // Advance to 5ms, and send a packet to the peer, which will set
4936 // the ping alarm.
4937 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4938 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4939 SendStreamDataToPeer(
dschinazi552accc2019-06-17 17:07:34 -07004940 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
4941 "GET /", 0, FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004942 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004943 EXPECT_EQ(QuicTime::Delta::FromSeconds(15),
4944 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004945
4946 // Now recevie an ACK of the previous packet, which will move the
4947 // ping alarm forward.
4948 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4949 QuicAckFrame frame = InitAckFrame(1);
4950 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4951 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4952 ProcessAckPacket(&frame);
4953 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4954 // The ping timer is set slightly less than 15 seconds in the future, because
4955 // of the 1s ping timer alarm granularity.
zhongyieef848f2019-10-18 07:09:37 -07004956 EXPECT_EQ(
4957 QuicTime::Delta::FromSeconds(15) - QuicTime::Delta::FromMilliseconds(5),
4958 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004959
4960 writer_->Reset();
4961 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15));
zhongyifbb25772019-04-10 16:54:08 -07004962 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004963 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07004964 size_t padding_frame_count = writer_->padding_frames().size();
4965 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004966 ASSERT_EQ(1u, writer_->ping_frames().size());
4967 writer_->Reset();
4968
4969 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4970 .WillRepeatedly(Return(false));
4971 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4972 SendAckPacketToPeer();
4973
4974 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4975}
4976
4977TEST_P(QuicConnectionTest, ReducedPingTimeout) {
QUICHE teamcd098022019-03-22 18:49:55 -07004978 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4979 return;
4980 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004981 EXPECT_TRUE(connection_.connected());
4982 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4983 .WillRepeatedly(Return(true));
4984 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4985
4986 // Use a reduced ping timeout for this connection.
4987 connection_.set_ping_timeout(QuicTime::Delta::FromSeconds(10));
4988
4989 // Advance to 5ms, and send a packet to the peer, which will set
4990 // the ping alarm.
4991 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4992 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4993 SendStreamDataToPeer(
dschinazi552accc2019-06-17 17:07:34 -07004994 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
4995 "GET /", 0, FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004996 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004997 EXPECT_EQ(QuicTime::Delta::FromSeconds(10),
4998 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004999
5000 // Now recevie an ACK of the previous packet, which will move the
5001 // ping alarm forward.
5002 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
5003 QuicAckFrame frame = InitAckFrame(1);
5004 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5005 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5006 ProcessAckPacket(&frame);
5007 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
5008 // The ping timer is set slightly less than 10 seconds in the future, because
5009 // of the 1s ping timer alarm granularity.
zhongyieef848f2019-10-18 07:09:37 -07005010 EXPECT_EQ(
5011 QuicTime::Delta::FromSeconds(10) - QuicTime::Delta::FromMilliseconds(5),
5012 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005013
5014 writer_->Reset();
5015 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
5016 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
5017 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
5018 }));
5019 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07005020 size_t padding_frame_count = writer_->padding_frames().size();
5021 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005022 ASSERT_EQ(1u, writer_->ping_frames().size());
5023 writer_->Reset();
5024
5025 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
5026 .WillRepeatedly(Return(false));
5027 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
5028 SendAckPacketToPeer();
5029
5030 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
5031}
5032
5033// Tests whether sending an MTU discovery packet to peer successfully causes the
5034// maximum packet size to increase.
5035TEST_P(QuicConnectionTest, SendMtuDiscoveryPacket) {
wub031d47c2019-11-21 08:04:07 -08005036 MtuDiscoveryTestInit();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005037
5038 // Send an MTU probe.
5039 const size_t new_mtu = kDefaultMaxPacketSize + 100;
5040 QuicByteCount mtu_probe_size;
5041 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5042 .WillOnce(SaveArg<3>(&mtu_probe_size));
5043 connection_.SendMtuDiscoveryPacket(new_mtu);
5044 EXPECT_EQ(new_mtu, mtu_probe_size);
5045 EXPECT_EQ(QuicPacketNumber(1u), creator_->packet_number());
5046
5047 // Send more than MTU worth of data. No acknowledgement was received so far,
5048 // so the MTU should be at its old value.
vasilvvc48c8712019-03-11 13:38:16 -07005049 const std::string data(kDefaultMaxPacketSize + 1, '.');
QUICHE teama6ef0a62019-03-07 20:34:33 -05005050 QuicByteCount size_before_mtu_change;
5051 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5052 .Times(2)
5053 .WillOnce(SaveArg<3>(&size_before_mtu_change))
5054 .WillOnce(Return());
5055 connection_.SendStreamDataWithString(3, data, 0, FIN);
5056 EXPECT_EQ(QuicPacketNumber(3u), creator_->packet_number());
5057 EXPECT_EQ(kDefaultMaxPacketSize, size_before_mtu_change);
5058
5059 // Acknowledge all packets so far.
5060 QuicAckFrame probe_ack = InitAckFrame(3);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005061 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5062 ProcessAckPacket(&probe_ack);
5063 EXPECT_EQ(new_mtu, connection_.max_packet_length());
5064
5065 // Send the same data again. Check that it fits into a single packet now.
5066 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
5067 connection_.SendStreamDataWithString(3, data, 0, FIN);
5068 EXPECT_EQ(QuicPacketNumber(4u), creator_->packet_number());
5069}
5070
wubb442b862020-01-31 08:16:21 -08005071// Verifies that when a MTU probe packet is sent and buffered in a batch writer,
5072// the writer is flushed immediately.
5073TEST_P(QuicConnectionTest, BatchWriterFlushedAfterMtuDiscoveryPacket) {
5074 writer_->SetBatchMode(true);
5075 MtuDiscoveryTestInit();
5076
5077 // Send an MTU probe.
5078 const size_t target_mtu = kDefaultMaxPacketSize + 100;
5079 QuicByteCount mtu_probe_size;
5080 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5081 .WillOnce(SaveArg<3>(&mtu_probe_size));
5082 const uint32_t prior_flush_attempts = writer_->flush_attempts();
5083 connection_.SendMtuDiscoveryPacket(target_mtu);
5084 EXPECT_EQ(target_mtu, mtu_probe_size);
wub18f47342020-03-16 15:56:03 -07005085 EXPECT_EQ(writer_->flush_attempts(), prior_flush_attempts + 1);
wubb442b862020-01-31 08:16:21 -08005086}
5087
QUICHE teama6ef0a62019-03-07 20:34:33 -05005088// Tests whether MTU discovery does not happen when it is not explicitly enabled
5089// by the connection options.
5090TEST_P(QuicConnectionTest, MtuDiscoveryDisabled) {
wub031d47c2019-11-21 08:04:07 -08005091 MtuDiscoveryTestInit();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005092
5093 const QuicPacketCount packets_between_probes_base = 10;
5094 set_packets_between_probes_base(packets_between_probes_base);
5095
5096 const QuicPacketCount number_of_packets = packets_between_probes_base * 2;
5097 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
5098 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5099 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5100 EXPECT_EQ(0u, connection_.mtu_probe_count());
5101 }
5102}
5103
wubf76cf2a2019-10-11 18:49:07 -07005104// Tests whether MTU discovery works when all probes are acknowledged on the
QUICHE teama6ef0a62019-03-07 20:34:33 -05005105// first try.
5106TEST_P(QuicConnectionTest, MtuDiscoveryEnabled) {
wub031d47c2019-11-21 08:04:07 -08005107 MtuDiscoveryTestInit();
nharperc6b99512019-09-19 11:13:48 -07005108
QUICHE teama6ef0a62019-03-07 20:34:33 -05005109 const QuicPacketCount packets_between_probes_base = 5;
5110 set_packets_between_probes_base(packets_between_probes_base);
5111
wubf76cf2a2019-10-11 18:49:07 -07005112 connection_.EnablePathMtuDiscovery(send_algorithm_);
5113
QUICHE teama6ef0a62019-03-07 20:34:33 -05005114 // Send enough packets so that the next one triggers path MTU discovery.
5115 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5116 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5117 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5118 }
5119
5120 // Trigger the probe.
5121 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5122 nullptr);
5123 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5124 QuicByteCount probe_size;
5125 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5126 .WillOnce(SaveArg<3>(&probe_size));
5127 connection_.GetMtuDiscoveryAlarm()->Fire();
wub173916e2019-11-27 14:36:24 -08005128
5129 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(),
5130 kMtuDiscoveryTargetPacketSizeHigh));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005131
5132 const QuicPacketNumber probe_packet_number =
5133 FirstSendingPacketNumber() + packets_between_probes_base;
5134 ASSERT_EQ(probe_packet_number, creator_->packet_number());
5135
5136 // Acknowledge all packets sent so far.
5137 QuicAckFrame probe_ack = InitAckFrame(probe_packet_number);
wubf76cf2a2019-10-11 18:49:07 -07005138 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5139 .Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005140 ProcessAckPacket(&probe_ack);
wubf76cf2a2019-10-11 18:49:07 -07005141 EXPECT_EQ(probe_size, connection_.max_packet_length());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005142 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5143
wubf76cf2a2019-10-11 18:49:07 -07005144 EXPECT_EQ(1u, connection_.mtu_probe_count());
5145
wubf76cf2a2019-10-11 18:49:07 -07005146 QuicStreamOffset stream_offset = packets_between_probes_base;
wubecb643f2020-03-19 08:58:46 -07005147 QuicByteCount last_probe_size = 0;
wubf76cf2a2019-10-11 18:49:07 -07005148 for (size_t num_probes = 1; num_probes < kMtuDiscoveryAttempts;
5149 ++num_probes) {
5150 // Send just enough packets without triggering the next probe.
5151 for (QuicPacketCount i = 0;
5152 i < (packets_between_probes_base << num_probes) - 1; ++i) {
5153 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5154 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5155 }
5156
5157 // Trigger the next probe.
5158 SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
5159 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5160 QuicByteCount new_probe_size;
5161 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5162 .WillOnce(SaveArg<3>(&new_probe_size));
5163 connection_.GetMtuDiscoveryAlarm()->Fire();
5164 EXPECT_THAT(new_probe_size,
5165 InRange(probe_size, kMtuDiscoveryTargetPacketSizeHigh));
5166 EXPECT_EQ(num_probes + 1, connection_.mtu_probe_count());
5167
5168 // Acknowledge all packets sent so far.
5169 QuicAckFrame probe_ack = InitAckFrame(creator_->packet_number());
5170 ProcessAckPacket(&probe_ack);
5171 EXPECT_EQ(new_probe_size, connection_.max_packet_length());
5172 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5173
wubecb643f2020-03-19 08:58:46 -07005174 last_probe_size = probe_size;
wubf76cf2a2019-10-11 18:49:07 -07005175 probe_size = new_probe_size;
5176 }
5177
5178 // The last probe size should be equal to the target.
5179 EXPECT_EQ(probe_size, kMtuDiscoveryTargetPacketSizeHigh);
wubecb643f2020-03-19 08:58:46 -07005180
wubae6581a2020-05-04 12:13:05 -07005181 writer_->SetShouldWriteFail();
wubecb643f2020-03-19 08:58:46 -07005182
wubae6581a2020-05-04 12:13:05 -07005183 // Ignore PACKET_WRITE_ERROR once.
5184 SendStreamDataToPeer(3, "(", stream_offset++, NO_FIN, nullptr);
5185 EXPECT_EQ(last_probe_size, connection_.max_packet_length());
5186 EXPECT_TRUE(connection_.connected());
wubecb643f2020-03-19 08:58:46 -07005187
wubae6581a2020-05-04 12:13:05 -07005188 // Close connection on another PACKET_WRITE_ERROR.
5189 EXPECT_CALL(visitor_, OnConnectionClosed(_, _))
5190 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
5191 SendStreamDataToPeer(3, ")", stream_offset++, NO_FIN, nullptr);
5192 EXPECT_EQ(last_probe_size, connection_.max_packet_length());
5193 EXPECT_FALSE(connection_.connected());
5194 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
5195 IsError(QUIC_PACKET_WRITE_ERROR));
wubf76cf2a2019-10-11 18:49:07 -07005196}
5197
wub748e20b2020-03-20 14:33:59 -07005198// After a successful MTU probe, one and only one write error should be ignored
5199// if it happened in QuicConnection::FlushPacket.
5200TEST_P(QuicConnectionTest,
5201 MtuDiscoveryIgnoreOneWriteErrorInFlushAfterSuccessfulProbes) {
5202 MtuDiscoveryTestInit();
5203 writer_->SetBatchMode(true);
5204
5205 const QuicPacketCount packets_between_probes_base = 5;
5206 set_packets_between_probes_base(packets_between_probes_base);
5207
5208 connection_.EnablePathMtuDiscovery(send_algorithm_);
5209
5210 const QuicByteCount original_max_packet_length =
5211 connection_.max_packet_length();
5212 // Send enough packets so that the next one triggers path MTU discovery.
5213 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5214 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5215 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5216 }
5217
5218 // Trigger the probe.
5219 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5220 nullptr);
5221 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5222 QuicByteCount probe_size;
5223 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5224 .WillOnce(SaveArg<3>(&probe_size));
5225 connection_.GetMtuDiscoveryAlarm()->Fire();
5226
5227 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(),
5228 kMtuDiscoveryTargetPacketSizeHigh));
5229
5230 const QuicPacketNumber probe_packet_number =
5231 FirstSendingPacketNumber() + packets_between_probes_base;
5232 ASSERT_EQ(probe_packet_number, creator_->packet_number());
5233
5234 // Acknowledge all packets sent so far.
5235 QuicAckFrame probe_ack = InitAckFrame(probe_packet_number);
5236 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5237 .Times(AnyNumber());
5238 ProcessAckPacket(&probe_ack);
5239 EXPECT_EQ(probe_size, connection_.max_packet_length());
5240 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5241
5242 EXPECT_EQ(1u, connection_.mtu_probe_count());
5243
wubae6581a2020-05-04 12:13:05 -07005244 writer_->SetShouldWriteFail();
wub748e20b2020-03-20 14:33:59 -07005245
wubae6581a2020-05-04 12:13:05 -07005246 // Ignore PACKET_WRITE_ERROR once.
5247 {
5248 QuicConnection::ScopedPacketFlusher flusher(&connection_);
5249 // flusher's destructor will call connection_.FlushPackets, which should
5250 // get a WRITE_STATUS_ERROR from the writer and ignore it.
wub748e20b2020-03-20 14:33:59 -07005251 }
wubae6581a2020-05-04 12:13:05 -07005252 EXPECT_EQ(original_max_packet_length, connection_.max_packet_length());
5253 EXPECT_TRUE(connection_.connected());
5254
5255 // Close connection on another PACKET_WRITE_ERROR.
5256 EXPECT_CALL(visitor_, OnConnectionClosed(_, _))
5257 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
5258 {
5259 QuicConnection::ScopedPacketFlusher flusher(&connection_);
5260 // flusher's destructor will call connection_.FlushPackets, which should
5261 // get a WRITE_STATUS_ERROR from the writer and ignore it.
5262 }
5263 EXPECT_EQ(original_max_packet_length, connection_.max_packet_length());
5264 EXPECT_FALSE(connection_.connected());
5265 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
5266 IsError(QUIC_PACKET_WRITE_ERROR));
wub748e20b2020-03-20 14:33:59 -07005267}
5268
wubf76cf2a2019-10-11 18:49:07 -07005269// Simulate the case where the first attempt to send a probe is write blocked,
5270// and after unblock, the second attempt returns a MSG_TOO_BIG error.
5271TEST_P(QuicConnectionTest, MtuDiscoveryWriteBlocked) {
wub031d47c2019-11-21 08:04:07 -08005272 MtuDiscoveryTestInit();
wubf76cf2a2019-10-11 18:49:07 -07005273
5274 const QuicPacketCount packets_between_probes_base = 5;
5275 set_packets_between_probes_base(packets_between_probes_base);
5276
5277 connection_.EnablePathMtuDiscovery(send_algorithm_);
5278
5279 // Send enough packets so that the next one triggers path MTU discovery.
5280 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5281 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005282 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5283 }
5284
wubf76cf2a2019-10-11 18:49:07 -07005285 QuicByteCount original_max_packet_length = connection_.max_packet_length();
5286
5287 // Trigger the probe.
5288 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5289 nullptr);
5290 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
fayange62e63c2019-12-04 07:16:25 -08005291 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
wubf76cf2a2019-10-11 18:49:07 -07005292 BlockOnNextWrite();
5293 EXPECT_EQ(0u, connection_.NumQueuedPackets());
5294 connection_.GetMtuDiscoveryAlarm()->Fire();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005295 EXPECT_EQ(1u, connection_.mtu_probe_count());
wubf76cf2a2019-10-11 18:49:07 -07005296 EXPECT_EQ(1u, connection_.NumQueuedPackets());
5297 ASSERT_TRUE(connection_.connected());
5298
5299 writer_->SetWritable();
5300 SimulateNextPacketTooLarge();
5301 connection_.OnCanWrite();
5302 EXPECT_EQ(0u, connection_.NumQueuedPackets());
5303 EXPECT_EQ(original_max_packet_length, connection_.max_packet_length());
5304 EXPECT_TRUE(connection_.connected());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005305}
5306
5307// Tests whether MTU discovery works correctly when the probes never get
5308// acknowledged.
5309TEST_P(QuicConnectionTest, MtuDiscoveryFailed) {
wub031d47c2019-11-21 08:04:07 -08005310 MtuDiscoveryTestInit();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005311
QUICHE teama6ef0a62019-03-07 20:34:33 -05005312 // Lower the number of probes between packets in order to make the test go
5313 // much faster.
5314 const QuicPacketCount packets_between_probes_base = 5;
5315 set_packets_between_probes_base(packets_between_probes_base);
5316
wubf76cf2a2019-10-11 18:49:07 -07005317 connection_.EnablePathMtuDiscovery(send_algorithm_);
5318
5319 const QuicTime::Delta rtt = QuicTime::Delta::FromMilliseconds(100);
5320
5321 EXPECT_EQ(packets_between_probes_base,
5322 QuicConnectionPeer::GetPacketsBetweenMtuProbes(&connection_));
5323
QUICHE teama6ef0a62019-03-07 20:34:33 -05005324 // This tests sends more packets than strictly necessary to make sure that if
5325 // the connection was to send more discovery packets than needed, those would
5326 // get caught as well.
5327 const QuicPacketCount number_of_packets =
5328 packets_between_probes_base * (1 << (kMtuDiscoveryAttempts + 1));
5329 std::vector<QuicPacketNumber> mtu_discovery_packets;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005330 // Called on many acks.
5331 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5332 .Times(AnyNumber());
5333 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
5334 SendStreamDataToPeer(3, "!", i, NO_FIN, nullptr);
5335 clock_.AdvanceTime(rtt);
5336
5337 // Receive an ACK, which marks all data packets as received, and all MTU
5338 // discovery packets as missing.
5339
5340 QuicAckFrame ack;
5341
5342 if (!mtu_discovery_packets.empty()) {
5343 QuicPacketNumber min_packet = *min_element(mtu_discovery_packets.begin(),
5344 mtu_discovery_packets.end());
5345 QuicPacketNumber max_packet = *max_element(mtu_discovery_packets.begin(),
5346 mtu_discovery_packets.end());
5347 ack.packets.AddRange(QuicPacketNumber(1), min_packet);
5348 ack.packets.AddRange(QuicPacketNumber(max_packet + 1),
5349 creator_->packet_number() + 1);
5350 ack.largest_acked = creator_->packet_number();
5351
5352 } else {
5353 ack.packets.AddRange(QuicPacketNumber(1), creator_->packet_number() + 1);
5354 ack.largest_acked = creator_->packet_number();
5355 }
5356
5357 ProcessAckPacket(&ack);
5358
5359 // Trigger MTU probe if it would be scheduled now.
5360 if (!connection_.GetMtuDiscoveryAlarm()->IsSet()) {
5361 continue;
5362 }
5363
5364 // Fire the alarm. The alarm should cause a packet to be sent.
5365 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5366 connection_.GetMtuDiscoveryAlarm()->Fire();
5367 // Record the packet number of the MTU discovery packet in order to
5368 // mark it as NACK'd.
5369 mtu_discovery_packets.push_back(creator_->packet_number());
5370 }
5371
5372 // Ensure the number of packets between probes grows exponentially by checking
5373 // it against the closed-form expression for the packet number.
5374 ASSERT_EQ(kMtuDiscoveryAttempts, mtu_discovery_packets.size());
5375 for (uint64_t i = 0; i < kMtuDiscoveryAttempts; i++) {
5376 // 2^0 + 2^1 + 2^2 + ... + 2^n = 2^(n + 1) - 1
5377 const QuicPacketCount packets_between_probes =
5378 packets_between_probes_base * ((1 << (i + 1)) - 1);
5379 EXPECT_EQ(QuicPacketNumber(packets_between_probes + (i + 1)),
5380 mtu_discovery_packets[i]);
5381 }
5382
5383 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5384 EXPECT_EQ(kDefaultMaxPacketSize, connection_.max_packet_length());
5385 EXPECT_EQ(kMtuDiscoveryAttempts, connection_.mtu_probe_count());
5386}
5387
wubf76cf2a2019-10-11 18:49:07 -07005388// Probe 3 times, the first one succeeds, then fails, then succeeds again.
5389TEST_P(QuicConnectionTest, MtuDiscoverySecondProbeFailed) {
wub031d47c2019-11-21 08:04:07 -08005390 MtuDiscoveryTestInit();
wubf76cf2a2019-10-11 18:49:07 -07005391
5392 const QuicPacketCount packets_between_probes_base = 5;
5393 set_packets_between_probes_base(packets_between_probes_base);
5394
5395 connection_.EnablePathMtuDiscovery(send_algorithm_);
5396
5397 // Send enough packets so that the next one triggers path MTU discovery.
5398 QuicStreamOffset stream_offset = 0;
5399 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5400 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5401 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5402 }
5403
5404 // Trigger the probe.
5405 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5406 nullptr);
5407 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5408 QuicByteCount probe_size;
5409 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5410 .WillOnce(SaveArg<3>(&probe_size));
5411 connection_.GetMtuDiscoveryAlarm()->Fire();
5412 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(),
5413 kMtuDiscoveryTargetPacketSizeHigh));
5414
5415 const QuicPacketNumber probe_packet_number =
5416 FirstSendingPacketNumber() + packets_between_probes_base;
5417 ASSERT_EQ(probe_packet_number, creator_->packet_number());
5418
5419 // Acknowledge all packets sent so far.
5420 QuicAckFrame first_ack = InitAckFrame(probe_packet_number);
wubf76cf2a2019-10-11 18:49:07 -07005421 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5422 .Times(AnyNumber());
5423 ProcessAckPacket(&first_ack);
5424 EXPECT_EQ(probe_size, connection_.max_packet_length());
5425 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5426
5427 EXPECT_EQ(1u, connection_.mtu_probe_count());
5428
5429 // Send just enough packets without triggering the second probe.
5430 for (QuicPacketCount i = 0; i < (packets_between_probes_base << 1) - 1; ++i) {
5431 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5432 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5433 }
5434
5435 // Trigger the second probe.
5436 SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
5437 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5438 QuicByteCount second_probe_size;
5439 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5440 .WillOnce(SaveArg<3>(&second_probe_size));
5441 connection_.GetMtuDiscoveryAlarm()->Fire();
5442 EXPECT_THAT(second_probe_size,
5443 InRange(probe_size, kMtuDiscoveryTargetPacketSizeHigh));
5444 EXPECT_EQ(2u, connection_.mtu_probe_count());
5445
5446 // Acknowledge all packets sent so far, except the second probe.
5447 QuicPacketNumber second_probe_packet_number = creator_->packet_number();
5448 QuicAckFrame second_ack = InitAckFrame(second_probe_packet_number - 1);
5449 ProcessAckPacket(&first_ack);
5450 EXPECT_EQ(probe_size, connection_.max_packet_length());
5451
5452 // Send just enough packets without triggering the third probe.
5453 for (QuicPacketCount i = 0; i < (packets_between_probes_base << 2) - 1; ++i) {
5454 SendStreamDataToPeer(3, "@", stream_offset++, NO_FIN, nullptr);
5455 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5456 }
5457
5458 // Trigger the third probe.
5459 SendStreamDataToPeer(3, "#", stream_offset++, NO_FIN, nullptr);
5460 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5461 QuicByteCount third_probe_size;
5462 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5463 .WillOnce(SaveArg<3>(&third_probe_size));
5464 connection_.GetMtuDiscoveryAlarm()->Fire();
5465 EXPECT_THAT(third_probe_size, InRange(probe_size, second_probe_size));
5466 EXPECT_EQ(3u, connection_.mtu_probe_count());
5467
5468 // Acknowledge all packets sent so far, except the second probe.
5469 QuicAckFrame third_ack =
5470 ConstructAckFrame(creator_->packet_number(), second_probe_packet_number);
5471 ProcessAckPacket(&third_ack);
5472 EXPECT_EQ(third_probe_size, connection_.max_packet_length());
5473}
5474
QUICHE teama6ef0a62019-03-07 20:34:33 -05005475// Tests whether MTU discovery works when the writer has a limit on how large a
5476// packet can be.
5477TEST_P(QuicConnectionTest, MtuDiscoveryWriterLimited) {
wub031d47c2019-11-21 08:04:07 -08005478 MtuDiscoveryTestInit();
nharperc6b99512019-09-19 11:13:48 -07005479
QUICHE teama6ef0a62019-03-07 20:34:33 -05005480 const QuicByteCount mtu_limit = kMtuDiscoveryTargetPacketSizeHigh - 1;
5481 writer_->set_max_packet_size(mtu_limit);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005482
5483 const QuicPacketCount packets_between_probes_base = 5;
5484 set_packets_between_probes_base(packets_between_probes_base);
5485
wubf76cf2a2019-10-11 18:49:07 -07005486 connection_.EnablePathMtuDiscovery(send_algorithm_);
5487
QUICHE teama6ef0a62019-03-07 20:34:33 -05005488 // Send enough packets so that the next one triggers path MTU discovery.
5489 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5490 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5491 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5492 }
5493
5494 // Trigger the probe.
5495 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5496 nullptr);
5497 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5498 QuicByteCount probe_size;
5499 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5500 .WillOnce(SaveArg<3>(&probe_size));
5501 connection_.GetMtuDiscoveryAlarm()->Fire();
wub173916e2019-11-27 14:36:24 -08005502
5503 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(), mtu_limit));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005504
5505 const QuicPacketNumber probe_sequence_number =
5506 FirstSendingPacketNumber() + packets_between_probes_base;
5507 ASSERT_EQ(probe_sequence_number, creator_->packet_number());
5508
5509 // Acknowledge all packets sent so far.
5510 QuicAckFrame probe_ack = InitAckFrame(probe_sequence_number);
wubf76cf2a2019-10-11 18:49:07 -07005511 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5512 .Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005513 ProcessAckPacket(&probe_ack);
wubf76cf2a2019-10-11 18:49:07 -07005514 EXPECT_EQ(probe_size, connection_.max_packet_length());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005515 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5516
wubf76cf2a2019-10-11 18:49:07 -07005517 EXPECT_EQ(1u, connection_.mtu_probe_count());
5518
wubf76cf2a2019-10-11 18:49:07 -07005519 QuicStreamOffset stream_offset = packets_between_probes_base;
5520 for (size_t num_probes = 1; num_probes < kMtuDiscoveryAttempts;
5521 ++num_probes) {
5522 // Send just enough packets without triggering the next probe.
5523 for (QuicPacketCount i = 0;
5524 i < (packets_between_probes_base << num_probes) - 1; ++i) {
5525 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5526 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5527 }
5528
5529 // Trigger the next probe.
5530 SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
5531 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5532 QuicByteCount new_probe_size;
5533 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5534 .WillOnce(SaveArg<3>(&new_probe_size));
5535 connection_.GetMtuDiscoveryAlarm()->Fire();
5536 EXPECT_THAT(new_probe_size, InRange(probe_size, mtu_limit));
5537 EXPECT_EQ(num_probes + 1, connection_.mtu_probe_count());
5538
5539 // Acknowledge all packets sent so far.
5540 QuicAckFrame probe_ack = InitAckFrame(creator_->packet_number());
5541 ProcessAckPacket(&probe_ack);
5542 EXPECT_EQ(new_probe_size, connection_.max_packet_length());
5543 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5544
5545 probe_size = new_probe_size;
5546 }
5547
5548 // The last probe size should be equal to the target.
5549 EXPECT_EQ(probe_size, mtu_limit);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005550}
5551
5552// Tests whether MTU discovery works when the writer returns an error despite
5553// advertising higher packet length.
5554TEST_P(QuicConnectionTest, MtuDiscoveryWriterFailed) {
wub031d47c2019-11-21 08:04:07 -08005555 MtuDiscoveryTestInit();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005556
5557 const QuicByteCount mtu_limit = kMtuDiscoveryTargetPacketSizeHigh - 1;
5558 const QuicByteCount initial_mtu = connection_.max_packet_length();
5559 EXPECT_LT(initial_mtu, mtu_limit);
5560 writer_->set_max_packet_size(mtu_limit);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005561
5562 const QuicPacketCount packets_between_probes_base = 5;
5563 set_packets_between_probes_base(packets_between_probes_base);
5564
wubf76cf2a2019-10-11 18:49:07 -07005565 connection_.EnablePathMtuDiscovery(send_algorithm_);
5566
QUICHE teama6ef0a62019-03-07 20:34:33 -05005567 // Send enough packets so that the next one triggers path MTU discovery.
5568 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5569 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5570 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5571 }
5572
5573 // Trigger the probe.
5574 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5575 nullptr);
5576 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5577 writer_->SimulateNextPacketTooLarge();
5578 connection_.GetMtuDiscoveryAlarm()->Fire();
5579 ASSERT_TRUE(connection_.connected());
5580
5581 // Send more data.
5582 QuicPacketNumber probe_number = creator_->packet_number();
5583 QuicPacketCount extra_packets = packets_between_probes_base * 3;
5584 for (QuicPacketCount i = 0; i < extra_packets; i++) {
5585 connection_.EnsureWritableAndSendStreamData5();
5586 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5587 }
5588
5589 // Acknowledge all packets sent so far, except for the lost probe.
5590 QuicAckFrame probe_ack =
5591 ConstructAckFrame(creator_->packet_number(), probe_number);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005592 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5593 ProcessAckPacket(&probe_ack);
5594 EXPECT_EQ(initial_mtu, connection_.max_packet_length());
5595
5596 // Send more packets, and ensure that none of them sets the alarm.
5597 for (QuicPacketCount i = 0; i < 4 * packets_between_probes_base; i++) {
5598 connection_.EnsureWritableAndSendStreamData5();
5599 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5600 }
5601
5602 EXPECT_EQ(initial_mtu, connection_.max_packet_length());
5603 EXPECT_EQ(1u, connection_.mtu_probe_count());
5604}
5605
5606TEST_P(QuicConnectionTest, NoMtuDiscoveryAfterConnectionClosed) {
wub031d47c2019-11-21 08:04:07 -08005607 MtuDiscoveryTestInit();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005608
QUICHE teama6ef0a62019-03-07 20:34:33 -05005609 const QuicPacketCount packets_between_probes_base = 10;
5610 set_packets_between_probes_base(packets_between_probes_base);
5611
wubf76cf2a2019-10-11 18:49:07 -07005612 connection_.EnablePathMtuDiscovery(send_algorithm_);
5613
QUICHE teama6ef0a62019-03-07 20:34:33 -05005614 // Send enough packets so that the next one triggers path MTU discovery.
5615 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5616 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5617 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5618 }
5619
5620 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5621 nullptr);
5622 EXPECT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5623
fkastenholz5d880a92019-06-21 09:01:56 -07005624 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005625 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
5626 ConnectionCloseBehavior::SILENT_CLOSE);
5627 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5628}
5629
dschinazi9a6194e2020-04-30 16:21:09 -07005630TEST_P(QuicConnectionTest, TimeoutAfterSendDuringHandshake) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005631 EXPECT_TRUE(connection_.connected());
5632 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5633 QuicConfig config;
5634 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005635
5636 const QuicTime::Delta initial_idle_timeout =
5637 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5638 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5639 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
5640
5641 // When we send a packet, the timeout will change to 5ms +
5642 // kInitialIdleTimeoutSecs.
5643 clock_.AdvanceTime(five_ms);
5644 SendStreamDataToPeer(
5645 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5646 0, FIN, nullptr);
fayang2205d952020-05-12 13:45:56 -07005647 if (GetQuicReloadableFlag(quic_use_idle_network_detector)) {
fayangb9c88442020-03-26 07:03:57 -07005648 EXPECT_EQ(default_timeout + five_ms,
5649 connection_.GetTimeoutAlarm()->deadline());
5650 } else {
5651 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5652 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005653
5654 // Now send more data. This will not move the timeout because
5655 // no data has been received since the previous write.
5656 clock_.AdvanceTime(five_ms);
5657 SendStreamDataToPeer(
5658 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5659 3, FIN, nullptr);
fayang2205d952020-05-12 13:45:56 -07005660 if (GetQuicReloadableFlag(quic_use_idle_network_detector)) {
fayangb9c88442020-03-26 07:03:57 -07005661 EXPECT_EQ(default_timeout + five_ms,
5662 connection_.GetTimeoutAlarm()->deadline());
5663 } else {
5664 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5665 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005666
5667 // The original alarm will fire. We should not time out because we had a
5668 // network event at t=5ms. The alarm will reregister.
5669 clock_.AdvanceTime(initial_idle_timeout - five_ms - five_ms);
5670 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
fayang2205d952020-05-12 13:45:56 -07005671 if (!GetQuicReloadableFlag(quic_use_idle_network_detector)) {
fayangb9c88442020-03-26 07:03:57 -07005672 connection_.GetTimeoutAlarm()->Fire();
5673 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005674 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5675 EXPECT_TRUE(connection_.connected());
5676 EXPECT_EQ(default_timeout + five_ms,
5677 connection_.GetTimeoutAlarm()->deadline());
5678
5679 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07005680 EXPECT_CALL(visitor_,
5681 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07005682 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005683 clock_.AdvanceTime(five_ms);
5684 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5685 connection_.GetTimeoutAlarm()->Fire();
5686 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5687 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005688 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005689}
5690
5691TEST_P(QuicConnectionTest, TimeoutAfterRetransmission) {
fayang5f135052019-08-22 17:59:40 -07005692 if (connection_.PtoEnabled()) {
5693 return;
5694 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005695 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5696 EXPECT_TRUE(connection_.connected());
5697 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5698 QuicConfig config;
5699 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005700
5701 const QuicTime start_time = clock_.Now();
5702 const QuicTime::Delta initial_idle_timeout =
5703 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5704 QuicTime default_timeout = clock_.Now() + initial_idle_timeout;
5705
5706 connection_.SetMaxTailLossProbes(0);
5707 const QuicTime default_retransmission_time =
5708 start_time + DefaultRetransmissionTime();
5709
5710 ASSERT_LT(default_retransmission_time, default_timeout);
5711
5712 // When we send a packet, the timeout will change to 5 ms +
5713 // kInitialIdleTimeoutSecs (but it will not reschedule the alarm).
5714 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5715 const QuicTime send_time = start_time + five_ms;
5716 clock_.AdvanceTime(five_ms);
5717 ASSERT_EQ(send_time, clock_.Now());
5718 SendStreamDataToPeer(
5719 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5720 0, FIN, nullptr);
fayang2205d952020-05-12 13:45:56 -07005721 if (GetQuicReloadableFlag(quic_use_idle_network_detector)) {
fayangb9c88442020-03-26 07:03:57 -07005722 EXPECT_EQ(default_timeout + five_ms,
5723 connection_.GetTimeoutAlarm()->deadline());
5724 } else {
5725 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5726 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005727
5728 // Move forward 5 ms and receive a packet, which will move the timeout
5729 // forward 5 ms more (but will not reschedule the alarm).
5730 const QuicTime receive_time = send_time + five_ms;
5731 clock_.AdvanceTime(receive_time - clock_.Now());
5732 ASSERT_EQ(receive_time, clock_.Now());
5733 ProcessPacket(1);
5734
5735 // Now move forward to the retransmission time and retransmit the
5736 // packet, which should move the timeout forward again (but will not
5737 // reschedule the alarm).
5738 EXPECT_EQ(default_retransmission_time + five_ms,
5739 connection_.GetRetransmissionAlarm()->deadline());
5740 // Simulate the retransmission alarm firing.
5741 const QuicTime rto_time = send_time + DefaultRetransmissionTime();
5742 const QuicTime final_timeout = rto_time + initial_idle_timeout;
5743 clock_.AdvanceTime(rto_time - clock_.Now());
5744 ASSERT_EQ(rto_time, clock_.Now());
5745 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _));
5746 connection_.GetRetransmissionAlarm()->Fire();
5747
5748 // Advance to the original timeout and fire the alarm. The connection should
5749 // timeout, and the alarm should be registered based on the time of the
5750 // retransmission.
5751 clock_.AdvanceTime(default_timeout - clock_.Now());
5752 ASSERT_EQ(default_timeout.ToDebuggingValue(),
5753 clock_.Now().ToDebuggingValue());
5754 EXPECT_EQ(default_timeout, clock_.Now());
fayang2205d952020-05-12 13:45:56 -07005755 if (!GetQuicReloadableFlag(quic_use_idle_network_detector)) {
fayangb9c88442020-03-26 07:03:57 -07005756 connection_.GetTimeoutAlarm()->Fire();
5757 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005758 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5759 EXPECT_TRUE(connection_.connected());
5760 ASSERT_EQ(final_timeout.ToDebuggingValue(),
5761 connection_.GetTimeoutAlarm()->deadline().ToDebuggingValue());
5762
5763 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07005764 EXPECT_CALL(visitor_,
5765 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07005766 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005767 clock_.AdvanceTime(final_timeout - clock_.Now());
5768 EXPECT_EQ(connection_.GetTimeoutAlarm()->deadline(), clock_.Now());
5769 EXPECT_EQ(final_timeout, clock_.Now());
5770 connection_.GetTimeoutAlarm()->Fire();
5771 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5772 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005773 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005774}
5775
dschinazi9a6194e2020-04-30 16:21:09 -07005776TEST_P(QuicConnectionTest, TimeoutAfterSendAfterHandshake) {
5777 // When the idle timeout fires, verify that by default we do not send any
5778 // connection close packets.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005779 EXPECT_TRUE(connection_.connected());
5780 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5781 QuicConfig config;
5782
5783 // Create a handshake message that also enables silent close.
5784 CryptoHandshakeMessage msg;
vasilvvc48c8712019-03-11 13:38:16 -07005785 std::string error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005786 QuicConfig client_config;
5787 client_config.SetInitialStreamFlowControlWindowToSend(
5788 kInitialStreamFlowControlWindowForTest);
5789 client_config.SetInitialSessionFlowControlWindowToSend(
5790 kInitialSessionFlowControlWindowForTest);
5791 client_config.SetIdleNetworkTimeout(
dschinazi027366e2020-05-01 14:31:19 -07005792 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs));
fkastenholzd3a1de92019-05-15 07:00:07 -07005793 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005794 const QuicErrorCode error =
5795 config.ProcessPeerHello(msg, CLIENT, &error_details);
bncf54082a2019-11-27 10:19:47 -08005796 EXPECT_THAT(error, IsQuicNoError());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005797
dschinazie7c38a52020-05-29 15:25:45 -07005798 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
5799 QuicConfigPeer::SetReceivedOriginalConnectionId(
5800 &config, connection_.connection_id());
5801 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
5802 &config, connection_.connection_id());
5803 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005804 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005805
5806 const QuicTime::Delta default_idle_timeout =
dschinazi027366e2020-05-01 14:31:19 -07005807 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs - 1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005808 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5809 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5810
5811 // When we send a packet, the timeout will change to 5ms +
5812 // kInitialIdleTimeoutSecs.
5813 clock_.AdvanceTime(five_ms);
5814 SendStreamDataToPeer(
5815 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5816 0, FIN, nullptr);
fayang2205d952020-05-12 13:45:56 -07005817 if (GetQuicReloadableFlag(quic_use_idle_network_detector)) {
fayangb9c88442020-03-26 07:03:57 -07005818 EXPECT_EQ(default_timeout + five_ms,
5819 connection_.GetTimeoutAlarm()->deadline());
5820 } else {
5821 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5822 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005823
5824 // Now send more data. This will not move the timeout because
5825 // no data has been received since the previous write.
5826 clock_.AdvanceTime(five_ms);
5827 SendStreamDataToPeer(
5828 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5829 3, FIN, nullptr);
fayang2205d952020-05-12 13:45:56 -07005830 if (GetQuicReloadableFlag(quic_use_idle_network_detector)) {
fayangb9c88442020-03-26 07:03:57 -07005831 EXPECT_EQ(default_timeout + five_ms,
5832 connection_.GetTimeoutAlarm()->deadline());
5833 } else {
5834 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5835 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005836
5837 // The original alarm will fire. We should not time out because we had a
5838 // network event at t=5ms. The alarm will reregister.
5839 clock_.AdvanceTime(default_idle_timeout - five_ms - five_ms);
5840 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
fayang2205d952020-05-12 13:45:56 -07005841 if (!GetQuicReloadableFlag(quic_use_idle_network_detector)) {
fayangb9c88442020-03-26 07:03:57 -07005842 connection_.GetTimeoutAlarm()->Fire();
5843 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005844 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5845 EXPECT_TRUE(connection_.connected());
5846 EXPECT_EQ(default_timeout + five_ms,
5847 connection_.GetTimeoutAlarm()->deadline());
5848
5849 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07005850 // This results in a SILENT_CLOSE, so the writer will not be invoked
5851 // and will not save the frame. Grab the frame from OnConnectionClosed
5852 // directly.
5853 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
5854 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
5855
QUICHE teama6ef0a62019-03-07 20:34:33 -05005856 clock_.AdvanceTime(five_ms);
5857 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5858 connection_.GetTimeoutAlarm()->Fire();
5859 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5860 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005861 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08005862 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
5863 IsError(QUIC_NETWORK_IDLE_TIMEOUT));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005864}
5865
5866TEST_P(QuicConnectionTest, TimeoutAfterSendSilentCloseAndTLP) {
fayang5f135052019-08-22 17:59:40 -07005867 if (connection_.PtoEnabled()) {
5868 return;
5869 }
dschinazi9a6194e2020-04-30 16:21:09 -07005870 // Same test as above, but sending TLPs causes a connection close to be sent.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005871 EXPECT_TRUE(connection_.connected());
5872 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5873 QuicConfig config;
5874
5875 // Create a handshake message that also enables silent close.
5876 CryptoHandshakeMessage msg;
vasilvvc48c8712019-03-11 13:38:16 -07005877 std::string error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005878 QuicConfig client_config;
5879 client_config.SetInitialStreamFlowControlWindowToSend(
5880 kInitialStreamFlowControlWindowForTest);
5881 client_config.SetInitialSessionFlowControlWindowToSend(
5882 kInitialSessionFlowControlWindowForTest);
5883 client_config.SetIdleNetworkTimeout(
dschinazi027366e2020-05-01 14:31:19 -07005884 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs));
fkastenholzd3a1de92019-05-15 07:00:07 -07005885 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005886 const QuicErrorCode error =
5887 config.ProcessPeerHello(msg, CLIENT, &error_details);
bncf54082a2019-11-27 10:19:47 -08005888 EXPECT_THAT(error, IsQuicNoError());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005889
5890 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005891
5892 const QuicTime::Delta default_idle_timeout =
dschinazi027366e2020-05-01 14:31:19 -07005893 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs - 1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005894 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5895 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5896
5897 // When we send a packet, the timeout will change to 5ms +
5898 // kInitialIdleTimeoutSecs.
5899 clock_.AdvanceTime(five_ms);
5900 SendStreamDataToPeer(
5901 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5902 0, FIN, nullptr);
fayang2205d952020-05-12 13:45:56 -07005903 if (GetQuicReloadableFlag(quic_use_idle_network_detector)) {
fayangb9c88442020-03-26 07:03:57 -07005904 EXPECT_EQ(default_timeout + five_ms,
5905 connection_.GetTimeoutAlarm()->deadline());
5906 } else {
5907 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5908 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005909
5910 // Retransmit the packet via tail loss probe.
5911 clock_.AdvanceTime(connection_.GetRetransmissionAlarm()->deadline() -
5912 clock_.Now());
5913 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _));
5914 connection_.GetRetransmissionAlarm()->Fire();
5915
5916 // This time, we should time out and send a connection close due to the TLP.
fkastenholz5d880a92019-06-21 09:01:56 -07005917 EXPECT_CALL(visitor_,
5918 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07005919 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005920 clock_.AdvanceTime(connection_.GetTimeoutAlarm()->deadline() -
5921 clock_.ApproximateNow() + five_ms);
5922 connection_.GetTimeoutAlarm()->Fire();
5923 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5924 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005925 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005926}
5927
5928TEST_P(QuicConnectionTest, TimeoutAfterSendSilentCloseWithOpenStreams) {
dschinazi9a6194e2020-04-30 16:21:09 -07005929 // Same test as above, but having open streams causes a connection close
5930 // to be sent.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005931 EXPECT_TRUE(connection_.connected());
5932 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5933 QuicConfig config;
5934
5935 // Create a handshake message that also enables silent close.
5936 CryptoHandshakeMessage msg;
vasilvvc48c8712019-03-11 13:38:16 -07005937 std::string error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005938 QuicConfig client_config;
5939 client_config.SetInitialStreamFlowControlWindowToSend(
5940 kInitialStreamFlowControlWindowForTest);
5941 client_config.SetInitialSessionFlowControlWindowToSend(
5942 kInitialSessionFlowControlWindowForTest);
5943 client_config.SetIdleNetworkTimeout(
dschinazi027366e2020-05-01 14:31:19 -07005944 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs));
fkastenholzd3a1de92019-05-15 07:00:07 -07005945 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005946 const QuicErrorCode error =
5947 config.ProcessPeerHello(msg, CLIENT, &error_details);
bncf54082a2019-11-27 10:19:47 -08005948 EXPECT_THAT(error, IsQuicNoError());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005949
dschinazie7c38a52020-05-29 15:25:45 -07005950 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
5951 QuicConfigPeer::SetReceivedOriginalConnectionId(
5952 &config, connection_.connection_id());
5953 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
5954 &config, connection_.connection_id());
5955 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005956 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005957
5958 const QuicTime::Delta default_idle_timeout =
dschinazi027366e2020-05-01 14:31:19 -07005959 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs - 1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005960 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5961 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5962
5963 // When we send a packet, the timeout will change to 5ms +
5964 // kInitialIdleTimeoutSecs.
5965 clock_.AdvanceTime(five_ms);
5966 SendStreamDataToPeer(
5967 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5968 0, FIN, nullptr);
fayang2205d952020-05-12 13:45:56 -07005969 if (GetQuicReloadableFlag(quic_use_idle_network_detector)) {
fayangb9c88442020-03-26 07:03:57 -07005970 EXPECT_EQ(default_timeout + five_ms,
5971 connection_.GetTimeoutAlarm()->deadline());
5972 } else {
5973 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5974 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005975
5976 // Indicate streams are still open.
5977 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
5978 .WillRepeatedly(Return(true));
5979
5980 // This time, we should time out and send a connection close due to the TLP.
fkastenholz5d880a92019-06-21 09:01:56 -07005981 EXPECT_CALL(visitor_,
5982 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07005983 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005984 clock_.AdvanceTime(connection_.GetTimeoutAlarm()->deadline() -
5985 clock_.ApproximateNow() + five_ms);
5986 connection_.GetTimeoutAlarm()->Fire();
5987 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5988 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005989 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005990}
5991
5992TEST_P(QuicConnectionTest, TimeoutAfterReceive) {
5993 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5994 EXPECT_TRUE(connection_.connected());
5995 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5996 QuicConfig config;
5997 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005998
5999 const QuicTime::Delta initial_idle_timeout =
6000 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
6001 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
6002 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
6003
6004 connection_.SendStreamDataWithString(
6005 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6006 0, NO_FIN);
6007 connection_.SendStreamDataWithString(
6008 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6009 3, NO_FIN);
6010
6011 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
6012 clock_.AdvanceTime(five_ms);
6013
6014 // When we receive a packet, the timeout will change to 5ms +
6015 // kInitialIdleTimeoutSecs.
6016 QuicAckFrame ack = InitAckFrame(2);
6017 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
6018 ProcessAckPacket(&ack);
6019
6020 // The original alarm will fire. We should not time out because we had a
6021 // network event at t=5ms. The alarm will reregister.
6022 clock_.AdvanceTime(initial_idle_timeout - five_ms);
6023 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
fayang2205d952020-05-12 13:45:56 -07006024 if (!GetQuicReloadableFlag(quic_use_idle_network_detector)) {
fayangb9c88442020-03-26 07:03:57 -07006025 connection_.GetTimeoutAlarm()->Fire();
6026 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006027 EXPECT_TRUE(connection_.connected());
6028 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
6029 EXPECT_EQ(default_timeout + five_ms,
6030 connection_.GetTimeoutAlarm()->deadline());
6031
6032 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07006033 EXPECT_CALL(visitor_,
6034 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07006035 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006036 clock_.AdvanceTime(five_ms);
6037 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
6038 connection_.GetTimeoutAlarm()->Fire();
6039 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
6040 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07006041 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006042}
6043
6044TEST_P(QuicConnectionTest, TimeoutAfterReceiveNotSendWhenUnacked) {
6045 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6046 EXPECT_TRUE(connection_.connected());
6047 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6048 QuicConfig config;
6049 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006050
6051 const QuicTime::Delta initial_idle_timeout =
6052 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
6053 connection_.SetNetworkTimeouts(
6054 QuicTime::Delta::Infinite(),
6055 initial_idle_timeout + QuicTime::Delta::FromSeconds(1));
6056 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
6057 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
6058
6059 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
6060 connection_.SendStreamDataWithString(
6061 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6062 0, NO_FIN);
6063 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
6064 connection_.SendStreamDataWithString(
6065 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6066 3, NO_FIN);
6067
6068 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
6069
6070 clock_.AdvanceTime(five_ms);
6071
6072 // When we receive a packet, the timeout will change to 5ms +
6073 // kInitialIdleTimeoutSecs.
6074 QuicAckFrame ack = InitAckFrame(2);
6075 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
6076 ProcessAckPacket(&ack);
6077
6078 // The original alarm will fire. We should not time out because we had a
6079 // network event at t=5ms. The alarm will reregister.
6080 clock_.AdvanceTime(initial_idle_timeout - five_ms);
6081 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
fayang2205d952020-05-12 13:45:56 -07006082 if (!GetQuicReloadableFlag(quic_use_idle_network_detector)) {
fayangb9c88442020-03-26 07:03:57 -07006083 connection_.GetTimeoutAlarm()->Fire();
6084 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006085 EXPECT_TRUE(connection_.connected());
6086 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
6087 EXPECT_EQ(default_timeout + five_ms,
6088 connection_.GetTimeoutAlarm()->deadline());
6089
6090 // Now, send packets while advancing the time and verify that the connection
6091 // eventually times out.
fkastenholz5d880a92019-06-21 09:01:56 -07006092 EXPECT_CALL(visitor_,
6093 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006094 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
6095 for (int i = 0; i < 100 && connection_.connected(); ++i) {
6096 QUIC_LOG(INFO) << "sending data packet";
6097 connection_.SendStreamDataWithString(
6098 GetNthClientInitiatedStreamId(1, connection_.transport_version()),
6099 "foo", 0, NO_FIN);
6100 connection_.GetTimeoutAlarm()->Fire();
6101 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
6102 }
6103 EXPECT_FALSE(connection_.connected());
6104 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07006105 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006106}
6107
6108TEST_P(QuicConnectionTest, TimeoutAfter5ClientRTOs) {
fayang5f135052019-08-22 17:59:40 -07006109 if (connection_.PtoEnabled()) {
6110 return;
6111 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006112 connection_.SetMaxTailLossProbes(2);
6113 EXPECT_TRUE(connection_.connected());
6114 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6115 QuicConfig config;
6116 QuicTagVector connection_options;
6117 connection_options.push_back(k5RTO);
6118 config.SetConnectionOptionsToSend(connection_options);
dschinazif7c6a912020-05-05 11:39:53 -07006119 QuicConfigPeer::SetNegotiated(&config, true);
fayangf78b6932020-06-08 08:36:45 -07006120 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection)) {
6121 EXPECT_CALL(visitor_, GetHandshakeState())
6122 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
6123 }
dschinazie7c38a52020-05-29 15:25:45 -07006124 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
6125 QuicConfigPeer::SetReceivedOriginalConnectionId(
6126 &config, connection_.connection_id());
6127 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
6128 &config, connection_.connection_id());
6129 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006130 connection_.SetFromConfig(config);
6131
6132 // Send stream data.
6133 SendStreamDataToPeer(
6134 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6135 0, FIN, nullptr);
6136
6137 // Fire the retransmission alarm 6 times, twice for TLP and 4 times for RTO.
6138 for (int i = 0; i < 6; ++i) {
6139 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
6140 connection_.GetRetransmissionAlarm()->Fire();
6141 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
6142 EXPECT_TRUE(connection_.connected());
6143 }
fayang2205d952020-05-12 13:45:56 -07006144 EXPECT_CALL(visitor_, OnPathDegrading());
6145 connection_.PathDegradingTimeout();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006146
6147 EXPECT_EQ(2u, connection_.sent_packet_manager().GetConsecutiveTlpCount());
6148 EXPECT_EQ(4u, connection_.sent_packet_manager().GetConsecutiveRtoCount());
6149 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07006150 EXPECT_CALL(visitor_,
6151 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07006152 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
fayang2205d952020-05-12 13:45:56 -07006153 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
6154 connection_.GetBlackholeDetectorAlarm()->Fire();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006155 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
6156 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07006157 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006158}
6159
6160TEST_P(QuicConnectionTest, SendScheduler) {
6161 // Test that if we send a packet without delay, it is not queued.
6162 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
QUICHE team8c1daa22019-03-13 08:33:41 -07006163 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07006164 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006165 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
6166 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
QUICHE team6987b4a2019-03-15 16:23:04 -07006167 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05006168 HAS_RETRANSMITTABLE_DATA, false, false);
6169 EXPECT_EQ(0u, connection_.NumQueuedPackets());
6170}
6171
6172TEST_P(QuicConnectionTest, FailToSendFirstPacket) {
6173 // Test that the connection does not crash when it fails to send the first
6174 // packet at which point self_address_ might be uninitialized.
6175 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
fkastenholz5d880a92019-06-21 09:01:56 -07006176 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
QUICHE team8c1daa22019-03-13 08:33:41 -07006177 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07006178 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006179 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
6180 writer_->SetShouldWriteFail();
QUICHE team6987b4a2019-03-15 16:23:04 -07006181 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05006182 HAS_RETRANSMITTABLE_DATA, false, false);
6183}
6184
6185TEST_P(QuicConnectionTest, SendSchedulerEAGAIN) {
6186 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
QUICHE team8c1daa22019-03-13 08:33:41 -07006187 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07006188 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006189 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
6190 BlockOnNextWrite();
6191 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _))
6192 .Times(0);
QUICHE team6987b4a2019-03-15 16:23:04 -07006193 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05006194 HAS_RETRANSMITTABLE_DATA, false, false);
6195 EXPECT_EQ(1u, connection_.NumQueuedPackets());
6196}
6197
6198TEST_P(QuicConnectionTest, TestQueueLimitsOnSendStreamData) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006199 // Queue the first packet.
ianswett3085da82019-04-04 07:24:24 -07006200 size_t payload_length = connection_.max_packet_length();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006201 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(testing::Return(false));
vasilvvc48c8712019-03-11 13:38:16 -07006202 const std::string payload(payload_length, 'a');
ianswett3085da82019-04-04 07:24:24 -07006203 QuicStreamId first_bidi_stream_id(QuicUtils::GetFirstBidirectionalStreamId(
6204 connection_.version().transport_version, Perspective::IS_CLIENT));
6205 EXPECT_EQ(0u, connection_
6206 .SendStreamDataWithString(first_bidi_stream_id, payload, 0,
6207 NO_FIN)
QUICHE teama6ef0a62019-03-07 20:34:33 -05006208 .bytes_consumed);
6209 EXPECT_EQ(0u, connection_.NumQueuedPackets());
6210}
6211
ianswett3085da82019-04-04 07:24:24 -07006212TEST_P(QuicConnectionTest, SendingThreePackets) {
ianswett3085da82019-04-04 07:24:24 -07006213 // Make the payload twice the size of the packet, so 3 packets are written.
6214 size_t total_payload_length = 2 * connection_.max_packet_length();
vasilvvc48c8712019-03-11 13:38:16 -07006215 const std::string payload(total_payload_length, 'a');
ianswett3085da82019-04-04 07:24:24 -07006216 QuicStreamId first_bidi_stream_id(QuicUtils::GetFirstBidirectionalStreamId(
6217 connection_.version().transport_version, Perspective::IS_CLIENT));
6218 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
6219 EXPECT_EQ(payload.size(), connection_
6220 .SendStreamDataWithString(first_bidi_stream_id,
6221 payload, 0, NO_FIN)
6222 .bytes_consumed);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006223}
6224
6225TEST_P(QuicConnectionTest, LoopThroughSendingPacketsWithTruncation) {
6226 set_perspective(Perspective::IS_SERVER);
fayangd4291e42019-05-30 10:31:21 -07006227 if (!VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006228 // For IETF QUIC, encryption level will be switched to FORWARD_SECURE in
6229 // SendStreamDataWithString.
6230 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
6231 }
6232 // Set up a larger payload than will fit in one packet.
vasilvvc48c8712019-03-11 13:38:16 -07006233 const std::string payload(connection_.max_packet_length(), 'a');
QUICHE teama6ef0a62019-03-07 20:34:33 -05006234 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
6235
6236 // Now send some packets with no truncation.
6237 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
6238 EXPECT_EQ(payload.size(),
6239 connection_.SendStreamDataWithString(3, payload, 0, NO_FIN)
6240 .bytes_consumed);
6241 // Track the size of the second packet here. The overhead will be the largest
6242 // we see in this test, due to the non-truncated connection id.
6243 size_t non_truncated_packet_size = writer_->last_packet_size();
6244
6245 // Change to a 0 byte connection id.
6246 QuicConfig config;
6247 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
6248 connection_.SetFromConfig(config);
6249 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
6250 EXPECT_EQ(payload.size(),
6251 connection_.SendStreamDataWithString(3, payload, 1350, NO_FIN)
6252 .bytes_consumed);
fayangd4291e42019-05-30 10:31:21 -07006253 if (VersionHasIetfInvariantHeader(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006254 // Short header packets sent from server omit connection ID already, and
6255 // stream offset size increases from 0 to 2.
6256 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() - 2);
6257 } else {
6258 // Just like above, we save 8 bytes on payload, and 8 on truncation. -2
6259 // because stream offset size is 2 instead of 0.
6260 EXPECT_EQ(non_truncated_packet_size,
6261 writer_->last_packet_size() + 8 * 2 - 2);
6262 }
6263}
6264
6265TEST_P(QuicConnectionTest, SendDelayedAck) {
6266 QuicTime ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6267 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006268 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006269 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006270 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006271 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006272 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006273 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006274 // Process a packet from the non-crypto stream.
6275 frame1_.stream_id = 3;
6276
6277 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006278 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006279 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6280 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6281
6282 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006283 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006284 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6285 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07006286 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006287 connection_.GetAckAlarm()->Fire();
6288 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006289 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006290 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006291 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006292 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6293 } else {
nharper55fa6132019-05-07 19:37:21 -07006294 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006295 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6296 }
6297 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006298 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006299}
6300
6301TEST_P(QuicConnectionTest, SendDelayedAfterQuiescence) {
6302 QuicConnectionPeer::SetFastAckAfterQuiescence(&connection_, true);
6303
6304 // The beginning of the connection counts as quiescence.
ianswett8f90e512019-12-18 10:50:27 -08006305 QuicTime ack_time = clock_.ApproximateNow() + kAlarmGranularity;
QUICHE teama6ef0a62019-03-07 20:34:33 -05006306 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006307 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006308 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006309 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006310 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006311 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006312 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006313 // Process a packet from the non-crypto stream.
6314 frame1_.stream_id = 3;
6315
6316 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006317 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006318 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6319 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6320
6321 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006322 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006323 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6324 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07006325 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006326 connection_.GetAckAlarm()->Fire();
6327 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006328 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006329 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006330 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006331 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6332 } else {
nharper55fa6132019-05-07 19:37:21 -07006333 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006334 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6335 }
6336 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006337 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006338
6339 // Process another packet immedately after sending the ack and expect the
6340 // ack alarm to be set delayed ack time in the future.
6341 ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6342 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6343 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6344
6345 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006346 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006347 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6348 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07006349 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006350 connection_.GetAckAlarm()->Fire();
6351 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006352 padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006353 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006354 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006355 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6356 } else {
nharper55fa6132019-05-07 19:37:21 -07006357 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006358 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6359 }
6360 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006361 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006362
ianswett8f90e512019-12-18 10:50:27 -08006363 // Wait 1 second and ensure the ack alarm is set to 1ms in the future.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006364 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
6365 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
6366 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6367 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6368
6369 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006370 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006371 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6372}
6373
6374TEST_P(QuicConnectionTest, SendDelayedAckDecimation) {
6375 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6376 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION);
6377
6378 const size_t kMinRttMs = 40;
6379 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6380 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6381 QuicTime::Delta::Zero(), QuicTime::Zero());
6382 // The ack time should be based on min_rtt/4, since it's less than the
6383 // default delayed ack time.
6384 QuicTime ack_time = clock_.ApproximateNow() +
6385 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6386 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006387 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006388 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006389 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006390 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006391 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006392 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006393 // Process a packet from the non-crypto stream.
6394 frame1_.stream_id = 3;
6395
6396 // Process all the initial packets in order so there aren't missing packets.
6397 uint64_t kFirstDecimatedPacket = 101;
6398 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6399 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6400 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6401 }
fayang9adfb532020-06-04 06:58:45 -07006402 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006403 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006404 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006405 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6406 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6407 ENCRYPTION_ZERO_RTT);
6408
6409 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006410 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006411 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6412
6413 // The 10th received packet causes an ack to be sent.
6414 for (int i = 0; i < 9; ++i) {
fayang9adfb532020-06-04 06:58:45 -07006415 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006416 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6417 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6418 ENCRYPTION_ZERO_RTT);
6419 }
6420 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07006421 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006422 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07006423 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006424 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6425 } else {
nharperc32d8ab2019-10-09 11:09:06 -07006426 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006427 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6428 }
6429 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006430 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006431}
6432
6433TEST_P(QuicConnectionTest, SendDelayedAckAckDecimationAfterQuiescence) {
6434 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6435 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION);
6436 QuicConnectionPeer::SetFastAckAfterQuiescence(&connection_, true);
6437
6438 const size_t kMinRttMs = 40;
6439 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6440 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6441 QuicTime::Delta::Zero(), QuicTime::Zero());
6442
6443 // The beginning of the connection counts as quiescence.
6444 QuicTime ack_time =
6445 clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
6446 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006447 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006448 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006449 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006450 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006451 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006452 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006453 // Process a packet from the non-crypto stream.
6454 frame1_.stream_id = 3;
6455
6456 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006457 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006458 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6459 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6460
6461 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006462 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006463 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6464 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07006465 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006466 connection_.GetAckAlarm()->Fire();
6467 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006468 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006469 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006470 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006471 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6472 } else {
nharper55fa6132019-05-07 19:37:21 -07006473 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006474 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6475 }
6476 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006477 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006478
6479 // Process another packet immedately after sending the ack and expect the
6480 // ack alarm to be set delayed ack time in the future.
6481 ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6482 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6483 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6484
6485 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006486 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006487 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6488 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07006489 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006490 connection_.GetAckAlarm()->Fire();
6491 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006492 padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006493 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006494 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006495 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6496 } else {
nharper55fa6132019-05-07 19:37:21 -07006497 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006498 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6499 }
6500 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006501 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006502
6503 // Wait 1 second and enesure the ack alarm is set to 1ms in the future.
6504 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
6505 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
6506 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6507 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6508
6509 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006510 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006511 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6512
6513 // Process enough packets to get into ack decimation behavior.
6514 // The ack time should be based on min_rtt/4, since it's less than the
6515 // default delayed ack time.
6516 ack_time = clock_.ApproximateNow() +
6517 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6518 uint64_t kFirstDecimatedPacket = 101;
6519 for (unsigned int i = 0; i < kFirstDecimatedPacket - 4; ++i) {
6520 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6521 ProcessDataPacketAtLevel(4 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6522 }
fayang9adfb532020-06-04 06:58:45 -07006523 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006524 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006525 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006526 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6527 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6528 ENCRYPTION_ZERO_RTT);
6529
6530 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006531 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006532 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6533
6534 // The 10th received packet causes an ack to be sent.
6535 for (int i = 0; i < 9; ++i) {
fayang9adfb532020-06-04 06:58:45 -07006536 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006537 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6538 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6539 ENCRYPTION_ZERO_RTT);
6540 }
6541 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07006542 padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006543 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07006544 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006545 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6546 } else {
nharperc32d8ab2019-10-09 11:09:06 -07006547 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006548 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6549 }
6550 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006551 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006552
6553 // Wait 1 second and enesure the ack alarm is set to 1ms in the future.
6554 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
6555 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
6556 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6557 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 10, !kHasStopWaiting,
6558 ENCRYPTION_ZERO_RTT);
6559
6560 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006561 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006562 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6563}
6564
6565TEST_P(QuicConnectionTest, SendDelayedAckDecimationUnlimitedAggregation) {
6566 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6567 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6568 QuicConfig config;
6569 QuicTagVector connection_options;
6570 connection_options.push_back(kACKD);
6571 // No limit on the number of packets received before sending an ack.
6572 connection_options.push_back(kAKDU);
6573 config.SetConnectionOptionsToSend(connection_options);
6574 connection_.SetFromConfig(config);
6575
6576 const size_t kMinRttMs = 40;
6577 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6578 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6579 QuicTime::Delta::Zero(), QuicTime::Zero());
6580 // The ack time should be based on min_rtt/4, since it's less than the
6581 // default delayed ack time.
6582 QuicTime ack_time = clock_.ApproximateNow() +
6583 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6584 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006585 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006586 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006587 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006588 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006589 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006590 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006591 // Process a packet from the non-crypto stream.
6592 frame1_.stream_id = 3;
6593
6594 // Process all the initial packets in order so there aren't missing packets.
6595 uint64_t kFirstDecimatedPacket = 101;
6596 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6597 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6598 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6599 }
fayang9adfb532020-06-04 06:58:45 -07006600 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006601 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006602 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006603 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6604 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6605 ENCRYPTION_ZERO_RTT);
6606
6607 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006608 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006609 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6610
6611 // 18 packets will not cause an ack to be sent. 19 will because when
6612 // stop waiting frames are in use, we ack every 20 packets no matter what.
6613 for (int i = 0; i < 18; ++i) {
fayang9adfb532020-06-04 06:58:45 -07006614 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006615 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6616 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6617 ENCRYPTION_ZERO_RTT);
6618 }
6619 // The delayed ack timer should still be set to the expected deadline.
fayang9adfb532020-06-04 06:58:45 -07006620 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006621 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6622}
6623
6624TEST_P(QuicConnectionTest, SendDelayedAckDecimationEighthRtt) {
6625 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6626 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION);
6627 QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
6628
6629 const size_t kMinRttMs = 40;
6630 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6631 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6632 QuicTime::Delta::Zero(), QuicTime::Zero());
6633 // The ack time should be based on min_rtt/8, since it's less than the
6634 // default delayed ack time.
6635 QuicTime ack_time = clock_.ApproximateNow() +
6636 QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
6637 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006638 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006639 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006640 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006641 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006642 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006643 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006644 // Process a packet from the non-crypto stream.
6645 frame1_.stream_id = 3;
6646
6647 // Process all the initial packets in order so there aren't missing packets.
6648 uint64_t kFirstDecimatedPacket = 101;
6649 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6650 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6651 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6652 }
fayang9adfb532020-06-04 06:58:45 -07006653 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006654 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006655 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006656 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6657 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6658 ENCRYPTION_ZERO_RTT);
6659
6660 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006661 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006662 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6663
6664 // The 10th received packet causes an ack to be sent.
6665 for (int i = 0; i < 9; ++i) {
fayang9adfb532020-06-04 06:58:45 -07006666 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006667 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6668 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6669 ENCRYPTION_ZERO_RTT);
6670 }
6671 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07006672 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006673 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07006674 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006675 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6676 } else {
nharperc32d8ab2019-10-09 11:09:06 -07006677 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006678 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6679 }
6680 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006681 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006682}
6683
6684TEST_P(QuicConnectionTest, SendDelayedAckDecimationWithReordering) {
6685 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6686 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6687
6688 const size_t kMinRttMs = 40;
6689 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6690 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6691 QuicTime::Delta::Zero(), QuicTime::Zero());
6692 // The ack time should be based on min_rtt/4, since it's less than the
6693 // default delayed ack time.
6694 QuicTime ack_time = clock_.ApproximateNow() +
6695 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6696 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006697 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006698 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006699 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006700 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006701 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006702 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006703 // Process a packet from the non-crypto stream.
6704 frame1_.stream_id = 3;
6705
6706 // Process all the initial packets in order so there aren't missing packets.
6707 uint64_t kFirstDecimatedPacket = 101;
6708 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6709 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6710 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6711 }
fayang9adfb532020-06-04 06:58:45 -07006712 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006713
6714 // Receive one packet out of order and then the rest in order.
6715 // The loop leaves a one packet gap between acks sent to simulate some loss.
6716 for (int j = 0; j < 3; ++j) {
6717 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6718 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6719 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 9 + (j * 11),
6720 !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6721 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
fayang9adfb532020-06-04 06:58:45 -07006722 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006723 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6724
6725 // The 10th received packet causes an ack to be sent.
6726 writer_->Reset();
6727 for (int i = 0; i < 9; ++i) {
fayang9adfb532020-06-04 06:58:45 -07006728 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006729 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6730 // The ACK shouldn't be sent until the 10th packet is processed.
6731 EXPECT_TRUE(writer_->ack_frames().empty());
6732 ProcessDataPacketAtLevel(kFirstDecimatedPacket + i + (j * 11),
6733 !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6734 }
6735 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07006736 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006737 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07006738 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006739 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6740 } else {
nharperc32d8ab2019-10-09 11:09:06 -07006741 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006742 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6743 }
6744 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006745 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006746 }
6747}
6748
6749TEST_P(QuicConnectionTest, SendDelayedAckDecimationWithLargeReordering) {
6750 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6751 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6752
6753 const size_t kMinRttMs = 40;
6754 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6755 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6756 QuicTime::Delta::Zero(), QuicTime::Zero());
6757 // The ack time should be based on min_rtt/4, since it's less than the
6758 // default delayed ack time.
6759 QuicTime ack_time = clock_.ApproximateNow() +
6760 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6761 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006762 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006763 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006764 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006765 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006766 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006767 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006768 // Process a packet from the non-crypto stream.
6769 frame1_.stream_id = 3;
6770
6771 // Process all the initial packets in order so there aren't missing packets.
6772 uint64_t kFirstDecimatedPacket = 101;
6773 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6774 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6775 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6776 }
fayang9adfb532020-06-04 06:58:45 -07006777 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006778 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006779 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006780 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6781 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6782 ENCRYPTION_ZERO_RTT);
6783
6784 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006785 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006786 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6787
6788 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6789 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6790 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 19, !kHasStopWaiting,
6791 ENCRYPTION_ZERO_RTT);
6792 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
fayang9adfb532020-06-04 06:58:45 -07006793 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006794 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6795
6796 // The 10th received packet causes an ack to be sent.
6797 for (int i = 0; i < 8; ++i) {
fayang9adfb532020-06-04 06:58:45 -07006798 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006799 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6800 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6801 ENCRYPTION_ZERO_RTT);
6802 }
6803 // Check that ack is sent and that delayed ack alarm is reset.
6804 if (GetParam().no_stop_waiting) {
fayang58f71072019-11-05 08:47:02 -08006805 EXPECT_EQ(writer_->padding_frames().size() + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006806 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6807 } else {
6808 EXPECT_EQ(2u, writer_->frame_count());
6809 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6810 }
6811 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006812 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006813
6814 // The next packet received in order will cause an immediate ack,
6815 // because it fills a hole.
fayang9adfb532020-06-04 06:58:45 -07006816 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006817 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6818 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 10, !kHasStopWaiting,
6819 ENCRYPTION_ZERO_RTT);
6820 // Check that ack is sent and that delayed ack alarm is reset.
6821 if (GetParam().no_stop_waiting) {
fayang58f71072019-11-05 08:47:02 -08006822 EXPECT_EQ(writer_->padding_frames().size() + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006823 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6824 } else {
6825 EXPECT_EQ(2u, writer_->frame_count());
6826 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6827 }
6828 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006829 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006830}
6831
6832TEST_P(QuicConnectionTest, SendDelayedAckDecimationWithReorderingEighthRtt) {
6833 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6834 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6835 QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
6836
6837 const size_t kMinRttMs = 40;
6838 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6839 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6840 QuicTime::Delta::Zero(), QuicTime::Zero());
6841 // The ack time should be based on min_rtt/8, since it's less than the
6842 // default delayed ack time.
6843 QuicTime ack_time = clock_.ApproximateNow() +
6844 QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
6845 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006846 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006847 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006848 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006849 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006850 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006851 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006852 // Process a packet from the non-crypto stream.
6853 frame1_.stream_id = 3;
6854
6855 // Process all the initial packets in order so there aren't missing packets.
6856 uint64_t kFirstDecimatedPacket = 101;
6857 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6858 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6859 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6860 }
fayang9adfb532020-06-04 06:58:45 -07006861 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006862 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006863 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006864 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6865 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6866 ENCRYPTION_ZERO_RTT);
6867
6868 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006869 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006870 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6871
6872 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6873 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6874 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 9, !kHasStopWaiting,
6875 ENCRYPTION_ZERO_RTT);
6876 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
fayang9adfb532020-06-04 06:58:45 -07006877 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006878 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6879
6880 // The 10th received packet causes an ack to be sent.
6881 for (int i = 0; i < 8; ++i) {
fayang9adfb532020-06-04 06:58:45 -07006882 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006883 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6884 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6885 ENCRYPTION_ZERO_RTT);
6886 }
6887 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07006888 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006889 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07006890 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006891 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6892 } else {
nharperc32d8ab2019-10-09 11:09:06 -07006893 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006894 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6895 }
6896 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006897 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006898}
6899
6900TEST_P(QuicConnectionTest,
6901 SendDelayedAckDecimationWithLargeReorderingEighthRtt) {
6902 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6903 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6904 QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
6905
6906 const size_t kMinRttMs = 40;
6907 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6908 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6909 QuicTime::Delta::Zero(), QuicTime::Zero());
6910 // The ack time should be based on min_rtt/8, since it's less than the
6911 // default delayed ack time.
6912 QuicTime ack_time = clock_.ApproximateNow() +
6913 QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
6914 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006915 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006916 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006917 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006918 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006919 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006920 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006921 // Process a packet from the non-crypto stream.
6922 frame1_.stream_id = 3;
6923
6924 // Process all the initial packets in order so there aren't missing packets.
6925 uint64_t kFirstDecimatedPacket = 101;
6926 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6927 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6928 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6929 }
fayang9adfb532020-06-04 06:58:45 -07006930 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006931 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006932 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006933 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6934 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6935 ENCRYPTION_ZERO_RTT);
6936
6937 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006938 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006939 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6940
6941 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6942 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6943 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 19, !kHasStopWaiting,
6944 ENCRYPTION_ZERO_RTT);
6945 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
fayang9adfb532020-06-04 06:58:45 -07006946 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006947 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6948
6949 // The 10th received packet causes an ack to be sent.
6950 for (int i = 0; i < 8; ++i) {
fayang9adfb532020-06-04 06:58:45 -07006951 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006952 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6953 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6954 ENCRYPTION_ZERO_RTT);
6955 }
6956 // Check that ack is sent and that delayed ack alarm is reset.
6957 if (GetParam().no_stop_waiting) {
fayang58f71072019-11-05 08:47:02 -08006958 EXPECT_EQ(writer_->padding_frames().size() + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006959 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6960 } else {
6961 EXPECT_EQ(2u, writer_->frame_count());
6962 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6963 }
6964 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006965 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006966
6967 // The next packet received in order will cause an immediate ack,
6968 // because it fills a hole.
fayang9adfb532020-06-04 06:58:45 -07006969 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006970 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6971 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 10, !kHasStopWaiting,
6972 ENCRYPTION_ZERO_RTT);
6973 // Check that ack is sent and that delayed ack alarm is reset.
6974 if (GetParam().no_stop_waiting) {
fayang58f71072019-11-05 08:47:02 -08006975 EXPECT_EQ(writer_->padding_frames().size() + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006976 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6977 } else {
6978 EXPECT_EQ(2u, writer_->frame_count());
6979 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6980 }
6981 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006982 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006983}
6984
6985TEST_P(QuicConnectionTest, SendDelayedAckOnHandshakeConfirmed) {
6986 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6987 ProcessPacket(1);
6988 // Check that ack is sent and that delayed ack alarm is set.
fayang9adfb532020-06-04 06:58:45 -07006989 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006990 QuicTime ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6991 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6992
6993 // Completing the handshake as the server does nothing.
6994 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_SERVER);
6995 connection_.OnHandshakeComplete();
fayang9adfb532020-06-04 06:58:45 -07006996 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006997 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6998
6999 // Complete the handshake as the client decreases the delayed ack time to 0ms.
7000 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_CLIENT);
7001 connection_.OnHandshakeComplete();
fayang9adfb532020-06-04 06:58:45 -07007002 EXPECT_TRUE(connection_.HasPendingAcks());
fayangb296fb82020-02-11 08:14:28 -08007003 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7004 EXPECT_EQ(clock_.ApproximateNow() + DefaultDelayedAckTime(),
7005 connection_.GetAckAlarm()->deadline());
7006 } else {
7007 EXPECT_EQ(clock_.ApproximateNow(), connection_.GetAckAlarm()->deadline());
7008 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007009}
7010
7011TEST_P(QuicConnectionTest, SendDelayedAckOnSecondPacket) {
7012 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7013 ProcessPacket(1);
7014 ProcessPacket(2);
7015 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07007016 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05007017 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07007018 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007019 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
7020 } else {
nharper55fa6132019-05-07 19:37:21 -07007021 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007022 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
7023 }
7024 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07007025 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007026}
7027
7028TEST_P(QuicConnectionTest, NoAckOnOldNacks) {
7029 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang6dba4902019-06-17 10:04:23 -07007030 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007031 ProcessPacket(2);
7032 size_t frames_per_ack = GetParam().no_stop_waiting ? 1 : 2;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007033
7034 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7035 ProcessPacket(3);
nharper55fa6132019-05-07 19:37:21 -07007036 size_t padding_frame_count = writer_->padding_frames().size();
7037 EXPECT_EQ(padding_frame_count + frames_per_ack, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007038 EXPECT_FALSE(writer_->ack_frames().empty());
7039 writer_->Reset();
7040
fayang6dba4902019-06-17 10:04:23 -07007041 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007042 ProcessPacket(4);
fayang6dba4902019-06-17 10:04:23 -07007043 EXPECT_EQ(0u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007044
7045 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7046 ProcessPacket(5);
nharper55fa6132019-05-07 19:37:21 -07007047 padding_frame_count = writer_->padding_frames().size();
7048 EXPECT_EQ(padding_frame_count + frames_per_ack, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007049 EXPECT_FALSE(writer_->ack_frames().empty());
7050 writer_->Reset();
7051
7052 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
7053 // Now only set the timer on the 6th packet, instead of sending another ack.
7054 ProcessPacket(6);
nharper55fa6132019-05-07 19:37:21 -07007055 padding_frame_count = writer_->padding_frames().size();
7056 EXPECT_EQ(padding_frame_count, writer_->frame_count());
fayang9adfb532020-06-04 06:58:45 -07007057 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007058}
7059
7060TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingPacket) {
7061 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
QUICHE team8c1daa22019-03-13 08:33:41 -07007062 EXPECT_CALL(visitor_, OnStreamFrame(_));
7063 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07007064 std::make_unique<TaggingEncrypter>(0x01));
zhongyi546cc452019-04-12 15:27:49 -07007065 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07007066 std::make_unique<StrictTaggingDecrypter>(0x01));
nharper2c9f02a2019-05-08 10:25:50 -07007067 ProcessDataPacket(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007068 connection_.SendStreamDataWithString(
7069 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
7070 0, NO_FIN);
7071 // Check that ack is bundled with outgoing data and that delayed ack
7072 // alarm is reset.
7073 if (GetParam().no_stop_waiting) {
7074 EXPECT_EQ(2u, writer_->frame_count());
7075 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
7076 } else {
7077 EXPECT_EQ(3u, writer_->frame_count());
7078 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
7079 }
7080 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07007081 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007082}
7083
7084TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingCryptoPacket) {
7085 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayangc31c9952019-06-05 13:54:48 -07007086 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
7087 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
7088 } else {
7089 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7090 }
7091 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
nharper46833c32019-05-15 21:33:05 -07007092 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007093 // Check that ack is bundled with outgoing crypto data.
7094 if (GetParam().no_stop_waiting) {
7095 EXPECT_EQ(3u, writer_->frame_count());
7096 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
7097 } else {
7098 EXPECT_EQ(4u, writer_->frame_count());
7099 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
7100 }
fayang9adfb532020-06-04 06:58:45 -07007101 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007102}
7103
7104TEST_P(QuicConnectionTest, BlockAndBufferOnFirstCHLOPacketOfTwo) {
7105 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7106 ProcessPacket(1);
7107 BlockOnNextWrite();
7108 writer_->set_is_write_blocked_data_buffered(true);
fayang6a258412020-05-28 08:57:12 -07007109 if (GetQuicReloadableFlag(quic_move_amplification_limit) &&
7110 QuicVersionUsesCryptoFrames(connection_.transport_version())) {
7111 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7112 } else {
7113 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
7114 }
nharper46833c32019-05-15 21:33:05 -07007115 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007116 EXPECT_TRUE(writer_->IsWriteBlocked());
7117 EXPECT_FALSE(connection_.HasQueuedData());
nharper46833c32019-05-15 21:33:05 -07007118 connection_.SendCryptoDataWithString("bar", 3);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007119 EXPECT_TRUE(writer_->IsWriteBlocked());
fayang6a258412020-05-28 08:57:12 -07007120 if (GetQuicReloadableFlag(quic_move_amplification_limit) &&
7121 QuicVersionUsesCryptoFrames(connection_.transport_version())) {
7122 // CRYPTO frames are not flushed when writer is blocked.
7123 EXPECT_FALSE(connection_.HasQueuedData());
7124 } else {
7125 EXPECT_TRUE(connection_.HasQueuedData());
7126 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007127}
7128
7129TEST_P(QuicConnectionTest, BundleAckForSecondCHLO) {
7130 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07007131 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007132 EXPECT_CALL(visitor_, OnCanWrite())
7133 .WillOnce(IgnoreResult(InvokeWithoutArgs(
7134 &connection_, &TestConnection::SendCryptoStreamData)));
7135 // Process a packet from the crypto stream, which is frame1_'s default.
7136 // Receiving the CHLO as packet 2 first will cause the connection to
7137 // immediately send an ack, due to the packet gap.
fayangc31c9952019-06-05 13:54:48 -07007138 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
7139 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
7140 } else {
7141 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7142 }
7143 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007144 // Check that ack is sent and that delayed ack alarm is reset.
7145 if (GetParam().no_stop_waiting) {
7146 EXPECT_EQ(3u, writer_->frame_count());
7147 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
7148 } else {
7149 EXPECT_EQ(4u, writer_->frame_count());
7150 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
7151 }
QUICHE teamea740082019-03-11 17:58:43 -07007152 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007153 EXPECT_EQ(1u, writer_->stream_frames().size());
7154 } else {
7155 EXPECT_EQ(1u, writer_->crypto_frames().size());
7156 }
7157 EXPECT_EQ(1u, writer_->padding_frames().size());
7158 ASSERT_FALSE(writer_->ack_frames().empty());
7159 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(writer_->ack_frames().front()));
fayang9adfb532020-06-04 06:58:45 -07007160 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007161}
7162
7163TEST_P(QuicConnectionTest, BundleAckForSecondCHLOTwoPacketReject) {
7164 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07007165 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007166
7167 // Process two packets from the crypto stream, which is frame1_'s default,
7168 // simulating a 2 packet reject.
7169 {
fayangc31c9952019-06-05 13:54:48 -07007170 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
7171 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
7172 } else {
7173 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7174 }
7175 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007176 // Send the new CHLO when the REJ is processed.
fayangc31c9952019-06-05 13:54:48 -07007177 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
7178 EXPECT_CALL(visitor_, OnCryptoFrame(_))
7179 .WillOnce(IgnoreResult(InvokeWithoutArgs(
7180 &connection_, &TestConnection::SendCryptoStreamData)));
7181 } else {
7182 EXPECT_CALL(visitor_, OnStreamFrame(_))
7183 .WillOnce(IgnoreResult(InvokeWithoutArgs(
7184 &connection_, &TestConnection::SendCryptoStreamData)));
7185 }
7186 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007187 }
7188 // Check that ack is sent and that delayed ack alarm is reset.
7189 if (GetParam().no_stop_waiting) {
7190 EXPECT_EQ(3u, writer_->frame_count());
7191 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
7192 } else {
7193 EXPECT_EQ(4u, writer_->frame_count());
7194 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
7195 }
QUICHE teamea740082019-03-11 17:58:43 -07007196 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007197 EXPECT_EQ(1u, writer_->stream_frames().size());
7198 } else {
7199 EXPECT_EQ(1u, writer_->crypto_frames().size());
7200 }
7201 EXPECT_EQ(1u, writer_->padding_frames().size());
7202 ASSERT_FALSE(writer_->ack_frames().empty());
7203 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(writer_->ack_frames().front()));
fayang9adfb532020-06-04 06:58:45 -07007204 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007205}
7206
7207TEST_P(QuicConnectionTest, BundleAckWithDataOnIncomingAck) {
7208 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7209 connection_.SendStreamDataWithString(
7210 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
7211 0, NO_FIN);
7212 connection_.SendStreamDataWithString(
7213 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
7214 3, NO_FIN);
7215 // Ack the second packet, which will retransmit the first packet.
7216 QuicAckFrame ack = ConstructAckFrame(2, 1);
7217 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07007218 lost_packets.push_back(
7219 LostPacket(QuicPacketNumber(1), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007220 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07007221 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
7222 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007223 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7224 ProcessAckPacket(&ack);
nharper55fa6132019-05-07 19:37:21 -07007225 size_t padding_frame_count = writer_->padding_frames().size();
7226 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007227 EXPECT_EQ(1u, writer_->stream_frames().size());
7228 writer_->Reset();
7229
7230 // Now ack the retransmission, which will both raise the high water mark
7231 // and see if there is more data to send.
7232 ack = ConstructAckFrame(3, 1);
7233 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
7234 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7235 ProcessAckPacket(&ack);
7236
7237 // Check that no packet is sent and the ack alarm isn't set.
7238 EXPECT_EQ(0u, writer_->frame_count());
fayang9adfb532020-06-04 06:58:45 -07007239 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007240 writer_->Reset();
7241
7242 // Send the same ack, but send both data and an ack together.
7243 ack = ConstructAckFrame(3, 1);
7244 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
7245 EXPECT_CALL(visitor_, OnCanWrite())
7246 .WillOnce(IgnoreResult(InvokeWithoutArgs(
7247 &connection_, &TestConnection::EnsureWritableAndSendStreamData5)));
7248 ProcessAckPacket(&ack);
7249
7250 // Check that ack is bundled with outgoing data and the delayed ack
7251 // alarm is reset.
7252 if (GetParam().no_stop_waiting) {
fayang8a27b0f2019-11-04 11:27:40 -08007253 // Do not ACK acks.
7254 EXPECT_EQ(1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007255 } else {
7256 EXPECT_EQ(3u, writer_->frame_count());
7257 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
7258 }
fayang8a27b0f2019-11-04 11:27:40 -08007259 if (GetParam().no_stop_waiting) {
fayang03916692019-05-22 17:57:18 -07007260 EXPECT_TRUE(writer_->ack_frames().empty());
7261 } else {
7262 EXPECT_FALSE(writer_->ack_frames().empty());
7263 EXPECT_EQ(QuicPacketNumber(3u),
7264 LargestAcked(writer_->ack_frames().front()));
7265 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007266 EXPECT_EQ(1u, writer_->stream_frames().size());
fayang9adfb532020-06-04 06:58:45 -07007267 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007268}
7269
7270TEST_P(QuicConnectionTest, NoAckSentForClose) {
7271 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7272 ProcessPacket(1);
fkastenholz5d880a92019-06-21 09:01:56 -07007273 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
7274 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007275 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
7276 ProcessClosePacket(2);
fkastenholz5d880a92019-06-21 09:01:56 -07007277 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007278 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7279 IsError(QUIC_PEER_GOING_AWAY));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007280}
7281
7282TEST_P(QuicConnectionTest, SendWhenDisconnected) {
7283 EXPECT_TRUE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07007284 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7285 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007286 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
7287 ConnectionCloseBehavior::SILENT_CLOSE);
7288 EXPECT_FALSE(connection_.connected());
ianswettfc16a2b2020-05-18 16:05:49 -07007289 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
QUICHE team8c1daa22019-03-13 08:33:41 -07007290 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07007291 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007292 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
7293 .Times(0);
QUICHE team6987b4a2019-03-15 16:23:04 -07007294 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05007295 HAS_RETRANSMITTABLE_DATA, false, false);
fkastenholz5d880a92019-06-21 09:01:56 -07007296 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007297 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7298 IsError(QUIC_PEER_GOING_AWAY));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007299}
7300
7301TEST_P(QuicConnectionTest, SendConnectivityProbingWhenDisconnected) {
7302 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
fayangc31c9952019-06-05 13:54:48 -07007303 if (!IsDefaultTestConfiguration()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007304 return;
7305 }
7306
7307 EXPECT_TRUE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07007308 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7309 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007310 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
7311 ConnectionCloseBehavior::SILENT_CLOSE);
7312 EXPECT_FALSE(connection_.connected());
ianswettfc16a2b2020-05-18 16:05:49 -07007313 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007314
7315 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
7316 .Times(0);
7317
7318 EXPECT_QUIC_BUG(connection_.SendConnectivityProbingPacket(
7319 writer_.get(), connection_.peer_address()),
7320 "Not sending connectivity probing packet as connection is "
7321 "disconnected.");
fkastenholz5d880a92019-06-21 09:01:56 -07007322 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007323 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7324 IsError(QUIC_PEER_GOING_AWAY));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007325}
7326
7327TEST_P(QuicConnectionTest, WriteBlockedAfterClientSendsConnectivityProbe) {
7328 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
7329 TestPacketWriter probing_writer(version(), &clock_);
7330 // Block next write so that sending connectivity probe will encounter a
7331 // blocked write when send a connectivity probe to the peer.
7332 probing_writer.BlockOnNextWrite();
7333 // Connection will not be marked as write blocked as connectivity probe only
7334 // affects the probing_writer which is not the default.
7335 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
7336
7337 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
7338 .Times(1);
7339 connection_.SendConnectivityProbingPacket(&probing_writer,
7340 connection_.peer_address());
7341}
7342
7343TEST_P(QuicConnectionTest, WriterBlockedAfterServerSendsConnectivityProbe) {
7344 set_perspective(Perspective::IS_SERVER);
7345 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
7346
7347 // Block next write so that sending connectivity probe will encounter a
7348 // blocked write when send a connectivity probe to the peer.
7349 writer_->BlockOnNextWrite();
7350 // Connection will be marked as write blocked as server uses the default
7351 // writer to send connectivity probes.
7352 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
7353
7354 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
7355 .Times(1);
7356 connection_.SendConnectivityProbingPacket(writer_.get(),
7357 connection_.peer_address());
7358}
7359
7360TEST_P(QuicConnectionTest, WriterErrorWhenClientSendsConnectivityProbe) {
7361 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
7362 TestPacketWriter probing_writer(version(), &clock_);
7363 probing_writer.SetShouldWriteFail();
7364
7365 // Connection should not be closed if a connectivity probe is failed to be
7366 // sent.
fkastenholz5d880a92019-06-21 09:01:56 -07007367 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007368
7369 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
7370 .Times(0);
7371 connection_.SendConnectivityProbingPacket(&probing_writer,
7372 connection_.peer_address());
7373}
7374
7375TEST_P(QuicConnectionTest, WriterErrorWhenServerSendsConnectivityProbe) {
7376 set_perspective(Perspective::IS_SERVER);
7377 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
7378
7379 writer_->SetShouldWriteFail();
7380 // Connection should not be closed if a connectivity probe is failed to be
7381 // sent.
fkastenholz5d880a92019-06-21 09:01:56 -07007382 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007383
7384 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
7385 .Times(0);
7386 connection_.SendConnectivityProbingPacket(writer_.get(),
7387 connection_.peer_address());
7388}
7389
7390TEST_P(QuicConnectionTest, PublicReset) {
fayangc31c9952019-06-05 13:54:48 -07007391 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007392 return;
7393 }
7394 QuicPublicResetPacket header;
7395 // Public reset packet in only built by server.
7396 header.connection_id = connection_id_;
7397 std::unique_ptr<QuicEncryptedPacket> packet(
7398 framer_.BuildPublicResetPacket(header));
7399 std::unique_ptr<QuicReceivedPacket> received(
7400 ConstructReceivedPacket(*packet, QuicTime::Zero()));
fkastenholz5d880a92019-06-21 09:01:56 -07007401 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
7402 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007403 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
fkastenholz5d880a92019-06-21 09:01:56 -07007404 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007405 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7406 IsError(QUIC_PUBLIC_RESET));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007407}
7408
7409TEST_P(QuicConnectionTest, IetfStatelessReset) {
fayangc31c9952019-06-05 13:54:48 -07007410 if (!VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007411 return;
7412 }
7413 const QuicUint128 kTestStatelessResetToken = 1010101;
7414 QuicConfig config;
7415 QuicConfigPeer::SetReceivedStatelessResetToken(&config,
7416 kTestStatelessResetToken);
7417 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7418 connection_.SetFromConfig(config);
7419 std::unique_ptr<QuicEncryptedPacket> packet(
7420 QuicFramer::BuildIetfStatelessResetPacket(connection_id_,
7421 kTestStatelessResetToken));
7422 std::unique_ptr<QuicReceivedPacket> received(
7423 ConstructReceivedPacket(*packet, QuicTime::Zero()));
renjietang7f483b52020-05-20 14:30:47 -07007424 EXPECT_CALL(visitor_, ValidateStatelessReset(_, _)).WillOnce(Return(true));
fkastenholz5d880a92019-06-21 09:01:56 -07007425 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
7426 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007427 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
fkastenholz5d880a92019-06-21 09:01:56 -07007428 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007429 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7430 IsError(QUIC_PUBLIC_RESET));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007431}
7432
7433TEST_P(QuicConnectionTest, GoAway) {
fkastenholz305e1732019-06-18 05:01:22 -07007434 if (VersionHasIetfQuicFrames(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007435 // GoAway is not available in version 99.
7436 return;
7437 }
7438
7439 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7440
wub8a5dafa2020-05-13 12:30:17 -07007441 QuicGoAwayFrame* goaway = new QuicGoAwayFrame();
7442 goaway->last_good_stream_id = 1;
7443 goaway->error_code = QUIC_PEER_GOING_AWAY;
7444 goaway->reason_phrase = "Going away.";
QUICHE teama6ef0a62019-03-07 20:34:33 -05007445 EXPECT_CALL(visitor_, OnGoAway(_));
wub8a5dafa2020-05-13 12:30:17 -07007446 ProcessGoAwayPacket(goaway);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007447}
7448
7449TEST_P(QuicConnectionTest, WindowUpdate) {
7450 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7451
wub8a5dafa2020-05-13 12:30:17 -07007452 QuicWindowUpdateFrame* window_update = new QuicWindowUpdateFrame();
7453 window_update->stream_id = 3;
7454 window_update->max_data = 1234;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007455 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
wub8a5dafa2020-05-13 12:30:17 -07007456 ProcessFramePacket(QuicFrame(window_update));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007457}
7458
7459TEST_P(QuicConnectionTest, Blocked) {
7460 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7461
wub8a5dafa2020-05-13 12:30:17 -07007462 QuicBlockedFrame* blocked = new QuicBlockedFrame();
7463 blocked->stream_id = 3;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007464 EXPECT_CALL(visitor_, OnBlockedFrame(_));
wub8a5dafa2020-05-13 12:30:17 -07007465 ProcessFramePacket(QuicFrame(blocked));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007466 EXPECT_EQ(1u, connection_.GetStats().blocked_frames_received);
7467 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7468}
7469
7470TEST_P(QuicConnectionTest, ZeroBytePacket) {
7471 // Don't close the connection for zero byte packets.
fkastenholz5d880a92019-06-21 09:01:56 -07007472 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007473 QuicReceivedPacket encrypted(nullptr, 0, QuicTime::Zero());
7474 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, encrypted);
7475}
7476
7477TEST_P(QuicConnectionTest, MissingPacketsBeforeLeastUnacked) {
fayangd4291e42019-05-30 10:31:21 -07007478 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007479 return;
7480 }
7481 // Set the packet number of the ack packet to be least unacked (4).
7482 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 3);
7483 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7484 ProcessStopWaitingPacket(InitStopWaitingFrame(4));
fayangc31c9952019-06-05 13:54:48 -07007485 EXPECT_FALSE(connection_.ack_frame().packets.Empty());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007486}
7487
QUICHE teama6ef0a62019-03-07 20:34:33 -05007488TEST_P(QuicConnectionTest, ClientHandlesVersionNegotiation) {
dschinazi48ac9192019-07-31 00:07:26 -07007489 // All supported versions except the one the connection supports.
7490 ParsedQuicVersionVector versions;
7491 for (auto version : AllSupportedVersions()) {
7492 if (version != connection_.version()) {
7493 versions.push_back(version);
7494 }
7495 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007496
7497 // Send a version negotiation packet.
7498 std::unique_ptr<QuicEncryptedPacket> encrypted(
dschinazib417d602019-05-29 13:08:45 -07007499 QuicFramer::BuildVersionNegotiationPacket(
7500 connection_id_, EmptyQuicConnectionId(),
fayangd4291e42019-05-30 10:31:21 -07007501 VersionHasIetfInvariantHeader(connection_.transport_version()),
dschinazi48ac9192019-07-31 00:07:26 -07007502 connection_.version().HasLengthPrefixedConnectionIds(), versions));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007503 std::unique_ptr<QuicReceivedPacket> received(
7504 ConstructReceivedPacket(*encrypted, QuicTime::Zero()));
fkastenholz5d880a92019-06-21 09:01:56 -07007505 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7506 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
fayang95cef072019-10-10 12:44:14 -07007507 // Verify no connection close packet gets sent.
7508 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007509 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
fayang9ed391a2019-06-20 11:16:59 -07007510 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07007511 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007512 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7513 IsError(QUIC_INVALID_VERSION));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007514}
7515
7516TEST_P(QuicConnectionTest, BadVersionNegotiation) {
7517 // Send a version negotiation packet with the version the client started with.
7518 // It should be rejected.
fkastenholz5d880a92019-06-21 09:01:56 -07007519 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7520 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007521 std::unique_ptr<QuicEncryptedPacket> encrypted(
dschinazib417d602019-05-29 13:08:45 -07007522 QuicFramer::BuildVersionNegotiationPacket(
7523 connection_id_, EmptyQuicConnectionId(),
fayangd4291e42019-05-30 10:31:21 -07007524 VersionHasIetfInvariantHeader(connection_.transport_version()),
dschinazi48ac9192019-07-31 00:07:26 -07007525 connection_.version().HasLengthPrefixedConnectionIds(),
QUICHE teama6ef0a62019-03-07 20:34:33 -05007526 AllSupportedVersions()));
7527 std::unique_ptr<QuicReceivedPacket> received(
7528 ConstructReceivedPacket(*encrypted, QuicTime::Zero()));
7529 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
fkastenholz5d880a92019-06-21 09:01:56 -07007530 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007531 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7532 IsError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007533}
7534
7535TEST_P(QuicConnectionTest, CheckSendStats) {
fayang5f135052019-08-22 17:59:40 -07007536 if (connection_.PtoEnabled()) {
7537 return;
7538 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007539 connection_.SetMaxTailLossProbes(0);
7540
7541 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7542 connection_.SendStreamDataWithString(3, "first", 0, NO_FIN);
7543 size_t first_packet_size = writer_->last_packet_size();
7544
7545 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7546 connection_.SendStreamDataWithString(5, "second", 0, NO_FIN);
7547 size_t second_packet_size = writer_->last_packet_size();
7548
7549 // 2 retransmissions due to rto, 1 due to explicit nack.
7550 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
7551 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
7552
7553 // Retransmit due to RTO.
7554 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
7555 connection_.GetRetransmissionAlarm()->Fire();
7556
7557 // Retransmit due to explicit nacks.
7558 QuicAckFrame nack_three =
7559 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)},
7560 {QuicPacketNumber(4), QuicPacketNumber(5)}});
7561
7562 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07007563 lost_packets.push_back(
7564 LostPacket(QuicPacketNumber(1), kMaxOutgoingPacketSize));
7565 lost_packets.push_back(
7566 LostPacket(QuicPacketNumber(3), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007567 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07007568 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
7569 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007570 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007571 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7572 ProcessAckPacket(&nack_three);
7573
7574 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
7575 .WillOnce(Return(QuicBandwidth::Zero()));
7576
7577 const QuicConnectionStats& stats = connection_.GetStats();
7578 // For IETF QUIC, version is not included as the encryption level switches to
7579 // FORWARD_SECURE in SendStreamDataWithString.
7580 size_t save_on_version =
fayangd4291e42019-05-30 10:31:21 -07007581 VersionHasIetfInvariantHeader(GetParam().version.transport_version)
7582 ? 0
7583 : kQuicVersionSize;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007584 EXPECT_EQ(3 * first_packet_size + 2 * second_packet_size - save_on_version,
7585 stats.bytes_sent);
7586 EXPECT_EQ(5u, stats.packets_sent);
7587 EXPECT_EQ(2 * first_packet_size + second_packet_size - save_on_version,
7588 stats.bytes_retransmitted);
7589 EXPECT_EQ(3u, stats.packets_retransmitted);
7590 EXPECT_EQ(1u, stats.rto_count);
7591 EXPECT_EQ(kDefaultMaxPacketSize, stats.max_packet_size);
7592}
7593
7594TEST_P(QuicConnectionTest, ProcessFramesIfPacketClosedConnection) {
7595 // Construct a packet with stream frame and connection close frame.
7596 QuicPacketHeader header;
dschinazi5e1a7b22019-07-31 12:23:21 -07007597 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
QUICHE team2252b702019-05-14 23:55:14 -04007598 header.source_connection_id = connection_id_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007599 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
fayangd4291e42019-05-30 10:31:21 -07007600 if (!VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04007601 header.source_connection_id_included = CONNECTION_ID_PRESENT;
7602 }
7603 } else {
7604 header.destination_connection_id = connection_id_;
fayangd4291e42019-05-30 10:31:21 -07007605 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04007606 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
7607 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007608 }
7609 header.packet_number = QuicPacketNumber(1);
7610 header.version_flag = false;
7611
fkastenholz488a4622019-08-26 06:24:46 -07007612 QuicErrorCode kQuicErrorCode = QUIC_PEER_GOING_AWAY;
7613 // This QuicConnectionCloseFrame will default to being for a Google QUIC
7614 // close. If doing IETF QUIC then set fields appropriately for CC/T or CC/A,
7615 // depending on the mapping.
fkastenholz591814c2019-09-06 12:11:46 -07007616 QuicConnectionCloseFrame qccf(peer_framer_.transport_version(),
7617 kQuicErrorCode, "",
7618 /*transport_close_frame_type=*/0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007619 QuicFrames frames;
7620 frames.push_back(QuicFrame(frame1_));
7621 frames.push_back(QuicFrame(&qccf));
7622 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
7623 EXPECT_TRUE(nullptr != packet);
dschinazi66dea072019-04-09 11:41:06 -07007624 char buffer[kMaxOutgoingPacketSize];
nharperc6b99512019-09-19 11:13:48 -07007625 size_t encrypted_length = peer_framer_.EncryptPayload(
7626 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
7627 kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007628
fkastenholz5d880a92019-06-21 09:01:56 -07007629 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
7630 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007631 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7632 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7633
7634 connection_.ProcessUdpPacket(
7635 kSelfAddress, kPeerAddress,
7636 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
fkastenholz5d880a92019-06-21 09:01:56 -07007637 EXPECT_EQ(1, connection_close_frame_count_);
bnc77e77b82020-04-05 10:36:49 -07007638 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
bncf54082a2019-11-27 10:19:47 -08007639 IsError(QUIC_PEER_GOING_AWAY));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007640}
7641
7642TEST_P(QuicConnectionTest, SelectMutualVersion) {
7643 connection_.SetSupportedVersions(AllSupportedVersions());
7644 // Set the connection to speak the lowest quic version.
7645 connection_.set_version(QuicVersionMin());
7646 EXPECT_EQ(QuicVersionMin(), connection_.version());
7647
7648 // Pass in available versions which includes a higher mutually supported
7649 // version. The higher mutually supported version should be selected.
7650 ParsedQuicVersionVector supported_versions = AllSupportedVersions();
7651 EXPECT_TRUE(connection_.SelectMutualVersion(supported_versions));
7652 EXPECT_EQ(QuicVersionMax(), connection_.version());
7653
7654 // Expect that the lowest version is selected.
7655 // Ensure the lowest supported version is less than the max, unless they're
7656 // the same.
7657 ParsedQuicVersionVector lowest_version_vector;
7658 lowest_version_vector.push_back(QuicVersionMin());
7659 EXPECT_TRUE(connection_.SelectMutualVersion(lowest_version_vector));
7660 EXPECT_EQ(QuicVersionMin(), connection_.version());
7661
7662 // Shouldn't be able to find a mutually supported version.
7663 ParsedQuicVersionVector unsupported_version;
7664 unsupported_version.push_back(UnsupportedQuicVersion());
7665 EXPECT_FALSE(connection_.SelectMutualVersion(unsupported_version));
7666}
7667
7668TEST_P(QuicConnectionTest, ConnectionCloseWhenWritable) {
7669 EXPECT_FALSE(writer_->IsWriteBlocked());
7670
7671 // Send a packet.
7672 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7673 EXPECT_EQ(0u, connection_.NumQueuedPackets());
7674 EXPECT_EQ(1u, writer_->packets_write_attempts());
7675
7676 TriggerConnectionClose();
rch39c88ab2019-10-16 19:24:40 -07007677 EXPECT_LE(2u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007678}
7679
7680TEST_P(QuicConnectionTest, ConnectionCloseGettingWriteBlocked) {
7681 BlockOnNextWrite();
7682 TriggerConnectionClose();
7683 EXPECT_EQ(1u, writer_->packets_write_attempts());
7684 EXPECT_TRUE(writer_->IsWriteBlocked());
7685}
7686
7687TEST_P(QuicConnectionTest, ConnectionCloseWhenWriteBlocked) {
7688 BlockOnNextWrite();
7689 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7690 EXPECT_EQ(1u, connection_.NumQueuedPackets());
7691 EXPECT_EQ(1u, writer_->packets_write_attempts());
7692 EXPECT_TRUE(writer_->IsWriteBlocked());
7693 TriggerConnectionClose();
7694 EXPECT_EQ(1u, writer_->packets_write_attempts());
7695}
7696
7697TEST_P(QuicConnectionTest, OnPacketSentDebugVisitor) {
7698 MockQuicConnectionDebugVisitor debug_visitor;
7699 connection_.set_debug_visitor(&debug_visitor);
7700
fayangcff885a2019-10-22 07:39:04 -07007701 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007702 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7703
fayangcff885a2019-10-22 07:39:04 -07007704 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007705 connection_.SendConnectivityProbingPacket(writer_.get(),
7706 connection_.peer_address());
7707}
7708
7709TEST_P(QuicConnectionTest, OnPacketHeaderDebugVisitor) {
7710 QuicPacketHeader header;
7711 header.packet_number = QuicPacketNumber(1);
fayangd4291e42019-05-30 10:31:21 -07007712 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007713 header.form = IETF_QUIC_LONG_HEADER_PACKET;
7714 }
7715
7716 MockQuicConnectionDebugVisitor debug_visitor;
7717 connection_.set_debug_visitor(&debug_visitor);
7718 EXPECT_CALL(debug_visitor, OnPacketHeader(Ref(header))).Times(1);
7719 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(1);
7720 EXPECT_CALL(debug_visitor, OnSuccessfulVersionNegotiation(_)).Times(1);
7721 connection_.OnPacketHeader(header);
7722}
7723
7724TEST_P(QuicConnectionTest, Pacing) {
7725 TestConnection server(connection_id_, kSelfAddress, helper_.get(),
7726 alarm_factory_.get(), writer_.get(),
7727 Perspective::IS_SERVER, version());
7728 TestConnection client(connection_id_, kPeerAddress, helper_.get(),
7729 alarm_factory_.get(), writer_.get(),
7730 Perspective::IS_CLIENT, version());
7731 EXPECT_FALSE(QuicSentPacketManagerPeer::UsingPacing(
7732 static_cast<const QuicSentPacketManager*>(
7733 &client.sent_packet_manager())));
7734 EXPECT_FALSE(QuicSentPacketManagerPeer::UsingPacing(
7735 static_cast<const QuicSentPacketManager*>(
7736 &server.sent_packet_manager())));
7737}
7738
7739TEST_P(QuicConnectionTest, WindowUpdateInstigateAcks) {
7740 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7741
7742 // Send a WINDOW_UPDATE frame.
wub8a5dafa2020-05-13 12:30:17 -07007743 QuicWindowUpdateFrame* window_update = new QuicWindowUpdateFrame();
7744 window_update->stream_id = 3;
7745 window_update->max_data = 1234;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007746 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
wub8a5dafa2020-05-13 12:30:17 -07007747 ProcessFramePacket(QuicFrame(window_update));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007748
7749 // Ensure that this has caused the ACK alarm to be set.
fayang9adfb532020-06-04 06:58:45 -07007750 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007751}
7752
7753TEST_P(QuicConnectionTest, BlockedFrameInstigateAcks) {
7754 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7755
7756 // Send a BLOCKED frame.
wub8a5dafa2020-05-13 12:30:17 -07007757 QuicBlockedFrame* blocked = new QuicBlockedFrame();
7758 blocked->stream_id = 3;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007759 EXPECT_CALL(visitor_, OnBlockedFrame(_));
wub8a5dafa2020-05-13 12:30:17 -07007760 ProcessFramePacket(QuicFrame(blocked));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007761
7762 // Ensure that this has caused the ACK alarm to be set.
fayang9adfb532020-06-04 06:58:45 -07007763 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007764}
7765
7766TEST_P(QuicConnectionTest, ReevaluateTimeUntilSendOnAck) {
7767 // Enable pacing.
7768 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7769 QuicConfig config;
7770 connection_.SetFromConfig(config);
7771
7772 // Send two packets. One packet is not sufficient because if it gets acked,
7773 // there will be no packets in flight after that and the pacer will always
7774 // allow the next packet in that situation.
7775 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7776 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
7777 connection_.SendStreamDataWithString(
7778 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
7779 0, NO_FIN);
7780 connection_.SendStreamDataWithString(
7781 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "bar",
7782 3, NO_FIN);
7783 connection_.OnCanWrite();
7784
7785 // Schedule the next packet for a few milliseconds in future.
7786 QuicSentPacketManagerPeer::DisablePacerBursts(manager_);
7787 QuicTime scheduled_pacing_time =
7788 clock_.Now() + QuicTime::Delta::FromMilliseconds(5);
7789 QuicSentPacketManagerPeer::SetNextPacedPacketTime(manager_,
7790 scheduled_pacing_time);
7791
7792 // Send a packet and have it be blocked by congestion control.
7793 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(false));
7794 connection_.SendStreamDataWithString(
7795 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "baz",
7796 6, NO_FIN);
7797 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
7798
7799 // Process an ack and the send alarm will be set to the new 5ms delay.
7800 QuicAckFrame ack = InitAckFrame(1);
7801 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
7802 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7803 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
7804 ProcessAckPacket(&ack);
nharper55fa6132019-05-07 19:37:21 -07007805 size_t padding_frame_count = writer_->padding_frames().size();
7806 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007807 EXPECT_EQ(1u, writer_->stream_frames().size());
7808 EXPECT_TRUE(connection_.GetSendAlarm()->IsSet());
7809 EXPECT_EQ(scheduled_pacing_time, connection_.GetSendAlarm()->deadline());
7810 writer_->Reset();
7811}
7812
7813TEST_P(QuicConnectionTest, SendAcksImmediately) {
QUICHE teamcd098022019-03-22 18:49:55 -07007814 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7815 return;
7816 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007817 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7818 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7819 ProcessDataPacket(1);
7820 CongestionBlockWrites();
7821 SendAckPacketToPeer();
7822}
7823
7824TEST_P(QuicConnectionTest, SendPingImmediately) {
7825 MockQuicConnectionDebugVisitor debug_visitor;
7826 connection_.set_debug_visitor(&debug_visitor);
7827
7828 CongestionBlockWrites();
fayang93cc53a2019-08-22 12:47:30 -07007829 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007830 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
fayangcff885a2019-10-22 07:39:04 -07007831 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007832 EXPECT_CALL(debug_visitor, OnPingSent()).Times(1);
7833 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
7834 EXPECT_FALSE(connection_.HasQueuedData());
7835}
7836
7837TEST_P(QuicConnectionTest, SendBlockedImmediately) {
7838 MockQuicConnectionDebugVisitor debug_visitor;
7839 connection_.set_debug_visitor(&debug_visitor);
7840
fayang93cc53a2019-08-22 12:47:30 -07007841 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007842 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
fayangcff885a2019-10-22 07:39:04 -07007843 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007844 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7845 connection_.SendControlFrame(QuicFrame(new QuicBlockedFrame(1, 3)));
7846 EXPECT_EQ(1u, connection_.GetStats().blocked_frames_sent);
7847 EXPECT_FALSE(connection_.HasQueuedData());
7848}
7849
fayang93cc53a2019-08-22 12:47:30 -07007850TEST_P(QuicConnectionTest, FailedToSendBlockedFrames) {
7851 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
7852 return;
7853 }
7854 MockQuicConnectionDebugVisitor debug_visitor;
7855 connection_.set_debug_visitor(&debug_visitor);
7856 QuicBlockedFrame blocked(1, 3);
7857
7858 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
fayangcff885a2019-10-22 07:39:04 -07007859 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(0);
fayang93cc53a2019-08-22 12:47:30 -07007860 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7861 connection_.SendControlFrame(QuicFrame(&blocked));
7862 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7863 EXPECT_FALSE(connection_.HasQueuedData());
7864}
7865
QUICHE teama6ef0a62019-03-07 20:34:33 -05007866TEST_P(QuicConnectionTest, SendingUnencryptedStreamDataFails) {
7867 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
7868 if (!IsDefaultTestConfiguration()) {
7869 return;
7870 }
7871
fkastenholz5d880a92019-06-21 09:01:56 -07007872 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7873 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007874 struct iovec iov;
7875 MakeIOVector("", &iov);
7876 EXPECT_QUIC_BUG(connection_.SaveAndSendStreamData(3, &iov, 1, 0, 0, FIN),
fayang49523232019-05-03 06:28:22 -07007877 "Cannot send stream data with level: ENCRYPTION_INITIAL");
QUICHE teama6ef0a62019-03-07 20:34:33 -05007878 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07007879 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007880 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7881 IsError(QUIC_ATTEMPT_TO_SEND_UNENCRYPTED_STREAM_DATA));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007882}
7883
7884TEST_P(QuicConnectionTest, SetRetransmissionAlarmForCryptoPacket) {
7885 EXPECT_TRUE(connection_.connected());
7886 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
7887
7888 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7889 connection_.SendCryptoStreamData();
7890
7891 // Verify retransmission timer is correctly set after crypto packet has been
7892 // sent.
7893 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
7894 QuicTime retransmission_time =
7895 QuicConnectionPeer::GetSentPacketManager(&connection_)
7896 ->GetRetransmissionTime();
7897 EXPECT_NE(retransmission_time, clock_.ApproximateNow());
7898 EXPECT_EQ(retransmission_time,
7899 connection_.GetRetransmissionAlarm()->deadline());
7900
7901 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7902 connection_.GetRetransmissionAlarm()->Fire();
7903}
7904
7905TEST_P(QuicConnectionTest, PathDegradingAlarmForCryptoPacket) {
7906 EXPECT_TRUE(connection_.connected());
fayangb59c6f12020-03-23 15:06:14 -07007907 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007908 EXPECT_FALSE(connection_.IsPathDegrading());
7909
7910 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7911 connection_.SendCryptoStreamData();
7912
fayangb59c6f12020-03-23 15:06:14 -07007913 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007914 EXPECT_FALSE(connection_.IsPathDegrading());
7915 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7916 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07007917 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7918 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007919
7920 // Fire the path degrading alarm, path degrading signal should be sent to
7921 // the visitor.
7922 EXPECT_CALL(visitor_, OnPathDegrading());
7923 clock_.AdvanceTime(delay);
fayangb59c6f12020-03-23 15:06:14 -07007924 connection_.PathDegradingTimeout();
QUICHE teama6ef0a62019-03-07 20:34:33 -05007925 EXPECT_TRUE(connection_.IsPathDegrading());
fayangb59c6f12020-03-23 15:06:14 -07007926 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007927}
7928
vasilvv693d5b02019-04-09 21:58:56 -07007929// Includes regression test for b/69979024.
QUICHE teama6ef0a62019-03-07 20:34:33 -05007930TEST_P(QuicConnectionTest, PathDegradingAlarmForNonCryptoPackets) {
7931 EXPECT_TRUE(connection_.connected());
fayangb59c6f12020-03-23 15:06:14 -07007932 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007933 EXPECT_FALSE(connection_.IsPathDegrading());
7934
7935 const char data[] = "data";
7936 size_t data_size = strlen(data);
7937 QuicStreamOffset offset = 0;
7938
7939 for (int i = 0; i < 2; ++i) {
7940 // Send a packet. Now there's a retransmittable packet on the wire, so the
7941 // path degrading alarm should be set.
7942 connection_.SendStreamDataWithString(
7943 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
7944 offset, NO_FIN);
7945 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07007946 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007947 // Check the deadline of the path degrading alarm.
7948 QuicTime::Delta delay =
7949 QuicConnectionPeer::GetSentPacketManager(&connection_)
7950 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07007951 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7952 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007953
7954 // Send a second packet. The path degrading alarm's deadline should remain
7955 // the same.
vasilvv693d5b02019-04-09 21:58:56 -07007956 // Regression test for b/69979024.
QUICHE teama6ef0a62019-03-07 20:34:33 -05007957 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
fayang2205d952020-05-12 13:45:56 -07007958 QuicTime prev_deadline =
7959 connection_.GetBlackholeDetectorAlarm()->deadline();
QUICHE teama6ef0a62019-03-07 20:34:33 -05007960 connection_.SendStreamDataWithString(
7961 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
7962 offset, NO_FIN);
7963 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07007964 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
fayang2205d952020-05-12 13:45:56 -07007965 EXPECT_EQ(prev_deadline,
7966 connection_.GetBlackholeDetectorAlarm()->deadline());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007967
7968 // Now receive an ACK of the first packet. This should advance the path
7969 // degrading alarm's deadline since forward progress has been made.
7970 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7971 if (i == 0) {
7972 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7973 }
7974 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7975 QuicAckFrame frame = InitAckFrame(
7976 {{QuicPacketNumber(1u + 2u * i), QuicPacketNumber(2u + 2u * i)}});
7977 ProcessAckPacket(&frame);
fayangb59c6f12020-03-23 15:06:14 -07007978 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007979 // Check the deadline of the path degrading alarm.
7980 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7981 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07007982 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7983 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007984
7985 if (i == 0) {
7986 // Now receive an ACK of the second packet. Since there are no more
7987 // retransmittable packets on the wire, this should cancel the path
7988 // degrading alarm.
7989 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7990 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7991 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
7992 ProcessAckPacket(&frame);
fayangb59c6f12020-03-23 15:06:14 -07007993 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007994 } else {
7995 // Advance time to the path degrading alarm's deadline and simulate
7996 // firing the alarm.
7997 clock_.AdvanceTime(delay);
7998 EXPECT_CALL(visitor_, OnPathDegrading());
fayangb59c6f12020-03-23 15:06:14 -07007999 connection_.PathDegradingTimeout();
8000 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008001 }
8002 }
8003 EXPECT_TRUE(connection_.IsPathDegrading());
8004}
8005
8006TEST_P(QuicConnectionTest, RetransmittableOnWireSetsPingAlarm) {
8007 const QuicTime::Delta retransmittable_on_wire_timeout =
8008 QuicTime::Delta::FromMilliseconds(50);
zhongyi79ace162019-10-21 15:57:09 -07008009 connection_.set_initial_retransmittable_on_wire_timeout(
QUICHE teama6ef0a62019-03-07 20:34:33 -05008010 retransmittable_on_wire_timeout);
8011
8012 EXPECT_TRUE(connection_.connected());
8013 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8014 .WillRepeatedly(Return(true));
8015
fayangb59c6f12020-03-23 15:06:14 -07008016 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008017 EXPECT_FALSE(connection_.IsPathDegrading());
8018 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8019
8020 const char data[] = "data";
8021 size_t data_size = strlen(data);
8022 QuicStreamOffset offset = 0;
8023
8024 // Send a packet.
8025 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8026 offset += data_size;
8027 // Now there's a retransmittable packet on the wire, so the path degrading
8028 // alarm should be set.
8029 // The retransmittable-on-wire alarm should not be set.
fayangb59c6f12020-03-23 15:06:14 -07008030 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008031 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
8032 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07008033 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
8034 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008035 ASSERT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8036 // The ping alarm is set for the ping timeout, not the shorter
8037 // retransmittable_on_wire_timeout.
8038 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8039 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
zhongyieef848f2019-10-18 07:09:37 -07008040 EXPECT_EQ(ping_delay,
8041 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008042
8043 // Now receive an ACK of the packet.
8044 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8045 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8046 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8047 QuicAckFrame frame =
8048 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8049 ProcessAckPacket(&frame);
8050 // No more retransmittable packets on the wire, so the path degrading alarm
8051 // should be cancelled, and the ping alarm should be set to the
8052 // retransmittable_on_wire_timeout.
fayangb59c6f12020-03-23 15:06:14 -07008053 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008054 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07008055 EXPECT_EQ(retransmittable_on_wire_timeout,
8056 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008057
8058 // Simulate firing the ping alarm and sending a PING.
8059 clock_.AdvanceTime(retransmittable_on_wire_timeout);
8060 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8061 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
8062 }));
8063 connection_.GetPingAlarm()->Fire();
8064
8065 // Now there's a retransmittable packet (PING) on the wire, so the path
8066 // degrading alarm should be set.
fayangb59c6f12020-03-23 15:06:14 -07008067 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008068 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
8069 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07008070 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
8071 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008072}
8073
8074// This test verifies that the connection marks path as degrading and does not
8075// spin timer to detect path degrading when a new packet is sent on the
8076// degraded path.
8077TEST_P(QuicConnectionTest, NoPathDegradingAlarmIfPathIsDegrading) {
8078 EXPECT_TRUE(connection_.connected());
fayangb59c6f12020-03-23 15:06:14 -07008079 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008080 EXPECT_FALSE(connection_.IsPathDegrading());
8081
8082 const char data[] = "data";
8083 size_t data_size = strlen(data);
8084 QuicStreamOffset offset = 0;
8085
8086 // Send the first packet. Now there's a retransmittable packet on the wire, so
8087 // the path degrading alarm should be set.
8088 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8089 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07008090 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008091 // Check the deadline of the path degrading alarm.
8092 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
8093 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07008094 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
8095 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008096
8097 // Send a second packet. The path degrading alarm's deadline should remain
8098 // the same.
8099 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
fayang2205d952020-05-12 13:45:56 -07008100 QuicTime prev_deadline = connection_.GetBlackholeDetectorAlarm()->deadline();
QUICHE teama6ef0a62019-03-07 20:34:33 -05008101 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8102 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07008103 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
fayang2205d952020-05-12 13:45:56 -07008104 EXPECT_EQ(prev_deadline, connection_.GetBlackholeDetectorAlarm()->deadline());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008105
8106 // Now receive an ACK of the first packet. This should advance the path
8107 // degrading alarm's deadline since forward progress has been made.
8108 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8109 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8110 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8111 QuicAckFrame frame =
8112 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
8113 ProcessAckPacket(&frame);
fayangb59c6f12020-03-23 15:06:14 -07008114 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008115 // Check the deadline of the path degrading alarm.
8116 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
8117 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07008118 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
8119 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008120
8121 // Advance time to the path degrading alarm's deadline and simulate
8122 // firing the path degrading alarm. This path will be considered as
8123 // degrading.
8124 clock_.AdvanceTime(delay);
8125 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
fayangb59c6f12020-03-23 15:06:14 -07008126 connection_.PathDegradingTimeout();
8127 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008128 EXPECT_TRUE(connection_.IsPathDegrading());
8129
8130 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
fayangb59c6f12020-03-23 15:06:14 -07008131 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008132 // Send a third packet. The path degrading alarm is no longer set but path
8133 // should still be marked as degrading.
8134 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8135 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07008136 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008137 EXPECT_TRUE(connection_.IsPathDegrading());
8138}
8139
8140// This test verifies that the connection unmarks path as degrarding and spins
8141// the timer to detect future path degrading when forward progress is made
8142// after path has been marked degrading.
8143TEST_P(QuicConnectionTest, UnmarkPathDegradingOnForwardProgress) {
8144 EXPECT_TRUE(connection_.connected());
fayangb59c6f12020-03-23 15:06:14 -07008145 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008146 EXPECT_FALSE(connection_.IsPathDegrading());
8147
8148 const char data[] = "data";
8149 size_t data_size = strlen(data);
8150 QuicStreamOffset offset = 0;
8151
8152 // Send the first packet. Now there's a retransmittable packet on the wire, so
8153 // the path degrading alarm should be set.
8154 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8155 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07008156 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008157 // Check the deadline of the path degrading alarm.
8158 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
8159 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07008160 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
8161 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008162
8163 // Send a second packet. The path degrading alarm's deadline should remain
8164 // the same.
8165 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
fayang2205d952020-05-12 13:45:56 -07008166 QuicTime prev_deadline = connection_.GetBlackholeDetectorAlarm()->deadline();
QUICHE teama6ef0a62019-03-07 20:34:33 -05008167 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8168 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07008169 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
fayang2205d952020-05-12 13:45:56 -07008170 EXPECT_EQ(prev_deadline, connection_.GetBlackholeDetectorAlarm()->deadline());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008171
8172 // Now receive an ACK of the first packet. This should advance the path
8173 // degrading alarm's deadline since forward progress has been made.
8174 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8175 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8176 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8177 QuicAckFrame frame =
8178 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
8179 ProcessAckPacket(&frame);
fayangb59c6f12020-03-23 15:06:14 -07008180 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008181 // Check the deadline of the path degrading alarm.
8182 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
8183 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07008184 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
8185 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008186
8187 // Advance time to the path degrading alarm's deadline and simulate
8188 // firing the alarm.
8189 clock_.AdvanceTime(delay);
8190 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
fayangb59c6f12020-03-23 15:06:14 -07008191 connection_.PathDegradingTimeout();
8192 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008193 EXPECT_TRUE(connection_.IsPathDegrading());
8194
8195 // Send a third packet. The path degrading alarm is no longer set but path
8196 // should still be marked as degrading.
8197 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
fayangb59c6f12020-03-23 15:06:14 -07008198 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008199 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8200 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07008201 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008202 EXPECT_TRUE(connection_.IsPathDegrading());
8203
8204 // Now receive an ACK of the second packet. This should unmark the path as
8205 // degrading. And will set a timer to detect new path degrading.
8206 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8207 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8208 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, OnForwardProgressConfirmed) {
9040 EXPECT_CALL(visitor_, OnForwardProgressConfirmed()).Times(Exactly(0));
9041 EXPECT_TRUE(connection_.connected());
9042
9043 const char data[] = "data";
9044 size_t data_size = strlen(data);
9045 QuicStreamOffset offset = 0;
9046
9047 // Send two packets.
9048 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
9049 offset += data_size;
9050 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
9051 offset += data_size;
9052
9053 // Ack packet 1. This increases the largest_acked to 1, so
9054 // OnForwardProgressConfirmed() should be called
9055 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
9056 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9057 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
9058 EXPECT_CALL(visitor_, OnForwardProgressConfirmed());
9059 QuicAckFrame frame =
9060 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
9061 ProcessAckPacket(&frame);
9062
9063 // Ack packet 1 again. largest_acked remains at 1, so
9064 // OnForwardProgressConfirmed() should not be called.
9065 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
9066 frame = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
9067 ProcessAckPacket(&frame);
9068
9069 // Ack packet 2. This increases the largest_acked to 2, so
9070 // OnForwardProgressConfirmed() should be called.
9071 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
9072 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
9073 EXPECT_CALL(visitor_, OnForwardProgressConfirmed());
9074 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
9075 ProcessAckPacket(&frame);
9076}
9077
9078TEST_P(QuicConnectionTest, ValidStatelessResetToken) {
9079 const QuicUint128 kTestToken = 1010101;
9080 const QuicUint128 kWrongTestToken = 1010100;
9081 QuicConfig config;
9082 // No token has been received.
9083 EXPECT_FALSE(connection_.IsValidStatelessResetToken(kTestToken));
9084
9085 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(2);
9086 // Token is different from received token.
9087 QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestToken);
9088 connection_.SetFromConfig(config);
9089 EXPECT_FALSE(connection_.IsValidStatelessResetToken(kWrongTestToken));
9090
9091 QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestToken);
9092 connection_.SetFromConfig(config);
9093 EXPECT_TRUE(connection_.IsValidStatelessResetToken(kTestToken));
9094}
9095
9096TEST_P(QuicConnectionTest, WriteBlockedWithInvalidAck) {
9097 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayange62e63c2019-12-04 07:16:25 -08009098 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05009099 BlockOnNextWrite();
fayange62e63c2019-12-04 07:16:25 -08009100 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05009101 connection_.SendStreamDataWithString(5, "foo", 0, FIN);
9102 // This causes connection to be closed because packet 1 has not been sent yet.
9103 QuicAckFrame frame = InitAckFrame(1);
fayange62e63c2019-12-04 07:16:25 -08009104 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05009105 ProcessAckPacket(1, &frame);
fayange62e63c2019-12-04 07:16:25 -08009106 EXPECT_EQ(0, connection_close_frame_count_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05009107}
9108
9109TEST_P(QuicConnectionTest, SendMessage) {
fayangc31c9952019-06-05 13:54:48 -07009110 if (!VersionSupportsMessageFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05009111 return;
9112 }
dschinazied459c02020-05-07 16:12:23 -07009113 if (connection_.version().UsesTls()) {
9114 QuicConfig config;
9115 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
9116 &config, kMaxAcceptedDatagramFrameSize);
9117 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9118 connection_.SetFromConfig(config);
9119 }
ianswettb239f862019-04-05 09:15:06 -07009120 std::string message(connection_.GetCurrentLargestMessagePayload() * 2, 'a');
dmcardlecf0bfcf2019-12-13 08:08:21 -08009121 quiche::QuicheStringPiece message_data(message);
QUICHE teama6ef0a62019-03-07 20:34:33 -05009122 QuicMemSliceStorage storage(nullptr, 0, nullptr, 0);
9123 {
fayanga4b37b22019-06-18 13:37:47 -07009124 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05009125 connection_.SendStreamData3();
9126 // Send a message which cannot fit into current open packet, and 2 packets
9127 // get sent, one contains stream frame, and the other only contains the
9128 // message frame.
9129 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
QUICHE team350e9e62019-11-19 13:16:24 -08009130 EXPECT_EQ(MESSAGE_STATUS_SUCCESS,
9131 connection_.SendMessage(
9132 1,
9133 MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(),
dmcardlecf0bfcf2019-12-13 08:08:21 -08009134 quiche::QuicheStringPiece(
QUICHE team350e9e62019-11-19 13:16:24 -08009135 message_data.data(),
9136 connection_.GetCurrentLargestMessagePayload()),
9137 &storage),
9138 false));
QUICHE teama6ef0a62019-03-07 20:34:33 -05009139 }
9140 // Fail to send a message if connection is congestion control blocked.
9141 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(Return(false));
QUICHE team350e9e62019-11-19 13:16:24 -08009142 EXPECT_EQ(MESSAGE_STATUS_BLOCKED,
9143 connection_.SendMessage(
9144 2,
9145 MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(),
9146 "message", &storage),
9147 false));
QUICHE teama6ef0a62019-03-07 20:34:33 -05009148
9149 // Always fail to send a message which cannot fit into one packet.
9150 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE team350e9e62019-11-19 13:16:24 -08009151 EXPECT_EQ(MESSAGE_STATUS_TOO_LARGE,
9152 connection_.SendMessage(
9153 3,
9154 MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(),
dmcardlecf0bfcf2019-12-13 08:08:21 -08009155 quiche::QuicheStringPiece(
QUICHE team350e9e62019-11-19 13:16:24 -08009156 message_data.data(),
9157 connection_.GetCurrentLargestMessagePayload() + 1),
9158 &storage),
9159 false));
QUICHE teama6ef0a62019-03-07 20:34:33 -05009160}
9161
dschinazied459c02020-05-07 16:12:23 -07009162TEST_P(QuicConnectionTest, GetCurrentLargestMessagePayload) {
9163 if (!connection_.version().SupportsMessageFrames()) {
9164 return;
9165 }
9166 // Force use of this encrypter to simplify test expectations by making sure
9167 // that the encryption overhead is constant across versions.
9168 connection_.SetEncrypter(ENCRYPTION_INITIAL,
9169 std::make_unique<TaggingEncrypter>(0x00));
9170 QuicPacketLength expected_largest_payload = 1319;
9171 if (connection_.version().SendsVariableLengthPacketNumberInLongHeader()) {
9172 expected_largest_payload += 3;
9173 }
9174 if (connection_.version().HasLongHeaderLengths()) {
9175 expected_largest_payload -= 2;
9176 }
9177 if (connection_.version().HasLengthPrefixedConnectionIds()) {
9178 expected_largest_payload -= 1;
9179 }
9180 if (connection_.version().UsesTls()) {
9181 // QUIC+TLS disallows DATAGRAM/MESSAGE frames before the handshake.
9182 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), 0);
9183 QuicConfig config;
9184 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
9185 &config, kMaxAcceptedDatagramFrameSize);
9186 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9187 connection_.SetFromConfig(config);
9188 // Verify the value post-handshake.
9189 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(),
9190 expected_largest_payload);
9191 } else {
9192 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(),
9193 expected_largest_payload);
9194 }
9195}
9196
9197TEST_P(QuicConnectionTest, GetGuaranteedLargestMessagePayload) {
9198 if (!connection_.version().SupportsMessageFrames()) {
9199 return;
9200 }
9201 // Force use of this encrypter to simplify test expectations by making sure
9202 // that the encryption overhead is constant across versions.
9203 connection_.SetEncrypter(ENCRYPTION_INITIAL,
9204 std::make_unique<TaggingEncrypter>(0x00));
9205 QuicPacketLength expected_largest_payload = 1319;
9206 if (connection_.version().HasLongHeaderLengths()) {
9207 expected_largest_payload -= 2;
9208 }
9209 if (connection_.version().HasLengthPrefixedConnectionIds()) {
9210 expected_largest_payload -= 1;
9211 }
9212 if (connection_.version().UsesTls()) {
9213 // QUIC+TLS disallows DATAGRAM/MESSAGE frames before the handshake.
9214 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(), 0);
9215 QuicConfig config;
9216 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
9217 &config, kMaxAcceptedDatagramFrameSize);
9218 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9219 connection_.SetFromConfig(config);
9220 // Verify the value post-handshake.
9221 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(),
9222 expected_largest_payload);
9223 } else {
9224 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(),
9225 expected_largest_payload);
9226 }
9227}
9228
9229TEST_P(QuicConnectionTest, LimitedLargestMessagePayload) {
9230 if (!connection_.version().SupportsMessageFrames() ||
9231 !connection_.version().UsesTls()) {
9232 return;
9233 }
9234 constexpr QuicPacketLength kFrameSizeLimit = 1000;
9235 constexpr QuicPacketLength kPayloadSizeLimit =
9236 kFrameSizeLimit - kQuicFrameTypeSize;
9237 // QUIC+TLS disallows DATAGRAM/MESSAGE frames before the handshake.
9238 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), 0);
9239 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(), 0);
9240 QuicConfig config;
9241 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(&config, kFrameSizeLimit);
9242 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9243 connection_.SetFromConfig(config);
9244 // Verify the value post-handshake.
9245 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), kPayloadSizeLimit);
9246 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(),
9247 kPayloadSizeLimit);
9248}
9249
QUICHE teama6ef0a62019-03-07 20:34:33 -05009250// Test to check that the path challenge/path response logic works
9251// correctly. This test is only for version-99
9252TEST_P(QuicConnectionTest, PathChallengeResponse) {
fkastenholz305e1732019-06-18 05:01:22 -07009253 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05009254 return;
9255 }
9256 // First check if we can probe from server to client and back
9257 set_perspective(Perspective::IS_SERVER);
9258 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
9259
9260 // Create and send the probe request (PATH_CHALLENGE frame).
9261 // SendConnectivityProbingPacket ends up calling
9262 // TestPacketWriter::WritePacket() which in turns receives and parses the
9263 // packet by calling framer_.ProcessPacket() -- which in turn calls
9264 // SimpleQuicFramer::OnPathChallengeFrame(). SimpleQuicFramer saves
9265 // the packet in writer_->path_challenge_frames()
9266 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9267 connection_.SendConnectivityProbingPacket(writer_.get(),
9268 connection_.peer_address());
9269 // Save the random contents of the challenge for later comparison to the
9270 // response.
nharper55fa6132019-05-07 19:37:21 -07009271 ASSERT_GE(writer_->path_challenge_frames().size(), 1u);
QUICHE teama6ef0a62019-03-07 20:34:33 -05009272 QuicPathFrameBuffer challenge_data =
9273 writer_->path_challenge_frames().front().data_buffer;
9274
9275 // Normally, QuicConnection::OnPathChallengeFrame and OnPaddingFrame would be
9276 // called and it will perform actions to ensure that the rest of the protocol
9277 // is performed (specifically, call UpdatePacketContent to say that this is a
9278 // path challenge so that when QuicConnection::OnPacketComplete is called
9279 // (again, out of the framer), the response is generated). Simulate those
9280 // calls so that the right internal state is set up for generating
9281 // the response.
9282 EXPECT_TRUE(connection_.OnPathChallengeFrame(
9283 writer_->path_challenge_frames().front()));
9284 EXPECT_TRUE(connection_.OnPaddingFrame(writer_->padding_frames().front()));
9285 // Cause the response to be created and sent. Result is that the response
9286 // should be stashed in writer's path_response_frames.
9287 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9288 connection_.SendConnectivityProbingResponsePacket(connection_.peer_address());
9289
9290 // The final check is to ensure that the random data in the response matches
9291 // the random data from the challenge.
9292 EXPECT_EQ(0, memcmp(&challenge_data,
9293 &(writer_->path_response_frames().front().data_buffer),
9294 sizeof(challenge_data)));
9295}
9296
9297// Regression test for b/110259444
9298TEST_P(QuicConnectionTest, DoNotScheduleSpuriousAckAlarm) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05009299 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9300 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
9301 writer_->SetWriteBlocked();
9302
9303 ProcessPacket(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05009304 // Verify ack alarm is set.
fayang9adfb532020-06-04 06:58:45 -07009305 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05009306 // Fire the ack alarm, verify no packet is sent because the writer is blocked.
9307 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9308 connection_.GetAckAlarm()->Fire();
9309
9310 writer_->SetWritable();
9311 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9312 ProcessPacket(2);
9313 // Verify ack alarm is not set.
fayang9adfb532020-06-04 06:58:45 -07009314 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05009315}
9316
9317TEST_P(QuicConnectionTest, DisablePacingOffloadConnectionOptions) {
9318 EXPECT_FALSE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
9319 writer_->set_supports_release_time(true);
9320 QuicConfig config;
9321 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9322 connection_.SetFromConfig(config);
9323 EXPECT_TRUE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
9324
9325 QuicTagVector connection_options;
9326 connection_options.push_back(kNPCO);
9327 config.SetConnectionOptionsToSend(connection_options);
9328 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9329 connection_.SetFromConfig(config);
9330 // Verify pacing offload is disabled.
9331 EXPECT_FALSE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
9332}
9333
9334// Regression test for b/110259444
9335// Get a path response without having issued a path challenge...
9336TEST_P(QuicConnectionTest, OrphanPathResponse) {
9337 QuicPathFrameBuffer data = {{0, 1, 2, 3, 4, 5, 6, 7}};
9338
9339 QuicPathResponseFrame frame(99, data);
9340 EXPECT_TRUE(connection_.OnPathResponseFrame(frame));
9341 // If PATH_RESPONSE was accepted (payload matches the payload saved
9342 // in QuicConnection::transmitted_connectivity_probe_payload_) then
9343 // current_packet_content_ would be set to FIRST_FRAME_IS_PING.
9344 // Since this PATH_RESPONSE does not match, current_packet_content_
9345 // must not be FIRST_FRAME_IS_PING.
9346 EXPECT_NE(QuicConnection::FIRST_FRAME_IS_PING,
9347 QuicConnectionPeer::GetCurrentPacketContent(&connection_));
9348}
9349
9350// Regression test for b/120791670
9351TEST_P(QuicConnectionTest, StopProcessingGQuicPacketInIetfQuicConnection) {
9352 // This test mimics a problematic scenario where an IETF QUIC connection
9353 // receives a Google QUIC packet and continue processing it using Google QUIC
9354 // wire format.
fayangd4291e42019-05-30 10:31:21 -07009355 if (!VersionHasIetfInvariantHeader(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05009356 return;
9357 }
9358 set_perspective(Perspective::IS_SERVER);
nharper46833c32019-05-15 21:33:05 -07009359 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07009360 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
9361 } else {
nharper46833c32019-05-15 21:33:05 -07009362 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
9363 }
wub8a5dafa2020-05-13 12:30:17 -07009364 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
9365 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05009366
9367 // Let connection process a Google QUIC packet.
9368 peer_framer_.set_version_for_tests(
9369 ParsedQuicVersion(PROTOCOL_QUIC_CRYPTO, QUIC_VERSION_43));
QUICHE team8c1daa22019-03-13 08:33:41 -07009370 std::unique_ptr<QuicPacket> packet(
QUICHE team6987b4a2019-03-15 16:23:04 -07009371 ConstructDataPacket(2, !kHasStopWaiting, ENCRYPTION_INITIAL));
dschinazi66dea072019-04-09 11:41:06 -07009372 char buffer[kMaxOutgoingPacketSize];
9373 size_t encrypted_length =
9374 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(2),
9375 *packet, buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05009376 // Make sure no stream frame is processed.
9377 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(0);
9378 connection_.ProcessUdpPacket(
9379 kSelfAddress, kPeerAddress,
9380 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
9381
9382 EXPECT_EQ(2u, connection_.GetStats().packets_received);
9383 EXPECT_EQ(1u, connection_.GetStats().packets_processed);
9384}
9385
9386TEST_P(QuicConnectionTest, AcceptPacketNumberZero) {
fkastenholz305e1732019-06-18 05:01:22 -07009387 if (!VersionHasIetfQuicFrames(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05009388 return;
9389 }
9390 // Set first_sending_packet_number to be 0 to allow successfully processing
9391 // acks which ack packet number 0.
9392 QuicFramerPeer::SetFirstSendingPacketNumber(writer_->framer()->framer(), 0);
9393 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9394
9395 ProcessPacket(0);
fayangc31c9952019-06-05 13:54:48 -07009396 EXPECT_EQ(QuicPacketNumber(0), LargestAcked(connection_.ack_frame()));
9397 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05009398
9399 ProcessPacket(1);
fayangc31c9952019-06-05 13:54:48 -07009400 EXPECT_EQ(QuicPacketNumber(1), LargestAcked(connection_.ack_frame()));
9401 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05009402
9403 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07009404 EXPECT_EQ(QuicPacketNumber(2), LargestAcked(connection_.ack_frame()));
9405 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05009406}
9407
QUICHE teamcd098022019-03-22 18:49:55 -07009408TEST_P(QuicConnectionTest, MultiplePacketNumberSpacesBasicSending) {
9409 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
9410 return;
9411 }
9412 use_tagging_decrypter();
9413 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07009414 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teamcd098022019-03-22 18:49:55 -07009415
9416 connection_.SendCryptoStreamData();
9417 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9418 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
9419 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
9420 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9421 QuicAckFrame frame1 = InitAckFrame(1);
9422 // Received ACK for packet 1.
9423 ProcessFramePacketAtLevel(30, QuicFrame(&frame1), ENCRYPTION_INITIAL);
9424
9425 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(4);
9426 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
9427 NO_FIN);
9428 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 4,
9429 NO_FIN);
9430 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
9431 8, NO_FIN);
9432 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
9433 12, FIN);
9434 // Received ACK for packets 2, 4, 5.
9435 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
9436 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
9437 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9438 QuicAckFrame frame2 =
9439 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)},
9440 {QuicPacketNumber(4), QuicPacketNumber(6)}});
9441 // Make sure although the same packet number is used, but they are in
9442 // different packet number spaces.
9443 ProcessFramePacketAtLevel(30, QuicFrame(&frame2), ENCRYPTION_FORWARD_SECURE);
9444}
9445
9446TEST_P(QuicConnectionTest, PeerAcksPacketsInWrongPacketNumberSpace) {
9447 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
9448 return;
9449 }
9450 use_tagging_decrypter();
9451 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07009452 std::make_unique<TaggingEncrypter>(0x01));
rch39c88ab2019-10-16 19:24:40 -07009453 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
9454 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teamcd098022019-03-22 18:49:55 -07009455
9456 connection_.SendCryptoStreamData();
9457 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9458 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
9459 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
9460 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9461 QuicAckFrame frame1 = InitAckFrame(1);
9462 // Received ACK for packet 1.
9463 ProcessFramePacketAtLevel(30, QuicFrame(&frame1), ENCRYPTION_INITIAL);
9464
9465 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
9466 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
9467 NO_FIN);
9468 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 4,
9469 NO_FIN);
9470
9471 // Received ACK for packets 2 and 3 in wrong packet number space.
9472 QuicAckFrame invalid_ack =
9473 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(4)}});
fkastenholz5d880a92019-06-21 09:01:56 -07009474 EXPECT_CALL(visitor_,
9475 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07009476 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teamcd098022019-03-22 18:49:55 -07009477 ProcessFramePacketAtLevel(300, QuicFrame(&invalid_ack), ENCRYPTION_INITIAL);
fkastenholz5d880a92019-06-21 09:01:56 -07009478 TestConnectionCloseQuicErrorCode(QUIC_INVALID_ACK_DATA);
QUICHE teamcd098022019-03-22 18:49:55 -07009479}
9480
9481TEST_P(QuicConnectionTest, MultiplePacketNumberSpacesBasicReceiving) {
9482 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
9483 return;
9484 }
9485 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
nharper46833c32019-05-15 21:33:05 -07009486 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9487 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9488 }
QUICHE teamcd098022019-03-22 18:49:55 -07009489 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
9490 use_tagging_decrypter();
9491 // Receives packet 1000 in initial data.
nharper46833c32019-05-15 21:33:05 -07009492 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
fayang9adfb532020-06-04 06:58:45 -07009493 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teamcd098022019-03-22 18:49:55 -07009494 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07009495 std::make_unique<TaggingEncrypter>(0x02));
zhongyi546cc452019-04-12 15:27:49 -07009496 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07009497 std::make_unique<StrictTaggingDecrypter>(0x02));
QUICHE teamcd098022019-03-22 18:49:55 -07009498 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07009499 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teamcd098022019-03-22 18:49:55 -07009500 // Receives packet 1000 in application data.
9501 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
fayang9adfb532020-06-04 06:58:45 -07009502 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teamcd098022019-03-22 18:49:55 -07009503 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
9504 NO_FIN);
9505 // Verify application data ACK gets bundled with outgoing data.
9506 EXPECT_EQ(2u, writer_->frame_count());
9507 // Make sure ACK alarm is still set because initial data is not ACKed.
fayang9adfb532020-06-04 06:58:45 -07009508 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teamcd098022019-03-22 18:49:55 -07009509 // Receive packet 1001 in application data.
9510 ProcessDataPacketAtLevel(1001, false, ENCRYPTION_ZERO_RTT);
9511 clock_.AdvanceTime(DefaultRetransmissionTime());
9512 // Simulates ACK alarm fires and verify two ACKs are flushed.
9513 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
9514 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07009515 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teamcd098022019-03-22 18:49:55 -07009516 connection_.GetAckAlarm()->Fire();
fayang9adfb532020-06-04 06:58:45 -07009517 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teamcd098022019-03-22 18:49:55 -07009518 // Receives more packets in application data.
9519 ProcessDataPacketAtLevel(1002, false, ENCRYPTION_ZERO_RTT);
fayang9adfb532020-06-04 06:58:45 -07009520 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teamcd098022019-03-22 18:49:55 -07009521
9522 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07009523 std::make_unique<TaggingEncrypter>(0x02));
zhongyi546cc452019-04-12 15:27:49 -07009524 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07009525 std::make_unique<StrictTaggingDecrypter>(0x02));
QUICHE teamcd098022019-03-22 18:49:55 -07009526 // Verify zero rtt and forward secure packets get acked in the same packet.
9527 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
nharper2c9f02a2019-05-08 10:25:50 -07009528 ProcessDataPacket(1003);
fayang9adfb532020-06-04 06:58:45 -07009529 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teamcd098022019-03-22 18:49:55 -07009530}
9531
QUICHE team552f71f2019-03-23 15:37:59 -07009532TEST_P(QuicConnectionTest, CancelAckAlarmOnWriteBlocked) {
9533 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
9534 return;
9535 }
9536 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
nharper46833c32019-05-15 21:33:05 -07009537 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9538 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9539 }
QUICHE team552f71f2019-03-23 15:37:59 -07009540 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
9541 use_tagging_decrypter();
9542 // Receives packet 1000 in initial data.
nharper46833c32019-05-15 21:33:05 -07009543 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
fayang9adfb532020-06-04 06:58:45 -07009544 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE team552f71f2019-03-23 15:37:59 -07009545 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07009546 std::make_unique<TaggingEncrypter>(0x02));
zhongyi546cc452019-04-12 15:27:49 -07009547 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07009548 std::make_unique<StrictTaggingDecrypter>(0x02));
QUICHE team552f71f2019-03-23 15:37:59 -07009549 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07009550 std::make_unique<TaggingEncrypter>(0x02));
QUICHE team552f71f2019-03-23 15:37:59 -07009551 // Receives packet 1000 in application data.
9552 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
fayang9adfb532020-06-04 06:58:45 -07009553 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE team552f71f2019-03-23 15:37:59 -07009554
9555 writer_->SetWriteBlocked();
9556 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AnyNumber());
9557 // Simulates ACK alarm fires and verify no ACK is flushed because of write
9558 // blocked.
9559 clock_.AdvanceTime(DefaultDelayedAckTime());
9560 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9561 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07009562 std::make_unique<TaggingEncrypter>(0x02));
QUICHE team552f71f2019-03-23 15:37:59 -07009563 connection_.GetAckAlarm()->Fire();
9564 // Verify ACK alarm is not set.
fayang9adfb532020-06-04 06:58:45 -07009565 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE team552f71f2019-03-23 15:37:59 -07009566
9567 writer_->SetWritable();
9568 // Verify 2 ACKs are sent when connection gets unblocked.
9569 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
9570 connection_.OnCanWrite();
fayang9adfb532020-06-04 06:58:45 -07009571 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE team552f71f2019-03-23 15:37:59 -07009572}
9573
dschinazi346b7ce2019-06-05 01:38:18 -07009574// Make sure a packet received with the right client connection ID is processed.
9575TEST_P(QuicConnectionTest, ValidClientConnectionId) {
dschinazi346b7ce2019-06-05 01:38:18 -07009576 if (!framer_.version().SupportsClientConnectionIds()) {
9577 return;
9578 }
9579 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9580 connection_.set_client_connection_id(TestConnectionId(0x33));
9581 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_FORWARD_SECURE);
9582 header.destination_connection_id = TestConnectionId(0x33);
9583 header.destination_connection_id_included = CONNECTION_ID_PRESENT;
9584 header.source_connection_id_included = CONNECTION_ID_ABSENT;
9585 QuicFrames frames;
9586 QuicPingFrame ping_frame;
9587 QuicPaddingFrame padding_frame;
9588 frames.push_back(QuicFrame(ping_frame));
9589 frames.push_back(QuicFrame(padding_frame));
9590 std::unique_ptr<QuicPacket> packet =
9591 BuildUnsizedDataPacket(&framer_, header, frames);
9592 char buffer[kMaxOutgoingPacketSize];
9593 size_t encrypted_length = peer_framer_.EncryptPayload(
9594 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
9595 kMaxOutgoingPacketSize);
9596 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9597 false);
9598 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9599 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9600 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9601}
9602
9603// Make sure a packet received with a different client connection ID is dropped.
9604TEST_P(QuicConnectionTest, InvalidClientConnectionId) {
dschinazi346b7ce2019-06-05 01:38:18 -07009605 if (!framer_.version().SupportsClientConnectionIds()) {
9606 return;
9607 }
9608 connection_.set_client_connection_id(TestConnectionId(0x33));
9609 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_FORWARD_SECURE);
9610 header.destination_connection_id = TestConnectionId(0xbad);
9611 header.destination_connection_id_included = CONNECTION_ID_PRESENT;
9612 header.source_connection_id_included = CONNECTION_ID_ABSENT;
9613 QuicFrames frames;
9614 QuicPingFrame ping_frame;
9615 QuicPaddingFrame padding_frame;
9616 frames.push_back(QuicFrame(ping_frame));
9617 frames.push_back(QuicFrame(padding_frame));
9618 std::unique_ptr<QuicPacket> packet =
9619 BuildUnsizedDataPacket(&framer_, header, frames);
9620 char buffer[kMaxOutgoingPacketSize];
9621 size_t encrypted_length = peer_framer_.EncryptPayload(
9622 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
9623 kMaxOutgoingPacketSize);
9624 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9625 false);
9626 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9627 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9628 EXPECT_EQ(1u, connection_.GetStats().packets_dropped);
9629}
9630
9631// Make sure the first packet received with a different client connection ID on
9632// the server is processed and it changes the client connection ID.
9633TEST_P(QuicConnectionTest, UpdateClientConnectionIdFromFirstPacket) {
dschinazi346b7ce2019-06-05 01:38:18 -07009634 if (!framer_.version().SupportsClientConnectionIds()) {
9635 return;
9636 }
dschinazi346b7ce2019-06-05 01:38:18 -07009637 set_perspective(Perspective::IS_SERVER);
9638 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_INITIAL);
9639 header.source_connection_id = TestConnectionId(0x33);
9640 header.source_connection_id_included = CONNECTION_ID_PRESENT;
9641 QuicFrames frames;
9642 QuicPingFrame ping_frame;
9643 QuicPaddingFrame padding_frame;
9644 frames.push_back(QuicFrame(ping_frame));
9645 frames.push_back(QuicFrame(padding_frame));
9646 std::unique_ptr<QuicPacket> packet =
9647 BuildUnsizedDataPacket(&framer_, header, frames);
9648 char buffer[kMaxOutgoingPacketSize];
nharperc6b99512019-09-19 11:13:48 -07009649 size_t encrypted_length =
9650 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(1),
9651 *packet, buffer, kMaxOutgoingPacketSize);
dschinazi346b7ce2019-06-05 01:38:18 -07009652 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9653 false);
9654 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9655 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9656 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9657 EXPECT_EQ(TestConnectionId(0x33), connection_.client_connection_id());
9658}
9659
fayang40ec3ac2019-06-05 09:07:54 -07009660// Regression test for b/134416344.
9661TEST_P(QuicConnectionTest, CheckConnectedBeforeFlush) {
9662 // This test mimics a scenario where a connection processes 2 packets and the
9663 // 2nd packet contains connection close frame. When the 2nd flusher goes out
9664 // of scope, a delayed ACK is pending, and ACK alarm should not be scheduled
9665 // because connection is disconnected.
9666 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fkastenholz5d880a92019-06-21 09:01:56 -07009667 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
fayang40ec3ac2019-06-05 09:07:54 -07009668 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
fkastenholz88d08f42019-09-06 07:38:04 -07009669 const QuicErrorCode kErrorCode = QUIC_INTERNAL_ERROR;
fayang40ec3ac2019-06-05 09:07:54 -07009670 std::unique_ptr<QuicConnectionCloseFrame> connection_close_frame(
fkastenholz591814c2019-09-06 12:11:46 -07009671 new QuicConnectionCloseFrame(connection_.transport_version(), kErrorCode,
9672 "",
9673 /*transport_close_frame_type=*/0));
9674
fayang40ec3ac2019-06-05 09:07:54 -07009675 // Received 2 packets.
fayang40ec3ac2019-06-05 09:07:54 -07009676 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
fayang40ec3ac2019-06-05 09:07:54 -07009677 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9678 } else {
fayang40ec3ac2019-06-05 09:07:54 -07009679 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
9680 }
wub8a5dafa2020-05-13 12:30:17 -07009681 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
9682 kPeerAddress);
fayang9adfb532020-06-04 06:58:45 -07009683 EXPECT_TRUE(connection_.HasPendingAcks());
wub8a5dafa2020-05-13 12:30:17 -07009684 ProcessFramePacketWithAddresses(QuicFrame(connection_close_frame.release()),
fayang40ec3ac2019-06-05 09:07:54 -07009685 kSelfAddress, kPeerAddress);
fayang0f0c4e62019-07-16 08:55:54 -07009686 // Verify ack alarm is not set.
fayang9adfb532020-06-04 06:58:45 -07009687 EXPECT_FALSE(connection_.HasPendingAcks());
fayang40ec3ac2019-06-05 09:07:54 -07009688}
9689
dschinazi8d551132019-08-02 19:17:16 -07009690// Verify that a packet containing three coalesced packets is parsed correctly.
9691TEST_P(QuicConnectionTest, CoalescedPacket) {
9692 if (!QuicVersionHasLongHeaderLengths(connection_.transport_version())) {
9693 // Coalesced packets can only be encoded using long header lengths.
9694 return;
9695 }
9696 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9697 EXPECT_TRUE(connection_.connected());
9698 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9699 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(3);
9700 } else {
9701 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(3);
9702 }
9703
9704 uint64_t packet_numbers[3] = {1, 2, 3};
9705 EncryptionLevel encryption_levels[3] = {
9706 ENCRYPTION_INITIAL, ENCRYPTION_INITIAL, ENCRYPTION_FORWARD_SECURE};
9707 char buffer[kMaxOutgoingPacketSize] = {};
9708 size_t total_encrypted_length = 0;
9709 for (int i = 0; i < 3; i++) {
9710 QuicPacketHeader header =
9711 ConstructPacketHeader(packet_numbers[i], encryption_levels[i]);
9712 QuicFrames frames;
9713 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9714 frames.push_back(QuicFrame(&crypto_frame_));
9715 } else {
9716 frames.push_back(QuicFrame(frame1_));
9717 }
9718 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
9719 peer_creator_.set_encryption_level(encryption_levels[i]);
9720 size_t encrypted_length = peer_framer_.EncryptPayload(
9721 encryption_levels[i], QuicPacketNumber(packet_numbers[i]), *packet,
9722 buffer + total_encrypted_length,
9723 sizeof(buffer) - total_encrypted_length);
9724 EXPECT_GT(encrypted_length, 0u);
9725 total_encrypted_length += encrypted_length;
9726 }
9727 connection_.ProcessUdpPacket(
9728 kSelfAddress, kPeerAddress,
9729 QuicReceivedPacket(buffer, total_encrypted_length, clock_.Now(), false));
9730 if (connection_.GetSendAlarm()->IsSet()) {
9731 connection_.GetSendAlarm()->Fire();
9732 }
9733
9734 EXPECT_TRUE(connection_.connected());
9735}
9736
dschinazi66fc0242019-08-16 10:00:25 -07009737// Regression test for crbug.com/992831.
9738TEST_P(QuicConnectionTest, CoalescedPacketThatSavesFrames) {
9739 if (!QuicVersionHasLongHeaderLengths(connection_.transport_version())) {
9740 // Coalesced packets can only be encoded using long header lengths.
9741 return;
9742 }
9743 if (connection_.SupportsMultiplePacketNumberSpaces()) {
9744 // TODO(b/129151114) Enable this test with multiple packet number spaces.
9745 return;
9746 }
9747 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9748 EXPECT_TRUE(connection_.connected());
9749 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9750 EXPECT_CALL(visitor_, OnCryptoFrame(_))
9751 .Times(3)
9752 .WillRepeatedly([this](const QuicCryptoFrame& /*frame*/) {
9753 // QuicFrame takes ownership of the QuicBlockedFrame.
9754 connection_.SendControlFrame(QuicFrame(new QuicBlockedFrame(1, 3)));
9755 });
9756 } else {
9757 EXPECT_CALL(visitor_, OnStreamFrame(_))
9758 .Times(3)
9759 .WillRepeatedly([this](const QuicStreamFrame& /*frame*/) {
9760 // QuicFrame takes ownership of the QuicBlockedFrame.
9761 connection_.SendControlFrame(QuicFrame(new QuicBlockedFrame(1, 3)));
9762 });
9763 }
9764
9765 uint64_t packet_numbers[3] = {1, 2, 3};
9766 EncryptionLevel encryption_levels[3] = {
9767 ENCRYPTION_INITIAL, ENCRYPTION_INITIAL, ENCRYPTION_FORWARD_SECURE};
9768 char buffer[kMaxOutgoingPacketSize] = {};
9769 size_t total_encrypted_length = 0;
9770 for (int i = 0; i < 3; i++) {
9771 QuicPacketHeader header =
9772 ConstructPacketHeader(packet_numbers[i], encryption_levels[i]);
9773 QuicFrames frames;
9774 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9775 frames.push_back(QuicFrame(&crypto_frame_));
9776 } else {
9777 frames.push_back(QuicFrame(frame1_));
9778 }
9779 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
9780 peer_creator_.set_encryption_level(encryption_levels[i]);
9781 size_t encrypted_length = peer_framer_.EncryptPayload(
9782 encryption_levels[i], QuicPacketNumber(packet_numbers[i]), *packet,
9783 buffer + total_encrypted_length,
9784 sizeof(buffer) - total_encrypted_length);
9785 EXPECT_GT(encrypted_length, 0u);
9786 total_encrypted_length += encrypted_length;
9787 }
9788 connection_.ProcessUdpPacket(
9789 kSelfAddress, kPeerAddress,
9790 QuicReceivedPacket(buffer, total_encrypted_length, clock_.Now(), false));
9791 if (connection_.GetSendAlarm()->IsSet()) {
9792 connection_.GetSendAlarm()->Fire();
9793 }
9794
9795 EXPECT_TRUE(connection_.connected());
9796
9797 SendAckPacketToPeer();
9798}
9799
fayangd3016832019-08-08 07:24:45 -07009800// Regresstion test for b/138962304.
9801TEST_P(QuicConnectionTest, RtoAndWriteBlocked) {
fayangd3016832019-08-08 07:24:45 -07009802 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9803
9804 QuicStreamId stream_id = 2;
9805 QuicPacketNumber last_data_packet;
9806 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
9807 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9808
9809 // Writer gets blocked.
9810 writer_->SetWriteBlocked();
9811
9812 // Cancel the stream.
9813 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9814 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
fayang67f82272019-08-14 16:08:45 -07009815 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
9816 .WillRepeatedly(
9817 Invoke(&notifier_, &SimpleSessionNotifier::WillingToWrite));
fayangd3016832019-08-08 07:24:45 -07009818 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9819
9820 // Retransmission timer fires in RTO mode.
9821 connection_.GetRetransmissionAlarm()->Fire();
9822 // Verify no packets get flushed when writer is blocked.
9823 EXPECT_EQ(0u, connection_.NumQueuedPackets());
9824}
9825
9826// Regresstion test for b/138962304.
9827TEST_P(QuicConnectionTest, TlpAndWriteBlocked) {
fayangd3016832019-08-08 07:24:45 -07009828 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9829 connection_.SetMaxTailLossProbes(1);
9830
9831 QuicStreamId stream_id = 2;
9832 QuicPacketNumber last_data_packet;
9833 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
9834 SendStreamDataToPeer(4, "foo", 0, NO_FIN, &last_data_packet);
9835 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9836
9837 // Writer gets blocked.
9838 writer_->SetWriteBlocked();
9839
9840 // Cancel stream 2.
9841 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9842 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
9843 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9844
fayange62e63c2019-12-04 07:16:25 -08009845 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
fayangd3016832019-08-08 07:24:45 -07009846 // Retransmission timer fires in TLP mode.
9847 connection_.GetRetransmissionAlarm()->Fire();
9848 // Verify one packets is forced flushed when writer is blocked.
9849 EXPECT_EQ(1u, connection_.NumQueuedPackets());
9850}
9851
fayang67f82272019-08-14 16:08:45 -07009852// Regresstion test for b/139375344.
9853TEST_P(QuicConnectionTest, RtoForcesSendingPing) {
fayangcff885a2019-10-22 07:39:04 -07009854 if (connection_.PtoEnabled()) {
fayang67f82272019-08-14 16:08:45 -07009855 return;
9856 }
9857 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9858 connection_.SetMaxTailLossProbes(2);
9859 EXPECT_EQ(0u, connection_.GetStats().tlp_count);
9860 EXPECT_EQ(0u, connection_.GetStats().rto_count);
9861
9862 SendStreamDataToPeer(2, "foo", 0, NO_FIN, nullptr);
9863 QuicTime retransmission_time =
9864 connection_.GetRetransmissionAlarm()->deadline();
9865 EXPECT_NE(QuicTime::Zero(), retransmission_time);
9866 // TLP fires.
9867 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
9868 clock_.AdvanceTime(retransmission_time - clock_.Now());
9869 connection_.GetRetransmissionAlarm()->Fire();
9870 EXPECT_EQ(1u, connection_.GetStats().tlp_count);
9871 EXPECT_EQ(0u, connection_.GetStats().rto_count);
9872 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9873
9874 // Packet 1 gets acked.
9875 QuicAckFrame frame = InitAckFrame(1);
9876 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
9877 ProcessAckPacket(1, &frame);
9878 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9879 retransmission_time = connection_.GetRetransmissionAlarm()->deadline();
9880
9881 // RTO fires, verify a PING packet gets sent because there is no data to send.
9882 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(3), _, _));
9883 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
9884 clock_.AdvanceTime(retransmission_time - clock_.Now());
9885 connection_.GetRetransmissionAlarm()->Fire();
9886 EXPECT_EQ(1u, connection_.GetStats().tlp_count);
9887 EXPECT_EQ(1u, connection_.GetStats().rto_count);
9888 EXPECT_EQ(1u, writer_->ping_frames().size());
9889}
9890
fayangce0a3162019-08-15 09:05:36 -07009891TEST_P(QuicConnectionTest, ProbeTimeout) {
fayangce0a3162019-08-15 09:05:36 -07009892 QuicConfig config;
9893 QuicTagVector connection_options;
9894 connection_options.push_back(k2PTO);
9895 config.SetConnectionOptionsToSend(connection_options);
9896 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9897 connection_.SetFromConfig(config);
9898 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9899
9900 QuicStreamId stream_id = 2;
9901 QuicPacketNumber last_packet;
9902 SendStreamDataToPeer(stream_id, "foooooo", 0, NO_FIN, &last_packet);
9903 SendStreamDataToPeer(stream_id, "foooooo", 7, NO_FIN, &last_packet);
9904 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9905
9906 // Reset stream.
9907 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9908 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9909
9910 // Fire the PTO and verify only the RST_STREAM is resent, not stream data.
9911 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9912 connection_.GetRetransmissionAlarm()->Fire();
9913 EXPECT_EQ(0u, writer_->stream_frames().size());
9914 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
9915 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9916}
9917
fayang97ce41e2019-10-07 08:37:29 -07009918TEST_P(QuicConnectionTest, CloseConnectionAfter6ClientPTOs) {
fayang97ce41e2019-10-07 08:37:29 -07009919 QuicConfig config;
9920 QuicTagVector connection_options;
9921 connection_options.push_back(k1PTO);
9922 connection_options.push_back(k6PTO);
9923 config.SetConnectionOptionsToSend(connection_options);
dschinazif7c6a912020-05-05 11:39:53 -07009924 QuicConfigPeer::SetNegotiated(&config, true);
dschinazie7c38a52020-05-29 15:25:45 -07009925 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
9926 QuicConfigPeer::SetReceivedOriginalConnectionId(
9927 &config, connection_.connection_id());
9928 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
9929 &config, connection_.connection_id());
9930 }
fayang97ce41e2019-10-07 08:37:29 -07009931 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9932 connection_.SetFromConfig(config);
fayangaa4f3f22020-06-05 16:22:00 -07009933 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection)) {
9934 EXPECT_CALL(visitor_, GetHandshakeState())
9935 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
9936 }
fayang97ce41e2019-10-07 08:37:29 -07009937 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9938
9939 // Send stream data.
9940 SendStreamDataToPeer(
9941 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
9942 0, FIN, nullptr);
9943
fayang97ce41e2019-10-07 08:37:29 -07009944 // Fire the retransmission alarm 5 times.
9945 for (int i = 0; i < 5; ++i) {
ianswett825b48b2020-05-11 06:25:04 -07009946 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
fayang97ce41e2019-10-07 08:37:29 -07009947 connection_.GetRetransmissionAlarm()->Fire();
9948 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
9949 EXPECT_TRUE(connection_.connected());
9950 }
fayang2205d952020-05-12 13:45:56 -07009951 EXPECT_CALL(visitor_, OnPathDegrading());
9952 connection_.PathDegradingTimeout();
fayang97ce41e2019-10-07 08:37:29 -07009953
9954 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveTlpCount());
9955 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveRtoCount());
9956 EXPECT_EQ(5u, connection_.sent_packet_manager().GetConsecutivePtoCount());
9957 // Closes connection on 6th PTO.
ianswett825b48b2020-05-11 06:25:04 -07009958 // May send multiple connecction close packets with multiple PN spaces.
9959 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
fayang97ce41e2019-10-07 08:37:29 -07009960 EXPECT_CALL(visitor_,
9961 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
fayang2205d952020-05-12 13:45:56 -07009962 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
9963 connection_.GetBlackholeDetectorAlarm()->Fire();
fayang97ce41e2019-10-07 08:37:29 -07009964 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
9965 EXPECT_FALSE(connection_.connected());
9966 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
9967}
9968
fayangce0a3162019-08-15 09:05:36 -07009969TEST_P(QuicConnectionTest, CloseConnectionAfter7ClientPTOs) {
fayangce0a3162019-08-15 09:05:36 -07009970 QuicConfig config;
9971 QuicTagVector connection_options;
9972 connection_options.push_back(k2PTO);
9973 connection_options.push_back(k7PTO);
9974 config.SetConnectionOptionsToSend(connection_options);
dschinazif7c6a912020-05-05 11:39:53 -07009975 QuicConfigPeer::SetNegotiated(&config, true);
dschinazie7c38a52020-05-29 15:25:45 -07009976 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
9977 QuicConfigPeer::SetReceivedOriginalConnectionId(
9978 &config, connection_.connection_id());
9979 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
9980 &config, connection_.connection_id());
9981 }
fayangce0a3162019-08-15 09:05:36 -07009982 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9983 connection_.SetFromConfig(config);
fayangaa4f3f22020-06-05 16:22:00 -07009984 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection)) {
9985 EXPECT_CALL(visitor_, GetHandshakeState())
9986 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
9987 }
fayangce0a3162019-08-15 09:05:36 -07009988 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9989
9990 // Send stream data.
9991 SendStreamDataToPeer(
9992 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
9993 0, FIN, nullptr);
9994
9995 // Fire the retransmission alarm 6 times.
9996 for (int i = 0; i < 6; ++i) {
9997 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
9998 connection_.GetRetransmissionAlarm()->Fire();
9999 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
10000 EXPECT_TRUE(connection_.connected());
10001 }
fayang2205d952020-05-12 13:45:56 -070010002 EXPECT_CALL(visitor_, OnPathDegrading());
10003 connection_.PathDegradingTimeout();
fayangce0a3162019-08-15 09:05:36 -070010004
10005 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveTlpCount());
10006 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveRtoCount());
10007 EXPECT_EQ(6u, connection_.sent_packet_manager().GetConsecutivePtoCount());
10008 // Closes connection on 7th PTO.
10009 EXPECT_CALL(visitor_,
10010 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -070010011 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
fayang2205d952020-05-12 13:45:56 -070010012 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
10013 connection_.GetBlackholeDetectorAlarm()->Fire();
fayangce0a3162019-08-15 09:05:36 -070010014 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
10015 EXPECT_FALSE(connection_.connected());
10016 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
10017}
10018
10019TEST_P(QuicConnectionTest, CloseConnectionAfter8ClientPTOs) {
fayangce0a3162019-08-15 09:05:36 -070010020 QuicConfig config;
10021 QuicTagVector connection_options;
10022 connection_options.push_back(k2PTO);
10023 connection_options.push_back(k8PTO);
dschinazif7c6a912020-05-05 11:39:53 -070010024 QuicConfigPeer::SetNegotiated(&config, true);
dschinazie7c38a52020-05-29 15:25:45 -070010025 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
10026 QuicConfigPeer::SetReceivedOriginalConnectionId(
10027 &config, connection_.connection_id());
10028 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
10029 &config, connection_.connection_id());
10030 }
fayangce0a3162019-08-15 09:05:36 -070010031 config.SetConnectionOptionsToSend(connection_options);
10032 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10033 connection_.SetFromConfig(config);
fayangaa4f3f22020-06-05 16:22:00 -070010034 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection)) {
10035 EXPECT_CALL(visitor_, GetHandshakeState())
10036 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
10037 }
fayangce0a3162019-08-15 09:05:36 -070010038 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
10039
10040 // Send stream data.
10041 SendStreamDataToPeer(
10042 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
10043 0, FIN, nullptr);
10044
10045 // Fire the retransmission alarm 7 times.
10046 for (int i = 0; i < 7; ++i) {
10047 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
10048 connection_.GetRetransmissionAlarm()->Fire();
10049 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
10050 EXPECT_TRUE(connection_.connected());
10051 }
fayang2205d952020-05-12 13:45:56 -070010052 EXPECT_CALL(visitor_, OnPathDegrading());
10053 connection_.PathDegradingTimeout();
fayangce0a3162019-08-15 09:05:36 -070010054
10055 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveTlpCount());
10056 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveRtoCount());
10057 EXPECT_EQ(7u, connection_.sent_packet_manager().GetConsecutivePtoCount());
10058 // Closes connection on 8th PTO.
10059 EXPECT_CALL(visitor_,
10060 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -070010061 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
fayang2205d952020-05-12 13:45:56 -070010062 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
10063 connection_.GetBlackholeDetectorAlarm()->Fire();
fayangce0a3162019-08-15 09:05:36 -070010064 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
10065 EXPECT_FALSE(connection_.connected());
10066 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
10067}
10068
fayang5f135052019-08-22 17:59:40 -070010069TEST_P(QuicConnectionTest, DeprecateHandshakeMode) {
10070 if (!connection_.version().SupportsAntiAmplificationLimit()) {
10071 return;
10072 }
10073 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10074 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
10075
10076 // Send CHLO.
10077 connection_.SendCryptoStreamData();
10078 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
10079
10080 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
10081 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
10082 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
10083 QuicAckFrame frame1 = InitAckFrame(1);
10084 // Received ACK for packet 1.
10085 ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL);
10086
10087 // Verify retransmission alarm is still set because handshake is not
10088 // confirmed although there is nothing in flight.
10089 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
10090 EXPECT_EQ(0u, connection_.GetStats().pto_count);
10091 EXPECT_EQ(0u, connection_.GetStats().crypto_retransmit_count);
10092
10093 // PTO fires, verify a PING packet gets sent because there is no data to send.
fayang5d011982020-05-13 14:14:38 -070010094 EXPECT_CALL(*send_algorithm_,
10095 OnPacketSent(_, _,
10096 GetQuicReloadableFlag(quic_default_on_pto)
10097 ? QuicPacketNumber(2)
10098 : QuicPacketNumber(3),
10099 _, _));
fayang5f135052019-08-22 17:59:40 -070010100 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
10101 connection_.GetRetransmissionAlarm()->Fire();
10102 EXPECT_EQ(1u, connection_.GetStats().pto_count);
fayangaf9903b2020-05-14 14:34:28 -070010103 EXPECT_EQ(1u, connection_.GetStats().crypto_retransmit_count);
fayang5f135052019-08-22 17:59:40 -070010104 EXPECT_EQ(1u, writer_->ping_frames().size());
10105}
10106
10107TEST_P(QuicConnectionTest, AntiAmplificationLimit) {
10108 if (!connection_.version().SupportsAntiAmplificationLimit()) {
10109 return;
10110 }
fayang5f135052019-08-22 17:59:40 -070010111 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10112
10113 set_perspective(Perspective::IS_SERVER);
10114 // Verify no data can be sent at the beginning because bytes received is 0.
10115 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
10116 connection_.SendCryptoDataWithString("foo", 0);
fayang6a258412020-05-28 08:57:12 -070010117 if (GetQuicReloadableFlag(quic_move_amplification_limit)) {
10118 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
10119 EXPECT_FALSE(connection_.CanWrite(NO_RETRANSMITTABLE_DATA));
10120 }
fayang5f135052019-08-22 17:59:40 -070010121 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
10122
10123 // Receives packet 1.
10124 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
10125
10126 const size_t anti_amplification_factor =
fayang6a258412020-05-28 08:57:12 -070010127 connection_.anti_amplification_factor();
fayang5f135052019-08-22 17:59:40 -070010128 // Verify now packets can be sent.
10129 for (size_t i = 0; i < anti_amplification_factor; ++i) {
10130 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10131 connection_.SendCryptoDataWithString("foo", i * 3);
10132 // Verify retransmission alarm is not set if throttled by anti-amplification
10133 // limit.
10134 EXPECT_EQ(i != anti_amplification_factor - 1,
10135 connection_.GetRetransmissionAlarm()->IsSet());
10136 }
10137 // Verify server is throttled by anti-amplification limit.
10138 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
10139 connection_.SendCryptoDataWithString("foo", anti_amplification_factor * 3);
10140
10141 // Receives packet 2.
10142 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
10143 // Verify more packets can be sent.
10144 for (size_t i = anti_amplification_factor; i < anti_amplification_factor * 2;
10145 ++i) {
10146 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10147 connection_.SendCryptoDataWithString("foo", i * 3);
10148 }
10149 // Verify server is throttled by anti-amplification limit.
10150 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
10151 connection_.SendCryptoDataWithString("foo",
10152 2 * anti_amplification_factor * 3);
10153
10154 ProcessPacket(3);
10155 // Verify anti-amplification limit is gone after address validation.
10156 for (size_t i = 0; i < 100; ++i) {
10157 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10158 connection_.SendStreamDataWithString(3, "first", i * 0, NO_FIN);
10159 }
10160}
10161
fayang6a258412020-05-28 08:57:12 -070010162TEST_P(QuicConnectionTest, AckPendingWithAmplificationLimited) {
10163 if (!connection_.version().SupportsAntiAmplificationLimit() ||
10164 !GetQuicReloadableFlag(quic_move_amplification_limit)) {
10165 return;
10166 }
10167 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10168 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(AnyNumber());
10169 set_perspective(Perspective::IS_SERVER);
10170 use_tagging_decrypter();
10171 connection_.SetEncrypter(ENCRYPTION_INITIAL,
10172 std::make_unique<TaggingEncrypter>(0x01));
10173 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10174 // Receives packet 1.
10175 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
10176 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10177 std::make_unique<TaggingEncrypter>(0x02));
10178 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
fayang9adfb532020-06-04 06:58:45 -070010179 EXPECT_TRUE(connection_.HasPendingAcks());
fayang6a258412020-05-28 08:57:12 -070010180 // Send response in different encryption level and cause amplification factor
10181 // throttled.
10182 size_t i = 0;
10183 while (connection_.CanWrite(HAS_RETRANSMITTABLE_DATA)) {
10184 connection_.SendCryptoDataWithString(std::string(1024, 'a'), i * 1024,
10185 ENCRYPTION_HANDSHAKE);
10186 ++i;
10187 }
10188 // Verify ACK is still pending.
fayang9adfb532020-06-04 06:58:45 -070010189 EXPECT_TRUE(connection_.HasPendingAcks());
fayang6a258412020-05-28 08:57:12 -070010190
10191 // Fire ACK alarm and verify ACK cannot be sent due to amplification factor.
10192 clock_.AdvanceTime(connection_.GetAckAlarm()->deadline() - clock_.Now());
10193 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
10194 connection_.GetAckAlarm()->Fire();
10195 // Verify ACK alarm is cancelled.
fayang9adfb532020-06-04 06:58:45 -070010196 EXPECT_FALSE(connection_.HasPendingAcks());
fayang6a258412020-05-28 08:57:12 -070010197
10198 // Receives packet 2 and verify ACK gets flushed.
10199 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10200 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
10201 EXPECT_FALSE(writer_->ack_frames().empty());
10202}
10203
fkastenholza3660102019-08-28 05:19:24 -070010204TEST_P(QuicConnectionTest, ConnectionCloseFrameType) {
10205 if (!VersionHasIetfQuicFrames(version().transport_version)) {
10206 // Test relevent only for IETF QUIC.
10207 return;
10208 }
10209 const QuicErrorCode kQuicErrorCode = IETF_QUIC_PROTOCOL_VIOLATION;
10210 // Use the (unknown) frame type of 9999 to avoid triggering any logic
10211 // which might be associated with the processing of a known frame type.
10212 const uint64_t kTransportCloseFrameType = 9999u;
10213 QuicFramerPeer::set_current_received_frame_type(
10214 QuicConnectionPeer::GetFramer(&connection_), kTransportCloseFrameType);
10215 // Do a transport connection close
10216 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10217 connection_.CloseConnection(
10218 kQuicErrorCode, "Some random error message",
10219 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10220 const std::vector<QuicConnectionCloseFrame>& connection_close_frames =
10221 writer_->connection_close_frames();
10222 ASSERT_EQ(1u, connection_close_frames.size());
10223 EXPECT_EQ(IETF_QUIC_TRANSPORT_CONNECTION_CLOSE,
10224 connection_close_frames[0].close_type);
bnc77e77b82020-04-05 10:36:49 -070010225 EXPECT_EQ(kQuicErrorCode, connection_close_frames[0].quic_error_code);
fkastenholza3660102019-08-28 05:19:24 -070010226 EXPECT_EQ(kTransportCloseFrameType,
10227 connection_close_frames[0].transport_close_frame_type);
10228}
10229
fayang0fcbf352019-08-30 11:15:58 -070010230// Regression test for b/137401387 and b/138962304.
10231TEST_P(QuicConnectionTest, RtoPacketAsTwo) {
fayangcff885a2019-10-22 07:39:04 -070010232 if (connection_.PtoEnabled()) {
fayang0fcbf352019-08-30 11:15:58 -070010233 return;
10234 }
10235 connection_.SetMaxTailLossProbes(1);
10236 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10237 std::string stream_data(3000, 's');
10238 // Send packets 1 - 66 and exhaust cwnd.
10239 for (size_t i = 0; i < 22; ++i) {
10240 // 3 packets for each stream, the first 2 are guaranteed to be full packets.
10241 SendStreamDataToPeer(i + 2, stream_data, 0, FIN, nullptr);
10242 }
10243 CongestionBlockWrites();
10244
10245 // Fires TLP. Please note, this tail loss probe has 1 byte less stream data
10246 // compared to packet 1 because packet number length increases.
10247 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(67), _, _));
10248 connection_.GetRetransmissionAlarm()->Fire();
10249 // Fires RTO. Please note, although packets 2 and 3 *should* be RTOed, but
10250 // packet 2 gets RTOed to two packets because packet number length increases.
10251 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(68), _, _));
10252 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(69), _, _));
10253 connection_.GetRetransmissionAlarm()->Fire();
10254
10255 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10256 // Resets all streams except 2 and ack packets 1 and 2. Now, packet 3 is the
10257 // only one containing retransmittable frames.
10258 for (size_t i = 1; i < 22; ++i) {
10259 notifier_.OnStreamReset(i + 2, QUIC_STREAM_CANCELLED);
10260 }
10261 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
10262 QuicAckFrame frame =
10263 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(3)}});
10264 ProcessAckPacket(1, &frame);
10265 CongestionUnblockWrites();
10266
10267 // Fires TLP, verify a PING gets sent because packet 3 is marked
10268 // RTO_RETRANSMITTED.
10269 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(70), _, _));
10270 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
10271 connection_.GetRetransmissionAlarm()->Fire();
10272}
10273
fayang4c1c2362019-09-13 07:20:01 -070010274TEST_P(QuicConnectionTest, PtoSkipsPacketNumber) {
fayang4c1c2362019-09-13 07:20:01 -070010275 QuicConfig config;
10276 QuicTagVector connection_options;
10277 connection_options.push_back(k1PTO);
10278 connection_options.push_back(kPTOS);
10279 config.SetConnectionOptionsToSend(connection_options);
10280 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10281 connection_.SetFromConfig(config);
10282 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
10283
10284 QuicStreamId stream_id = 2;
10285 QuicPacketNumber last_packet;
10286 SendStreamDataToPeer(stream_id, "foooooo", 0, NO_FIN, &last_packet);
10287 SendStreamDataToPeer(stream_id, "foooooo", 7, NO_FIN, &last_packet);
10288 EXPECT_EQ(QuicPacketNumber(2), last_packet);
10289 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
10290
10291 // Fire PTO and verify the PTO retransmission skips one packet number.
10292 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10293 connection_.GetRetransmissionAlarm()->Fire();
10294 EXPECT_EQ(1u, writer_->stream_frames().size());
10295 EXPECT_EQ(QuicPacketNumber(4), writer_->last_packet_header().packet_number);
10296 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
10297}
10298
fayang58f71072019-11-05 08:47:02 -080010299TEST_P(QuicConnectionTest, SendCoalescedPackets) {
10300 if (!connection_.version().CanSendCoalescedPackets()) {
10301 return;
10302 }
fayang6100ab72020-03-18 13:16:25 -070010303 MockQuicConnectionDebugVisitor debug_visitor;
10304 connection_.set_debug_visitor(&debug_visitor);
10305 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(3);
10306 EXPECT_CALL(debug_visitor, OnCoalescedPacketSent(_, _)).Times(1);
fayang44ae4e92020-04-28 13:09:42 -070010307 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
fayang58f71072019-11-05 08:47:02 -080010308 {
10309 QuicConnection::ScopedPacketFlusher flusher(&connection_);
10310 use_tagging_decrypter();
10311 connection_.SetEncrypter(ENCRYPTION_INITIAL,
10312 std::make_unique<TaggingEncrypter>(0x01));
10313 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10314 connection_.SendCryptoDataWithString("foo", 0);
10315 // Verify this packet is on hold.
10316 EXPECT_EQ(0u, writer_->packets_write_attempts());
10317
10318 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10319 std::make_unique<TaggingEncrypter>(0x02));
10320 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10321 connection_.SendCryptoDataWithString("bar", 3);
10322 EXPECT_EQ(0u, writer_->packets_write_attempts());
10323
10324 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
10325 std::make_unique<TaggingEncrypter>(0x03));
10326 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10327 SendStreamDataToPeer(2, "baz", 3, NO_FIN, nullptr);
10328 }
10329 // Verify all 3 packets are coalesced in the same UDP datagram.
10330 EXPECT_EQ(1u, writer_->packets_write_attempts());
10331 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
10332 // Verify the packet is padded to full.
10333 EXPECT_EQ(connection_.max_packet_length(), writer_->last_packet_size());
10334
10335 // Verify packet process.
10336 EXPECT_EQ(1u, writer_->crypto_frames().size());
10337 EXPECT_EQ(0u, writer_->stream_frames().size());
10338 // Verify there is coalesced packet.
10339 EXPECT_NE(nullptr, writer_->coalesced_packet());
10340}
10341
fayang01062942020-01-22 07:23:23 -080010342TEST_P(QuicConnectionTest, ClientReceivedHandshakeDone) {
10343 if (!connection_.version().HasHandshakeDone()) {
10344 return;
10345 }
10346 EXPECT_CALL(visitor_, OnHandshakeDoneReceived());
10347 QuicFrames frames;
10348 frames.push_back(QuicFrame(QuicHandshakeDoneFrame()));
10349 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10350 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10351}
10352
10353TEST_P(QuicConnectionTest, ServerReceivedHandshakeDone) {
10354 if (!connection_.version().HasHandshakeDone()) {
10355 return;
10356 }
10357 set_perspective(Perspective::IS_SERVER);
10358 EXPECT_CALL(visitor_, OnHandshakeDoneReceived()).Times(0);
10359 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10360 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
10361 QuicFrames frames;
10362 frames.push_back(QuicFrame(QuicHandshakeDoneFrame()));
10363 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10364 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10365 EXPECT_EQ(1, connection_close_frame_count_);
10366 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
10367 IsError(IETF_QUIC_PROTOCOL_VIOLATION));
10368}
10369
fayang18ff23b2020-01-28 09:19:00 -080010370TEST_P(QuicConnectionTest, MultiplePacketNumberSpacePto) {
10371 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10372 return;
10373 }
10374 use_tagging_decrypter();
10375 // Send handshake packet.
10376 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10377 std::make_unique<TaggingEncrypter>(0x02));
10378 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
fayang44ae4e92020-04-28 13:09:42 -070010379 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
fayang18ff23b2020-01-28 09:19:00 -080010380 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
10381 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
10382
10383 // Send application data.
10384 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
10385 0, NO_FIN);
10386 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
10387 QuicTime retransmission_time =
10388 connection_.GetRetransmissionAlarm()->deadline();
10389 EXPECT_NE(QuicTime::Zero(), retransmission_time);
10390
10391 // Retransmit handshake data.
10392 clock_.AdvanceTime(retransmission_time - clock_.Now());
fayang5d011982020-05-13 14:14:38 -070010393 EXPECT_CALL(*send_algorithm_,
10394 OnPacketSent(_, _,
10395 GetQuicReloadableFlag(quic_default_on_pto)
10396 ? QuicPacketNumber(3)
10397 : QuicPacketNumber(4),
10398 _, _));
fayang44ae4e92020-04-28 13:09:42 -070010399 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
fayang18ff23b2020-01-28 09:19:00 -080010400 connection_.GetRetransmissionAlarm()->Fire();
10401 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
10402
10403 // Send application data.
10404 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
10405 4, NO_FIN);
10406 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
10407 retransmission_time = connection_.GetRetransmissionAlarm()->deadline();
10408 EXPECT_NE(QuicTime::Zero(), retransmission_time);
10409
10410 // Retransmit handshake data again.
10411 clock_.AdvanceTime(retransmission_time - clock_.Now());
fayang5d011982020-05-13 14:14:38 -070010412 EXPECT_CALL(*send_algorithm_,
10413 OnPacketSent(_, _,
10414 GetQuicReloadableFlag(quic_default_on_pto)
10415 ? QuicPacketNumber(5)
10416 : QuicPacketNumber(7),
10417 _, _));
fayang44ae4e92020-04-28 13:09:42 -070010418 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
fayang18ff23b2020-01-28 09:19:00 -080010419 connection_.GetRetransmissionAlarm()->Fire();
10420 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
10421
10422 // Discard handshake key.
10423 connection_.OnHandshakeComplete();
10424 retransmission_time = connection_.GetRetransmissionAlarm()->deadline();
10425 EXPECT_NE(QuicTime::Zero(), retransmission_time);
10426
10427 // Retransmit application data.
10428 clock_.AdvanceTime(retransmission_time - clock_.Now());
fayang5d011982020-05-13 14:14:38 -070010429 EXPECT_CALL(*send_algorithm_,
10430 OnPacketSent(_, _,
10431 GetQuicReloadableFlag(quic_default_on_pto)
10432 ? QuicPacketNumber(6)
10433 : QuicPacketNumber(9),
10434 _, _));
fayang18ff23b2020-01-28 09:19:00 -080010435 connection_.GetRetransmissionAlarm()->Fire();
10436 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
10437}
10438
dschinazie7c38a52020-05-29 15:25:45 -070010439void QuicConnectionTest::TestClientRetryHandling(
10440 bool invalid_retry_tag,
10441 bool missing_original_id_in_config,
10442 bool wrong_original_id_in_config,
10443 bool missing_retry_id_in_config,
10444 bool wrong_retry_id_in_config) {
dschinazi39e5e552020-05-06 13:55:24 -070010445 if (invalid_retry_tag) {
dschinazie7c38a52020-05-29 15:25:45 -070010446 ASSERT_FALSE(missing_original_id_in_config);
10447 ASSERT_FALSE(wrong_original_id_in_config);
10448 ASSERT_FALSE(missing_retry_id_in_config);
10449 ASSERT_FALSE(wrong_retry_id_in_config);
dschinazi39e5e552020-05-06 13:55:24 -070010450 } else {
dschinazie7c38a52020-05-29 15:25:45 -070010451 ASSERT_FALSE(missing_original_id_in_config && wrong_original_id_in_config);
10452 ASSERT_FALSE(missing_retry_id_in_config && wrong_retry_id_in_config);
dschinazi39e5e552020-05-06 13:55:24 -070010453 }
dschinazi278efae2020-01-28 17:03:09 -080010454 if (!version().HasRetryIntegrityTag()) {
10455 return;
10456 }
dschinazi39e5e552020-05-06 13:55:24 -070010457
10458 // These values come from draft-ietf-quic-tls Appendix A.4.
10459 char retry_packet25[] = {
10460 0xff, 0xff, 0x00, 0x00, 0x19, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a,
10461 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x1e, 0x5e, 0xc5, 0xb0,
10462 0x14, 0xcb, 0xb1, 0xf0, 0xfd, 0x93, 0xdf, 0x40, 0x48, 0xc4, 0x46, 0xa6};
10463 char retry_packet27[] = {
10464 0xff, 0xff, 0x00, 0x00, 0x1b, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a,
10465 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0xa5, 0x23, 0xcb, 0x5b,
10466 0xa5, 0x24, 0x69, 0x5f, 0x65, 0x69, 0xf2, 0x93, 0xa1, 0x35, 0x9d, 0x8e};
dschinazi2c78aac2020-05-21 17:21:58 -070010467 char retry_packet28[] = {
10468 0xff, 0xff, 0x00, 0x00, 0x1c, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a,
10469 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0xf7, 0x1a, 0x5f, 0x12,
10470 0xaf, 0xe3, 0xec, 0xf8, 0x00, 0x1a, 0x92, 0x0e, 0x6f, 0xdf, 0x1d, 0x63};
dschinazi39e5e552020-05-06 13:55:24 -070010471
10472 char* retry_packet;
10473 size_t retry_packet_length;
10474 if (version() ==
dschinazi2c78aac2020-05-21 17:21:58 -070010475 ParsedQuicVersion(PROTOCOL_TLS1_3, QUIC_VERSION_IETF_DRAFT_28)) {
10476 retry_packet = retry_packet28;
10477 retry_packet_length = QUICHE_ARRAYSIZE(retry_packet28);
10478 } else if (version() ==
10479 ParsedQuicVersion(PROTOCOL_TLS1_3, QUIC_VERSION_IETF_DRAFT_27)) {
dschinazi39e5e552020-05-06 13:55:24 -070010480 retry_packet = retry_packet27;
10481 retry_packet_length = QUICHE_ARRAYSIZE(retry_packet27);
10482 } else if (version() ==
10483 ParsedQuicVersion(PROTOCOL_TLS1_3, QUIC_VERSION_IETF_DRAFT_25)) {
10484 retry_packet = retry_packet25;
10485 retry_packet_length = QUICHE_ARRAYSIZE(retry_packet25);
10486 } else {
dschinazi278efae2020-01-28 17:03:09 -080010487 // TODO(dschinazi) generate retry packets for all versions once we have
10488 // server-side support for generating these programmatically.
10489 return;
10490 }
10491
dschinazi278efae2020-01-28 17:03:09 -080010492 char original_connection_id_bytes[] = {0x83, 0x94, 0xc8, 0xf0,
10493 0x3e, 0x51, 0x57, 0x08};
10494 char new_connection_id_bytes[] = {0xf0, 0x67, 0xa5, 0x50,
10495 0x2a, 0x42, 0x62, 0xb5};
10496 char retry_token_bytes[] = {0x74, 0x6f, 0x6b, 0x65, 0x6e};
10497
10498 QuicConnectionId original_connection_id(
10499 original_connection_id_bytes,
10500 QUICHE_ARRAYSIZE(original_connection_id_bytes));
10501 QuicConnectionId new_connection_id(new_connection_id_bytes,
10502 QUICHE_ARRAYSIZE(new_connection_id_bytes));
10503
10504 std::string retry_token(retry_token_bytes,
10505 QUICHE_ARRAYSIZE(retry_token_bytes));
10506
dschinazi39e5e552020-05-06 13:55:24 -070010507 if (invalid_retry_tag) {
10508 // Flip the last bit of the retry packet to prevent the integrity tag
10509 // from validating correctly.
10510 retry_packet[retry_packet_length - 1] ^= 1;
dschinazi278efae2020-01-28 17:03:09 -080010511 }
10512
dschinazi39e5e552020-05-06 13:55:24 -070010513 QuicConnectionId config_original_connection_id = original_connection_id;
dschinazie7c38a52020-05-29 15:25:45 -070010514 if (wrong_original_id_in_config) {
dschinazi39e5e552020-05-06 13:55:24 -070010515 // Flip the first bit of the connection ID.
10516 ASSERT_FALSE(config_original_connection_id.IsEmpty());
10517 config_original_connection_id.mutable_data()[0] ^= 0x80;
10518 }
dschinazie7c38a52020-05-29 15:25:45 -070010519 QuicConnectionId config_retry_source_connection_id = new_connection_id;
10520 if (wrong_retry_id_in_config) {
10521 // Flip the first bit of the connection ID.
10522 ASSERT_FALSE(config_retry_source_connection_id.IsEmpty());
10523 config_retry_source_connection_id.mutable_data()[0] ^= 0x80;
10524 }
dschinazi278efae2020-01-28 17:03:09 -080010525
dschinazi39e5e552020-05-06 13:55:24 -070010526 // Make sure the connection uses the connection ID from the test vectors,
10527 QuicConnectionPeer::SetServerConnectionId(&connection_,
10528 original_connection_id);
dschinazi278efae2020-01-28 17:03:09 -080010529
dschinazi39e5e552020-05-06 13:55:24 -070010530 // Process the RETRY packet.
10531 connection_.ProcessUdpPacket(
10532 kSelfAddress, kPeerAddress,
10533 QuicReceivedPacket(retry_packet, retry_packet_length, clock_.Now()));
10534
10535 if (invalid_retry_tag) {
10536 // Make sure we refuse to process a RETRY with invalid tag.
10537 EXPECT_FALSE(connection_.GetStats().retry_packet_processed);
10538 EXPECT_EQ(connection_.connection_id(), original_connection_id);
dschinazi278efae2020-01-28 17:03:09 -080010539 EXPECT_TRUE(QuicPacketCreatorPeer::GetRetryToken(
dschinazi39e5e552020-05-06 13:55:24 -070010540 QuicConnectionPeer::GetPacketCreator(&connection_))
dschinazi278efae2020-01-28 17:03:09 -080010541 .empty());
dschinazi39e5e552020-05-06 13:55:24 -070010542 return;
dschinazi278efae2020-01-28 17:03:09 -080010543 }
dschinazi39e5e552020-05-06 13:55:24 -070010544
10545 // Make sure we correctly parsed the RETRY.
10546 EXPECT_TRUE(connection_.GetStats().retry_packet_processed);
10547 EXPECT_EQ(connection_.connection_id(), new_connection_id);
10548 EXPECT_EQ(QuicPacketCreatorPeer::GetRetryToken(
10549 QuicConnectionPeer::GetPacketCreator(&connection_)),
10550 retry_token);
10551 // Make sure our fake framer has the new post-retry INITIAL keys.
10552 writer_->framer()->framer()->SetInitialObfuscators(new_connection_id);
10553
10554 // Test validating the original_connection_id from the config.
10555 QuicConfig received_config;
10556 QuicConfigPeer::SetNegotiated(&received_config, true);
dschinazie7c38a52020-05-29 15:25:45 -070010557 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
10558 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
10559 &received_config, connection_.connection_id());
10560 if (!missing_retry_id_in_config) {
10561 QuicConfigPeer::SetReceivedRetrySourceConnectionId(
10562 &received_config, config_retry_source_connection_id);
10563 }
10564 }
10565 if (!missing_original_id_in_config) {
dschinazi39e5e552020-05-06 13:55:24 -070010566 QuicConfigPeer::SetReceivedOriginalConnectionId(
10567 &received_config, config_original_connection_id);
10568 }
dschinazie7c38a52020-05-29 15:25:45 -070010569
10570 if (missing_original_id_in_config || wrong_original_id_in_config ||
10571 missing_retry_id_in_config || wrong_retry_id_in_config) {
dschinazi39e5e552020-05-06 13:55:24 -070010572 EXPECT_CALL(visitor_,
10573 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10574 .Times(1);
10575 } else {
10576 EXPECT_CALL(visitor_,
10577 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10578 .Times(0);
10579 }
10580 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
10581 connection_.SetFromConfig(received_config);
dschinazie7c38a52020-05-29 15:25:45 -070010582 if (missing_original_id_in_config || wrong_original_id_in_config ||
10583 missing_retry_id_in_config || wrong_retry_id_in_config) {
10584 ASSERT_FALSE(connection_.connected());
dschinazi39e5e552020-05-06 13:55:24 -070010585 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
10586 } else {
10587 EXPECT_TRUE(connection_.connected());
10588 }
10589}
10590
10591TEST_P(QuicConnectionTest, ClientParsesRetry) {
10592 TestClientRetryHandling(/*invalid_retry_tag=*/false,
dschinazie7c38a52020-05-29 15:25:45 -070010593 /*missing_original_id_in_config=*/false,
10594 /*wrong_original_id_in_config=*/false,
10595 /*missing_retry_id_in_config=*/false,
10596 /*wrong_retry_id_in_config=*/false);
dschinazi39e5e552020-05-06 13:55:24 -070010597}
10598
dschinazie7c38a52020-05-29 15:25:45 -070010599TEST_P(QuicConnectionTest, ClientParsesRetryInvalidTag) {
dschinazi39e5e552020-05-06 13:55:24 -070010600 TestClientRetryHandling(/*invalid_retry_tag=*/true,
dschinazie7c38a52020-05-29 15:25:45 -070010601 /*missing_original_id_in_config=*/false,
10602 /*wrong_original_id_in_config=*/false,
10603 /*missing_retry_id_in_config=*/false,
10604 /*wrong_retry_id_in_config=*/false);
dschinazi39e5e552020-05-06 13:55:24 -070010605}
10606
dschinazie7c38a52020-05-29 15:25:45 -070010607TEST_P(QuicConnectionTest, ClientParsesRetryMissingOriginalId) {
dschinazi39e5e552020-05-06 13:55:24 -070010608 TestClientRetryHandling(/*invalid_retry_tag=*/false,
dschinazie7c38a52020-05-29 15:25:45 -070010609 /*missing_original_id_in_config=*/true,
10610 /*wrong_original_id_in_config=*/false,
10611 /*missing_retry_id_in_config=*/false,
10612 /*wrong_retry_id_in_config=*/false);
dschinazi39e5e552020-05-06 13:55:24 -070010613}
10614
dschinazie7c38a52020-05-29 15:25:45 -070010615TEST_P(QuicConnectionTest, ClientParsesRetryWrongOriginalId) {
dschinazi39e5e552020-05-06 13:55:24 -070010616 TestClientRetryHandling(/*invalid_retry_tag=*/false,
dschinazie7c38a52020-05-29 15:25:45 -070010617 /*missing_original_id_in_config=*/false,
10618 /*wrong_original_id_in_config=*/true,
10619 /*missing_retry_id_in_config=*/false,
10620 /*wrong_retry_id_in_config=*/false);
10621}
10622
10623TEST_P(QuicConnectionTest, ClientParsesRetryMissingRetryId) {
10624 if (!connection_.version().AuthenticatesHandshakeConnectionIds()) {
10625 // Versions that do not authenticate connection IDs never send the
10626 // retry_source_connection_id transport parameter.
10627 return;
10628 }
10629 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10630 /*missing_original_id_in_config=*/false,
10631 /*wrong_original_id_in_config=*/false,
10632 /*missing_retry_id_in_config=*/true,
10633 /*wrong_retry_id_in_config=*/false);
10634}
10635
10636TEST_P(QuicConnectionTest, ClientParsesRetryWrongRetryId) {
10637 if (!connection_.version().AuthenticatesHandshakeConnectionIds()) {
10638 // Versions that do not authenticate connection IDs never send the
10639 // retry_source_connection_id transport parameter.
10640 return;
10641 }
10642 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10643 /*missing_original_id_in_config=*/false,
10644 /*wrong_original_id_in_config=*/false,
10645 /*missing_retry_id_in_config=*/false,
10646 /*wrong_retry_id_in_config=*/true);
dschinazi39e5e552020-05-06 13:55:24 -070010647}
10648
10649TEST_P(QuicConnectionTest, ClientReceivesOriginalConnectionIdWithoutRetry) {
dschinazie7c38a52020-05-29 15:25:45 -070010650 if (!connection_.version().UsesTls()) {
10651 // QUIC+TLS is required to transmit connection ID transport parameters.
10652 return;
10653 }
10654 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
10655 // Versions that authenticate connection IDs always send the
10656 // original_destination_connection_id transport parameter.
10657 return;
10658 }
10659 // Make sure that receiving the original_destination_connection_id transport
10660 // parameter fails the handshake when no RETRY packet was received before it.
dschinazi39e5e552020-05-06 13:55:24 -070010661 QuicConfig received_config;
10662 QuicConfigPeer::SetNegotiated(&received_config, true);
10663 QuicConfigPeer::SetReceivedOriginalConnectionId(&received_config,
10664 TestConnectionId(0x12345));
10665 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
10666 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10667 .Times(1);
10668 connection_.SetFromConfig(received_config);
10669 EXPECT_FALSE(connection_.connected());
10670 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
dschinazi278efae2020-01-28 17:03:09 -080010671}
10672
dschinazie7c38a52020-05-29 15:25:45 -070010673TEST_P(QuicConnectionTest, ClientReceivesRetrySourceConnectionIdWithoutRetry) {
10674 if (!connection_.version().AuthenticatesHandshakeConnectionIds()) {
10675 // Versions that do not authenticate connection IDs never send the
10676 // retry_source_connection_id transport parameter.
10677 return;
10678 }
10679 // Make sure that receiving the retry_source_connection_id transport parameter
10680 // fails the handshake when no RETRY packet was received before it.
10681 QuicConfig received_config;
10682 QuicConfigPeer::SetNegotiated(&received_config, true);
10683 QuicConfigPeer::SetReceivedRetrySourceConnectionId(&received_config,
10684 TestConnectionId(0x12345));
10685 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
10686 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10687 .Times(1);
10688 connection_.SetFromConfig(received_config);
10689 EXPECT_FALSE(connection_.connected());
10690 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
10691}
10692
fayang0e3035e2020-02-03 13:30:36 -080010693// Regression test for http://crbug/1047977
10694TEST_P(QuicConnectionTest, MaxStreamsFrameCausesConnectionClose) {
10695 if (!VersionHasIetfQuicFrames(connection_.transport_version())) {
10696 return;
10697 }
10698 // Received frame causes connection close.
10699 EXPECT_CALL(visitor_, OnMaxStreamsFrame(_))
10700 .WillOnce(InvokeWithoutArgs([this]() {
10701 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10702 connection_.CloseConnection(
10703 QUIC_TOO_MANY_BUFFERED_CONTROL_FRAMES, "error",
10704 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10705 return true;
10706 }));
10707 QuicFrames frames;
10708 frames.push_back(QuicFrame(QuicMaxStreamsFrame()));
10709 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10710 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10711}
10712
10713TEST_P(QuicConnectionTest, StreamsBlockedFrameCausesConnectionClose) {
10714 if (!VersionHasIetfQuicFrames(connection_.transport_version())) {
10715 return;
10716 }
10717 // Received frame causes connection close.
10718 EXPECT_CALL(visitor_, OnStreamsBlockedFrame(_))
10719 .WillOnce(InvokeWithoutArgs([this]() {
10720 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10721 connection_.CloseConnection(
10722 QUIC_TOO_MANY_BUFFERED_CONTROL_FRAMES, "error",
10723 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10724 return true;
10725 }));
10726 QuicFrames frames;
10727 frames.push_back(
10728 QuicFrame(QuicStreamsBlockedFrame(kInvalidControlFrameId, 10, false)));
10729 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10730 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10731}
10732
fayang79400d52020-02-13 10:13:05 -080010733TEST_P(QuicConnectionTest,
10734 BundleAckWithConnectionCloseMultiplePacketNumberSpace) {
10735 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10736 return;
10737 }
10738 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10739 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10740 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
10741 // Receives packet 1000 in initial data.
10742 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
10743 // Receives packet 2000 in application data.
10744 ProcessDataPacketAtLevel(2000, false, ENCRYPTION_FORWARD_SECURE);
10745 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10746 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
10747 connection_.CloseConnection(
10748 kQuicErrorCode, "Some random error message",
10749 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10750
10751 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
10752
10753 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
10754 EXPECT_EQ(1u, writer_->connection_close_frames().size());
10755 // Verify ack is bundled.
10756 EXPECT_EQ(1u, writer_->ack_frames().size());
10757
10758 if (!connection_.version().CanSendCoalescedPackets()) {
10759 // Each connection close packet should be sent in distinct UDP packets.
10760 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
10761 writer_->connection_close_packets());
10762 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
10763 writer_->packets_write_attempts());
10764 return;
10765 }
10766
10767 // A single UDP packet should be sent with multiple connection close packets
10768 // coalesced together.
10769 EXPECT_EQ(1u, writer_->packets_write_attempts());
10770
10771 // Only the first packet has been processed yet.
10772 EXPECT_EQ(1u, writer_->connection_close_packets());
10773
10774 // ProcessPacket resets the visitor and frees the coalesced packet.
10775 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
10776 auto packet = writer_->coalesced_packet()->Clone();
10777 writer_->framer()->ProcessPacket(*packet);
10778 EXPECT_EQ(1u, writer_->connection_close_packets());
10779 EXPECT_EQ(1u, writer_->connection_close_frames().size());
10780 // Verify ack is bundled.
10781 EXPECT_EQ(1u, writer_->ack_frames().size());
10782 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
10783}
10784
fayang61453cb2020-03-11 11:32:26 -070010785// Regression test for b/151220135.
10786TEST_P(QuicConnectionTest, SendPingWhenSkipPacketNumberForPto) {
10787 if (!VersionSupportsMessageFrames(connection_.transport_version())) {
10788 return;
10789 }
10790 QuicConfig config;
10791 QuicTagVector connection_options;
10792 connection_options.push_back(kPTOS);
10793 connection_options.push_back(k1PTO);
10794 config.SetConnectionOptionsToSend(connection_options);
dschinazied459c02020-05-07 16:12:23 -070010795 if (connection_.version().UsesTls()) {
10796 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
10797 &config, kMaxAcceptedDatagramFrameSize);
10798 }
fayang61453cb2020-03-11 11:32:26 -070010799 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10800 connection_.SetFromConfig(config);
10801 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
10802
10803 EXPECT_EQ(MESSAGE_STATUS_SUCCESS, SendMessage("message"));
10804 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
10805
fayang80f9cc62020-04-22 08:08:20 -070010806 // PTO fires, verify a PING packet gets sent because there is no data to
10807 // send.
10808 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(3), _, _));
10809 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
fayang61453cb2020-03-11 11:32:26 -070010810 connection_.GetRetransmissionAlarm()->Fire();
fayang80f9cc62020-04-22 08:08:20 -070010811 EXPECT_EQ(1u, connection_.GetStats().pto_count);
10812 EXPECT_EQ(0u, connection_.GetStats().crypto_retransmit_count);
10813 EXPECT_EQ(1u, writer_->ping_frames().size());
fayang61453cb2020-03-11 11:32:26 -070010814}
10815
fayangcc210e72020-05-05 14:41:34 -070010816// Regression test for b/155757133
10817TEST_P(QuicConnectionTest, DonotChangeQueuedAcks) {
10818 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10819 return;
10820 }
10821 const size_t kMinRttMs = 40;
10822 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
10823 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
10824 QuicTime::Delta::Zero(), QuicTime::Zero());
10825 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10826 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
10827 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10828
10829 ProcessPacket(2);
10830 ProcessPacket(3);
10831 ProcessPacket(4);
10832 // Process a packet containing stream frame followed by ACK of packets 1.
10833 QuicFrames frames;
10834 frames.push_back(QuicFrame(QuicStreamFrame(
10835 QuicUtils::GetFirstBidirectionalStreamId(
10836 connection_.version().transport_version, Perspective::IS_CLIENT),
10837 false, 0u, quiche::QuicheStringPiece())));
10838 QuicAckFrame ack_frame = InitAckFrame(1);
10839 frames.push_back(QuicFrame(&ack_frame));
10840 // Receiving stream frame causes something to send.
10841 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([this]() {
10842 connection_.SendControlFrame(QuicFrame(new QuicWindowUpdateFrame(1, 0, 0)));
10843 // Verify now the queued ACK contains packet number 2.
10844 EXPECT_TRUE(QuicPacketCreatorPeer::QueuedFrames(
10845 QuicConnectionPeer::GetPacketCreator(&connection_))[0]
10846 .ack_frame->packets.Contains(QuicPacketNumber(2)));
10847 }));
10848 ProcessFramesPacketAtLevel(9, frames, ENCRYPTION_FORWARD_SECURE);
10849 if (GetQuicReloadableFlag(quic_donot_change_queued_ack)) {
10850 EXPECT_TRUE(writer_->ack_frames()[0].packets.Contains(QuicPacketNumber(2)));
10851 } else {
10852 // ACK frame changes mid packet serialiation!
10853 EXPECT_FALSE(
10854 writer_->ack_frames()[0].packets.Contains(QuicPacketNumber(2)));
10855 }
10856}
10857
fayange9304002020-05-07 11:57:48 -070010858TEST_P(QuicConnectionTest, DonotExtendIdleTimeOnUndecryptablePackets) {
10859 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10860 QuicConfig config;
10861 connection_.SetFromConfig(config);
10862 // Subtract a second from the idle timeout on the client side.
10863 QuicTime initial_deadline =
10864 clock_.ApproximateNow() +
10865 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
10866 EXPECT_EQ(initial_deadline, connection_.GetTimeoutAlarm()->deadline());
10867
10868 // Received an undecryptable packet.
10869 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
10870 const uint8_t tag = 0x07;
10871 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
10872 std::make_unique<TaggingEncrypter>(tag));
10873 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
fayang2205d952020-05-12 13:45:56 -070010874 if (GetQuicReloadableFlag(quic_extend_idle_time_on_decryptable_packets)) {
fayange9304002020-05-07 11:57:48 -070010875 // Verify deadline does not get extended.
10876 EXPECT_EQ(initial_deadline, connection_.GetTimeoutAlarm()->deadline());
10877 }
10878 if (GetQuicReloadableFlag(quic_extend_idle_time_on_decryptable_packets)) {
10879 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
10880 } else {
10881 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
10882 }
10883 QuicTime::Delta delay = initial_deadline - clock_.ApproximateNow();
10884 clock_.AdvanceTime(delay);
fayang2205d952020-05-12 13:45:56 -070010885 if (GetQuicReloadableFlag(quic_extend_idle_time_on_decryptable_packets)) {
fayange9304002020-05-07 11:57:48 -070010886 connection_.GetTimeoutAlarm()->Fire();
10887 }
10888 if (GetQuicReloadableFlag(quic_extend_idle_time_on_decryptable_packets)) {
10889 // Verify connection gets closed.
10890 EXPECT_FALSE(connection_.connected());
10891 } else {
10892 // Verify the timeout alarm deadline is updated.
10893 EXPECT_TRUE(connection_.connected());
10894 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
10895 }
10896}
10897
fayang9f430a52020-05-08 07:28:33 -070010898TEST_P(QuicConnectionTest, BundleAckWithImmediateResponse) {
10899 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10900 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10901
10902 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([this]() {
10903 connection_.SendControlFrame(QuicFrame(new QuicWindowUpdateFrame(1, 0, 0)));
10904 }));
10905 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10906 ProcessDataPacket(1);
fayang9f430a52020-05-08 07:28:33 -070010907 if (GetQuicReloadableFlag(quic_advance_ack_timeout_update)) {
10908 // Verify ACK is bundled with WINDOW_UPDATE.
10909 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -070010910 EXPECT_FALSE(connection_.HasPendingAcks());
fayang9f430a52020-05-08 07:28:33 -070010911 } else {
10912 // ACK is pending.
10913 EXPECT_TRUE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -070010914 EXPECT_TRUE(connection_.HasPendingAcks());
fayang9f430a52020-05-08 07:28:33 -070010915 }
10916}
10917
fayangf44a6672020-05-27 12:51:45 -070010918TEST_P(QuicConnectionTest, AckAlarmFiresEarly) {
10919 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10920 return;
10921 }
10922 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10923 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
10924 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10925 }
10926 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
10927 use_tagging_decrypter();
10928 // Receives packet 1000 in initial data.
10929 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
fayang9adfb532020-06-04 06:58:45 -070010930 EXPECT_TRUE(connection_.HasPendingAcks());
fayangf44a6672020-05-27 12:51:45 -070010931
10932 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
10933 std::make_unique<TaggingEncrypter>(0x02));
10934 SetDecrypter(ENCRYPTION_ZERO_RTT,
10935 std::make_unique<StrictTaggingDecrypter>(0x02));
10936 connection_.SetEncrypter(ENCRYPTION_INITIAL,
10937 std::make_unique<TaggingEncrypter>(0x02));
10938 // Receives packet 1000 in application data.
10939 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
fayang9adfb532020-06-04 06:58:45 -070010940 EXPECT_TRUE(connection_.HasPendingAcks());
fayangf44a6672020-05-27 12:51:45 -070010941 // Verify ACK deadline does not change.
10942 EXPECT_EQ(clock_.ApproximateNow() + kAlarmGranularity,
10943 connection_.GetAckAlarm()->deadline());
10944
10945 // Ack alarm fires early.
10946 if (GetQuicReloadableFlag(quic_always_send_earliest_ack)) {
10947 // Verify the earliest ACK is flushed.
10948 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10949 } else {
10950 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
10951 }
10952 connection_.GetAckAlarm()->Fire();
fayang9adfb532020-06-04 06:58:45 -070010953 EXPECT_TRUE(connection_.HasPendingAcks());
fayangf44a6672020-05-27 12:51:45 -070010954 if (GetQuicReloadableFlag(quic_always_send_earliest_ack)) {
10955 EXPECT_EQ(clock_.ApproximateNow() + DefaultDelayedAckTime(),
10956 connection_.GetAckAlarm()->deadline());
10957 } else {
10958 // No forward progress has been made.
10959 EXPECT_EQ(clock_.ApproximateNow() + kAlarmGranularity,
10960 connection_.GetAckAlarm()->deadline());
10961 }
10962}
10963
fayangf78b6932020-06-08 08:36:45 -070010964TEST_P(QuicConnectionTest, ClientOnlyBlackholeDetectionClient) {
10965 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection)) {
10966 return;
10967 }
10968 QuicConfig config;
10969 QuicTagVector connection_options;
10970 connection_options.push_back(kCBHD);
10971 config.SetConnectionOptionsToSend(connection_options);
10972 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10973 connection_.SetFromConfig(config);
10974 EXPECT_CALL(visitor_, GetHandshakeState())
10975 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
10976 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
10977 // Send stream data.
10978 SendStreamDataToPeer(
10979 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
10980 0, FIN, nullptr);
10981 // Verify blackhole detection is in progress.
10982 EXPECT_TRUE(connection_.GetBlackholeDetectorAlarm()->IsSet());
10983}
10984
10985TEST_P(QuicConnectionTest, ClientOnlyBlackholeDetectionServer) {
10986 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection)) {
10987 return;
10988 }
10989 set_perspective(Perspective::IS_SERVER);
10990 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
10991 if (version().SupportsAntiAmplificationLimit()) {
10992 QuicConnectionPeer::SetAddressValidated(&connection_);
10993 }
10994 QuicConfig config;
10995 QuicTagVector connection_options;
10996 connection_options.push_back(kCBHD);
10997 config.SetInitialReceivedConnectionOptions(connection_options);
10998 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10999 connection_.SetFromConfig(config);
11000 EXPECT_CALL(visitor_, GetHandshakeState())
11001 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
11002 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
11003 // Send stream data.
11004 SendStreamDataToPeer(
11005 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
11006 0, FIN, nullptr);
11007 // Verify blackhole detection is disabled.
11008 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
11009}
11010
11011TEST_P(QuicConnectionTest, 2RtoBlackholeDetection) {
11012 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection)) {
11013 return;
11014 }
11015 QuicConfig config;
11016 QuicTagVector connection_options;
11017 connection_options.push_back(k2RTO);
11018 config.SetConnectionOptionsToSend(connection_options);
11019 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11020 connection_.SetFromConfig(config);
11021 const size_t kMinRttMs = 40;
11022 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
11023 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
11024 QuicTime::Delta::Zero(), QuicTime::Zero());
11025 EXPECT_CALL(visitor_, GetHandshakeState())
11026 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
11027 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
11028 // Send stream data.
11029 SendStreamDataToPeer(
11030 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
11031 0, FIN, nullptr);
11032 // Verify blackhole delay is expected.
11033 EXPECT_EQ(clock_.Now() +
11034 connection_.sent_packet_manager().GetNetworkBlackholeDelay(2),
11035 QuicConnectionPeer::GetBlackholeDetectionDeadline(&connection_));
11036}
11037
11038TEST_P(QuicConnectionTest, 3RtoBlackholeDetection) {
11039 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection)) {
11040 return;
11041 }
11042 QuicConfig config;
11043 QuicTagVector connection_options;
11044 connection_options.push_back(k3RTO);
11045 config.SetConnectionOptionsToSend(connection_options);
11046 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11047 connection_.SetFromConfig(config);
11048 const size_t kMinRttMs = 40;
11049 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
11050 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
11051 QuicTime::Delta::Zero(), QuicTime::Zero());
11052 EXPECT_CALL(visitor_, GetHandshakeState())
11053 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
11054 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
11055 // Send stream data.
11056 SendStreamDataToPeer(
11057 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
11058 0, FIN, nullptr);
11059 // Verify blackhole delay is expected.
11060 EXPECT_EQ(clock_.Now() +
11061 connection_.sent_packet_manager().GetNetworkBlackholeDelay(3),
11062 QuicConnectionPeer::GetBlackholeDetectionDeadline(&connection_));
11063}
11064
11065TEST_P(QuicConnectionTest, 4RtoBlackholeDetection) {
11066 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection)) {
11067 return;
11068 }
11069 QuicConfig config;
11070 QuicTagVector connection_options;
11071 connection_options.push_back(k4RTO);
11072 config.SetConnectionOptionsToSend(connection_options);
11073 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11074 connection_.SetFromConfig(config);
11075 const size_t kMinRttMs = 40;
11076 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
11077 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
11078 QuicTime::Delta::Zero(), QuicTime::Zero());
11079 EXPECT_CALL(visitor_, GetHandshakeState())
11080 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
11081 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
11082 // Send stream data.
11083 SendStreamDataToPeer(
11084 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
11085 0, FIN, nullptr);
11086 // Verify blackhole delay is expected.
11087 EXPECT_EQ(clock_.Now() +
11088 connection_.sent_packet_manager().GetNetworkBlackholeDelay(4),
11089 QuicConnectionPeer::GetBlackholeDetectionDeadline(&connection_));
11090}
11091
11092TEST_P(QuicConnectionTest, 6RtoBlackholeDetection) {
11093 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection)) {
11094 return;
11095 }
11096 QuicConfig config;
11097 QuicTagVector connection_options;
11098 connection_options.push_back(k6RTO);
11099 config.SetConnectionOptionsToSend(connection_options);
11100 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11101 connection_.SetFromConfig(config);
11102 const size_t kMinRttMs = 40;
11103 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
11104 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
11105 QuicTime::Delta::Zero(), QuicTime::Zero());
11106 EXPECT_CALL(visitor_, GetHandshakeState())
11107 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
11108 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
11109 // Send stream data.
11110 SendStreamDataToPeer(
11111 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
11112 0, FIN, nullptr);
11113 // Verify blackhole delay is expected.
11114 EXPECT_EQ(clock_.Now() +
11115 connection_.sent_packet_manager().GetNetworkBlackholeDelay(6),
11116 QuicConnectionPeer::GetBlackholeDetectionDeadline(&connection_));
11117}
11118
QUICHE teama6ef0a62019-03-07 20:34:33 -050011119} // namespace
11120} // namespace test
11121} // namespace quic