blob: f3bb4e11dad726300f93e157d414bfec2aaccd54 [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"
21#include "net/third_party/quiche/src/quic/core/quic_packets.h"
22#include "net/third_party/quiche/src/quic/core/quic_simple_buffer_allocator.h"
23#include "net/third_party/quiche/src/quic/core/quic_types.h"
24#include "net/third_party/quiche/src/quic/core/quic_utils.h"
dschinazi278efae2020-01-28 17:03:09 -080025#include "net/third_party/quiche/src/quic/core/quic_versions.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050026#include "net/third_party/quiche/src/quic/platform/api/quic_error_code_wrappers.h"
27#include "net/third_party/quiche/src/quic/platform/api/quic_expect_bug.h"
28#include "net/third_party/quiche/src/quic/platform/api/quic_flags.h"
29#include "net/third_party/quiche/src/quic/platform/api/quic_logging.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050030#include "net/third_party/quiche/src/quic/platform/api/quic_reference_counted.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050031#include "net/third_party/quiche/src/quic/platform/api/quic_test.h"
32#include "net/third_party/quiche/src/quic/test_tools/mock_clock.h"
33#include "net/third_party/quiche/src/quic/test_tools/mock_random.h"
34#include "net/third_party/quiche/src/quic/test_tools/quic_config_peer.h"
35#include "net/third_party/quiche/src/quic/test_tools/quic_connection_peer.h"
36#include "net/third_party/quiche/src/quic/test_tools/quic_framer_peer.h"
37#include "net/third_party/quiche/src/quic/test_tools/quic_packet_creator_peer.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050038#include "net/third_party/quiche/src/quic/test_tools/quic_sent_packet_manager_peer.h"
39#include "net/third_party/quiche/src/quic/test_tools/quic_test_utils.h"
40#include "net/third_party/quiche/src/quic/test_tools/simple_data_producer.h"
41#include "net/third_party/quiche/src/quic/test_tools/simple_quic_framer.h"
42#include "net/third_party/quiche/src/quic/test_tools/simple_session_notifier.h"
dschinazi278efae2020-01-28 17:03:09 -080043#include "net/third_party/quiche/src/common/platform/api/quiche_arraysize.h"
dmcardlecf0bfcf2019-12-13 08:08:21 -080044#include "net/third_party/quiche/src/common/platform/api/quiche_str_cat.h"
45#include "net/third_party/quiche/src/common/platform/api/quiche_string_piece.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050046
47using testing::_;
48using testing::AnyNumber;
49using testing::AtLeast;
50using testing::DoAll;
51using testing::Exactly;
52using testing::Ge;
53using testing::IgnoreResult;
54using testing::InSequence;
55using testing::Invoke;
56using testing::InvokeWithoutArgs;
57using testing::Lt;
58using testing::Ref;
59using testing::Return;
60using testing::SaveArg;
61using testing::SetArgPointee;
62using testing::StrictMock;
63
64namespace quic {
65namespace test {
66namespace {
67
nharper55fa6132019-05-07 19:37:21 -070068const char data1[] = "foo data";
69const char data2[] = "bar data";
QUICHE teama6ef0a62019-03-07 20:34:33 -050070
71const bool kHasStopWaiting = true;
72
73const int kDefaultRetransmissionTimeMs = 500;
74
QUICHE team548d51b2019-03-14 10:06:54 -070075DiversificationNonce kTestDiversificationNonce = {
76 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a',
77 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b',
78 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b',
79};
80
QUICHE teama6ef0a62019-03-07 20:34:33 -050081const QuicSocketAddress kPeerAddress =
82 QuicSocketAddress(QuicIpAddress::Loopback6(),
83 /*port=*/12345);
84const QuicSocketAddress kSelfAddress =
85 QuicSocketAddress(QuicIpAddress::Loopback6(),
86 /*port=*/443);
87
QUICHE teama6ef0a62019-03-07 20:34:33 -050088QuicStreamId GetNthClientInitiatedStreamId(int n,
89 QuicTransportVersion version) {
dschinazi552accc2019-06-17 17:07:34 -070090 return QuicUtils::GetFirstBidirectionalStreamId(version,
91 Perspective::IS_CLIENT) +
92 n * 2;
QUICHE teama6ef0a62019-03-07 20:34:33 -050093}
94
QUICHE team8c1daa22019-03-13 08:33:41 -070095QuicLongHeaderType EncryptionlevelToLongHeaderType(EncryptionLevel level) {
96 switch (level) {
QUICHE team6987b4a2019-03-15 16:23:04 -070097 case ENCRYPTION_INITIAL:
QUICHE team8c1daa22019-03-13 08:33:41 -070098 return INITIAL;
QUICHE team88ea0082019-03-15 10:05:26 -070099 case ENCRYPTION_HANDSHAKE:
100 return HANDSHAKE;
QUICHE team8c1daa22019-03-13 08:33:41 -0700101 case ENCRYPTION_ZERO_RTT:
102 return ZERO_RTT_PROTECTED;
103 case ENCRYPTION_FORWARD_SECURE:
104 DCHECK(false);
105 return INVALID_PACKET_TYPE;
106 default:
107 DCHECK(false);
108 return INVALID_PACKET_TYPE;
109 }
110}
111
QUICHE teama6ef0a62019-03-07 20:34:33 -0500112// TaggingEncrypter appends kTagSize bytes of |tag| to the end of each message.
113class TaggingEncrypter : public QuicEncrypter {
114 public:
115 explicit TaggingEncrypter(uint8_t tag) : tag_(tag) {}
116 TaggingEncrypter(const TaggingEncrypter&) = delete;
117 TaggingEncrypter& operator=(const TaggingEncrypter&) = delete;
118
119 ~TaggingEncrypter() override {}
120
121 // QuicEncrypter interface.
dmcardlecf0bfcf2019-12-13 08:08:21 -0800122 bool SetKey(quiche::QuicheStringPiece /*key*/) override { return true; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500123
dmcardlecf0bfcf2019-12-13 08:08:21 -0800124 bool SetNoncePrefix(quiche::QuicheStringPiece /*nonce_prefix*/) override {
dschinazi17d42422019-06-18 16:35:07 -0700125 return true;
126 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500127
dmcardlecf0bfcf2019-12-13 08:08:21 -0800128 bool SetIV(quiche::QuicheStringPiece /*iv*/) override { return true; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500129
dmcardlecf0bfcf2019-12-13 08:08:21 -0800130 bool SetHeaderProtectionKey(quiche::QuicheStringPiece /*key*/) override {
131 return true;
132 }
QUICHE team2d187972019-03-19 16:23:47 -0700133
dschinazi17d42422019-06-18 16:35:07 -0700134 bool EncryptPacket(uint64_t /*packet_number*/,
dmcardlecf0bfcf2019-12-13 08:08:21 -0800135 quiche::QuicheStringPiece /*associated_data*/,
136 quiche::QuicheStringPiece plaintext,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500137 char* output,
138 size_t* output_length,
139 size_t max_output_length) override {
140 const size_t len = plaintext.size() + kTagSize;
141 if (max_output_length < len) {
142 return false;
143 }
144 // Memmove is safe for inplace encryption.
145 memmove(output, plaintext.data(), plaintext.size());
146 output += plaintext.size();
147 memset(output, tag_, kTagSize);
148 *output_length = len;
149 return true;
150 }
151
dschinazi17d42422019-06-18 16:35:07 -0700152 std::string GenerateHeaderProtectionMask(
dmcardlecf0bfcf2019-12-13 08:08:21 -0800153 quiche::QuicheStringPiece /*sample*/) override {
QUICHE team2d187972019-03-19 16:23:47 -0700154 return std::string(5, 0);
155 }
156
QUICHE teama6ef0a62019-03-07 20:34:33 -0500157 size_t GetKeySize() const override { return 0; }
158 size_t GetNoncePrefixSize() const override { return 0; }
159 size_t GetIVSize() const override { return 0; }
160
161 size_t GetMaxPlaintextSize(size_t ciphertext_size) const override {
162 return ciphertext_size - kTagSize;
163 }
164
165 size_t GetCiphertextSize(size_t plaintext_size) const override {
166 return plaintext_size + kTagSize;
167 }
168
dmcardlecf0bfcf2019-12-13 08:08:21 -0800169 quiche::QuicheStringPiece GetKey() const override {
170 return quiche::QuicheStringPiece();
171 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500172
dmcardlecf0bfcf2019-12-13 08:08:21 -0800173 quiche::QuicheStringPiece GetNoncePrefix() const override {
174 return quiche::QuicheStringPiece();
175 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500176
177 private:
178 enum {
179 kTagSize = 12,
180 };
181
182 const uint8_t tag_;
183};
184
185// TaggingDecrypter ensures that the final kTagSize bytes of the message all
186// have the same value and then removes them.
187class TaggingDecrypter : public QuicDecrypter {
188 public:
189 ~TaggingDecrypter() override {}
190
191 // QuicDecrypter interface
dmcardlecf0bfcf2019-12-13 08:08:21 -0800192 bool SetKey(quiche::QuicheStringPiece /*key*/) override { return true; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500193
dmcardlecf0bfcf2019-12-13 08:08:21 -0800194 bool SetNoncePrefix(quiche::QuicheStringPiece /*nonce_prefix*/) override {
dschinazi17d42422019-06-18 16:35:07 -0700195 return true;
196 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500197
dmcardlecf0bfcf2019-12-13 08:08:21 -0800198 bool SetIV(quiche::QuicheStringPiece /*iv*/) override { return true; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500199
dmcardlecf0bfcf2019-12-13 08:08:21 -0800200 bool SetHeaderProtectionKey(quiche::QuicheStringPiece /*key*/) override {
201 return true;
202 }
QUICHE team2d187972019-03-19 16:23:47 -0700203
dmcardlecf0bfcf2019-12-13 08:08:21 -0800204 bool SetPreliminaryKey(quiche::QuicheStringPiece /*key*/) override {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500205 QUIC_BUG << "should not be called";
206 return false;
207 }
208
dschinazi17d42422019-06-18 16:35:07 -0700209 bool SetDiversificationNonce(const DiversificationNonce& /*key*/) override {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500210 return true;
211 }
212
dschinazi17d42422019-06-18 16:35:07 -0700213 bool DecryptPacket(uint64_t /*packet_number*/,
dmcardlecf0bfcf2019-12-13 08:08:21 -0800214 quiche::QuicheStringPiece /*associated_data*/,
215 quiche::QuicheStringPiece ciphertext,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500216 char* output,
217 size_t* output_length,
dschinazi17d42422019-06-18 16:35:07 -0700218 size_t /*max_output_length*/) override {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500219 if (ciphertext.size() < kTagSize) {
220 return false;
221 }
222 if (!CheckTag(ciphertext, GetTag(ciphertext))) {
223 return false;
224 }
225 *output_length = ciphertext.size() - kTagSize;
226 memcpy(output, ciphertext.data(), *output_length);
227 return true;
228 }
229
QUICHE team2d187972019-03-19 16:23:47 -0700230 std::string GenerateHeaderProtectionMask(
dschinazi17d42422019-06-18 16:35:07 -0700231 QuicDataReader* /*sample_reader*/) override {
QUICHE team2d187972019-03-19 16:23:47 -0700232 return std::string(5, 0);
233 }
234
QUICHE teama6ef0a62019-03-07 20:34:33 -0500235 size_t GetKeySize() const override { return 0; }
nharper965e5922019-09-23 22:33:54 -0700236 size_t GetNoncePrefixSize() const override { return 0; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500237 size_t GetIVSize() const override { return 0; }
dmcardlecf0bfcf2019-12-13 08:08:21 -0800238 quiche::QuicheStringPiece GetKey() const override {
239 return quiche::QuicheStringPiece();
240 }
241 quiche::QuicheStringPiece GetNoncePrefix() const override {
242 return quiche::QuicheStringPiece();
243 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500244 // Use a distinct value starting with 0xFFFFFF, which is never used by TLS.
245 uint32_t cipher_id() const override { return 0xFFFFFFF0; }
246
247 protected:
dmcardlecf0bfcf2019-12-13 08:08:21 -0800248 virtual uint8_t GetTag(quiche::QuicheStringPiece ciphertext) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500249 return ciphertext.data()[ciphertext.size() - 1];
250 }
251
252 private:
253 enum {
254 kTagSize = 12,
255 };
256
dmcardlecf0bfcf2019-12-13 08:08:21 -0800257 bool CheckTag(quiche::QuicheStringPiece ciphertext, uint8_t tag) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500258 for (size_t i = ciphertext.size() - kTagSize; i < ciphertext.size(); i++) {
259 if (ciphertext.data()[i] != tag) {
260 return false;
261 }
262 }
263
264 return true;
265 }
266};
267
268// StringTaggingDecrypter ensures that the final kTagSize bytes of the message
269// match the expected value.
270class StrictTaggingDecrypter : public TaggingDecrypter {
271 public:
272 explicit StrictTaggingDecrypter(uint8_t tag) : tag_(tag) {}
273 ~StrictTaggingDecrypter() override {}
274
275 // TaggingQuicDecrypter
dmcardlecf0bfcf2019-12-13 08:08:21 -0800276 uint8_t GetTag(quiche::QuicheStringPiece /*ciphertext*/) override {
277 return tag_;
278 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500279
280 // Use a distinct value starting with 0xFFFFFF, which is never used by TLS.
281 uint32_t cipher_id() const override { return 0xFFFFFFF1; }
282
283 private:
284 const uint8_t tag_;
285};
286
287class TestConnectionHelper : public QuicConnectionHelperInterface {
288 public:
289 TestConnectionHelper(MockClock* clock, MockRandom* random_generator)
290 : clock_(clock), random_generator_(random_generator) {
291 clock_->AdvanceTime(QuicTime::Delta::FromSeconds(1));
292 }
293 TestConnectionHelper(const TestConnectionHelper&) = delete;
294 TestConnectionHelper& operator=(const TestConnectionHelper&) = delete;
295
296 // QuicConnectionHelperInterface
297 const QuicClock* GetClock() const override { return clock_; }
298
299 QuicRandom* GetRandomGenerator() override { return random_generator_; }
300
301 QuicBufferAllocator* GetStreamSendBufferAllocator() override {
302 return &buffer_allocator_;
303 }
304
305 private:
306 MockClock* clock_;
307 MockRandom* random_generator_;
308 SimpleBufferAllocator buffer_allocator_;
309};
310
311class TestAlarmFactory : public QuicAlarmFactory {
312 public:
313 class TestAlarm : public QuicAlarm {
314 public:
315 explicit TestAlarm(QuicArenaScopedPtr<QuicAlarm::Delegate> delegate)
316 : QuicAlarm(std::move(delegate)) {}
317
318 void SetImpl() override {}
319 void CancelImpl() override {}
320 using QuicAlarm::Fire;
321 };
322
323 TestAlarmFactory() {}
324 TestAlarmFactory(const TestAlarmFactory&) = delete;
325 TestAlarmFactory& operator=(const TestAlarmFactory&) = delete;
326
327 QuicAlarm* CreateAlarm(QuicAlarm::Delegate* delegate) override {
328 return new TestAlarm(QuicArenaScopedPtr<QuicAlarm::Delegate>(delegate));
329 }
330
331 QuicArenaScopedPtr<QuicAlarm> CreateAlarm(
332 QuicArenaScopedPtr<QuicAlarm::Delegate> delegate,
333 QuicConnectionArena* arena) override {
334 return arena->New<TestAlarm>(std::move(delegate));
335 }
336};
337
338class TestPacketWriter : public QuicPacketWriter {
339 public:
340 TestPacketWriter(ParsedQuicVersion version, MockClock* clock)
341 : version_(version),
342 framer_(SupportedVersions(version_), Perspective::IS_SERVER),
wubb442b862020-01-31 08:16:21 -0800343 clock_(clock) {
dschinazib953d022019-08-01 18:05:58 -0700344 QuicFramerPeer::SetLastSerializedServerConnectionId(framer_.framer(),
345 TestConnectionId());
nharperc6b99512019-09-19 11:13:48 -0700346 framer_.framer()->SetInitialObfuscators(TestConnectionId());
dschinazib953d022019-08-01 18:05:58 -0700347 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500348 TestPacketWriter(const TestPacketWriter&) = delete;
349 TestPacketWriter& operator=(const TestPacketWriter&) = delete;
350
351 // QuicPacketWriter interface
352 WriteResult WritePacket(const char* buffer,
353 size_t buf_len,
dschinazi17d42422019-06-18 16:35:07 -0700354 const QuicIpAddress& /*self_address*/,
355 const QuicSocketAddress& /*peer_address*/,
356 PerPacketOptions* /*options*/) override {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500357 QuicEncryptedPacket packet(buffer, buf_len);
358 ++packets_write_attempts_;
359
360 if (packet.length() >= sizeof(final_bytes_of_last_packet_)) {
361 final_bytes_of_previous_packet_ = final_bytes_of_last_packet_;
362 memcpy(&final_bytes_of_last_packet_, packet.data() + packet.length() - 4,
363 sizeof(final_bytes_of_last_packet_));
364 }
365
366 if (use_tagging_decrypter_) {
zhongyi546cc452019-04-12 15:27:49 -0700367 if (framer_.framer()->version().KnowsWhichDecrypterToUse()) {
vasilvv0fc587f2019-09-06 13:33:08 -0700368 framer_.framer()->InstallDecrypter(
369 ENCRYPTION_INITIAL, std::make_unique<TaggingDecrypter>());
370 framer_.framer()->InstallDecrypter(
fayang18ff23b2020-01-28 09:19:00 -0800371 ENCRYPTION_HANDSHAKE, std::make_unique<TaggingDecrypter>());
372 framer_.framer()->InstallDecrypter(
vasilvv0fc587f2019-09-06 13:33:08 -0700373 ENCRYPTION_ZERO_RTT, std::make_unique<TaggingDecrypter>());
374 framer_.framer()->InstallDecrypter(
375 ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingDecrypter>());
zhongyi546cc452019-04-12 15:27:49 -0700376 } else {
377 framer_.framer()->SetDecrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -0700378 std::make_unique<TaggingDecrypter>());
zhongyi546cc452019-04-12 15:27:49 -0700379 }
380 } else if (framer_.framer()->version().KnowsWhichDecrypterToUse()) {
381 framer_.framer()->InstallDecrypter(
382 ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -0700383 std::make_unique<NullDecrypter>(Perspective::IS_SERVER));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500384 }
dschinazi39e5e552020-05-06 13:55:24 -0700385 EXPECT_TRUE(framer_.ProcessPacket(packet))
386 << framer_.framer()->detailed_error();
QUICHE teama6ef0a62019-03-07 20:34:33 -0500387 if (block_on_next_write_) {
388 write_blocked_ = true;
389 block_on_next_write_ = false;
390 }
391 if (next_packet_too_large_) {
392 next_packet_too_large_ = false;
393 return WriteResult(WRITE_STATUS_ERROR, QUIC_EMSGSIZE);
394 }
395 if (always_get_packet_too_large_) {
396 return WriteResult(WRITE_STATUS_ERROR, QUIC_EMSGSIZE);
397 }
398 if (IsWriteBlocked()) {
399 return WriteResult(is_write_blocked_data_buffered_
400 ? WRITE_STATUS_BLOCKED_DATA_BUFFERED
401 : WRITE_STATUS_BLOCKED,
402 0);
403 }
404
405 if (ShouldWriteFail()) {
406 return WriteResult(WRITE_STATUS_ERROR, 0);
407 }
408
409 last_packet_size_ = packet.length();
410 last_packet_header_ = framer_.header();
rchd672c6d2019-11-27 15:30:54 -0800411 if (!framer_.connection_close_frames().empty()) {
412 ++connection_close_packets_;
413 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500414 if (!write_pause_time_delta_.IsZero()) {
415 clock_->AdvanceTime(write_pause_time_delta_);
416 }
wubb442b862020-01-31 08:16:21 -0800417 if (is_batch_mode_) {
418 bytes_buffered_ += last_packet_size_;
419 return WriteResult(WRITE_STATUS_OK, 0);
420 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500421 return WriteResult(WRITE_STATUS_OK, last_packet_size_);
422 }
423
424 bool ShouldWriteFail() { return write_should_fail_; }
425
426 bool IsWriteBlocked() const override { return write_blocked_; }
427
428 void SetWriteBlocked() { write_blocked_ = true; }
429
430 void SetWritable() override { write_blocked_ = false; }
431
432 void SetShouldWriteFail() { write_should_fail_ = true; }
433
434 QuicByteCount GetMaxPacketSize(
435 const QuicSocketAddress& /*peer_address*/) const override {
436 return max_packet_size_;
437 }
438
dschinazi61eb6432019-06-14 16:27:16 -0700439 bool SupportsReleaseTime() const override { return supports_release_time_; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500440
441 bool IsBatchMode() const override { return is_batch_mode_; }
442
dschinazi17d42422019-06-18 16:35:07 -0700443 char* GetNextWriteLocation(
444 const QuicIpAddress& /*self_address*/,
445 const QuicSocketAddress& /*peer_address*/) override {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500446 return nullptr;
447 }
448
449 WriteResult Flush() override {
wubb442b862020-01-31 08:16:21 -0800450 flush_attempts_++;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500451 if (block_on_next_flush_) {
452 block_on_next_flush_ = false;
453 SetWriteBlocked();
454 return WriteResult(WRITE_STATUS_BLOCKED, /*errno*/ -1);
455 }
wub748e20b2020-03-20 14:33:59 -0700456 if (write_should_fail_) {
457 return WriteResult(WRITE_STATUS_ERROR, /*errno*/ -1);
458 }
wubb442b862020-01-31 08:16:21 -0800459 int bytes_flushed = bytes_buffered_;
460 bytes_buffered_ = 0;
461 return WriteResult(WRITE_STATUS_OK, bytes_flushed);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500462 }
463
464 void BlockOnNextFlush() { block_on_next_flush_ = true; }
465
466 void BlockOnNextWrite() { block_on_next_write_ = true; }
467
468 void SimulateNextPacketTooLarge() { next_packet_too_large_ = true; }
469
470 void AlwaysGetPacketTooLarge() { always_get_packet_too_large_ = true; }
471
472 // Sets the amount of time that the writer should before the actual write.
473 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
474 write_pause_time_delta_ = delta;
475 }
476
477 void SetBatchMode(bool new_value) { is_batch_mode_ = new_value; }
478
479 const QuicPacketHeader& header() { return framer_.header(); }
480
481 size_t frame_count() const { return framer_.num_frames(); }
482
483 const std::vector<QuicAckFrame>& ack_frames() const {
484 return framer_.ack_frames();
485 }
486
487 const std::vector<QuicStopWaitingFrame>& stop_waiting_frames() const {
488 return framer_.stop_waiting_frames();
489 }
490
491 const std::vector<QuicConnectionCloseFrame>& connection_close_frames() const {
492 return framer_.connection_close_frames();
493 }
494
495 const std::vector<QuicRstStreamFrame>& rst_stream_frames() const {
496 return framer_.rst_stream_frames();
497 }
498
499 const std::vector<std::unique_ptr<QuicStreamFrame>>& stream_frames() const {
500 return framer_.stream_frames();
501 }
502
503 const std::vector<std::unique_ptr<QuicCryptoFrame>>& crypto_frames() const {
504 return framer_.crypto_frames();
505 }
506
507 const std::vector<QuicPingFrame>& ping_frames() const {
508 return framer_.ping_frames();
509 }
510
511 const std::vector<QuicMessageFrame>& message_frames() const {
512 return framer_.message_frames();
513 }
514
515 const std::vector<QuicWindowUpdateFrame>& window_update_frames() const {
516 return framer_.window_update_frames();
517 }
518
519 const std::vector<QuicPaddingFrame>& padding_frames() const {
520 return framer_.padding_frames();
521 }
522
523 const std::vector<QuicPathChallengeFrame>& path_challenge_frames() const {
524 return framer_.path_challenge_frames();
525 }
526
527 const std::vector<QuicPathResponseFrame>& path_response_frames() const {
528 return framer_.path_response_frames();
529 }
530
fayang58f71072019-11-05 08:47:02 -0800531 const QuicEncryptedPacket* coalesced_packet() const {
532 return framer_.coalesced_packet();
533 }
534
QUICHE teama6ef0a62019-03-07 20:34:33 -0500535 size_t last_packet_size() { return last_packet_size_; }
536
537 const QuicPacketHeader& last_packet_header() const {
538 return last_packet_header_;
539 }
540
541 const QuicVersionNegotiationPacket* version_negotiation_packet() {
542 return framer_.version_negotiation_packet();
543 }
544
545 void set_is_write_blocked_data_buffered(bool buffered) {
546 is_write_blocked_data_buffered_ = buffered;
547 }
548
549 void set_perspective(Perspective perspective) {
550 // We invert perspective here, because the framer needs to parse packets
551 // we send.
552 QuicFramerPeer::SetPerspective(framer_.framer(),
nharper4eba09b2019-06-26 20:17:25 -0700553 QuicUtils::InvertPerspective(perspective));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500554 }
555
556 // final_bytes_of_last_packet_ returns the last four bytes of the previous
557 // packet as a little-endian, uint32_t. This is intended to be used with a
558 // TaggingEncrypter so that tests can determine which encrypter was used for
559 // a given packet.
560 uint32_t final_bytes_of_last_packet() { return final_bytes_of_last_packet_; }
561
562 // Returns the final bytes of the second to last packet.
563 uint32_t final_bytes_of_previous_packet() {
564 return final_bytes_of_previous_packet_;
565 }
566
567 void use_tagging_decrypter() { use_tagging_decrypter_ = true; }
568
wubb442b862020-01-31 08:16:21 -0800569 uint32_t packets_write_attempts() const { return packets_write_attempts_; }
570
571 uint32_t flush_attempts() const { return flush_attempts_; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500572
rchd672c6d2019-11-27 15:30:54 -0800573 uint32_t connection_close_packets() const {
574 return connection_close_packets_;
575 }
576
QUICHE teama6ef0a62019-03-07 20:34:33 -0500577 void Reset() { framer_.Reset(); }
578
579 void SetSupportedVersions(const ParsedQuicVersionVector& versions) {
580 framer_.SetSupportedVersions(versions);
581 }
582
583 void set_max_packet_size(QuicByteCount max_packet_size) {
584 max_packet_size_ = max_packet_size;
585 }
586
587 void set_supports_release_time(bool supports_release_time) {
588 supports_release_time_ = supports_release_time;
589 }
590
591 SimpleQuicFramer* framer() { return &framer_; }
592
593 private:
594 ParsedQuicVersion version_;
595 SimpleQuicFramer framer_;
wubb442b862020-01-31 08:16:21 -0800596 size_t last_packet_size_ = 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500597 QuicPacketHeader last_packet_header_;
wubb442b862020-01-31 08:16:21 -0800598 bool write_blocked_ = false;
599 bool write_should_fail_ = false;
600 bool block_on_next_flush_ = false;
601 bool block_on_next_write_ = false;
602 bool next_packet_too_large_ = false;
603 bool always_get_packet_too_large_ = false;
604 bool is_write_blocked_data_buffered_ = false;
605 bool is_batch_mode_ = false;
606 // Number of times Flush() was called.
607 uint32_t flush_attempts_ = 0;
608 // (Batch mode only) Number of bytes buffered in writer. It is used as the
609 // return value of a successful Flush().
610 uint32_t bytes_buffered_ = 0;
611 uint32_t final_bytes_of_last_packet_ = 0;
612 uint32_t final_bytes_of_previous_packet_ = 0;
613 bool use_tagging_decrypter_ = false;
614 uint32_t packets_write_attempts_ = 0;
615 uint32_t connection_close_packets_ = 0;
616 MockClock* clock_ = nullptr;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500617 // If non-zero, the clock will pause during WritePacket for this amount of
618 // time.
wubb442b862020-01-31 08:16:21 -0800619 QuicTime::Delta write_pause_time_delta_ = QuicTime::Delta::Zero();
620 QuicByteCount max_packet_size_ = kMaxOutgoingPacketSize;
621 bool supports_release_time_ = false;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500622};
623
624class TestConnection : public QuicConnection {
625 public:
626 TestConnection(QuicConnectionId connection_id,
627 QuicSocketAddress address,
628 TestConnectionHelper* helper,
629 TestAlarmFactory* alarm_factory,
630 TestPacketWriter* writer,
631 Perspective perspective,
632 ParsedQuicVersion version)
633 : QuicConnection(connection_id,
634 address,
635 helper,
636 alarm_factory,
637 writer,
638 /* owns_writer= */ false,
639 perspective,
640 SupportedVersions(version)),
641 notifier_(nullptr) {
642 writer->set_perspective(perspective);
643 SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -0700644 std::make_unique<NullEncrypter>(perspective));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500645 SetDataProducer(&producer_);
646 }
647 TestConnection(const TestConnection&) = delete;
648 TestConnection& operator=(const TestConnection&) = delete;
649
QUICHE teama6ef0a62019-03-07 20:34:33 -0500650 void SetSendAlgorithm(SendAlgorithmInterface* send_algorithm) {
651 QuicConnectionPeer::SetSendAlgorithm(this, send_algorithm);
652 }
653
654 void SetLossAlgorithm(LossDetectionInterface* loss_algorithm) {
655 QuicConnectionPeer::SetLossAlgorithm(this, loss_algorithm);
656 }
657
dschinazi17d42422019-06-18 16:35:07 -0700658 void SendPacket(EncryptionLevel /*level*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500659 uint64_t packet_number,
660 std::unique_ptr<QuicPacket> packet,
661 HasRetransmittableData retransmittable,
662 bool has_ack,
663 bool has_pending_frames) {
fayang58f71072019-11-05 08:47:02 -0800664 ScopedPacketFlusher flusher(this);
dschinazi66dea072019-04-09 11:41:06 -0700665 char buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -0500666 size_t encrypted_length =
667 QuicConnectionPeer::GetFramer(this)->EncryptPayload(
QUICHE team6987b4a2019-03-15 16:23:04 -0700668 ENCRYPTION_INITIAL, QuicPacketNumber(packet_number), *packet,
dschinazi66dea072019-04-09 11:41:06 -0700669 buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500670 SerializedPacket serialized_packet(
671 QuicPacketNumber(packet_number), PACKET_4BYTE_PACKET_NUMBER, buffer,
672 encrypted_length, has_ack, has_pending_frames);
673 if (retransmittable == HAS_RETRANSMITTABLE_DATA) {
674 serialized_packet.retransmittable_frames.push_back(
fayang58f71072019-11-05 08:47:02 -0800675 QuicFrame(QuicPingFrame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500676 }
677 OnSerializedPacket(&serialized_packet);
678 }
679
680 QuicConsumedData SaveAndSendStreamData(QuicStreamId id,
681 const struct iovec* iov,
682 int iov_count,
683 size_t total_length,
684 QuicStreamOffset offset,
685 StreamSendingState state) {
fayanga4b37b22019-06-18 13:37:47 -0700686 ScopedPacketFlusher flusher(this);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500687 producer_.SaveStreamData(id, iov, iov_count, 0u, total_length);
688 if (notifier_ != nullptr) {
689 return notifier_->WriteOrBufferData(id, total_length, state);
690 }
691 return QuicConnection::SendStreamData(id, total_length, offset, state);
692 }
693
694 QuicConsumedData SendStreamDataWithString(QuicStreamId id,
dmcardlecf0bfcf2019-12-13 08:08:21 -0800695 quiche::QuicheStringPiece data,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500696 QuicStreamOffset offset,
697 StreamSendingState state) {
fayanga4b37b22019-06-18 13:37:47 -0700698 ScopedPacketFlusher flusher(this);
nharper46833c32019-05-15 21:33:05 -0700699 if (!QuicUtils::IsCryptoStreamId(transport_version(), id) &&
QUICHE team6987b4a2019-03-15 16:23:04 -0700700 this->encryption_level() == ENCRYPTION_INITIAL) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500701 this->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
fayangfa3b1d62019-11-18 08:02:13 -0800702 if (perspective() == Perspective::IS_CLIENT && !IsHandshakeComplete()) {
fayang5f135052019-08-22 17:59:40 -0700703 OnHandshakeComplete();
704 }
705 if (version().SupportsAntiAmplificationLimit()) {
706 QuicConnectionPeer::SetAddressValidated(this);
707 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500708 }
709 struct iovec iov;
710 MakeIOVector(data, &iov);
711 return SaveAndSendStreamData(id, &iov, 1, data.length(), offset, state);
712 }
713
QUICHE teamcd098022019-03-22 18:49:55 -0700714 QuicConsumedData SendApplicationDataAtLevel(EncryptionLevel encryption_level,
715 QuicStreamId id,
dmcardlecf0bfcf2019-12-13 08:08:21 -0800716 quiche::QuicheStringPiece data,
QUICHE teamcd098022019-03-22 18:49:55 -0700717 QuicStreamOffset offset,
718 StreamSendingState state) {
fayanga4b37b22019-06-18 13:37:47 -0700719 ScopedPacketFlusher flusher(this);
QUICHE teamcd098022019-03-22 18:49:55 -0700720 DCHECK(encryption_level >= ENCRYPTION_ZERO_RTT);
vasilvv0fc587f2019-09-06 13:33:08 -0700721 SetEncrypter(encryption_level, std::make_unique<TaggingEncrypter>(0x01));
QUICHE teamcd098022019-03-22 18:49:55 -0700722 SetDefaultEncryptionLevel(encryption_level);
723 struct iovec iov;
724 MakeIOVector(data, &iov);
725 return SaveAndSendStreamData(id, &iov, 1, data.length(), offset, state);
726 }
727
QUICHE teama6ef0a62019-03-07 20:34:33 -0500728 QuicConsumedData SendStreamData3() {
729 return SendStreamDataWithString(
730 GetNthClientInitiatedStreamId(1, transport_version()), "food", 0,
731 NO_FIN);
732 }
733
734 QuicConsumedData SendStreamData5() {
735 return SendStreamDataWithString(
736 GetNthClientInitiatedStreamId(2, transport_version()), "food2", 0,
737 NO_FIN);
738 }
739
740 // Ensures the connection can write stream data before writing.
741 QuicConsumedData EnsureWritableAndSendStreamData5() {
742 EXPECT_TRUE(CanWriteStreamData());
743 return SendStreamData5();
744 }
745
746 // The crypto stream has special semantics so that it is not blocked by a
747 // congestion window limitation, and also so that it gets put into a separate
748 // packet (so that it is easier to reason about a crypto frame not being
749 // split needlessly across packet boundaries). As a result, we have separate
750 // tests for some cases for this stream.
751 QuicConsumedData SendCryptoStreamData() {
752 QuicStreamOffset offset = 0;
dmcardlecf0bfcf2019-12-13 08:08:21 -0800753 quiche::QuicheStringPiece data("chlo");
fayang2ce66082019-10-02 06:29:04 -0700754 if (!QuicVersionUsesCryptoFrames(transport_version())) {
755 return SendCryptoDataWithString(data, offset);
756 }
757 producer_.SaveCryptoData(ENCRYPTION_INITIAL, offset, data);
758 size_t bytes_written;
759 if (notifier_) {
760 bytes_written =
761 notifier_->WriteCryptoData(ENCRYPTION_INITIAL, data.length(), offset);
762 } else {
763 bytes_written = QuicConnection::SendCryptoData(ENCRYPTION_INITIAL,
764 data.length(), offset);
765 }
766 return QuicConsumedData(bytes_written, /*fin_consumed*/ false);
nharper46833c32019-05-15 21:33:05 -0700767 }
768
dmcardlecf0bfcf2019-12-13 08:08:21 -0800769 QuicConsumedData SendCryptoDataWithString(quiche::QuicheStringPiece data,
nharper46833c32019-05-15 21:33:05 -0700770 QuicStreamOffset offset) {
fayang18ff23b2020-01-28 09:19:00 -0800771 return SendCryptoDataWithString(data, offset, ENCRYPTION_INITIAL);
772 }
773
774 QuicConsumedData SendCryptoDataWithString(quiche::QuicheStringPiece data,
775 QuicStreamOffset offset,
776 EncryptionLevel encryption_level) {
QUICHE teamea740082019-03-11 17:58:43 -0700777 if (!QuicVersionUsesCryptoFrames(transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500778 return SendStreamDataWithString(
779 QuicUtils::GetCryptoStreamId(transport_version()), data, offset,
780 NO_FIN);
781 }
fayang18ff23b2020-01-28 09:19:00 -0800782 producer_.SaveCryptoData(encryption_level, offset, data);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500783 size_t bytes_written;
784 if (notifier_) {
785 bytes_written =
fayang18ff23b2020-01-28 09:19:00 -0800786 notifier_->WriteCryptoData(encryption_level, data.length(), offset);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500787 } else {
fayang18ff23b2020-01-28 09:19:00 -0800788 bytes_written = QuicConnection::SendCryptoData(encryption_level,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500789 data.length(), offset);
790 }
791 return QuicConsumedData(bytes_written, /*fin_consumed*/ false);
792 }
793
794 void set_version(ParsedQuicVersion version) {
795 QuicConnectionPeer::GetFramer(this)->set_version(version);
796 }
797
798 void SetSupportedVersions(const ParsedQuicVersionVector& versions) {
799 QuicConnectionPeer::GetFramer(this)->SetSupportedVersions(versions);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500800 writer()->SetSupportedVersions(versions);
801 }
802
803 void set_perspective(Perspective perspective) {
804 writer()->set_perspective(perspective);
805 QuicConnectionPeer::SetPerspective(this, perspective);
806 }
807
808 // Enable path MTU discovery. Assumes that the test is performed from the
wub031d47c2019-11-21 08:04:07 -0800809 // server perspective and the higher value of MTU target is used.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500810 void EnablePathMtuDiscovery(MockSendAlgorithm* send_algorithm) {
wub031d47c2019-11-21 08:04:07 -0800811 ASSERT_EQ(Perspective::IS_SERVER, perspective());
QUICHE teama6ef0a62019-03-07 20:34:33 -0500812
813 QuicConfig config;
814 QuicTagVector connection_options;
815 connection_options.push_back(kMTUH);
wub031d47c2019-11-21 08:04:07 -0800816 config.SetInitialReceivedConnectionOptions(connection_options);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500817 EXPECT_CALL(*send_algorithm, SetFromConfig(_, _));
818 SetFromConfig(config);
819
820 // Normally, the pacing would be disabled in the test, but calling
821 // SetFromConfig enables it. Set nearly-infinite bandwidth to make the
822 // pacing algorithm work.
823 EXPECT_CALL(*send_algorithm, PacingRate(_))
824 .WillRepeatedly(Return(QuicBandwidth::Infinite()));
825 }
826
827 TestAlarmFactory::TestAlarm* GetAckAlarm() {
828 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
829 QuicConnectionPeer::GetAckAlarm(this));
830 }
831
832 TestAlarmFactory::TestAlarm* GetPingAlarm() {
833 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
834 QuicConnectionPeer::GetPingAlarm(this));
835 }
836
837 TestAlarmFactory::TestAlarm* GetRetransmissionAlarm() {
838 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
839 QuicConnectionPeer::GetRetransmissionAlarm(this));
840 }
841
842 TestAlarmFactory::TestAlarm* GetSendAlarm() {
843 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
844 QuicConnectionPeer::GetSendAlarm(this));
845 }
846
847 TestAlarmFactory::TestAlarm* GetTimeoutAlarm() {
fayangb9c88442020-03-26 07:03:57 -0700848 if (GetQuicReloadableFlag(quic_use_blackhole_detector) &&
849 GetQuicReloadableFlag(quic_use_idle_network_detector)) {
850 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
851 QuicConnectionPeer::GetIdleNetworkDetectorAlarm(this));
852 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500853 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
854 QuicConnectionPeer::GetTimeoutAlarm(this));
855 }
856
857 TestAlarmFactory::TestAlarm* GetMtuDiscoveryAlarm() {
858 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
859 QuicConnectionPeer::GetMtuDiscoveryAlarm(this));
860 }
861
862 TestAlarmFactory::TestAlarm* GetPathDegradingAlarm() {
863 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
864 QuicConnectionPeer::GetPathDegradingAlarm(this));
865 }
866
867 TestAlarmFactory::TestAlarm* GetProcessUndecryptablePacketsAlarm() {
868 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
869 QuicConnectionPeer::GetProcessUndecryptablePacketsAlarm(this));
870 }
871
fayangb59c6f12020-03-23 15:06:14 -0700872 TestAlarmFactory::TestAlarm* GetBlackholeDetectorAlarm() {
873 DCHECK(GetQuicReloadableFlag(quic_use_blackhole_detector));
874 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
875 QuicConnectionPeer::GetBlackholeDetectorAlarm(this));
876 }
877
878 void PathDegradingTimeout() {
879 DCHECK(PathDegradingDetectionInProgress());
880 if (GetQuicReloadableFlag(quic_use_blackhole_detector)) {
881 GetBlackholeDetectorAlarm()->Fire();
882 } else {
883 GetPathDegradingAlarm()->Fire();
884 }
885 }
886
887 bool PathDegradingDetectionInProgress() {
888 if (GetQuicReloadableFlag(quic_use_blackhole_detector)) {
889 return QuicConnectionPeer::GetPathDegradingDeadline(this).IsInitialized();
890 }
891 return GetPathDegradingAlarm()->IsSet();
892 }
893
894 bool BlackholeDetectionInProgress() {
895 DCHECK(GetQuicReloadableFlag(quic_use_blackhole_detector));
896 return QuicConnectionPeer::GetBlackholeDetectionDeadline(this)
897 .IsInitialized();
898 }
899
QUICHE teama6ef0a62019-03-07 20:34:33 -0500900 void SetMaxTailLossProbes(size_t max_tail_loss_probes) {
901 QuicSentPacketManagerPeer::SetMaxTailLossProbes(
902 QuicConnectionPeer::GetSentPacketManager(this), max_tail_loss_probes);
903 }
904
905 QuicByteCount GetBytesInFlight() {
ianswett9f459cb2019-04-21 06:39:59 -0700906 return QuicConnectionPeer::GetSentPacketManager(this)->GetBytesInFlight();
QUICHE teama6ef0a62019-03-07 20:34:33 -0500907 }
908
909 void set_notifier(SimpleSessionNotifier* notifier) { notifier_ = notifier; }
910
911 void ReturnEffectivePeerAddressForNextPacket(const QuicSocketAddress& addr) {
vasilvv0fc587f2019-09-06 13:33:08 -0700912 next_effective_peer_addr_ = std::make_unique<QuicSocketAddress>(addr);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500913 }
914
fayang5f135052019-08-22 17:59:40 -0700915 bool PtoEnabled() {
916 if (QuicConnectionPeer::GetSentPacketManager(this)->pto_enabled()) {
917 // PTO mode is default enabled for T099. And TLP/RTO related tests are
918 // stale.
fayang18ff23b2020-01-28 09:19:00 -0800919 DCHECK_EQ(PROTOCOL_TLS1_3, version().handshake_protocol);
fayang5f135052019-08-22 17:59:40 -0700920 return true;
921 }
922 return false;
923 }
924
nharper46833c32019-05-15 21:33:05 -0700925 SimpleDataProducer* producer() { return &producer_; }
926
QUICHE teama6ef0a62019-03-07 20:34:33 -0500927 using QuicConnection::active_effective_peer_migration_type;
928 using QuicConnection::IsCurrentPacketConnectivityProbing;
929 using QuicConnection::SelectMutualVersion;
930 using QuicConnection::SendProbingRetransmissions;
931 using QuicConnection::set_defer_send_in_response_to_packets;
932
933 protected:
934 QuicSocketAddress GetEffectivePeerAddressFromCurrentPacket() const override {
935 if (next_effective_peer_addr_) {
936 return *std::move(next_effective_peer_addr_);
937 }
938 return QuicConnection::GetEffectivePeerAddressFromCurrentPacket();
939 }
940
941 private:
942 TestPacketWriter* writer() {
943 return static_cast<TestPacketWriter*>(QuicConnection::writer());
944 }
945
946 SimpleDataProducer producer_;
947
948 SimpleSessionNotifier* notifier_;
949
950 std::unique_ptr<QuicSocketAddress> next_effective_peer_addr_;
951};
952
953enum class AckResponse { kDefer, kImmediate };
954
955// Run tests with combinations of {ParsedQuicVersion, AckResponse}.
956struct TestParams {
957 TestParams(ParsedQuicVersion version,
958 AckResponse ack_response,
959 bool no_stop_waiting)
960 : version(version),
961 ack_response(ack_response),
962 no_stop_waiting(no_stop_waiting) {}
963
QUICHE teama6ef0a62019-03-07 20:34:33 -0500964 ParsedQuicVersion version;
965 AckResponse ack_response;
966 bool no_stop_waiting;
967};
968
dschinazi142051a2019-09-18 18:17:29 -0700969// Used by ::testing::PrintToStringParamName().
970std::string PrintToString(const TestParams& p) {
dmcardlecf0bfcf2019-12-13 08:08:21 -0800971 return quiche::QuicheStrCat(
dschinazi142051a2019-09-18 18:17:29 -0700972 ParsedQuicVersionToString(p.version), "_",
973 (p.ack_response == AckResponse::kDefer ? "defer" : "immediate"), "_",
974 (p.no_stop_waiting ? "No" : ""), "StopWaiting");
975}
976
QUICHE teama6ef0a62019-03-07 20:34:33 -0500977// Constructs various test permutations.
978std::vector<TestParams> GetTestParams() {
979 QuicFlagSaver flags;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500980 std::vector<TestParams> params;
981 ParsedQuicVersionVector all_supported_versions = AllSupportedVersions();
982 for (size_t i = 0; i < all_supported_versions.size(); ++i) {
983 for (AckResponse ack_response :
984 {AckResponse::kDefer, AckResponse::kImmediate}) {
dschinazi142051a2019-09-18 18:17:29 -0700985 params.push_back(
986 TestParams(all_supported_versions[i], ack_response, true));
987 if (!VersionHasIetfInvariantHeader(
988 all_supported_versions[i].transport_version)) {
fayangd4291e42019-05-30 10:31:21 -0700989 params.push_back(
dschinazi142051a2019-09-18 18:17:29 -0700990 TestParams(all_supported_versions[i], ack_response, false));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500991 }
992 }
993 }
994 return params;
995}
996
997class QuicConnectionTest : public QuicTestWithParam<TestParams> {
fkastenholz5d880a92019-06-21 09:01:56 -0700998 public:
999 // For tests that do silent connection closes, no such packet is generated. In
1000 // order to verify the contents of the OnConnectionClosed upcall, EXPECTs
1001 // should invoke this method, saving the frame, and then the test can verify
1002 // the contents.
1003 void SaveConnectionCloseFrame(const QuicConnectionCloseFrame& frame,
1004 ConnectionCloseSource /*source*/) {
1005 saved_connection_close_frame_ = frame;
1006 connection_close_frame_count_++;
1007 }
1008
QUICHE teama6ef0a62019-03-07 20:34:33 -05001009 protected:
1010 QuicConnectionTest()
1011 : connection_id_(TestConnectionId()),
1012 framer_(SupportedVersions(version()),
1013 QuicTime::Zero(),
1014 Perspective::IS_CLIENT,
1015 connection_id_.length()),
1016 send_algorithm_(new StrictMock<MockSendAlgorithm>),
1017 loss_algorithm_(new MockLossAlgorithm()),
1018 helper_(new TestConnectionHelper(&clock_, &random_generator_)),
1019 alarm_factory_(new TestAlarmFactory()),
1020 peer_framer_(SupportedVersions(version()),
1021 QuicTime::Zero(),
1022 Perspective::IS_SERVER,
1023 connection_id_.length()),
1024 peer_creator_(connection_id_,
1025 &peer_framer_,
1026 /*delegate=*/nullptr),
1027 writer_(new TestPacketWriter(version(), &clock_)),
1028 connection_(connection_id_,
1029 kPeerAddress,
1030 helper_.get(),
1031 alarm_factory_.get(),
1032 writer_.get(),
1033 Perspective::IS_CLIENT,
1034 version()),
1035 creator_(QuicConnectionPeer::GetPacketCreator(&connection_)),
QUICHE teama6ef0a62019-03-07 20:34:33 -05001036 manager_(QuicConnectionPeer::GetSentPacketManager(&connection_)),
dmcardlecf0bfcf2019-12-13 08:08:21 -08001037 frame1_(0, false, 0, quiche::QuicheStringPiece(data1)),
1038 frame2_(0, false, 3, quiche::QuicheStringPiece(data2)),
1039 crypto_frame_(ENCRYPTION_INITIAL, 0, quiche::QuicheStringPiece(data1)),
QUICHE teama6ef0a62019-03-07 20:34:33 -05001040 packet_number_length_(PACKET_4BYTE_PACKET_NUMBER),
1041 connection_id_included_(CONNECTION_ID_PRESENT),
fkastenholz5d880a92019-06-21 09:01:56 -07001042 notifier_(&connection_),
1043 connection_close_frame_count_(0) {
dschinazi142051a2019-09-18 18:17:29 -07001044 QUIC_DVLOG(2) << "QuicConnectionTest(" << PrintToString(GetParam()) << ")";
QUICHE teama6ef0a62019-03-07 20:34:33 -05001045 connection_.set_defer_send_in_response_to_packets(GetParam().ack_response ==
1046 AckResponse::kDefer);
nharperc6b99512019-09-19 11:13:48 -07001047 framer_.SetInitialObfuscators(TestConnectionId());
1048 connection_.InstallInitialCrypters(TestConnectionId());
1049 CrypterPair crypters;
1050 CryptoUtils::CreateInitialObfuscators(Perspective::IS_SERVER, version(),
1051 TestConnectionId(), &crypters);
1052 peer_creator_.SetEncrypter(ENCRYPTION_INITIAL,
1053 std::move(crypters.encrypter));
1054 if (version().KnowsWhichDecrypterToUse()) {
1055 peer_framer_.InstallDecrypter(ENCRYPTION_INITIAL,
1056 std::move(crypters.decrypter));
1057 } else {
1058 peer_framer_.SetDecrypter(ENCRYPTION_INITIAL,
1059 std::move(crypters.decrypter));
1060 }
nharper2c9f02a2019-05-08 10:25:50 -07001061 for (EncryptionLevel level :
1062 {ENCRYPTION_ZERO_RTT, ENCRYPTION_FORWARD_SECURE}) {
1063 peer_creator_.SetEncrypter(
vasilvv0fc587f2019-09-06 13:33:08 -07001064 level, std::make_unique<NullEncrypter>(peer_framer_.perspective()));
nharper2c9f02a2019-05-08 10:25:50 -07001065 }
dschinazi7b9278c2019-05-20 07:36:21 -07001066 QuicFramerPeer::SetLastSerializedServerConnectionId(
QUICHE teama6ef0a62019-03-07 20:34:33 -05001067 QuicConnectionPeer::GetFramer(&connection_), connection_id_);
nharperc6b99512019-09-19 11:13:48 -07001068 QuicFramerPeer::SetLastWrittenPacketNumberLength(
1069 QuicConnectionPeer::GetFramer(&connection_), packet_number_length_);
fayangd4291e42019-05-30 10:31:21 -07001070 if (VersionHasIetfInvariantHeader(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001071 EXPECT_TRUE(QuicConnectionPeer::GetNoStopWaitingFrames(&connection_));
1072 } else {
1073 QuicConnectionPeer::SetNoStopWaitingFrames(&connection_,
1074 GetParam().no_stop_waiting);
1075 }
nharper46833c32019-05-15 21:33:05 -07001076 QuicStreamId stream_id;
1077 if (QuicVersionUsesCryptoFrames(version().transport_version)) {
1078 stream_id = QuicUtils::GetFirstBidirectionalStreamId(
1079 version().transport_version, Perspective::IS_CLIENT);
1080 } else {
1081 stream_id = QuicUtils::GetCryptoStreamId(version().transport_version);
1082 }
1083 frame1_.stream_id = stream_id;
1084 frame2_.stream_id = stream_id;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001085 connection_.set_visitor(&visitor_);
fayangcff885a2019-10-22 07:39:04 -07001086 connection_.SetSessionNotifier(&notifier_);
1087 connection_.set_notifier(&notifier_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001088 connection_.SetSendAlgorithm(send_algorithm_);
1089 connection_.SetLossAlgorithm(loss_algorithm_.get());
1090 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
1091 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1092 .Times(AnyNumber());
wubf4ab9652020-02-20 14:45:43 -08001093 EXPECT_CALL(*send_algorithm_, OnPacketNeutered(_)).Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -05001094 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
1095 .WillRepeatedly(Return(kDefaultTCPMSS));
1096 EXPECT_CALL(*send_algorithm_, PacingRate(_))
1097 .WillRepeatedly(Return(QuicBandwidth::Zero()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001098 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
1099 .Times(AnyNumber())
1100 .WillRepeatedly(Return(QuicBandwidth::Zero()));
wub5cd49592019-11-25 15:17:13 -08001101 EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_))
1102 .Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -05001103 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
1104 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
1105 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
1106 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).Times(AnyNumber());
fayangd58736d2019-11-27 13:35:31 -08001107 EXPECT_CALL(visitor_, OnPacketDecrypted(_)).Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -05001108 EXPECT_CALL(visitor_, HasPendingHandshake()).Times(AnyNumber());
fayangcff885a2019-10-22 07:39:04 -07001109 EXPECT_CALL(visitor_, OnCanWrite())
1110 .WillRepeatedly(Invoke(&notifier_, &SimpleSessionNotifier::OnCanWrite));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001111 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
1112 .WillRepeatedly(Return(false));
1113 EXPECT_CALL(visitor_, OnCongestionWindowChange(_)).Times(AnyNumber());
zhongyi83161e42019-08-19 09:06:25 -07001114 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -05001115 EXPECT_CALL(visitor_, OnForwardProgressConfirmed()).Times(AnyNumber());
wub256b2d62019-11-25 08:46:55 -08001116 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
fayang2f2915d2020-01-24 06:47:15 -08001117 EXPECT_CALL(visitor_, OnOneRttPacketAcknowledged())
1118 .Times(testing::AtMost(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001119 EXPECT_CALL(*loss_algorithm_, GetLossTimeout())
1120 .WillRepeatedly(Return(QuicTime::Zero()));
1121 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
1122 .Times(AnyNumber());
fayang5014e922020-01-22 12:28:11 -08001123 EXPECT_CALL(visitor_, GetHandshakeState())
1124 .WillRepeatedly(Return(HANDSHAKE_START));
zhongyi546cc452019-04-12 15:27:49 -07001125 if (connection_.version().KnowsWhichDecrypterToUse()) {
1126 connection_.InstallDecrypter(
1127 ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07001128 std::make_unique<NullDecrypter>(Perspective::IS_CLIENT));
zhongyi546cc452019-04-12 15:27:49 -07001129 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001130 }
1131
1132 QuicConnectionTest(const QuicConnectionTest&) = delete;
1133 QuicConnectionTest& operator=(const QuicConnectionTest&) = delete;
1134
1135 ParsedQuicVersion version() { return GetParam().version; }
1136
QUICHE teama6ef0a62019-03-07 20:34:33 -05001137 QuicStopWaitingFrame* stop_waiting() {
1138 QuicConnectionPeer::PopulateStopWaitingFrame(&connection_, &stop_waiting_);
1139 return &stop_waiting_;
1140 }
1141
1142 QuicPacketNumber least_unacked() {
1143 if (writer_->stop_waiting_frames().empty()) {
1144 return QuicPacketNumber();
1145 }
1146 return writer_->stop_waiting_frames()[0].least_unacked;
1147 }
1148
1149 void use_tagging_decrypter() { writer_->use_tagging_decrypter(); }
1150
zhongyi546cc452019-04-12 15:27:49 -07001151 void SetDecrypter(EncryptionLevel level,
1152 std::unique_ptr<QuicDecrypter> decrypter) {
1153 if (connection_.version().KnowsWhichDecrypterToUse()) {
1154 connection_.InstallDecrypter(level, std::move(decrypter));
1155 connection_.RemoveDecrypter(ENCRYPTION_INITIAL);
1156 } else {
1157 connection_.SetDecrypter(level, std::move(decrypter));
1158 }
1159 }
1160
QUICHE teama6ef0a62019-03-07 20:34:33 -05001161 void ProcessPacket(uint64_t number) {
1162 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
1163 ProcessDataPacket(number);
1164 if (connection_.GetSendAlarm()->IsSet()) {
1165 connection_.GetSendAlarm()->Fire();
1166 }
1167 }
1168
1169 void ProcessReceivedPacket(const QuicSocketAddress& self_address,
1170 const QuicSocketAddress& peer_address,
1171 const QuicReceivedPacket& packet) {
1172 connection_.ProcessUdpPacket(self_address, peer_address, packet);
1173 if (connection_.GetSendAlarm()->IsSet()) {
1174 connection_.GetSendAlarm()->Fire();
1175 }
1176 }
1177
1178 void ProcessFramePacket(QuicFrame frame) {
1179 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
1180 }
1181
1182 void ProcessFramePacketWithAddresses(QuicFrame frame,
1183 QuicSocketAddress self_address,
1184 QuicSocketAddress peer_address) {
1185 QuicFrames frames;
1186 frames.push_back(QuicFrame(frame));
zhongyif06ca342020-02-24 14:11:13 -08001187 return ProcessFramesPacketWithAddresses(frames, self_address, peer_address);
1188 }
1189
1190 void ProcessFramesPacketWithAddresses(QuicFrames frames,
1191 QuicSocketAddress self_address,
1192 QuicSocketAddress peer_address) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001193 QuicPacketCreatorPeer::SetSendVersionInPacket(
wub031d47c2019-11-21 08:04:07 -08001194 &peer_creator_,
1195 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_) <
1196 ENCRYPTION_FORWARD_SECURE &&
1197 connection_.perspective() == Perspective::IS_SERVER);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001198
dschinazi66dea072019-04-09 11:41:06 -07001199 char buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05001200 SerializedPacket serialized_packet =
dschinazi66dea072019-04-09 11:41:06 -07001201 QuicPacketCreatorPeer::SerializeAllFrames(
1202 &peer_creator_, frames, buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001203 connection_.ProcessUdpPacket(
1204 self_address, peer_address,
1205 QuicReceivedPacket(serialized_packet.encrypted_buffer,
1206 serialized_packet.encrypted_length, clock_.Now()));
1207 if (connection_.GetSendAlarm()->IsSet()) {
1208 connection_.GetSendAlarm()->Fire();
1209 }
1210 }
1211
1212 // Bypassing the packet creator is unrealistic, but allows us to process
1213 // packets the QuicPacketCreator won't allow us to create.
1214 void ForceProcessFramePacket(QuicFrame frame) {
1215 QuicFrames frames;
1216 frames.push_back(QuicFrame(frame));
zhongyi546cc452019-04-12 15:27:49 -07001217 bool send_version = connection_.perspective() == Perspective::IS_SERVER;
1218 if (connection_.version().KnowsWhichDecrypterToUse()) {
1219 send_version = true;
1220 }
1221 QuicPacketCreatorPeer::SetSendVersionInPacket(&peer_creator_, send_version);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001222 QuicPacketHeader header;
1223 QuicPacketCreatorPeer::FillPacketHeader(&peer_creator_, &header);
dschinazi66dea072019-04-09 11:41:06 -07001224 char encrypted_buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05001225 size_t length = peer_framer_.BuildDataPacket(
dschinazi66dea072019-04-09 11:41:06 -07001226 header, frames, encrypted_buffer, kMaxOutgoingPacketSize,
1227 ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001228 DCHECK_GT(length, 0u);
1229
1230 const size_t encrypted_length = peer_framer_.EncryptInPlace(
QUICHE team6987b4a2019-03-15 16:23:04 -07001231 ENCRYPTION_INITIAL, header.packet_number,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001232 GetStartOfEncryptedData(peer_framer_.version().transport_version,
1233 header),
dschinazi66dea072019-04-09 11:41:06 -07001234 length, kMaxOutgoingPacketSize, encrypted_buffer);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001235 DCHECK_GT(encrypted_length, 0u);
1236
1237 connection_.ProcessUdpPacket(
1238 kSelfAddress, kPeerAddress,
1239 QuicReceivedPacket(encrypted_buffer, encrypted_length, clock_.Now()));
1240 }
1241
1242 size_t ProcessFramePacketAtLevel(uint64_t number,
1243 QuicFrame frame,
1244 EncryptionLevel level) {
fayang01062942020-01-22 07:23:23 -08001245 QuicFrames frames;
1246 frames.push_back(frame);
1247 return ProcessFramesPacketAtLevel(number, frames, level);
1248 }
1249
1250 size_t ProcessFramesPacketAtLevel(uint64_t number,
1251 const QuicFrames& frames,
1252 EncryptionLevel level) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001253 QuicPacketHeader header;
1254 header.destination_connection_id = connection_id_;
1255 header.packet_number_length = packet_number_length_;
1256 header.destination_connection_id_included = connection_id_included_;
dschinazi5e1a7b22019-07-31 12:23:21 -07001257 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001258 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1259 }
zhongyi546cc452019-04-12 15:27:49 -07001260 if (level == ENCRYPTION_INITIAL &&
1261 peer_framer_.version().KnowsWhichDecrypterToUse()) {
1262 header.version_flag = true;
nharperd43f1d62019-07-01 15:18:20 -07001263 if (QuicVersionHasLongHeaderLengths(peer_framer_.transport_version())) {
1264 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
1265 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
1266 }
QUICHE team2252b702019-05-14 23:55:14 -04001267 }
dschinazi5e1a7b22019-07-31 12:23:21 -07001268 if (header.version_flag &&
QUICHE team2252b702019-05-14 23:55:14 -04001269 peer_framer_.perspective() == Perspective::IS_SERVER) {
1270 header.source_connection_id = connection_id_;
1271 header.source_connection_id_included = CONNECTION_ID_PRESENT;
zhongyi546cc452019-04-12 15:27:49 -07001272 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001273 header.packet_number = QuicPacketNumber(number);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001274 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
QUICHE teamcd098022019-03-22 18:49:55 -07001275 // Set the correct encryption level and encrypter on peer_creator and
1276 // peer_framer, respectively.
1277 peer_creator_.set_encryption_level(level);
1278 if (QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_) >
1279 ENCRYPTION_INITIAL) {
1280 peer_framer_.SetEncrypter(
1281 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
vasilvv0fc587f2019-09-06 13:33:08 -07001282 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teamcd098022019-03-22 18:49:55 -07001283 // Set the corresponding decrypter.
zhongyi546cc452019-04-12 15:27:49 -07001284 if (connection_.version().KnowsWhichDecrypterToUse()) {
1285 connection_.InstallDecrypter(
1286 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
vasilvv0fc587f2019-09-06 13:33:08 -07001287 std::make_unique<StrictTaggingDecrypter>(0x01));
zhongyi546cc452019-04-12 15:27:49 -07001288 connection_.RemoveDecrypter(ENCRYPTION_INITIAL);
1289 } else {
1290 connection_.SetDecrypter(
1291 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
vasilvv0fc587f2019-09-06 13:33:08 -07001292 std::make_unique<StrictTaggingDecrypter>(0x01));
zhongyi546cc452019-04-12 15:27:49 -07001293 }
QUICHE teamcd098022019-03-22 18:49:55 -07001294 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001295
dschinazi66dea072019-04-09 11:41:06 -07001296 char buffer[kMaxOutgoingPacketSize];
1297 size_t encrypted_length =
1298 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
1299 buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001300 connection_.ProcessUdpPacket(
1301 kSelfAddress, kPeerAddress,
QUICHE teamcd098022019-03-22 18:49:55 -07001302 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1303 if (connection_.GetSendAlarm()->IsSet()) {
1304 connection_.GetSendAlarm()->Fire();
1305 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001306 return encrypted_length;
1307 }
1308
1309 size_t ProcessDataPacket(uint64_t number) {
nharper2c9f02a2019-05-08 10:25:50 -07001310 return ProcessDataPacketAtLevel(number, false, ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001311 }
1312
1313 size_t ProcessDataPacket(QuicPacketNumber packet_number) {
nharper2c9f02a2019-05-08 10:25:50 -07001314 return ProcessDataPacketAtLevel(packet_number, false,
1315 ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001316 }
1317
1318 size_t ProcessDataPacketAtLevel(QuicPacketNumber packet_number,
1319 bool has_stop_waiting,
1320 EncryptionLevel level) {
1321 return ProcessDataPacketAtLevel(packet_number.ToUint64(), has_stop_waiting,
1322 level);
1323 }
1324
dschinazi17d42422019-06-18 16:35:07 -07001325 size_t ProcessCryptoPacketAtLevel(uint64_t number,
1326 EncryptionLevel /*level*/) {
fayangc31c9952019-06-05 13:54:48 -07001327 QuicPacketHeader header = ConstructPacketHeader(number, ENCRYPTION_INITIAL);
nharper46833c32019-05-15 21:33:05 -07001328 QuicFrames frames;
1329 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1330 frames.push_back(QuicFrame(&crypto_frame_));
1331 } else {
1332 frames.push_back(QuicFrame(frame1_));
1333 }
fayang5f135052019-08-22 17:59:40 -07001334 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
nharper46833c32019-05-15 21:33:05 -07001335 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
1336 char buffer[kMaxOutgoingPacketSize];
1337 peer_creator_.set_encryption_level(ENCRYPTION_INITIAL);
fayangc31c9952019-06-05 13:54:48 -07001338 size_t encrypted_length = peer_framer_.EncryptPayload(
1339 ENCRYPTION_INITIAL, QuicPacketNumber(number), *packet, buffer,
1340 kMaxOutgoingPacketSize);
nharper46833c32019-05-15 21:33:05 -07001341 connection_.ProcessUdpPacket(
1342 kSelfAddress, kPeerAddress,
1343 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1344 if (connection_.GetSendAlarm()->IsSet()) {
1345 connection_.GetSendAlarm()->Fire();
1346 }
1347 return encrypted_length;
1348 }
1349
QUICHE teama6ef0a62019-03-07 20:34:33 -05001350 size_t ProcessDataPacketAtLevel(uint64_t number,
1351 bool has_stop_waiting,
1352 EncryptionLevel level) {
1353 std::unique_ptr<QuicPacket> packet(
QUICHE team8c1daa22019-03-13 08:33:41 -07001354 ConstructDataPacket(number, has_stop_waiting, level));
dschinazi66dea072019-04-09 11:41:06 -07001355 char buffer[kMaxOutgoingPacketSize];
QUICHE teamcd098022019-03-22 18:49:55 -07001356 peer_creator_.set_encryption_level(level);
dschinazi66dea072019-04-09 11:41:06 -07001357 size_t encrypted_length =
1358 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
1359 buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001360 connection_.ProcessUdpPacket(
1361 kSelfAddress, kPeerAddress,
1362 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1363 if (connection_.GetSendAlarm()->IsSet()) {
1364 connection_.GetSendAlarm()->Fire();
1365 }
1366 return encrypted_length;
1367 }
1368
1369 void ProcessClosePacket(uint64_t number) {
1370 std::unique_ptr<QuicPacket> packet(ConstructClosePacket(number));
dschinazi66dea072019-04-09 11:41:06 -07001371 char buffer[kMaxOutgoingPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07001372 size_t encrypted_length = peer_framer_.EncryptPayload(
nharperc6b99512019-09-19 11:13:48 -07001373 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(number), *packet, buffer,
dschinazi66dea072019-04-09 11:41:06 -07001374 kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001375 connection_.ProcessUdpPacket(
1376 kSelfAddress, kPeerAddress,
1377 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
1378 }
1379
1380 QuicByteCount SendStreamDataToPeer(QuicStreamId id,
dmcardlecf0bfcf2019-12-13 08:08:21 -08001381 quiche::QuicheStringPiece data,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001382 QuicStreamOffset offset,
1383 StreamSendingState state,
1384 QuicPacketNumber* last_packet) {
1385 QuicByteCount packet_size;
fayang0fcbf352019-08-30 11:15:58 -07001386 // Save the last packet's size.
QUICHE teama6ef0a62019-03-07 20:34:33 -05001387 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
fayang0fcbf352019-08-30 11:15:58 -07001388 .Times(AnyNumber())
1389 .WillRepeatedly(SaveArg<3>(&packet_size));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001390 connection_.SendStreamDataWithString(id, data, offset, state);
1391 if (last_packet != nullptr) {
1392 *last_packet = creator_->packet_number();
1393 }
1394 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1395 .Times(AnyNumber());
1396 return packet_size;
1397 }
1398
1399 void SendAckPacketToPeer() {
1400 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1401 {
fayanga4b37b22019-06-18 13:37:47 -07001402 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001403 connection_.SendAck();
1404 }
1405 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1406 .Times(AnyNumber());
1407 }
1408
1409 void SendRstStream(QuicStreamId id,
1410 QuicRstStreamErrorCode error,
1411 QuicStreamOffset bytes_written) {
fayangcff885a2019-10-22 07:39:04 -07001412 notifier_.WriteOrBufferRstStream(id, error, bytes_written);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001413 connection_.OnStreamReset(id, error);
1414 }
1415
fayangcff885a2019-10-22 07:39:04 -07001416 void SendPing() { notifier_.WriteOrBufferPing(); }
zhongyifbb25772019-04-10 16:54:08 -07001417
fayang61453cb2020-03-11 11:32:26 -07001418 MessageStatus SendMessage(quiche::QuicheStringPiece message) {
1419 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1420 QuicMemSliceStorage storage(nullptr, 0, nullptr, 0);
1421 return connection_.SendMessage(
1422 1,
1423 MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(), message,
1424 &storage),
1425 false);
1426 }
1427
QUICHE teama6ef0a62019-03-07 20:34:33 -05001428 void ProcessAckPacket(uint64_t packet_number, QuicAckFrame* frame) {
1429 if (packet_number > 1) {
1430 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, packet_number - 1);
1431 } else {
1432 QuicPacketCreatorPeer::ClearPacketNumber(&peer_creator_);
1433 }
1434 ProcessFramePacket(QuicFrame(frame));
1435 }
1436
1437 void ProcessAckPacket(QuicAckFrame* frame) {
1438 ProcessFramePacket(QuicFrame(frame));
1439 }
1440
1441 void ProcessStopWaitingPacket(QuicStopWaitingFrame frame) {
1442 ProcessFramePacket(QuicFrame(frame));
1443 }
1444
1445 size_t ProcessStopWaitingPacketAtLevel(uint64_t number,
1446 QuicStopWaitingFrame frame,
dschinazi17d42422019-06-18 16:35:07 -07001447 EncryptionLevel /*level*/) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001448 return ProcessFramePacketAtLevel(number, QuicFrame(frame),
1449 ENCRYPTION_ZERO_RTT);
1450 }
1451
1452 void ProcessGoAwayPacket(QuicGoAwayFrame* frame) {
1453 ProcessFramePacket(QuicFrame(frame));
1454 }
1455
1456 bool IsMissing(uint64_t number) {
fayangc31c9952019-06-05 13:54:48 -07001457 return IsAwaitingPacket(connection_.ack_frame(), QuicPacketNumber(number),
QUICHE teama6ef0a62019-03-07 20:34:33 -05001458 QuicPacketNumber());
1459 }
1460
1461 std::unique_ptr<QuicPacket> ConstructPacket(const QuicPacketHeader& header,
1462 const QuicFrames& frames) {
1463 auto packet = BuildUnsizedDataPacket(&peer_framer_, header, frames);
1464 EXPECT_NE(nullptr, packet.get());
1465 return packet;
1466 }
1467
nharper46833c32019-05-15 21:33:05 -07001468 QuicPacketHeader ConstructPacketHeader(uint64_t number,
1469 EncryptionLevel level) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001470 QuicPacketHeader header;
fayangd4291e42019-05-30 10:31:21 -07001471 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version()) &&
QUICHE team8c1daa22019-03-13 08:33:41 -07001472 level < ENCRYPTION_FORWARD_SECURE) {
1473 // Set long header type accordingly.
1474 header.version_flag = true;
nharperc6b99512019-09-19 11:13:48 -07001475 header.form = IETF_QUIC_LONG_HEADER_PACKET;
QUICHE team8c1daa22019-03-13 08:33:41 -07001476 header.long_packet_type = EncryptionlevelToLongHeaderType(level);
1477 if (QuicVersionHasLongHeaderLengths(
1478 peer_framer_.version().transport_version)) {
1479 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
1480 if (header.long_packet_type == INITIAL) {
1481 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
1482 }
1483 }
1484 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001485 // Set connection_id to peer's in memory representation as this data packet
1486 // is created by peer_framer.
dschinazi5e1a7b22019-07-31 12:23:21 -07001487 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
QUICHE team2252b702019-05-14 23:55:14 -04001488 header.source_connection_id = connection_id_;
1489 header.source_connection_id_included = connection_id_included_;
1490 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1491 } else {
1492 header.destination_connection_id = connection_id_;
1493 header.destination_connection_id_included = connection_id_included_;
1494 }
fayangd4291e42019-05-30 10:31:21 -07001495 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version()) &&
QUICHE teama6ef0a62019-03-07 20:34:33 -05001496 peer_framer_.perspective() == Perspective::IS_SERVER) {
1497 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
QUICHE team8c1daa22019-03-13 08:33:41 -07001498 if (header.version_flag) {
1499 header.source_connection_id = connection_id_;
1500 header.source_connection_id_included = CONNECTION_ID_PRESENT;
1501 if (GetParam().version.handshake_protocol == PROTOCOL_QUIC_CRYPTO &&
1502 header.long_packet_type == ZERO_RTT_PROTECTED) {
QUICHE team548d51b2019-03-14 10:06:54 -07001503 header.nonce = &kTestDiversificationNonce;
QUICHE team8c1daa22019-03-13 08:33:41 -07001504 }
1505 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001506 }
QUICHE team2252b702019-05-14 23:55:14 -04001507 header.packet_number_length = packet_number_length_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001508 header.packet_number = QuicPacketNumber(number);
nharper46833c32019-05-15 21:33:05 -07001509 return header;
1510 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001511
nharper46833c32019-05-15 21:33:05 -07001512 std::unique_ptr<QuicPacket> ConstructDataPacket(uint64_t number,
1513 bool has_stop_waiting,
1514 EncryptionLevel level) {
1515 QuicPacketHeader header = ConstructPacketHeader(number, level);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001516 QuicFrames frames;
1517 frames.push_back(QuicFrame(frame1_));
1518 if (has_stop_waiting) {
1519 frames.push_back(QuicFrame(stop_waiting_));
1520 }
1521 return ConstructPacket(header, frames);
1522 }
1523
1524 OwningSerializedPacketPointer ConstructProbingPacket() {
fkastenholz305e1732019-06-18 05:01:22 -07001525 if (VersionHasIetfQuicFrames(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001526 QuicPathFrameBuffer payload = {
1527 {0xde, 0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xfe}};
1528 return QuicPacketCreatorPeer::
1529 SerializePathChallengeConnectivityProbingPacket(&peer_creator_,
1530 &payload);
1531 }
1532 return QuicPacketCreatorPeer::SerializeConnectivityProbingPacket(
1533 &peer_creator_);
1534 }
1535
1536 std::unique_ptr<QuicPacket> ConstructClosePacket(uint64_t number) {
1537 QuicPacketHeader header;
1538 // Set connection_id to peer's in memory representation as this connection
1539 // close packet 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_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001542 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
fayangd4291e42019-05-30 10:31:21 -07001543 if (!VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04001544 header.source_connection_id_included = CONNECTION_ID_PRESENT;
1545 }
1546 } else {
1547 header.destination_connection_id = connection_id_;
fayangd4291e42019-05-30 10:31:21 -07001548 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04001549 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1550 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001551 }
1552
QUICHE team2252b702019-05-14 23:55:14 -04001553 header.packet_number = QuicPacketNumber(number);
1554
fkastenholz0d6554a2019-08-05 12:20:35 -07001555 QuicErrorCode kQuicErrorCode = QUIC_PEER_GOING_AWAY;
fkastenholz591814c2019-09-06 12:11:46 -07001556 QuicConnectionCloseFrame qccf(peer_framer_.transport_version(),
1557 kQuicErrorCode, "",
1558 /*transport_close_frame_type=*/0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001559 QuicFrames frames;
1560 frames.push_back(QuicFrame(&qccf));
1561 return ConstructPacket(header, frames);
1562 }
1563
1564 QuicTime::Delta DefaultRetransmissionTime() {
1565 return QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
1566 }
1567
1568 QuicTime::Delta DefaultDelayedAckTime() {
1569 return QuicTime::Delta::FromMilliseconds(kDefaultDelayedAckTimeMs);
1570 }
1571
1572 const QuicStopWaitingFrame InitStopWaitingFrame(uint64_t least_unacked) {
1573 QuicStopWaitingFrame frame;
1574 frame.least_unacked = QuicPacketNumber(least_unacked);
1575 return frame;
1576 }
1577
1578 // Construct a ack_frame that acks all packet numbers between 1 and
1579 // |largest_acked|, except |missing|.
1580 // REQUIRES: 1 <= |missing| < |largest_acked|
1581 QuicAckFrame ConstructAckFrame(uint64_t largest_acked, uint64_t missing) {
1582 return ConstructAckFrame(QuicPacketNumber(largest_acked),
1583 QuicPacketNumber(missing));
1584 }
1585
1586 QuicAckFrame ConstructAckFrame(QuicPacketNumber largest_acked,
1587 QuicPacketNumber missing) {
1588 if (missing == QuicPacketNumber(1)) {
1589 return InitAckFrame({{missing + 1, largest_acked + 1}});
1590 }
1591 return InitAckFrame(
1592 {{QuicPacketNumber(1), missing}, {missing + 1, largest_acked + 1}});
1593 }
1594
1595 // Undo nacking a packet within the frame.
1596 void AckPacket(QuicPacketNumber arrived, QuicAckFrame* frame) {
1597 EXPECT_FALSE(frame->packets.Contains(arrived));
1598 frame->packets.Add(arrived);
1599 }
1600
1601 void TriggerConnectionClose() {
1602 // Send an erroneous packet to close the connection.
fkastenholz5d880a92019-06-21 09:01:56 -07001603 EXPECT_CALL(visitor_,
1604 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
1605 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
1606
QUICHE teamcd098022019-03-22 18:49:55 -07001607 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1608 // Triggers a connection by receiving ACK of unsent packet.
1609 QuicAckFrame frame = InitAckFrame(10000);
1610 ProcessAckPacket(1, &frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001611 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1612 nullptr);
fkastenholz5d880a92019-06-21 09:01:56 -07001613 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08001614 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
1615 IsError(QUIC_INVALID_ACK_DATA));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001616 }
1617
1618 void BlockOnNextWrite() {
1619 writer_->BlockOnNextWrite();
1620 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
1621 }
1622
1623 void SimulateNextPacketTooLarge() { writer_->SimulateNextPacketTooLarge(); }
1624
1625 void AlwaysGetPacketTooLarge() { writer_->AlwaysGetPacketTooLarge(); }
1626
1627 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
1628 writer_->SetWritePauseTimeDelta(delta);
1629 }
1630
1631 void CongestionBlockWrites() {
1632 EXPECT_CALL(*send_algorithm_, CanSend(_))
1633 .WillRepeatedly(testing::Return(false));
1634 }
1635
1636 void CongestionUnblockWrites() {
1637 EXPECT_CALL(*send_algorithm_, CanSend(_))
1638 .WillRepeatedly(testing::Return(true));
1639 }
1640
1641 void set_perspective(Perspective perspective) {
1642 connection_.set_perspective(perspective);
1643 if (perspective == Perspective::IS_SERVER) {
1644 connection_.set_can_truncate_connection_ids(true);
wub256b2d62019-11-25 08:46:55 -08001645 QuicConnectionPeer::SetNegotiatedVersion(&connection_);
wubbea386e2020-01-27 09:04:51 -08001646 connection_.OnSuccessfulVersionNegotiation();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001647 }
1648 QuicFramerPeer::SetPerspective(&peer_framer_,
nharper4eba09b2019-06-26 20:17:25 -07001649 QuicUtils::InvertPerspective(perspective));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001650 }
1651
1652 void set_packets_between_probes_base(
1653 const QuicPacketCount packets_between_probes_base) {
wub173916e2019-11-27 14:36:24 -08001654 QuicConnectionPeer::ReInitializeMtuDiscoverer(
1655 &connection_, packets_between_probes_base,
1656 QuicPacketNumber(packets_between_probes_base));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001657 }
1658
1659 bool IsDefaultTestConfiguration() {
1660 TestParams p = GetParam();
1661 return p.ack_response == AckResponse::kImmediate &&
1662 p.version == AllSupportedVersions()[0] && p.no_stop_waiting;
1663 }
1664
fkastenholz5d880a92019-06-21 09:01:56 -07001665 void TestConnectionCloseQuicErrorCode(QuicErrorCode expected_code) {
1666 // Not strictly needed for this test, but is commonly done.
1667 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1668 nullptr);
1669 const std::vector<QuicConnectionCloseFrame>& connection_close_frames =
1670 writer_->connection_close_frames();
1671 ASSERT_EQ(1u, connection_close_frames.size());
bnc77e77b82020-04-05 10:36:49 -07001672
dschinazi39e5e552020-05-06 13:55:24 -07001673 EXPECT_THAT(connection_close_frames[0].quic_error_code,
1674 IsError(expected_code));
bnc77e77b82020-04-05 10:36:49 -07001675
fkastenholz0d6554a2019-08-05 12:20:35 -07001676 if (!VersionHasIetfQuicFrames(version().transport_version)) {
dschinazi39e5e552020-05-06 13:55:24 -07001677 EXPECT_THAT(connection_close_frames[0].wire_error_code,
1678 IsError(expected_code));
fkastenholz0d6554a2019-08-05 12:20:35 -07001679 EXPECT_EQ(GOOGLE_QUIC_CONNECTION_CLOSE,
1680 connection_close_frames[0].close_type);
1681 return;
1682 }
1683
1684 QuicErrorCodeToIetfMapping mapping =
1685 QuicErrorCodeToTransportErrorCode(expected_code);
1686
bnc0054cc62020-04-09 18:22:57 -07001687 if (mapping.is_transport_close) {
fkastenholz0d6554a2019-08-05 12:20:35 -07001688 // This Google QUIC Error Code maps to a transport close,
1689 EXPECT_EQ(IETF_QUIC_TRANSPORT_CONNECTION_CLOSE,
1690 connection_close_frames[0].close_type);
fkastenholz0d6554a2019-08-05 12:20:35 -07001691 } else {
1692 // This maps to an application close.
fkastenholz0d6554a2019-08-05 12:20:35 -07001693 EXPECT_EQ(IETF_QUIC_APPLICATION_CONNECTION_CLOSE,
1694 connection_close_frames[0].close_type);
fkastenholz0d6554a2019-08-05 12:20:35 -07001695 }
bnc0054cc62020-04-09 18:22:57 -07001696 EXPECT_EQ(mapping.error_code, connection_close_frames[0].wire_error_code);
fkastenholz5d880a92019-06-21 09:01:56 -07001697 }
1698
wub031d47c2019-11-21 08:04:07 -08001699 void MtuDiscoveryTestInit() {
1700 set_perspective(Perspective::IS_SERVER);
wub031d47c2019-11-21 08:04:07 -08001701 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1702 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1703 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
1704 // QuicFramer::GetMaxPlaintextSize uses the smallest max plaintext size
1705 // across all encrypters. The initial encrypter used with IETF QUIC has a
1706 // 16-byte overhead, while the NullEncrypter used throughout this test has a
1707 // 12-byte overhead. This test tests behavior that relies on computing the
1708 // packet size correctly, so by unsetting the initial encrypter, we avoid
1709 // having a mismatch between the overheads for the encrypters used. In
1710 // non-test scenarios all encrypters used for a given connection have the
1711 // same overhead, either 12 bytes for ones using Google QUIC crypto, or 16
1712 // bytes for ones using TLS.
1713 connection_.SetEncrypter(ENCRYPTION_INITIAL, nullptr);
wubecb643f2020-03-19 08:58:46 -07001714 // Prevent packets from being coalesced.
1715 EXPECT_CALL(visitor_, GetHandshakeState())
1716 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
wub031d47c2019-11-21 08:04:07 -08001717 EXPECT_TRUE(connection_.connected());
1718 }
1719
dschinazi39e5e552020-05-06 13:55:24 -07001720 void TestClientRetryHandling(bool invalid_retry_tag,
1721 bool missing_id_in_config,
1722 bool wrong_id_in_config);
1723
QUICHE teama6ef0a62019-03-07 20:34:33 -05001724 QuicConnectionId connection_id_;
1725 QuicFramer framer_;
1726
1727 MockSendAlgorithm* send_algorithm_;
1728 std::unique_ptr<MockLossAlgorithm> loss_algorithm_;
1729 MockClock clock_;
1730 MockRandom random_generator_;
1731 SimpleBufferAllocator buffer_allocator_;
1732 std::unique_ptr<TestConnectionHelper> helper_;
1733 std::unique_ptr<TestAlarmFactory> alarm_factory_;
1734 QuicFramer peer_framer_;
1735 QuicPacketCreator peer_creator_;
1736 std::unique_ptr<TestPacketWriter> writer_;
1737 TestConnection connection_;
1738 QuicPacketCreator* creator_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001739 QuicSentPacketManager* manager_;
1740 StrictMock<MockQuicConnectionVisitor> visitor_;
1741
1742 QuicStreamFrame frame1_;
1743 QuicStreamFrame frame2_;
nharper46833c32019-05-15 21:33:05 -07001744 QuicCryptoFrame crypto_frame_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001745 QuicAckFrame ack_;
1746 QuicStopWaitingFrame stop_waiting_;
1747 QuicPacketNumberLength packet_number_length_;
1748 QuicConnectionIdIncluded connection_id_included_;
1749
1750 SimpleSessionNotifier notifier_;
fkastenholz5d880a92019-06-21 09:01:56 -07001751
1752 QuicConnectionCloseFrame saved_connection_close_frame_;
1753 int connection_close_frame_count_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001754};
1755
1756// Run all end to end tests with all supported versions.
dschinazi39e5e552020-05-06 13:55:24 -07001757INSTANTIATE_TEST_SUITE_P(QuicConnectionTests,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001758 QuicConnectionTest,
dschinazi142051a2019-09-18 18:17:29 -07001759 ::testing::ValuesIn(GetTestParams()),
1760 ::testing::PrintToStringParamName());
QUICHE teama6ef0a62019-03-07 20:34:33 -05001761
fkastenholz0d6554a2019-08-05 12:20:35 -07001762// These two tests ensure that the QuicErrorCode mapping works correctly.
1763// Both tests expect to see a Google QUIC close if not running IETF QUIC.
1764// If running IETF QUIC, the first will generate a transport connection
1765// close, the second an application connection close.
1766// The connection close codes for the two tests are manually chosen;
1767// they are expected to always map to transport- and application-
dschinazi39e5e552020-05-06 13:55:24 -07001768// closes, respectively. If that changes, new codes should be chosen.
fkastenholz0d6554a2019-08-05 12:20:35 -07001769TEST_P(QuicConnectionTest, CloseErrorCodeTestTransport) {
1770 EXPECT_TRUE(connection_.connected());
1771 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
1772 connection_.CloseConnection(
1773 IETF_QUIC_PROTOCOL_VIOLATION, "Should be transport close",
1774 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1775 EXPECT_FALSE(connection_.connected());
1776 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
1777}
1778
1779// Test that the IETF QUIC Error code mapping function works
1780// properly for application connection close codes.
1781TEST_P(QuicConnectionTest, CloseErrorCodeTestApplication) {
1782 EXPECT_TRUE(connection_.connected());
1783 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
1784 connection_.CloseConnection(
1785 QUIC_HEADERS_STREAM_DATA_DECOMPRESS_FAILURE,
1786 "Should be application close",
1787 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1788 EXPECT_FALSE(connection_.connected());
1789 TestConnectionCloseQuicErrorCode(QUIC_HEADERS_STREAM_DATA_DECOMPRESS_FAILURE);
1790}
1791
QUICHE teama6ef0a62019-03-07 20:34:33 -05001792TEST_P(QuicConnectionTest, SelfAddressChangeAtClient) {
1793 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1794
1795 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
1796 EXPECT_TRUE(connection_.connected());
1797
nharper46833c32019-05-15 21:33:05 -07001798 QuicFrame frame;
1799 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1800 frame = QuicFrame(&crypto_frame_);
1801 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1802 } else {
1803 frame = QuicFrame(QuicStreamFrame(
1804 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
dmcardlecf0bfcf2019-12-13 08:08:21 -08001805 0u, quiche::QuicheStringPiece()));
nharper46833c32019-05-15 21:33:05 -07001806 EXPECT_CALL(visitor_, OnStreamFrame(_));
1807 }
1808 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001809 // Cause change in self_address.
1810 QuicIpAddress host;
1811 host.FromString("1.1.1.1");
1812 QuicSocketAddress self_address(host, 123);
nharper46833c32019-05-15 21:33:05 -07001813 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1814 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1815 } else {
1816 EXPECT_CALL(visitor_, OnStreamFrame(_));
1817 }
1818 ProcessFramePacketWithAddresses(frame, self_address, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001819 EXPECT_TRUE(connection_.connected());
1820}
1821
1822TEST_P(QuicConnectionTest, SelfAddressChangeAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001823 set_perspective(Perspective::IS_SERVER);
1824 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1825
1826 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1827 EXPECT_TRUE(connection_.connected());
1828
nharper46833c32019-05-15 21:33:05 -07001829 QuicFrame frame;
1830 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1831 frame = QuicFrame(&crypto_frame_);
1832 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1833 } else {
1834 frame = QuicFrame(QuicStreamFrame(
1835 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
dmcardlecf0bfcf2019-12-13 08:08:21 -08001836 0u, quiche::QuicheStringPiece()));
nharper46833c32019-05-15 21:33:05 -07001837 EXPECT_CALL(visitor_, OnStreamFrame(_));
1838 }
1839 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001840 // Cause change in self_address.
1841 QuicIpAddress host;
1842 host.FromString("1.1.1.1");
1843 QuicSocketAddress self_address(host, 123);
1844 EXPECT_CALL(visitor_, AllowSelfAddressChange()).WillOnce(Return(false));
fkastenholz5d880a92019-06-21 09:01:56 -07001845 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
nharper46833c32019-05-15 21:33:05 -07001846 ProcessFramePacketWithAddresses(frame, self_address, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001847 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07001848 TestConnectionCloseQuicErrorCode(QUIC_ERROR_MIGRATING_ADDRESS);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001849}
1850
1851TEST_P(QuicConnectionTest, AllowSelfAddressChangeToMappedIpv4AddressAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001852 set_perspective(Perspective::IS_SERVER);
1853 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1854
1855 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1856 EXPECT_TRUE(connection_.connected());
1857
nharper46833c32019-05-15 21:33:05 -07001858 QuicFrame frame;
1859 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1860 frame = QuicFrame(&crypto_frame_);
1861 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(3);
1862 } else {
1863 frame = QuicFrame(QuicStreamFrame(
1864 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
dmcardlecf0bfcf2019-12-13 08:08:21 -08001865 0u, quiche::QuicheStringPiece()));
nharper46833c32019-05-15 21:33:05 -07001866 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(3);
1867 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001868 QuicIpAddress host;
1869 host.FromString("1.1.1.1");
1870 QuicSocketAddress self_address1(host, 443);
nharper46833c32019-05-15 21:33:05 -07001871 ProcessFramePacketWithAddresses(frame, self_address1, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001872 // Cause self_address change to mapped Ipv4 address.
1873 QuicIpAddress host2;
dmcardlecf0bfcf2019-12-13 08:08:21 -08001874 host2.FromString(quiche::QuicheStrCat(
1875 "::ffff:", connection_.self_address().host().ToString()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001876 QuicSocketAddress self_address2(host2, connection_.self_address().port());
nharper46833c32019-05-15 21:33:05 -07001877 ProcessFramePacketWithAddresses(frame, self_address2, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001878 EXPECT_TRUE(connection_.connected());
1879 // self_address change back to Ipv4 address.
nharper46833c32019-05-15 21:33:05 -07001880 ProcessFramePacketWithAddresses(frame, self_address1, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001881 EXPECT_TRUE(connection_.connected());
1882}
1883
1884TEST_P(QuicConnectionTest, ClientAddressChangeAndPacketReordered) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001885 set_perspective(Perspective::IS_SERVER);
1886 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1887
1888 // Clear direct_peer_address.
1889 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1890 // Clear effective_peer_address, it is the same as direct_peer_address for
1891 // this test.
1892 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1893 QuicSocketAddress());
1894
nharper46833c32019-05-15 21:33:05 -07001895 QuicFrame frame;
1896 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1897 frame = QuicFrame(&crypto_frame_);
1898 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1899 } else {
1900 frame = QuicFrame(QuicStreamFrame(
1901 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
dmcardlecf0bfcf2019-12-13 08:08:21 -08001902 0u, quiche::QuicheStringPiece()));
nharper46833c32019-05-15 21:33:05 -07001903 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1904 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001905 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001906 const QuicSocketAddress kNewPeerAddress =
1907 QuicSocketAddress(QuicIpAddress::Loopback6(),
1908 /*port=*/23456);
nharper46833c32019-05-15 21:33:05 -07001909 ProcessFramePacketWithAddresses(frame, kSelfAddress, kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001910 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1911 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1912
1913 // Decrease packet number to simulate out-of-order packets.
1914 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 4);
1915 // This is an old packet, do not migrate.
1916 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
nharper46833c32019-05-15 21:33:05 -07001917 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001918 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1919 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1920}
1921
1922TEST_P(QuicConnectionTest, PeerAddressChangeAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001923 set_perspective(Perspective::IS_SERVER);
1924 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1925 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1926
1927 // Clear direct_peer_address.
1928 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1929 // Clear effective_peer_address, it is the same as direct_peer_address for
1930 // this test.
1931 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1932 QuicSocketAddress());
1933 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1934
nharper46833c32019-05-15 21:33:05 -07001935 QuicFrame frame;
1936 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1937 frame = QuicFrame(&crypto_frame_);
1938 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1939 } else {
1940 frame = QuicFrame(QuicStreamFrame(
1941 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
dmcardlecf0bfcf2019-12-13 08:08:21 -08001942 0u, quiche::QuicheStringPiece()));
nharper46833c32019-05-15 21:33:05 -07001943 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1944 }
1945 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001946 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1947 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1948
1949 // Process another packet with a different peer address on server side will
1950 // start connection migration.
1951 const QuicSocketAddress kNewPeerAddress =
1952 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
1953 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
nharper46833c32019-05-15 21:33:05 -07001954 ProcessFramePacketWithAddresses(frame, kSelfAddress, kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001955 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1956 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1957}
1958
1959TEST_P(QuicConnectionTest, EffectivePeerAddressChangeAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001960 set_perspective(Perspective::IS_SERVER);
1961 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1962 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1963
1964 // Clear direct_peer_address.
1965 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1966 // Clear effective_peer_address, it is different from direct_peer_address for
1967 // this test.
1968 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1969 QuicSocketAddress());
1970 const QuicSocketAddress kEffectivePeerAddress =
1971 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/43210);
1972 connection_.ReturnEffectivePeerAddressForNextPacket(kEffectivePeerAddress);
1973
nharper46833c32019-05-15 21:33:05 -07001974 QuicFrame frame;
1975 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1976 frame = QuicFrame(&crypto_frame_);
1977 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1978 } else {
1979 frame = QuicFrame(QuicStreamFrame(
1980 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
dmcardlecf0bfcf2019-12-13 08:08:21 -08001981 0u, quiche::QuicheStringPiece()));
nharper46833c32019-05-15 21:33:05 -07001982 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1983 }
1984 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001985 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1986 EXPECT_EQ(kEffectivePeerAddress, connection_.effective_peer_address());
1987
1988 // Process another packet with the same direct peer address and different
1989 // effective peer address on server side will start connection migration.
1990 const QuicSocketAddress kNewEffectivePeerAddress =
1991 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/54321);
1992 connection_.ReturnEffectivePeerAddressForNextPacket(kNewEffectivePeerAddress);
1993 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
nharper46833c32019-05-15 21:33:05 -07001994 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001995 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1996 EXPECT_EQ(kNewEffectivePeerAddress, connection_.effective_peer_address());
1997
1998 // Process another packet with a different direct peer address and the same
1999 // effective peer address on server side will not start connection migration.
2000 const QuicSocketAddress kNewPeerAddress =
2001 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2002 connection_.ReturnEffectivePeerAddressForNextPacket(kNewEffectivePeerAddress);
2003 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2004 // ack_frame is used to complete the migration started by the last packet, we
2005 // need to make sure a new migration does not start after the previous one is
2006 // completed.
2007 QuicAckFrame ack_frame = InitAckFrame(1);
2008 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
2009 ProcessFramePacketWithAddresses(QuicFrame(&ack_frame), kSelfAddress,
2010 kNewPeerAddress);
2011 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2012 EXPECT_EQ(kNewEffectivePeerAddress, connection_.effective_peer_address());
2013
2014 // Process another packet with different direct peer address and different
2015 // effective peer address on server side will start connection migration.
2016 const QuicSocketAddress kNewerEffectivePeerAddress =
2017 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/65432);
2018 const QuicSocketAddress kFinalPeerAddress =
2019 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/34567);
2020 connection_.ReturnEffectivePeerAddressForNextPacket(
2021 kNewerEffectivePeerAddress);
2022 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
nharper46833c32019-05-15 21:33:05 -07002023 ProcessFramePacketWithAddresses(frame, kSelfAddress, kFinalPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002024 EXPECT_EQ(kFinalPeerAddress, connection_.peer_address());
2025 EXPECT_EQ(kNewerEffectivePeerAddress, connection_.effective_peer_address());
2026 EXPECT_EQ(PORT_CHANGE, connection_.active_effective_peer_migration_type());
2027
2028 // While the previous migration is ongoing, process another packet with the
2029 // same direct peer address and different effective peer address on server
2030 // side will start a new connection migration.
2031 const QuicSocketAddress kNewestEffectivePeerAddress =
2032 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/65430);
2033 connection_.ReturnEffectivePeerAddressForNextPacket(
2034 kNewestEffectivePeerAddress);
2035 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
2036 EXPECT_CALL(*send_algorithm_, OnConnectionMigration()).Times(1);
nharper46833c32019-05-15 21:33:05 -07002037 ProcessFramePacketWithAddresses(frame, kSelfAddress, kFinalPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002038 EXPECT_EQ(kFinalPeerAddress, connection_.peer_address());
2039 EXPECT_EQ(kNewestEffectivePeerAddress, connection_.effective_peer_address());
2040 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
2041 connection_.active_effective_peer_migration_type());
2042}
2043
zhongyif06ca342020-02-24 14:11:13 -08002044TEST_P(QuicConnectionTest, ReceivePathProbeWithNoAddressChangeAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002045 set_perspective(Perspective::IS_SERVER);
2046 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2047 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2048
2049 // Clear direct_peer_address.
2050 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2051 // Clear effective_peer_address, it is the same as direct_peer_address for
2052 // this test.
2053 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2054 QuicSocketAddress());
2055 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2056
nharper46833c32019-05-15 21:33:05 -07002057 QuicFrame frame;
2058 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2059 frame = QuicFrame(&crypto_frame_);
2060 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2061 } else {
2062 frame = QuicFrame(QuicStreamFrame(
2063 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
dmcardlecf0bfcf2019-12-13 08:08:21 -08002064 0u, quiche::QuicheStringPiece()));
nharper46833c32019-05-15 21:33:05 -07002065 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2066 }
2067 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002068 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2069 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2070
2071 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyi83161e42019-08-19 09:06:25 -07002072 EXPECT_CALL(visitor_, OnPacketReceived(_, _, false)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002073
2074 // Process a padded PING or PATH CHALLENGE packet with no peer address change
2075 // on server side will be ignored.
zhongyif06ca342020-02-24 14:11:13 -08002076 OwningSerializedPacketPointer probing_packet = ConstructProbingPacket();
2077
QUICHE teama6ef0a62019-03-07 20:34:33 -05002078 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2079 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2080 probing_packet->encrypted_length),
2081 clock_.Now()));
2082
2083 uint64_t num_probing_received =
2084 connection_.GetStats().num_connectivity_probing_received;
2085 ProcessReceivedPacket(kSelfAddress, kPeerAddress, *received);
2086
2087 EXPECT_EQ(num_probing_received,
2088 connection_.GetStats().num_connectivity_probing_received);
2089 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2090 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2091}
2092
2093TEST_P(QuicConnectionTest, WriteOutOfOrderQueuedPackets) {
2094 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
fayangc31c9952019-06-05 13:54:48 -07002095 if (!IsDefaultTestConfiguration()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002096 return;
2097 }
2098
2099 set_perspective(Perspective::IS_CLIENT);
2100
2101 BlockOnNextWrite();
2102
2103 QuicStreamId stream_id = 2;
2104 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
2105
2106 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2107
2108 writer_->SetWritable();
2109 connection_.SendConnectivityProbingPacket(writer_.get(),
2110 connection_.peer_address());
fayange62e63c2019-12-04 07:16:25 -08002111 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
2112 connection_.OnCanWrite();
QUICHE teama6ef0a62019-03-07 20:34:33 -05002113}
2114
2115TEST_P(QuicConnectionTest, DiscardQueuedPacketsAfterConnectionClose) {
2116 // Regression test for b/74073386.
2117 {
2118 InSequence seq;
rch39c88ab2019-10-16 19:24:40 -07002119 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2120 .Times(AtLeast(1));
2121 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002122 }
2123
2124 set_perspective(Perspective::IS_CLIENT);
2125
2126 writer_->SimulateNextPacketTooLarge();
2127
2128 // This packet write should fail, which should cause the connection to close
2129 // after sending a connection close packet, then the failed packet should be
2130 // queued.
2131 connection_.SendStreamDataWithString(/*id=*/2, "foo", 0, NO_FIN);
2132
2133 EXPECT_FALSE(connection_.connected());
fayange62e63c2019-12-04 07:16:25 -08002134 // No need to buffer packets.
2135 EXPECT_EQ(0u, connection_.NumQueuedPackets());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002136
2137 EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
2138 connection_.OnCanWrite();
fayang0f0c4e62019-07-16 08:55:54 -07002139 EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002140}
2141
zhongyif06ca342020-02-24 14:11:13 -08002142// Receive a path probe request at the server side, i.e.,
2143// in non-IETF version: receive a padded PING packet with a peer addess change;
2144// in IETF version: receive a packet contains PATH CHALLENGE with peer address
2145// change.
2146TEST_P(QuicConnectionTest, ReceivePathProbingAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002147 set_perspective(Perspective::IS_SERVER);
2148 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2149 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2150
2151 // Clear direct_peer_address.
2152 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2153 // Clear effective_peer_address, it is the same as direct_peer_address for
2154 // this test.
2155 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2156 QuicSocketAddress());
2157 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2158
nharper46833c32019-05-15 21:33:05 -07002159 QuicFrame frame;
2160 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2161 frame = QuicFrame(&crypto_frame_);
2162 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2163 } else {
2164 frame = QuicFrame(QuicStreamFrame(
2165 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
dmcardlecf0bfcf2019-12-13 08:08:21 -08002166 0u, quiche::QuicheStringPiece()));
nharper46833c32019-05-15 21:33:05 -07002167 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2168 }
2169 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002170 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2171 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2172
2173 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyif06ca342020-02-24 14:11:13 -08002174 if (!GetParam().version.HasIetfQuicFrames()) {
2175 EXPECT_CALL(visitor_,
2176 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2177 .Times(1);
2178 } else {
2179 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2180 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002181 // Process a padded PING packet from a new peer address on server side
2182 // is effectively receiving a connectivity probing.
2183 const QuicSocketAddress kNewPeerAddress =
2184 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2185
2186 OwningSerializedPacketPointer probing_packet = ConstructProbingPacket();
2187 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2188 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2189 probing_packet->encrypted_length),
2190 clock_.Now()));
2191
2192 uint64_t num_probing_received =
2193 connection_.GetStats().num_connectivity_probing_received;
2194 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2195
2196 EXPECT_EQ(num_probing_received + 1,
2197 connection_.GetStats().num_connectivity_probing_received);
2198 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2199 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2200
2201 // Process another packet with the old peer address on server side will not
2202 // start peer migration.
2203 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
nharper46833c32019-05-15 21:33:05 -07002204 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002205 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2206 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2207}
2208
zhongyif06ca342020-02-24 14:11:13 -08002209// Receive a padded PING packet with a port change on server side.
2210TEST_P(QuicConnectionTest, ReceivePaddedPingWithPortChangeAtServer) {
2211 set_perspective(Perspective::IS_SERVER);
2212 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2213 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2214
2215 // Clear direct_peer_address.
2216 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2217 // Clear effective_peer_address, it is the same as direct_peer_address for
2218 // this test.
2219 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2220 QuicSocketAddress());
2221 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2222
2223 QuicFrame frame;
2224 if (GetParam().version.UsesCryptoFrames()) {
2225 frame = QuicFrame(&crypto_frame_);
2226 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2227 } else {
2228 frame = QuicFrame(QuicStreamFrame(
2229 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
2230 0u, quiche::QuicheStringPiece()));
2231 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2232 }
2233 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
2234 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2235 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2236
2237 if (GetParam().version.HasIetfQuicFrames()) {
2238 // In IETF version, a padded PING packet with port change is not taken as
2239 // connectivity probe.
2240 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2241 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2242 } else {
2243 // In non-IETF version, process a padded PING packet from a new peer
2244 // address on server side is effectively receiving a connectivity probing.
2245 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2246 EXPECT_CALL(visitor_,
2247 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2248 .Times(1);
2249 }
2250 const QuicSocketAddress kNewPeerAddress =
2251 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2252
2253 QuicFrames frames;
2254 // Write a PING frame, which has no data payload.
2255 QuicPingFrame ping_frame;
2256 frames.push_back(QuicFrame(ping_frame));
2257
2258 // Add padding to the rest of the packet.
2259 QuicPaddingFrame padding_frame;
2260 frames.push_back(QuicFrame(padding_frame));
2261
2262 uint64_t num_probing_received =
2263 connection_.GetStats().num_connectivity_probing_received;
2264
2265 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress);
2266
2267 if (GetParam().version.HasIetfQuicFrames()) {
2268 // Padded PING with port changen is not considered as connectivity probe but
2269 // a PORT CHANGE.
2270 EXPECT_EQ(num_probing_received,
2271 connection_.GetStats().num_connectivity_probing_received);
2272 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2273 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2274 } else {
2275 EXPECT_EQ(num_probing_received + 1,
2276 connection_.GetStats().num_connectivity_probing_received);
2277 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2278 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2279 }
2280
2281 // Process another packet with the old peer address on server side.
2282 if (GetParam().version.HasIetfQuicFrames()) {
2283 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2284 } else {
2285 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2286 }
2287 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
2288 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2289 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2290}
2291
2292TEST_P(QuicConnectionTest, ReceiveReorderedPathProbingAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002293 set_perspective(Perspective::IS_SERVER);
2294 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2295 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2296
2297 // Clear direct_peer_address.
2298 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2299 // Clear effective_peer_address, it is the same as direct_peer_address for
2300 // this test.
2301 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2302 QuicSocketAddress());
2303 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2304
nharper46833c32019-05-15 21:33:05 -07002305 QuicFrame frame;
2306 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2307 frame = QuicFrame(&crypto_frame_);
2308 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2309 } else {
2310 frame = QuicFrame(QuicStreamFrame(
2311 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
dmcardlecf0bfcf2019-12-13 08:08:21 -08002312 0u, quiche::QuicheStringPiece()));
nharper46833c32019-05-15 21:33:05 -07002313 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2314 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002315 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
nharper46833c32019-05-15 21:33:05 -07002316 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002317 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2318 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2319
2320 // Decrease packet number to simulate out-of-order packets.
2321 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 4);
2322
2323 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyif06ca342020-02-24 14:11:13 -08002324 if (!GetParam().version.HasIetfQuicFrames()) {
2325 EXPECT_CALL(visitor_,
2326 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2327 .Times(1);
2328 } else {
2329 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2330 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002331
2332 // Process a padded PING packet from a new peer address on server side
2333 // is effectively receiving a connectivity probing, even if a newer packet has
2334 // been received before this one.
2335 const QuicSocketAddress kNewPeerAddress =
2336 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2337
2338 OwningSerializedPacketPointer probing_packet = ConstructProbingPacket();
2339 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2340 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2341 probing_packet->encrypted_length),
2342 clock_.Now()));
2343
2344 uint64_t num_probing_received =
2345 connection_.GetStats().num_connectivity_probing_received;
2346 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2347
2348 EXPECT_EQ(num_probing_received + 1,
2349 connection_.GetStats().num_connectivity_probing_received);
2350 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2351 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2352}
2353
2354TEST_P(QuicConnectionTest, MigrateAfterProbingAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002355 set_perspective(Perspective::IS_SERVER);
2356 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2357 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2358
2359 // Clear direct_peer_address.
2360 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2361 // Clear effective_peer_address, it is the same as direct_peer_address for
2362 // this test.
2363 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2364 QuicSocketAddress());
2365 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2366
nharper46833c32019-05-15 21:33:05 -07002367 QuicFrame frame;
2368 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2369 frame = QuicFrame(&crypto_frame_);
2370 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2371 } else {
2372 frame = QuicFrame(QuicStreamFrame(
2373 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
dmcardlecf0bfcf2019-12-13 08:08:21 -08002374 0u, quiche::QuicheStringPiece()));
nharper46833c32019-05-15 21:33:05 -07002375 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2376 }
2377 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002378 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2379 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2380
2381 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyif06ca342020-02-24 14:11:13 -08002382 if (!GetParam().version.HasIetfQuicFrames()) {
2383 EXPECT_CALL(visitor_,
2384 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2385 .Times(1);
2386 } else {
2387 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2388 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002389
2390 // Process a padded PING packet from a new peer address on server side
2391 // is effectively receiving a connectivity probing.
2392 const QuicSocketAddress kNewPeerAddress =
2393 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2394
2395 OwningSerializedPacketPointer probing_packet = ConstructProbingPacket();
2396 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2397 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2398 probing_packet->encrypted_length),
2399 clock_.Now()));
2400 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2401 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2402 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2403
2404 // Process another non-probing packet with the new peer address on server
2405 // side will start peer migration.
2406 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2407
nharper46833c32019-05-15 21:33:05 -07002408 ProcessFramePacketWithAddresses(frame, kSelfAddress, kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002409 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2410 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2411}
2412
2413TEST_P(QuicConnectionTest, ReceivePaddedPingAtClient) {
2414 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2415 set_perspective(Perspective::IS_CLIENT);
2416 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2417
2418 // Clear direct_peer_address.
2419 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2420 // Clear effective_peer_address, it is the same as direct_peer_address for
2421 // this test.
2422 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2423 QuicSocketAddress());
2424 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2425
nharper46833c32019-05-15 21:33:05 -07002426 QuicFrame frame;
2427 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2428 frame = QuicFrame(&crypto_frame_);
2429 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2430 } else {
2431 frame = QuicFrame(QuicStreamFrame(
2432 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
dmcardlecf0bfcf2019-12-13 08:08:21 -08002433 0u, quiche::QuicheStringPiece()));
nharper46833c32019-05-15 21:33:05 -07002434 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2435 }
2436 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002437 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2438 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2439
2440 // Client takes all padded PING packet as speculative connectivity
2441 // probing packet, and reports to visitor.
2442 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyi83161e42019-08-19 09:06:25 -07002443 EXPECT_CALL(visitor_, OnPacketReceived(_, _, false)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002444
2445 OwningSerializedPacketPointer probing_packet = ConstructProbingPacket();
2446 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2447 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2448 probing_packet->encrypted_length),
2449 clock_.Now()));
2450 uint64_t num_probing_received =
2451 connection_.GetStats().num_connectivity_probing_received;
2452 ProcessReceivedPacket(kSelfAddress, kPeerAddress, *received);
2453
2454 EXPECT_EQ(num_probing_received,
2455 connection_.GetStats().num_connectivity_probing_received);
2456 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2457 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2458}
2459
zhongyif06ca342020-02-24 14:11:13 -08002460TEST_P(QuicConnectionTest, ReceiveConnectivityProbingResponseAtClient) {
2461 // TODO(b/150095484): add test coverage for IETF to verify that client takes
2462 // PATH RESPONSE with peer address change as correct validation on the new
2463 // path.
2464 if (GetParam().version.HasIetfQuicFrames()) {
2465 return;
2466 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002467 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2468 set_perspective(Perspective::IS_CLIENT);
2469 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2470
2471 // Clear direct_peer_address.
2472 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2473 // Clear effective_peer_address, it is the same as direct_peer_address for
2474 // this test.
2475 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2476 QuicSocketAddress());
2477 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2478
nharper46833c32019-05-15 21:33:05 -07002479 QuicFrame frame;
2480 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2481 frame = QuicFrame(&crypto_frame_);
2482 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2483 } else {
2484 frame = QuicFrame(QuicStreamFrame(
2485 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
dmcardlecf0bfcf2019-12-13 08:08:21 -08002486 0u, quiche::QuicheStringPiece()));
nharper46833c32019-05-15 21:33:05 -07002487 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2488 }
2489 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002490 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2491 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2492
2493 // Process a padded PING packet with a different self address on client side
2494 // is effectively receiving a connectivity probing.
2495 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyif06ca342020-02-24 14:11:13 -08002496 if (!GetParam().version.HasIetfQuicFrames()) {
2497 EXPECT_CALL(visitor_,
2498 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2499 .Times(1);
2500 } else {
2501 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2502 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002503
2504 const QuicSocketAddress kNewSelfAddress =
2505 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2506
2507 OwningSerializedPacketPointer probing_packet = ConstructProbingPacket();
2508 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2509 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2510 probing_packet->encrypted_length),
2511 clock_.Now()));
2512 uint64_t num_probing_received =
2513 connection_.GetStats().num_connectivity_probing_received;
2514 ProcessReceivedPacket(kNewSelfAddress, kPeerAddress, *received);
2515
2516 EXPECT_EQ(num_probing_received + 1,
2517 connection_.GetStats().num_connectivity_probing_received);
2518 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2519 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2520}
2521
2522TEST_P(QuicConnectionTest, PeerAddressChangeAtClient) {
2523 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2524 set_perspective(Perspective::IS_CLIENT);
2525 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2526
2527 // Clear direct_peer_address.
2528 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2529 // Clear effective_peer_address, it is the same as direct_peer_address for
2530 // this test.
2531 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2532 QuicSocketAddress());
2533 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2534
nharper46833c32019-05-15 21:33:05 -07002535 QuicFrame frame;
2536 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2537 frame = QuicFrame(&crypto_frame_);
2538 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2539 } else {
2540 frame = QuicFrame(QuicStreamFrame(
2541 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
dmcardlecf0bfcf2019-12-13 08:08:21 -08002542 0u, quiche::QuicheStringPiece()));
nharper46833c32019-05-15 21:33:05 -07002543 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2544 }
2545 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002546 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2547 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2548
2549 // Process another packet with a different peer address on client side will
2550 // only update peer address.
2551 const QuicSocketAddress kNewPeerAddress =
2552 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2553 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
nharper46833c32019-05-15 21:33:05 -07002554 ProcessFramePacketWithAddresses(frame, kSelfAddress, kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002555 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2556 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2557}
2558
2559TEST_P(QuicConnectionTest, MaxPacketSize) {
2560 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2561 EXPECT_EQ(1350u, connection_.max_packet_length());
2562}
2563
dschinazi4ad1f462020-01-16 11:56:52 -08002564TEST_P(QuicConnectionTest, PeerLowersMaxPacketSize) {
2565 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2566
2567 // SetFromConfig is always called after construction from InitializeSession.
2568 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
2569 constexpr uint32_t kTestMaxPacketSize = 1233u;
2570 QuicConfig config;
2571 QuicConfigPeer::SetReceivedMaxPacketSize(&config, kTestMaxPacketSize);
2572 connection_.SetFromConfig(config);
2573
2574 EXPECT_EQ(kTestMaxPacketSize, connection_.max_packet_length());
2575}
2576
vasilvvebc5d0c2020-01-16 15:19:21 -08002577TEST_P(QuicConnectionTest, PeerCannotRaiseMaxPacketSize) {
2578 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2579
2580 // SetFromConfig is always called after construction from InitializeSession.
2581 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
2582 constexpr uint32_t kTestMaxPacketSize = 1450u;
2583 QuicConfig config;
2584 QuicConfigPeer::SetReceivedMaxPacketSize(&config, kTestMaxPacketSize);
2585 connection_.SetFromConfig(config);
2586
2587 EXPECT_EQ(kDefaultMaxPacketSize, connection_.max_packet_length());
2588}
2589
QUICHE teama6ef0a62019-03-07 20:34:33 -05002590TEST_P(QuicConnectionTest, SmallerServerMaxPacketSize) {
2591 TestConnection connection(TestConnectionId(), kPeerAddress, helper_.get(),
2592 alarm_factory_.get(), writer_.get(),
2593 Perspective::IS_SERVER, version());
2594 EXPECT_EQ(Perspective::IS_SERVER, connection.perspective());
2595 EXPECT_EQ(1000u, connection.max_packet_length());
2596}
2597
2598TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSize) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002599 set_perspective(Perspective::IS_SERVER);
2600 connection_.SetMaxPacketLength(1000);
2601
2602 QuicPacketHeader header;
2603 header.destination_connection_id = connection_id_;
2604 header.version_flag = true;
nharper21af28e2019-06-17 15:54:34 -07002605 header.packet_number = QuicPacketNumber(12);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002606
2607 if (QuicVersionHasLongHeaderLengths(
2608 peer_framer_.version().transport_version)) {
2609 header.long_packet_type = INITIAL;
2610 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
2611 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
2612 }
2613
2614 QuicFrames frames;
2615 QuicPaddingFrame padding;
nharper46833c32019-05-15 21:33:05 -07002616 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2617 frames.push_back(QuicFrame(&crypto_frame_));
2618 } else {
2619 frames.push_back(QuicFrame(frame1_));
2620 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002621 frames.push_back(QuicFrame(padding));
2622 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
dschinazi66dea072019-04-09 11:41:06 -07002623 char buffer[kMaxOutgoingPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07002624 size_t encrypted_length =
2625 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12),
dschinazi66dea072019-04-09 11:41:06 -07002626 *packet, buffer, kMaxOutgoingPacketSize);
2627 EXPECT_EQ(kMaxOutgoingPacketSize, encrypted_length);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002628
2629 framer_.set_version(version());
nharper46833c32019-05-15 21:33:05 -07002630 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2631 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
2632 } else {
2633 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2634 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002635 connection_.ProcessUdpPacket(
2636 kSelfAddress, kPeerAddress,
2637 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
2638
dschinazi66dea072019-04-09 11:41:06 -07002639 EXPECT_EQ(kMaxOutgoingPacketSize, connection_.max_packet_length());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002640}
2641
2642TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSizeWhileWriterLimited) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002643 const QuicByteCount lower_max_packet_size = 1240;
2644 writer_->set_max_packet_size(lower_max_packet_size);
2645 set_perspective(Perspective::IS_SERVER);
2646 connection_.SetMaxPacketLength(1000);
2647 EXPECT_EQ(1000u, connection_.max_packet_length());
2648
2649 QuicPacketHeader header;
2650 header.destination_connection_id = connection_id_;
2651 header.version_flag = true;
nharper21af28e2019-06-17 15:54:34 -07002652 header.packet_number = QuicPacketNumber(12);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002653
2654 if (QuicVersionHasLongHeaderLengths(
2655 peer_framer_.version().transport_version)) {
2656 header.long_packet_type = INITIAL;
2657 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
2658 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
2659 }
2660
2661 QuicFrames frames;
2662 QuicPaddingFrame padding;
nharper46833c32019-05-15 21:33:05 -07002663 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2664 frames.push_back(QuicFrame(&crypto_frame_));
2665 } else {
2666 frames.push_back(QuicFrame(frame1_));
2667 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002668 frames.push_back(QuicFrame(padding));
2669 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
dschinazi66dea072019-04-09 11:41:06 -07002670 char buffer[kMaxOutgoingPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07002671 size_t encrypted_length =
2672 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12),
dschinazi66dea072019-04-09 11:41:06 -07002673 *packet, buffer, kMaxOutgoingPacketSize);
2674 EXPECT_EQ(kMaxOutgoingPacketSize, encrypted_length);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002675
2676 framer_.set_version(version());
nharper46833c32019-05-15 21:33:05 -07002677 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2678 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
2679 } else {
2680 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2681 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002682 connection_.ProcessUdpPacket(
2683 kSelfAddress, kPeerAddress,
2684 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
2685
2686 // Here, the limit imposed by the writer is lower than the size of the packet
2687 // received, so the writer max packet size is used.
2688 EXPECT_EQ(lower_max_packet_size, connection_.max_packet_length());
2689}
2690
2691TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriter) {
2692 const QuicByteCount lower_max_packet_size = 1240;
2693 writer_->set_max_packet_size(lower_max_packet_size);
2694
2695 static_assert(lower_max_packet_size < kDefaultMaxPacketSize,
2696 "Default maximum packet size is too low");
2697 connection_.SetMaxPacketLength(kDefaultMaxPacketSize);
2698
2699 EXPECT_EQ(lower_max_packet_size, connection_.max_packet_length());
2700}
2701
2702TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriterForNewConnection) {
2703 const QuicConnectionId connection_id = TestConnectionId(17);
2704 const QuicByteCount lower_max_packet_size = 1240;
2705 writer_->set_max_packet_size(lower_max_packet_size);
2706 TestConnection connection(connection_id, kPeerAddress, helper_.get(),
2707 alarm_factory_.get(), writer_.get(),
2708 Perspective::IS_CLIENT, version());
2709 EXPECT_EQ(Perspective::IS_CLIENT, connection.perspective());
2710 EXPECT_EQ(lower_max_packet_size, connection.max_packet_length());
2711}
2712
2713TEST_P(QuicConnectionTest, PacketsInOrder) {
2714 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2715
2716 ProcessPacket(1);
fayangc31c9952019-06-05 13:54:48 -07002717 EXPECT_EQ(QuicPacketNumber(1u), LargestAcked(connection_.ack_frame()));
2718 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002719
2720 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07002721 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(connection_.ack_frame()));
2722 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002723
2724 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002725 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
2726 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002727}
2728
2729TEST_P(QuicConnectionTest, PacketsOutOfOrder) {
2730 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2731
2732 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002733 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002734 EXPECT_TRUE(IsMissing(2));
2735 EXPECT_TRUE(IsMissing(1));
2736
2737 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07002738 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002739 EXPECT_FALSE(IsMissing(2));
2740 EXPECT_TRUE(IsMissing(1));
2741
2742 ProcessPacket(1);
fayangc31c9952019-06-05 13:54:48 -07002743 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002744 EXPECT_FALSE(IsMissing(2));
2745 EXPECT_FALSE(IsMissing(1));
2746}
2747
2748TEST_P(QuicConnectionTest, DuplicatePacket) {
2749 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2750
2751 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002752 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002753 EXPECT_TRUE(IsMissing(2));
2754 EXPECT_TRUE(IsMissing(1));
2755
2756 // Send packet 3 again, but do not set the expectation that
2757 // the visitor OnStreamFrame() will be called.
2758 ProcessDataPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002759 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002760 EXPECT_TRUE(IsMissing(2));
2761 EXPECT_TRUE(IsMissing(1));
2762}
2763
2764TEST_P(QuicConnectionTest, PacketsOutOfOrderWithAdditionsAndLeastAwaiting) {
QUICHE teamcd098022019-03-22 18:49:55 -07002765 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2766 return;
2767 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002768 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2769
2770 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002771 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002772 EXPECT_TRUE(IsMissing(2));
2773 EXPECT_TRUE(IsMissing(1));
2774
2775 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07002776 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002777 EXPECT_TRUE(IsMissing(1));
2778
2779 ProcessPacket(5);
fayangc31c9952019-06-05 13:54:48 -07002780 EXPECT_EQ(QuicPacketNumber(5u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002781 EXPECT_TRUE(IsMissing(1));
2782 EXPECT_TRUE(IsMissing(4));
2783
2784 // Pretend at this point the client has gotten acks for 2 and 3 and 1 is a
2785 // packet the peer will not retransmit. It indicates this by sending 'least
2786 // awaiting' is 4. The connection should then realize 1 will not be
2787 // retransmitted, and will remove it from the missing list.
2788 QuicAckFrame frame = InitAckFrame(1);
2789 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
2790 ProcessAckPacket(6, &frame);
2791
2792 // Force an ack to be sent.
2793 SendAckPacketToPeer();
2794 EXPECT_TRUE(IsMissing(4));
2795}
2796
QUICHE teama6ef0a62019-03-07 20:34:33 -05002797TEST_P(QuicConnectionTest, RejectUnencryptedStreamData) {
2798 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
2799 if (!IsDefaultTestConfiguration()) {
2800 return;
2801 }
2802
2803 // Process an unencrypted packet from the non-crypto stream.
2804 frame1_.stream_id = 3;
2805 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fkastenholz5d880a92019-06-21 09:01:56 -07002806 EXPECT_CALL(visitor_,
2807 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
nharper2c9f02a2019-05-08 10:25:50 -07002808 EXPECT_QUIC_PEER_BUG(ProcessDataPacketAtLevel(1, false, ENCRYPTION_INITIAL),
2809 "");
fkastenholz5d880a92019-06-21 09:01:56 -07002810 TestConnectionCloseQuicErrorCode(QUIC_UNENCRYPTED_STREAM_DATA);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002811}
2812
2813TEST_P(QuicConnectionTest, OutOfOrderReceiptCausesAckSend) {
2814 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2815
2816 ProcessPacket(3);
fayang6dba4902019-06-17 10:04:23 -07002817 // Should not cause an ack.
2818 EXPECT_EQ(0u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002819
2820 ProcessPacket(2);
fayang6dba4902019-06-17 10:04:23 -07002821 // Should ack immediately, since this fills the last hole.
2822 EXPECT_EQ(1u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002823
2824 ProcessPacket(1);
2825 // Should ack immediately, since this fills the last hole.
fayang6dba4902019-06-17 10:04:23 -07002826 EXPECT_EQ(2u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002827
2828 ProcessPacket(4);
2829 // Should not cause an ack.
fayang6dba4902019-06-17 10:04:23 -07002830 EXPECT_EQ(2u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002831}
2832
2833TEST_P(QuicConnectionTest, OutOfOrderAckReceiptCausesNoAck) {
2834 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2835
2836 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
2837 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
2838 EXPECT_EQ(2u, writer_->packets_write_attempts());
2839
2840 QuicAckFrame ack1 = InitAckFrame(1);
2841 QuicAckFrame ack2 = InitAckFrame(2);
2842 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
fayang2f2915d2020-01-24 06:47:15 -08002843 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2844 EXPECT_CALL(visitor_, OnOneRttPacketAcknowledged()).Times(1);
2845 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002846 ProcessAckPacket(2, &ack2);
2847 // Should ack immediately since we have missing packets.
2848 EXPECT_EQ(2u, writer_->packets_write_attempts());
2849
fayang2f2915d2020-01-24 06:47:15 -08002850 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2851 EXPECT_CALL(visitor_, OnOneRttPacketAcknowledged()).Times(0);
2852 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002853 ProcessAckPacket(1, &ack1);
2854 // Should not ack an ack filling a missing packet.
2855 EXPECT_EQ(2u, writer_->packets_write_attempts());
2856}
2857
2858TEST_P(QuicConnectionTest, AckReceiptCausesAckSend) {
2859 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2860 QuicPacketNumber original, second;
2861
2862 QuicByteCount packet_size =
2863 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &original); // 1st packet.
2864 SendStreamDataToPeer(3, "bar", 3, NO_FIN, &second); // 2nd packet.
2865
2866 QuicAckFrame frame = InitAckFrame({{second, second + 1}});
2867 // First nack triggers early retransmit.
2868 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07002869 lost_packets.push_back(LostPacket(original, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002870 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
2871 .WillOnce(SetArgPointee<5>(lost_packets));
2872 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2873 QuicPacketNumber retransmission;
2874 // Packet 1 is short header for IETF QUIC because the encryption level
2875 // switched to ENCRYPTION_FORWARD_SECURE in SendStreamDataToPeer.
fayangd4291e42019-05-30 10:31:21 -07002876 EXPECT_CALL(*send_algorithm_,
2877 OnPacketSent(_, _, _,
2878 VersionHasIetfInvariantHeader(
2879 GetParam().version.transport_version)
2880 ? packet_size
2881 : packet_size - kQuicVersionSize,
2882 _))
QUICHE teama6ef0a62019-03-07 20:34:33 -05002883 .WillOnce(SaveArg<2>(&retransmission));
2884
2885 ProcessAckPacket(&frame);
2886
2887 QuicAckFrame frame2 = ConstructAckFrame(retransmission, original);
2888 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2889 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
2890 ProcessAckPacket(&frame2);
2891
2892 // Now if the peer sends an ack which still reports the retransmitted packet
2893 // as missing, that will bundle an ack with data after two acks in a row
2894 // indicate the high water mark needs to be raised.
2895 EXPECT_CALL(*send_algorithm_,
2896 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA));
2897 connection_.SendStreamDataWithString(3, "foo", 6, NO_FIN);
2898 // No ack sent.
nharper55fa6132019-05-07 19:37:21 -07002899 size_t padding_frame_count = writer_->padding_frames().size();
2900 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002901 EXPECT_EQ(1u, writer_->stream_frames().size());
2902
2903 // No more packet loss for the rest of the test.
2904 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
2905 .Times(AnyNumber());
2906 ProcessAckPacket(&frame2);
2907 EXPECT_CALL(*send_algorithm_,
2908 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA));
fayang03916692019-05-22 17:57:18 -07002909 connection_.SendStreamDataWithString(3, "foofoofoo", 9, NO_FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002910 // Ack bundled.
2911 if (GetParam().no_stop_waiting) {
fayang8a27b0f2019-11-04 11:27:40 -08002912 // Do not ACK acks.
2913 EXPECT_EQ(1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002914 } else {
2915 EXPECT_EQ(3u, writer_->frame_count());
2916 }
2917 EXPECT_EQ(1u, writer_->stream_frames().size());
fayang8a27b0f2019-11-04 11:27:40 -08002918 if (GetParam().no_stop_waiting) {
fayang03916692019-05-22 17:57:18 -07002919 EXPECT_TRUE(writer_->ack_frames().empty());
2920 } else {
2921 EXPECT_FALSE(writer_->ack_frames().empty());
2922 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002923
2924 // But an ack with no missing packets will not send an ack.
2925 AckPacket(original, &frame2);
2926 ProcessAckPacket(&frame2);
2927 ProcessAckPacket(&frame2);
2928}
2929
2930TEST_P(QuicConnectionTest, AckSentEveryNthPacket) {
2931 connection_.set_ack_frequency_before_ack_decimation(3);
2932
2933 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2934 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(39);
2935
2936 // Expect 13 acks, every 3rd packet.
2937 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(13);
2938 // Receives packets 1 - 39.
2939 for (size_t i = 1; i <= 39; ++i) {
2940 ProcessDataPacket(i);
2941 }
2942}
2943
2944TEST_P(QuicConnectionTest, AckDecimationReducesAcks) {
2945 const size_t kMinRttMs = 40;
2946 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
2947 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
2948 QuicTime::Delta::Zero(), QuicTime::Zero());
2949 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
2950
2951 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
2952
2953 // Start ack decimation from 10th packet.
2954 connection_.set_min_received_before_ack_decimation(10);
2955
2956 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2957 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(30);
2958
2959 // Expect 6 acks: 5 acks between packets 1-10, and ack at 20.
2960 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(6);
2961 // Receives packets 1 - 29.
2962 for (size_t i = 1; i <= 29; ++i) {
2963 ProcessDataPacket(i);
2964 }
2965
2966 // We now receive the 30th packet, and so we send an ack.
2967 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2968 ProcessDataPacket(30);
2969}
2970
2971TEST_P(QuicConnectionTest, AckNeedsRetransmittableFrames) {
ianswett68cf0042019-05-09 08:37:58 -07002972 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002973 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2974 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(99);
2975
2976 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(19);
2977 // Receives packets 1 - 39.
2978 for (size_t i = 1; i <= 39; ++i) {
2979 ProcessDataPacket(i);
2980 }
2981 // Receiving Packet 40 causes 20th ack to send. Session is informed and adds
2982 // WINDOW_UPDATE.
2983 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
2984 .WillOnce(Invoke([this]() {
2985 connection_.SendControlFrame(
2986 QuicFrame(new QuicWindowUpdateFrame(1, 0, 0)));
2987 }));
2988 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2989 EXPECT_EQ(0u, writer_->window_update_frames().size());
2990 ProcessDataPacket(40);
2991 EXPECT_EQ(1u, writer_->window_update_frames().size());
2992
2993 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(9);
2994 // Receives packets 41 - 59.
2995 for (size_t i = 41; i <= 59; ++i) {
2996 ProcessDataPacket(i);
2997 }
2998 // Send a packet containing stream frame.
QUICHE team8c1daa22019-03-13 08:33:41 -07002999 SendStreamDataToPeer(
nharper46833c32019-05-15 21:33:05 -07003000 QuicUtils::GetFirstBidirectionalStreamId(
3001 connection_.version().transport_version, Perspective::IS_CLIENT),
QUICHE team8c1daa22019-03-13 08:33:41 -07003002 "bar", 0, NO_FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003003
3004 // Session will not be informed until receiving another 20 packets.
3005 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(19);
3006 for (size_t i = 60; i <= 98; ++i) {
3007 ProcessDataPacket(i);
3008 EXPECT_EQ(0u, writer_->window_update_frames().size());
3009 }
3010 // Session does not add a retransmittable frame.
3011 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
3012 .WillOnce(Invoke([this]() {
3013 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
3014 }));
3015 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3016 EXPECT_EQ(0u, writer_->ping_frames().size());
3017 ProcessDataPacket(99);
3018 EXPECT_EQ(0u, writer_->window_update_frames().size());
3019 // A ping frame will be added.
3020 EXPECT_EQ(1u, writer_->ping_frames().size());
3021}
3022
ianswett6083a102020-02-09 12:04:04 -08003023TEST_P(QuicConnectionTest, AckNeedsRetransmittableFramesAfterPto) {
ianswett6083a102020-02-09 12:04:04 -08003024 // Disable TLP so the RTO fires immediately.
3025 connection_.SetMaxTailLossProbes(0);
3026 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3027 QuicConfig config;
3028 QuicTagVector connection_options;
3029 connection_options.push_back(kEACK);
3030 config.SetConnectionOptionsToSend(connection_options);
3031 connection_.SetFromConfig(config);
3032
3033 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3034 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3035 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(10);
3036
3037 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(4);
3038 // Receive packets 1 - 9.
3039 for (size_t i = 1; i <= 9; ++i) {
3040 ProcessDataPacket(i);
3041 }
3042
3043 // Send a ping and fire the retransmission alarm.
3044 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3045 SendPing();
3046 QuicTime retransmission_time =
3047 connection_.GetRetransmissionAlarm()->deadline();
3048 clock_.AdvanceTime(retransmission_time - clock_.Now());
3049 connection_.GetRetransmissionAlarm()->Fire();
3050 ASSERT_TRUE(manager_->GetConsecutiveRtoCount() > 0 ||
3051 manager_->GetConsecutivePtoCount() > 0);
3052
3053 // Process a packet, which requests a retransmittable frame be bundled
3054 // with the ACK.
3055 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
3056 .WillOnce(Invoke([this]() {
3057 connection_.SendControlFrame(
3058 QuicFrame(new QuicWindowUpdateFrame(1, 0, 0)));
3059 }));
3060 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3061 ProcessDataPacket(11);
3062 EXPECT_EQ(1u, writer_->window_update_frames().size());
3063}
3064
QUICHE teama6ef0a62019-03-07 20:34:33 -05003065TEST_P(QuicConnectionTest, LeastUnackedLower) {
fayangc31c9952019-06-05 13:54:48 -07003066 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003067 return;
3068 }
3069 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3070
3071 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
3072 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
3073 SendStreamDataToPeer(1, "eep", 6, NO_FIN, nullptr);
3074
3075 // Start out saying the least unacked is 2.
3076 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
3077 ProcessStopWaitingPacket(InitStopWaitingFrame(2));
3078
3079 // Change it to 1, but lower the packet number to fake out-of-order packets.
3080 // This should be fine.
3081 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 1);
3082 // The scheduler will not process out of order acks, but all packet processing
3083 // causes the connection to try to write.
3084 if (!GetParam().no_stop_waiting) {
3085 EXPECT_CALL(visitor_, OnCanWrite());
3086 }
3087 ProcessStopWaitingPacket(InitStopWaitingFrame(1));
3088
3089 // Now claim it's one, but set the ordering so it was sent "after" the first
3090 // one. This should cause a connection error.
3091 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 7);
3092 if (!GetParam().no_stop_waiting) {
rch39c88ab2019-10-16 19:24:40 -07003093 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3094 .Times(AtLeast(1));
fkastenholz5d880a92019-06-21 09:01:56 -07003095 EXPECT_CALL(visitor_,
rch39c88ab2019-10-16 19:24:40 -07003096 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
3097 .Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003098 }
3099 ProcessStopWaitingPacket(InitStopWaitingFrame(1));
fkastenholz5d880a92019-06-21 09:01:56 -07003100 if (!GetParam().no_stop_waiting) {
3101 TestConnectionCloseQuicErrorCode(QUIC_INVALID_STOP_WAITING_DATA);
3102 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003103}
3104
3105TEST_P(QuicConnectionTest, TooManySentPackets) {
3106 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3107
3108 QuicPacketCount max_tracked_packets = 50;
3109 QuicConnectionPeer::SetMaxTrackedPackets(&connection_, max_tracked_packets);
3110
3111 const int num_packets = max_tracked_packets + 5;
3112
3113 for (int i = 0; i < num_packets; ++i) {
3114 SendStreamDataToPeer(1, "foo", 3 * i, NO_FIN, nullptr);
3115 }
3116
3117 // Ack packet 1, which leaves more than the limit outstanding.
3118 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3119 EXPECT_CALL(visitor_,
fkastenholz5d880a92019-06-21 09:01:56 -07003120 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003121
3122 // Nack the first packet and ack the rest, leaving a huge gap.
3123 QuicAckFrame frame1 = ConstructAckFrame(num_packets, 1);
3124 ProcessAckPacket(&frame1);
fkastenholz5d880a92019-06-21 09:01:56 -07003125 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003126}
3127
3128TEST_P(QuicConnectionTest, LargestObservedLower) {
3129 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3130
3131 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
3132 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
3133 SendStreamDataToPeer(1, "eep", 6, NO_FIN, nullptr);
3134 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3135
3136 // Start out saying the largest observed is 2.
3137 QuicAckFrame frame1 = InitAckFrame(1);
3138 QuicAckFrame frame2 = InitAckFrame(2);
3139 ProcessAckPacket(&frame2);
3140
fayang745c93a2019-06-21 13:43:04 -07003141 EXPECT_CALL(visitor_, OnCanWrite());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003142 ProcessAckPacket(&frame1);
3143}
3144
3145TEST_P(QuicConnectionTest, AckUnsentData) {
3146 // Ack a packet which has not been sent.
fkastenholz5d880a92019-06-21 09:01:56 -07003147 EXPECT_CALL(visitor_,
3148 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003149 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
rch39c88ab2019-10-16 19:24:40 -07003150 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003151 QuicAckFrame frame = InitAckFrame(1);
3152 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
3153 ProcessAckPacket(&frame);
fkastenholz5d880a92019-06-21 09:01:56 -07003154 TestConnectionCloseQuicErrorCode(QUIC_INVALID_ACK_DATA);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003155}
3156
3157TEST_P(QuicConnectionTest, BasicSending) {
QUICHE teamcd098022019-03-22 18:49:55 -07003158 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3159 return;
3160 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003161 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3162 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3163 ProcessDataPacket(1);
3164 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
3165 QuicPacketNumber last_packet;
3166 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
3167 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
3168 SendAckPacketToPeer(); // Packet 2
3169
3170 if (GetParam().no_stop_waiting) {
3171 // Expect no stop waiting frame is sent.
3172 EXPECT_FALSE(least_unacked().IsInitialized());
3173 } else {
3174 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
3175 }
3176
3177 SendAckPacketToPeer(); // Packet 3
3178 if (GetParam().no_stop_waiting) {
3179 // Expect no stop waiting frame is sent.
3180 EXPECT_FALSE(least_unacked().IsInitialized());
3181 } else {
3182 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
3183 }
3184
3185 SendStreamDataToPeer(1, "bar", 3, NO_FIN, &last_packet); // Packet 4
3186 EXPECT_EQ(QuicPacketNumber(4u), last_packet);
3187 SendAckPacketToPeer(); // Packet 5
3188 if (GetParam().no_stop_waiting) {
3189 // Expect no stop waiting frame is sent.
3190 EXPECT_FALSE(least_unacked().IsInitialized());
3191 } else {
3192 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
3193 }
3194
3195 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3196
3197 // Peer acks up to packet 3.
3198 QuicAckFrame frame = InitAckFrame(3);
3199 ProcessAckPacket(&frame);
3200 SendAckPacketToPeer(); // Packet 6
3201
3202 // As soon as we've acked one, we skip ack packets 2 and 3 and note lack of
3203 // ack for 4.
3204 if (GetParam().no_stop_waiting) {
3205 // Expect no stop waiting frame is sent.
3206 EXPECT_FALSE(least_unacked().IsInitialized());
3207 } else {
3208 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
3209 }
3210
3211 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3212
3213 // Peer acks up to packet 4, the last packet.
3214 QuicAckFrame frame2 = InitAckFrame(6);
3215 ProcessAckPacket(&frame2); // Acks don't instigate acks.
3216
3217 // Verify that we did not send an ack.
3218 EXPECT_EQ(QuicPacketNumber(6u), writer_->header().packet_number);
3219
3220 // So the last ack has not changed.
3221 if (GetParam().no_stop_waiting) {
3222 // Expect no stop waiting frame is sent.
3223 EXPECT_FALSE(least_unacked().IsInitialized());
3224 } else {
3225 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
3226 }
3227
3228 // If we force an ack, we shouldn't change our retransmit state.
3229 SendAckPacketToPeer(); // Packet 7
3230 if (GetParam().no_stop_waiting) {
3231 // Expect no stop waiting frame is sent.
3232 EXPECT_FALSE(least_unacked().IsInitialized());
3233 } else {
3234 EXPECT_EQ(QuicPacketNumber(7u), least_unacked());
3235 }
3236
3237 // But if we send more data it should.
3238 SendStreamDataToPeer(1, "eep", 6, NO_FIN, &last_packet); // Packet 8
3239 EXPECT_EQ(QuicPacketNumber(8u), last_packet);
3240 SendAckPacketToPeer(); // Packet 9
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(7u), least_unacked());
3246 }
3247}
3248
3249// QuicConnection should record the packet sent-time prior to sending the
3250// packet.
3251TEST_P(QuicConnectionTest, RecordSentTimeBeforePacketSent) {
3252 // We're using a MockClock for the tests, so we have complete control over the
3253 // time.
3254 // Our recorded timestamp for the last packet sent time will be passed in to
3255 // the send_algorithm. Make sure that it is set to the correct value.
3256 QuicTime actual_recorded_send_time = QuicTime::Zero();
3257 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3258 .WillOnce(SaveArg<0>(&actual_recorded_send_time));
3259
3260 // First send without any pause and check the result.
3261 QuicTime expected_recorded_send_time = clock_.Now();
3262 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3263 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
3264 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
3265 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
3266
3267 // Now pause during the write, and check the results.
3268 actual_recorded_send_time = QuicTime::Zero();
3269 const QuicTime::Delta write_pause_time_delta =
3270 QuicTime::Delta::FromMilliseconds(5000);
3271 SetWritePauseTimeDelta(write_pause_time_delta);
3272 expected_recorded_send_time = clock_.Now();
3273
3274 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3275 .WillOnce(SaveArg<0>(&actual_recorded_send_time));
3276 connection_.SendStreamDataWithString(2, "baz", 0, NO_FIN);
3277 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
3278 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
3279 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
3280}
3281
3282TEST_P(QuicConnectionTest, FramePacking) {
3283 // Send two stream frames in 1 packet by queueing them.
3284 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3285 {
fayanga4b37b22019-06-18 13:37:47 -07003286 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003287 connection_.SendStreamData3();
3288 connection_.SendStreamData5();
3289 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3290 }
3291 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3292 EXPECT_FALSE(connection_.HasQueuedData());
3293
3294 // Parse the last packet and ensure it's an ack and two stream frames from
3295 // two different streams.
3296 if (GetParam().no_stop_waiting) {
3297 EXPECT_EQ(2u, writer_->frame_count());
3298 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
3299 } else {
3300 EXPECT_EQ(2u, writer_->frame_count());
3301 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
3302 }
3303
3304 EXPECT_TRUE(writer_->ack_frames().empty());
3305
3306 ASSERT_EQ(2u, writer_->stream_frames().size());
3307 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3308 writer_->stream_frames()[0]->stream_id);
3309 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3310 writer_->stream_frames()[1]->stream_id);
3311}
3312
3313TEST_P(QuicConnectionTest, FramePackingNonCryptoThenCrypto) {
3314 // Send two stream frames (one non-crypto, then one crypto) in 2 packets by
3315 // queueing them.
3316 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3317 {
3318 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
fayanga4b37b22019-06-18 13:37:47 -07003319 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003320 connection_.SendStreamData3();
fayang58f71072019-11-05 08:47:02 -08003321 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003322 connection_.SendCryptoStreamData();
fayang58f71072019-11-05 08:47:02 -08003323 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003324 }
3325 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3326 EXPECT_FALSE(connection_.HasQueuedData());
3327
3328 // Parse the last packet and ensure it's the crypto stream frame.
3329 EXPECT_EQ(2u, writer_->frame_count());
3330 ASSERT_EQ(1u, writer_->padding_frames().size());
QUICHE teamea740082019-03-11 17:58:43 -07003331 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003332 ASSERT_EQ(1u, writer_->stream_frames().size());
3333 EXPECT_EQ(QuicUtils::GetCryptoStreamId(connection_.transport_version()),
3334 writer_->stream_frames()[0]->stream_id);
3335 } else {
3336 EXPECT_EQ(1u, writer_->crypto_frames().size());
3337 }
3338}
3339
3340TEST_P(QuicConnectionTest, FramePackingCryptoThenNonCrypto) {
3341 // Send two stream frames (one crypto, then one non-crypto) in 2 packets by
3342 // queueing them.
3343 {
3344 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3345 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
fayanga4b37b22019-06-18 13:37:47 -07003346 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003347 connection_.SendCryptoStreamData();
3348 connection_.SendStreamData3();
3349 }
3350 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3351 EXPECT_FALSE(connection_.HasQueuedData());
3352
3353 // Parse the last packet and ensure it's the stream frame from stream 3.
nharper55fa6132019-05-07 19:37:21 -07003354 size_t padding_frame_count = writer_->padding_frames().size();
3355 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003356 ASSERT_EQ(1u, writer_->stream_frames().size());
3357 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3358 writer_->stream_frames()[0]->stream_id);
3359}
3360
3361TEST_P(QuicConnectionTest, FramePackingAckResponse) {
3362 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3363 // Process a data packet to queue up a pending ack.
fayang3451f6e2019-06-11 08:18:12 -07003364 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3365 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
3366 } else {
3367 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3368 }
3369 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
3370
QUICHE teama6ef0a62019-03-07 20:34:33 -05003371 QuicPacketNumber last_packet;
nharper46833c32019-05-15 21:33:05 -07003372 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3373 connection_.SendCryptoDataWithString("foo", 0);
3374 } else {
3375 SendStreamDataToPeer(
3376 QuicUtils::GetCryptoStreamId(connection_.transport_version()), "foo", 0,
3377 NO_FIN, &last_packet);
3378 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003379 // Verify ack is bundled with outging packet.
3380 EXPECT_FALSE(writer_->ack_frames().empty());
3381
3382 EXPECT_CALL(visitor_, OnCanWrite())
3383 .WillOnce(DoAll(IgnoreResult(InvokeWithoutArgs(
3384 &connection_, &TestConnection::SendStreamData3)),
3385 IgnoreResult(InvokeWithoutArgs(
3386 &connection_, &TestConnection::SendStreamData5))));
3387
3388 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3389
3390 // Process a data packet to cause the visitor's OnCanWrite to be invoked.
3391 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
QUICHE team8c1daa22019-03-13 08:33:41 -07003392 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07003393 std::make_unique<TaggingEncrypter>(0x01));
zhongyi546cc452019-04-12 15:27:49 -07003394 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07003395 std::make_unique<StrictTaggingDecrypter>(0x01));
nharper2c9f02a2019-05-08 10:25:50 -07003396 ProcessDataPacket(2);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003397
3398 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3399 EXPECT_FALSE(connection_.HasQueuedData());
3400
3401 // Parse the last packet and ensure it's an ack and two stream frames from
3402 // two different streams.
3403 if (GetParam().no_stop_waiting) {
3404 EXPECT_EQ(3u, writer_->frame_count());
3405 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
3406 } else {
3407 EXPECT_EQ(4u, writer_->frame_count());
3408 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3409 }
3410 EXPECT_FALSE(writer_->ack_frames().empty());
3411 ASSERT_EQ(2u, writer_->stream_frames().size());
3412 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3413 writer_->stream_frames()[0]->stream_id);
3414 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3415 writer_->stream_frames()[1]->stream_id);
3416}
3417
3418TEST_P(QuicConnectionTest, FramePackingSendv) {
nharper46833c32019-05-15 21:33:05 -07003419 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003420 // Send data in 1 packet by writing multiple blocks in a single iovector
3421 // using writev.
3422 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3423
3424 char data[] = "ABCDEF";
3425 struct iovec iov[2];
3426 iov[0].iov_base = data;
3427 iov[0].iov_len = 4;
3428 iov[1].iov_base = data + 4;
3429 iov[1].iov_len = 2;
nharper46833c32019-05-15 21:33:05 -07003430 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
3431 connection_.transport_version(), Perspective::IS_CLIENT);
3432 connection_.SaveAndSendStreamData(stream_id, iov, 2, 6, 0, NO_FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003433
3434 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3435 EXPECT_FALSE(connection_.HasQueuedData());
3436
3437 // Parse the last packet and ensure multiple iovector blocks have
3438 // been packed into a single stream frame from one stream.
nharper46833c32019-05-15 21:33:05 -07003439 EXPECT_EQ(1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003440 EXPECT_EQ(1u, writer_->stream_frames().size());
nharper46833c32019-05-15 21:33:05 -07003441 EXPECT_EQ(0u, writer_->padding_frames().size());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003442 QuicStreamFrame* frame = writer_->stream_frames()[0].get();
nharper46833c32019-05-15 21:33:05 -07003443 EXPECT_EQ(stream_id, frame->stream_id);
dmcardlecf0bfcf2019-12-13 08:08:21 -08003444 EXPECT_EQ("ABCDEF",
3445 quiche::QuicheStringPiece(frame->data_buffer, frame->data_length));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003446}
3447
3448TEST_P(QuicConnectionTest, FramePackingSendvQueued) {
nharper46833c32019-05-15 21:33:05 -07003449 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003450 // Try to send two stream frames in 1 packet by using writev.
3451 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3452
3453 BlockOnNextWrite();
3454 char data[] = "ABCDEF";
3455 struct iovec iov[2];
3456 iov[0].iov_base = data;
3457 iov[0].iov_len = 4;
3458 iov[1].iov_base = data + 4;
3459 iov[1].iov_len = 2;
nharper46833c32019-05-15 21:33:05 -07003460 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
3461 connection_.transport_version(), Perspective::IS_CLIENT);
3462 connection_.SaveAndSendStreamData(stream_id, iov, 2, 6, 0, NO_FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003463
3464 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3465 EXPECT_TRUE(connection_.HasQueuedData());
3466
3467 // Unblock the writes and actually send.
3468 writer_->SetWritable();
3469 connection_.OnCanWrite();
3470 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3471
3472 // Parse the last packet and ensure it's one stream frame from one stream.
nharper46833c32019-05-15 21:33:05 -07003473 EXPECT_EQ(1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003474 EXPECT_EQ(1u, writer_->stream_frames().size());
nharper46833c32019-05-15 21:33:05 -07003475 EXPECT_EQ(0u, writer_->padding_frames().size());
3476 EXPECT_EQ(stream_id, writer_->stream_frames()[0]->stream_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003477}
3478
3479TEST_P(QuicConnectionTest, SendingZeroBytes) {
3480 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3481 // Send a zero byte write with a fin using writev.
3482 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
nharper46833c32019-05-15 21:33:05 -07003483 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
3484 connection_.transport_version(), Perspective::IS_CLIENT);
3485 connection_.SaveAndSendStreamData(stream_id, nullptr, 0, 0, 0, FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003486
3487 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3488 EXPECT_FALSE(connection_.HasQueuedData());
3489
nharper55fa6132019-05-07 19:37:21 -07003490 // Padding frames are added by v99 to ensure a minimum packet size.
3491 size_t extra_padding_frames = 0;
3492 if (GetParam().version.HasHeaderProtection()) {
3493 extra_padding_frames = 1;
3494 }
3495
QUICHE teama6ef0a62019-03-07 20:34:33 -05003496 // Parse the last packet and ensure it's one stream frame from one stream.
nharper55fa6132019-05-07 19:37:21 -07003497 EXPECT_EQ(1u + extra_padding_frames, writer_->frame_count());
3498 EXPECT_EQ(extra_padding_frames, writer_->padding_frames().size());
3499 ASSERT_EQ(1u, writer_->stream_frames().size());
nharper46833c32019-05-15 21:33:05 -07003500 EXPECT_EQ(stream_id, writer_->stream_frames()[0]->stream_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003501 EXPECT_TRUE(writer_->stream_frames()[0]->fin);
3502}
3503
3504TEST_P(QuicConnectionTest, LargeSendWithPendingAck) {
3505 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3506 // Set the ack alarm by processing a ping frame.
3507 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3508
3509 // Processs a PING frame.
3510 ProcessFramePacket(QuicFrame(QuicPingFrame()));
3511 // Ensure that this has caused the ACK alarm to be set.
3512 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
3513 EXPECT_TRUE(ack_alarm->IsSet());
3514
3515 // Send data and ensure the ack is bundled.
3516 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(8);
3517 size_t len = 10000;
3518 std::unique_ptr<char[]> data_array(new char[len]);
3519 memset(data_array.get(), '?', len);
3520 struct iovec iov;
3521 iov.iov_base = data_array.get();
3522 iov.iov_len = len;
3523 QuicConsumedData consumed = connection_.SaveAndSendStreamData(
dschinazi552accc2019-06-17 17:07:34 -07003524 GetNthClientInitiatedStreamId(0, connection_.transport_version()), &iov,
3525 1, len, 0, FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003526 EXPECT_EQ(len, consumed.bytes_consumed);
3527 EXPECT_TRUE(consumed.fin_consumed);
3528 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3529 EXPECT_FALSE(connection_.HasQueuedData());
3530
3531 // Parse the last packet and ensure it's one stream frame with a fin.
3532 EXPECT_EQ(1u, writer_->frame_count());
nharper55fa6132019-05-07 19:37:21 -07003533 ASSERT_EQ(1u, writer_->stream_frames().size());
dschinazi552accc2019-06-17 17:07:34 -07003534 EXPECT_EQ(GetNthClientInitiatedStreamId(0, connection_.transport_version()),
QUICHE teama6ef0a62019-03-07 20:34:33 -05003535 writer_->stream_frames()[0]->stream_id);
3536 EXPECT_TRUE(writer_->stream_frames()[0]->fin);
3537 // Ensure the ack alarm was cancelled when the ack was sent.
3538 EXPECT_FALSE(ack_alarm->IsSet());
3539}
3540
3541TEST_P(QuicConnectionTest, OnCanWrite) {
3542 // Visitor's OnCanWrite will send data, but will have more pending writes.
3543 EXPECT_CALL(visitor_, OnCanWrite())
3544 .WillOnce(DoAll(IgnoreResult(InvokeWithoutArgs(
3545 &connection_, &TestConnection::SendStreamData3)),
3546 IgnoreResult(InvokeWithoutArgs(
3547 &connection_, &TestConnection::SendStreamData5))));
3548 {
3549 InSequence seq;
3550 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillOnce(Return(true));
3551 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
3552 .WillRepeatedly(Return(false));
3553 }
3554
3555 EXPECT_CALL(*send_algorithm_, CanSend(_))
3556 .WillRepeatedly(testing::Return(true));
3557
3558 connection_.OnCanWrite();
3559
3560 // Parse the last packet and ensure it's the two stream frames from
3561 // two different streams.
3562 EXPECT_EQ(2u, writer_->frame_count());
3563 EXPECT_EQ(2u, writer_->stream_frames().size());
3564 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3565 writer_->stream_frames()[0]->stream_id);
3566 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3567 writer_->stream_frames()[1]->stream_id);
3568}
3569
3570TEST_P(QuicConnectionTest, RetransmitOnNack) {
3571 QuicPacketNumber last_packet;
3572 QuicByteCount second_packet_size;
3573 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet); // Packet 1
3574 second_packet_size =
3575 SendStreamDataToPeer(3, "foos", 3, NO_FIN, &last_packet); // Packet 2
3576 SendStreamDataToPeer(3, "fooos", 7, NO_FIN, &last_packet); // Packet 3
3577
3578 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3579
3580 // Don't lose a packet on an ack, and nothing is retransmitted.
3581 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3582 QuicAckFrame ack_one = InitAckFrame(1);
3583 ProcessAckPacket(&ack_one);
3584
3585 // Lose a packet and ensure it triggers retransmission.
3586 QuicAckFrame nack_two = ConstructAckFrame(3, 2);
3587 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003588 lost_packets.push_back(
3589 LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003590 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3591 .WillOnce(SetArgPointee<5>(lost_packets));
3592 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3593 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3594 EXPECT_FALSE(QuicPacketCreatorPeer::SendVersionInPacket(creator_));
3595 ProcessAckPacket(&nack_two);
3596}
3597
3598TEST_P(QuicConnectionTest, DoNotSendQueuedPacketForResetStream) {
3599 // Block the connection to queue the packet.
3600 BlockOnNextWrite();
3601
3602 QuicStreamId stream_id = 2;
3603 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
3604
3605 // Now that there is a queued packet, reset the stream.
3606 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
3607
3608 // Unblock the connection and verify that only the RST_STREAM is sent.
3609 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3610 writer_->SetWritable();
3611 connection_.OnCanWrite();
nharper55fa6132019-05-07 19:37:21 -07003612 size_t padding_frame_count = writer_->padding_frames().size();
3613 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003614 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3615}
3616
3617TEST_P(QuicConnectionTest, SendQueuedPacketForQuicRstStreamNoError) {
3618 // Block the connection to queue the packet.
3619 BlockOnNextWrite();
3620
3621 QuicStreamId stream_id = 2;
fayange62e63c2019-12-04 07:16:25 -08003622 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003623 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
3624
3625 // Now that there is a queued packet, reset the stream.
3626 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 3);
3627
3628 // Unblock the connection and verify that the RST_STREAM is sent and the data
3629 // packet is sent.
fayange62e63c2019-12-04 07:16:25 -08003630 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003631 writer_->SetWritable();
3632 connection_.OnCanWrite();
nharper55fa6132019-05-07 19:37:21 -07003633 size_t padding_frame_count = writer_->padding_frames().size();
3634 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003635 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3636}
3637
3638TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnNack) {
3639 QuicStreamId stream_id = 2;
3640 QuicPacketNumber last_packet;
3641 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3642 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3643 SendStreamDataToPeer(stream_id, "fooos", 7, NO_FIN, &last_packet);
3644
3645 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3646 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 12);
3647
3648 // Lose a packet and ensure it does not trigger retransmission.
3649 QuicAckFrame nack_two = ConstructAckFrame(last_packet, last_packet - 1);
3650 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3651 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3652 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3653 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3654 ProcessAckPacket(&nack_two);
3655}
3656
3657TEST_P(QuicConnectionTest, RetransmitForQuicRstStreamNoErrorOnNack) {
3658 QuicStreamId stream_id = 2;
3659 QuicPacketNumber last_packet;
3660 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3661 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3662 SendStreamDataToPeer(stream_id, "fooos", 7, NO_FIN, &last_packet);
3663
3664 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3665 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 12);
3666
3667 // Lose a packet, ensure it triggers retransmission.
3668 QuicAckFrame nack_two = ConstructAckFrame(last_packet, last_packet - 1);
3669 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3670 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003671 lost_packets.push_back(LostPacket(last_packet - 1, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003672 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3673 .WillOnce(SetArgPointee<5>(lost_packets));
3674 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3675 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
3676 ProcessAckPacket(&nack_two);
3677}
3678
3679TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnRTO) {
3680 QuicStreamId stream_id = 2;
3681 QuicPacketNumber last_packet;
3682 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3683
3684 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3685 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
3686
3687 // Fire the RTO and verify that the RST_STREAM is resent, not stream data.
3688 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3689 clock_.AdvanceTime(DefaultRetransmissionTime());
3690 connection_.GetRetransmissionAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07003691 size_t padding_frame_count = writer_->padding_frames().size();
3692 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003693 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3694 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
3695}
3696
3697// Ensure that if the only data in flight is non-retransmittable, the
3698// retransmission alarm is not set.
3699TEST_P(QuicConnectionTest, CancelRetransmissionAlarmAfterResetStream) {
3700 QuicStreamId stream_id = 2;
3701 QuicPacketNumber last_data_packet;
3702 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
3703
3704 // Cancel the stream.
3705 const QuicPacketNumber rst_packet = last_data_packet + 1;
3706 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, rst_packet, _, _)).Times(1);
3707 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
3708
3709 // Ack the RST_STREAM frame (since it's retransmittable), but not the data
3710 // packet, which is no longer retransmittable since the stream was cancelled.
3711 QuicAckFrame nack_stream_data =
3712 ConstructAckFrame(rst_packet, last_data_packet);
3713 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3714 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3715 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3716 ProcessAckPacket(&nack_stream_data);
3717
3718 // Ensure that the data is still in flight, but the retransmission alarm is no
3719 // longer set.
ianswett9f459cb2019-04-21 06:39:59 -07003720 EXPECT_GT(manager_->GetBytesInFlight(), 0u);
fayangcff885a2019-10-22 07:39:04 -07003721 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003722}
3723
3724TEST_P(QuicConnectionTest, RetransmitForQuicRstStreamNoErrorOnRTO) {
3725 connection_.SetMaxTailLossProbes(0);
3726
3727 QuicStreamId stream_id = 2;
3728 QuicPacketNumber last_packet;
3729 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3730
3731 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3732 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 3);
3733
3734 // Fire the RTO and verify that the RST_STREAM is resent, the stream data
3735 // is sent.
fayang1c2d1ab2020-03-11 12:08:41 -07003736 const size_t num_retransmissions =
3737 connection_.SupportsMultiplePacketNumberSpaces() ? 1 : 2;
3738 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3739 .Times(AtLeast(num_retransmissions));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003740 clock_.AdvanceTime(DefaultRetransmissionTime());
3741 connection_.GetRetransmissionAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07003742 size_t padding_frame_count = writer_->padding_frames().size();
3743 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
fayang1c2d1ab2020-03-11 12:08:41 -07003744 if (num_retransmissions == 2) {
3745 ASSERT_EQ(1u, writer_->rst_stream_frames().size());
3746 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
3747 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003748}
3749
3750TEST_P(QuicConnectionTest, DoNotSendPendingRetransmissionForResetStream) {
3751 QuicStreamId stream_id = 2;
3752 QuicPacketNumber last_packet;
3753 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3754 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3755 BlockOnNextWrite();
3756 connection_.SendStreamDataWithString(stream_id, "fooos", 7, NO_FIN);
3757
3758 // Lose a packet which will trigger a pending retransmission.
3759 QuicAckFrame ack = ConstructAckFrame(last_packet, last_packet - 1);
3760 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3761 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3762 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3763 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3764 ProcessAckPacket(&ack);
3765
3766 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 12);
3767
3768 // Unblock the connection and verify that the RST_STREAM is sent but not the
3769 // second data packet nor a retransmit.
3770 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3771 writer_->SetWritable();
3772 connection_.OnCanWrite();
nharper55fa6132019-05-07 19:37:21 -07003773 size_t padding_frame_count = writer_->padding_frames().size();
3774 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
zhongyi546cc452019-04-12 15:27:49 -07003775 ASSERT_EQ(1u, writer_->rst_stream_frames().size());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003776 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
3777}
3778
3779TEST_P(QuicConnectionTest, SendPendingRetransmissionForQuicRstStreamNoError) {
3780 QuicStreamId stream_id = 2;
3781 QuicPacketNumber last_packet;
3782 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3783 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3784 BlockOnNextWrite();
3785 connection_.SendStreamDataWithString(stream_id, "fooos", 7, NO_FIN);
3786
3787 // Lose a packet which will trigger a pending retransmission.
3788 QuicAckFrame ack = ConstructAckFrame(last_packet, last_packet - 1);
3789 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3790 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003791 lost_packets.push_back(LostPacket(last_packet - 1, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003792 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3793 .WillOnce(SetArgPointee<5>(lost_packets));
3794 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3795 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3796 ProcessAckPacket(&ack);
3797
3798 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 12);
3799
3800 // Unblock the connection and verify that the RST_STREAM is sent and the
3801 // second data packet or a retransmit is sent.
3802 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(2));
3803 writer_->SetWritable();
3804 connection_.OnCanWrite();
3805 // The RST_STREAM_FRAME is sent after queued packets and pending
3806 // retransmission.
3807 connection_.SendControlFrame(QuicFrame(
3808 new QuicRstStreamFrame(1, stream_id, QUIC_STREAM_NO_ERROR, 14)));
nharper55fa6132019-05-07 19:37:21 -07003809 size_t padding_frame_count = writer_->padding_frames().size();
3810 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003811 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3812}
3813
3814TEST_P(QuicConnectionTest, RetransmitAckedPacket) {
3815 QuicPacketNumber last_packet;
3816 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
3817 SendStreamDataToPeer(1, "foos", 3, NO_FIN, &last_packet); // Packet 2
3818 SendStreamDataToPeer(1, "fooos", 7, NO_FIN, &last_packet); // Packet 3
3819
3820 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3821
3822 // Instigate a loss with an ack.
3823 QuicAckFrame nack_two = ConstructAckFrame(3, 2);
3824 // The first nack should trigger a fast retransmission, but we'll be
3825 // write blocked, so the packet will be queued.
3826 BlockOnNextWrite();
3827
3828 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003829 lost_packets.push_back(
3830 LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003831 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3832 .WillOnce(SetArgPointee<5>(lost_packets));
3833 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
fayange62e63c2019-12-04 07:16:25 -08003834 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _))
3835 .Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003836 ProcessAckPacket(&nack_two);
3837 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3838
3839 // Now, ack the previous transmission.
3840 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3841 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(false, _, _, _, _));
3842 QuicAckFrame ack_all = InitAckFrame(3);
3843 ProcessAckPacket(&ack_all);
3844
fayange62e63c2019-12-04 07:16:25 -08003845 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _))
3846 .Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003847
3848 writer_->SetWritable();
3849 connection_.OnCanWrite();
3850
3851 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3852 // We do not store retransmittable frames of this retransmission.
3853 EXPECT_FALSE(QuicConnectionPeer::HasRetransmittableFrames(&connection_, 4));
3854}
3855
3856TEST_P(QuicConnectionTest, RetransmitNackedLargestObserved) {
3857 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3858 QuicPacketNumber original, second;
3859
3860 QuicByteCount packet_size =
3861 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &original); // 1st packet.
3862 SendStreamDataToPeer(3, "bar", 3, NO_FIN, &second); // 2nd packet.
3863
3864 QuicAckFrame frame = InitAckFrame({{second, second + 1}});
3865 // The first nack should retransmit the largest observed packet.
3866 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003867 lost_packets.push_back(LostPacket(original, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003868 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3869 .WillOnce(SetArgPointee<5>(lost_packets));
3870 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3871 // Packet 1 is short header for IETF QUIC because the encryption level
3872 // switched to ENCRYPTION_FORWARD_SECURE in SendStreamDataToPeer.
fayangd4291e42019-05-30 10:31:21 -07003873 EXPECT_CALL(*send_algorithm_,
3874 OnPacketSent(_, _, _,
3875 VersionHasIetfInvariantHeader(
3876 GetParam().version.transport_version)
3877 ? packet_size
3878 : packet_size - kQuicVersionSize,
3879 _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003880 ProcessAckPacket(&frame);
3881}
3882
3883TEST_P(QuicConnectionTest, QueueAfterTwoRTOs) {
fayangcff885a2019-10-22 07:39:04 -07003884 if (connection_.PtoEnabled()) {
fayang5f135052019-08-22 17:59:40 -07003885 return;
3886 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003887 connection_.SetMaxTailLossProbes(0);
3888
3889 for (int i = 0; i < 10; ++i) {
3890 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3891 connection_.SendStreamDataWithString(3, "foo", i * 3, NO_FIN);
3892 }
3893
3894 // Block the writer and ensure they're queued.
3895 BlockOnNextWrite();
3896 clock_.AdvanceTime(DefaultRetransmissionTime());
fayange62e63c2019-12-04 07:16:25 -08003897 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003898 connection_.GetRetransmissionAlarm()->Fire();
3899 EXPECT_TRUE(connection_.HasQueuedData());
3900
3901 // Unblock the writer.
3902 writer_->SetWritable();
3903 clock_.AdvanceTime(QuicTime::Delta::FromMicroseconds(
3904 2 * DefaultRetransmissionTime().ToMicroseconds()));
fayange62e63c2019-12-04 07:16:25 -08003905 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003906 connection_.GetRetransmissionAlarm()->Fire();
3907 connection_.OnCanWrite();
3908}
3909
3910TEST_P(QuicConnectionTest, WriteBlockedBufferedThenSent) {
3911 BlockOnNextWrite();
3912 writer_->set_is_write_blocked_data_buffered(true);
3913 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3914 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3915 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3916
3917 writer_->SetWritable();
3918 connection_.OnCanWrite();
3919 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3920}
3921
3922TEST_P(QuicConnectionTest, WriteBlockedThenSent) {
3923 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3924 BlockOnNextWrite();
fayange62e63c2019-12-04 07:16:25 -08003925 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003926 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
fayange62e63c2019-12-04 07:16:25 -08003927 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003928 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3929
3930 // The second packet should also be queued, in order to ensure packets are
3931 // never sent out of order.
3932 writer_->SetWritable();
fayange62e63c2019-12-04 07:16:25 -08003933 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003934 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3935 EXPECT_EQ(2u, connection_.NumQueuedPackets());
3936
3937 // Now both are sent in order when we unblock.
fayange62e63c2019-12-04 07:16:25 -08003938 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003939 connection_.OnCanWrite();
3940 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
fayang2ce66082019-10-02 06:29:04 -07003941 EXPECT_EQ(0u, connection_.NumQueuedPackets());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003942}
3943
3944TEST_P(QuicConnectionTest, RetransmitWriteBlockedAckedOriginalThenSent) {
3945 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3946 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
3947 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3948
3949 BlockOnNextWrite();
3950 writer_->set_is_write_blocked_data_buffered(true);
3951 // Simulate the retransmission alarm firing.
3952 clock_.AdvanceTime(DefaultRetransmissionTime());
3953 connection_.GetRetransmissionAlarm()->Fire();
3954
3955 // Ack the sent packet before the callback returns, which happens in
3956 // rare circumstances with write blocked sockets.
3957 QuicAckFrame ack = InitAckFrame(1);
3958 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3959 ProcessAckPacket(&ack);
3960
3961 writer_->SetWritable();
3962 connection_.OnCanWrite();
fayangcff885a2019-10-22 07:39:04 -07003963 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
fayang1c2d1ab2020-03-11 12:08:41 -07003964 const uint64_t retransmission =
3965 connection_.SupportsMultiplePacketNumberSpaces() ? 3 : 2;
3966 EXPECT_FALSE(QuicConnectionPeer::HasRetransmittableFrames(&connection_,
3967 retransmission));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003968}
3969
3970TEST_P(QuicConnectionTest, AlarmsWhenWriteBlocked) {
3971 // Block the connection.
3972 BlockOnNextWrite();
3973 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
3974 EXPECT_EQ(1u, writer_->packets_write_attempts());
3975 EXPECT_TRUE(writer_->IsWriteBlocked());
3976
3977 // Set the send alarm. Fire the alarm and ensure it doesn't attempt to write.
3978 connection_.GetSendAlarm()->Set(clock_.ApproximateNow());
3979 connection_.GetSendAlarm()->Fire();
3980 EXPECT_TRUE(writer_->IsWriteBlocked());
3981 EXPECT_EQ(1u, writer_->packets_write_attempts());
3982}
3983
3984TEST_P(QuicConnectionTest, NoSendAlarmAfterProcessPacketWhenWriteBlocked) {
3985 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3986
3987 // Block the connection.
3988 BlockOnNextWrite();
3989 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
3990 EXPECT_TRUE(writer_->IsWriteBlocked());
3991 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3992 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
3993
3994 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3995 // Process packet number 1. Can not call ProcessPacket or ProcessDataPacket
3996 // here, because they will fire the alarm after QuicConnection::ProcessPacket
3997 // is returned.
3998 const uint64_t received_packet_num = 1;
3999 const bool has_stop_waiting = false;
nharperc6b99512019-09-19 11:13:48 -07004000 const EncryptionLevel level = ENCRYPTION_FORWARD_SECURE;
4001 std::unique_ptr<QuicPacket> packet(
4002 ConstructDataPacket(received_packet_num, has_stop_waiting, level));
dschinazi66dea072019-04-09 11:41:06 -07004003 char buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05004004 size_t encrypted_length =
4005 peer_framer_.EncryptPayload(level, QuicPacketNumber(received_packet_num),
dschinazi66dea072019-04-09 11:41:06 -07004006 *packet, buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004007 connection_.ProcessUdpPacket(
4008 kSelfAddress, kPeerAddress,
4009 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
4010
4011 EXPECT_TRUE(writer_->IsWriteBlocked());
4012 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4013}
4014
4015TEST_P(QuicConnectionTest, AddToWriteBlockedListIfWriterBlockedWhenProcessing) {
4016 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4017 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
4018
4019 // Simulate the case where a shared writer gets blocked by another connection.
4020 writer_->SetWriteBlocked();
4021
4022 // Process an ACK, make sure the connection calls visitor_->OnWriteBlocked().
4023 QuicAckFrame ack1 = InitAckFrame(1);
4024 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
4025 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
4026 ProcessAckPacket(1, &ack1);
4027}
4028
4029TEST_P(QuicConnectionTest, DoNotAddToWriteBlockedListAfterDisconnect) {
4030 writer_->SetBatchMode(true);
4031 EXPECT_TRUE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07004032 // Have to explicitly grab the OnConnectionClosed frame and check
4033 // its parameters because this is a silent connection close and the
4034 // frame is not also transmitted to the peer.
4035 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
4036 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004037
4038 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
4039
4040 {
fayanga4b37b22019-06-18 13:37:47 -07004041 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004042 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
4043 ConnectionCloseBehavior::SILENT_CLOSE);
4044
4045 EXPECT_FALSE(connection_.connected());
4046 writer_->SetWriteBlocked();
4047 }
fkastenholz5d880a92019-06-21 09:01:56 -07004048 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08004049 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
4050 IsError(QUIC_PEER_GOING_AWAY));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004051}
4052
4053TEST_P(QuicConnectionTest, AddToWriteBlockedListIfBlockedOnFlushPackets) {
4054 writer_->SetBatchMode(true);
4055 writer_->BlockOnNextFlush();
4056
4057 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
4058 {
fayanga4b37b22019-06-18 13:37:47 -07004059 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004060 // flusher's destructor will call connection_.FlushPackets, which should add
4061 // the connection to the write blocked list.
4062 }
4063}
4064
4065TEST_P(QuicConnectionTest, NoLimitPacketsPerNack) {
4066 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4067 int offset = 0;
4068 // Send packets 1 to 15.
4069 for (int i = 0; i < 15; ++i) {
4070 SendStreamDataToPeer(1, "foo", offset, NO_FIN, nullptr);
4071 offset += 3;
4072 }
4073
4074 // Ack 15, nack 1-14.
4075
4076 QuicAckFrame nack =
4077 InitAckFrame({{QuicPacketNumber(15), QuicPacketNumber(16)}});
4078
4079 // 14 packets have been NACK'd and lost.
4080 LostPacketVector lost_packets;
4081 for (int i = 1; i < 15; ++i) {
dschinazi66dea072019-04-09 11:41:06 -07004082 lost_packets.push_back(
4083 LostPacket(QuicPacketNumber(i), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004084 }
4085 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
4086 .WillOnce(SetArgPointee<5>(lost_packets));
4087 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
fayangcff885a2019-10-22 07:39:04 -07004088 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004089 ProcessAckPacket(&nack);
4090}
4091
4092// Test sending multiple acks from the connection to the session.
4093TEST_P(QuicConnectionTest, MultipleAcks) {
QUICHE teamcd098022019-03-22 18:49:55 -07004094 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4095 return;
4096 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004097 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4098 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4099 ProcessDataPacket(1);
4100 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
4101 QuicPacketNumber last_packet;
4102 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
4103 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4104 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet); // Packet 2
4105 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
4106 SendAckPacketToPeer(); // Packet 3
4107 SendStreamDataToPeer(5, "foo", 0, NO_FIN, &last_packet); // Packet 4
4108 EXPECT_EQ(QuicPacketNumber(4u), last_packet);
4109 SendStreamDataToPeer(1, "foo", 3, NO_FIN, &last_packet); // Packet 5
4110 EXPECT_EQ(QuicPacketNumber(5u), last_packet);
4111 SendStreamDataToPeer(3, "foo", 3, NO_FIN, &last_packet); // Packet 6
4112 EXPECT_EQ(QuicPacketNumber(6u), last_packet);
4113
4114 // Client will ack packets 1, 2, [!3], 4, 5.
4115 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4116 QuicAckFrame frame1 = ConstructAckFrame(5, 3);
4117 ProcessAckPacket(&frame1);
4118
4119 // Now the client implicitly acks 3, and explicitly acks 6.
4120 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4121 QuicAckFrame frame2 = InitAckFrame(6);
4122 ProcessAckPacket(&frame2);
4123}
4124
4125TEST_P(QuicConnectionTest, DontLatchUnackedPacket) {
QUICHE teamcd098022019-03-22 18:49:55 -07004126 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4127 return;
4128 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004129 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4130 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4131 ProcessDataPacket(1);
4132 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
4133 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr); // Packet 1;
4134 // From now on, we send acks, so the send algorithm won't mark them pending.
4135 SendAckPacketToPeer(); // Packet 2
4136
4137 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4138 QuicAckFrame frame = InitAckFrame(1);
4139 ProcessAckPacket(&frame);
4140
4141 // Verify that our internal state has least-unacked as 2, because we're still
4142 // waiting for a potential ack for 2.
4143
4144 EXPECT_EQ(QuicPacketNumber(2u), stop_waiting()->least_unacked);
4145
4146 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4147 frame = InitAckFrame(2);
4148 ProcessAckPacket(&frame);
4149 EXPECT_EQ(QuicPacketNumber(3u), stop_waiting()->least_unacked);
4150
4151 // When we send an ack, we make sure our least-unacked makes sense. In this
4152 // case since we're not waiting on an ack for 2 and all packets are acked, we
4153 // set it to 3.
4154 SendAckPacketToPeer(); // Packet 3
4155 // Least_unacked remains at 3 until another ack is received.
4156 EXPECT_EQ(QuicPacketNumber(3u), stop_waiting()->least_unacked);
4157 if (GetParam().no_stop_waiting) {
4158 // Expect no stop waiting frame is sent.
4159 EXPECT_FALSE(least_unacked().IsInitialized());
4160 } else {
4161 // Check that the outgoing ack had its packet number as least_unacked.
4162 EXPECT_EQ(QuicPacketNumber(3u), least_unacked());
4163 }
4164
4165 // Ack the ack, which updates the rtt and raises the least unacked.
4166 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4167 frame = InitAckFrame(3);
4168 ProcessAckPacket(&frame);
4169
4170 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr); // Packet 4
4171 EXPECT_EQ(QuicPacketNumber(4u), stop_waiting()->least_unacked);
4172 SendAckPacketToPeer(); // Packet 5
4173 if (GetParam().no_stop_waiting) {
4174 // Expect no stop waiting frame is sent.
4175 EXPECT_FALSE(least_unacked().IsInitialized());
4176 } else {
4177 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
4178 }
4179
4180 // Send two data packets at the end, and ensure if the last one is acked,
4181 // the least unacked is raised above the ack packets.
4182 SendStreamDataToPeer(1, "bar", 6, NO_FIN, nullptr); // Packet 6
4183 SendStreamDataToPeer(1, "bar", 9, NO_FIN, nullptr); // Packet 7
4184
4185 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4186 frame = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(5)},
4187 {QuicPacketNumber(7), QuicPacketNumber(8)}});
4188 ProcessAckPacket(&frame);
4189
4190 EXPECT_EQ(QuicPacketNumber(6u), stop_waiting()->least_unacked);
4191}
4192
4193TEST_P(QuicConnectionTest, TLP) {
4194 connection_.SetMaxTailLossProbes(1);
4195
4196 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
4197 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4198 QuicTime retransmission_time =
4199 connection_.GetRetransmissionAlarm()->deadline();
4200 EXPECT_NE(QuicTime::Zero(), retransmission_time);
4201
4202 EXPECT_EQ(QuicPacketNumber(1u), writer_->header().packet_number);
4203 // Simulate the retransmission alarm firing and sending a tlp,
4204 // so send algorithm's OnRetransmissionTimeout is not called.
4205 clock_.AdvanceTime(retransmission_time - clock_.Now());
fayang1c2d1ab2020-03-11 12:08:41 -07004206 const QuicPacketNumber retransmission(
4207 connection_.SupportsMultiplePacketNumberSpaces() ? 3 : 2);
4208 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, retransmission, _, _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004209 connection_.GetRetransmissionAlarm()->Fire();
fayang1c2d1ab2020-03-11 12:08:41 -07004210 EXPECT_EQ(retransmission, writer_->header().packet_number);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004211 // We do not raise the high water mark yet.
4212 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4213}
4214
zhongyifbb25772019-04-10 16:54:08 -07004215TEST_P(QuicConnectionTest, TailLossProbeDelayForStreamDataInTLPR) {
fayangcff885a2019-10-22 07:39:04 -07004216 if (connection_.PtoEnabled()) {
zhongyi1b2f7832019-06-14 13:31:34 -07004217 return;
4218 }
4219
zhongyifbb25772019-04-10 16:54:08 -07004220 // Set TLPR from QuicConfig.
4221 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4222 QuicConfig config;
4223 QuicTagVector options;
4224 options.push_back(kTLPR);
4225 config.SetConnectionOptionsToSend(options);
4226 connection_.SetFromConfig(config);
4227 connection_.SetMaxTailLossProbes(1);
4228
4229 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
4230 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4231
4232 QuicTime retransmission_time =
4233 connection_.GetRetransmissionAlarm()->deadline();
4234 EXPECT_NE(QuicTime::Zero(), retransmission_time);
4235 QuicTime::Delta expected_tlp_delay =
4236 0.5 * manager_->GetRttStats()->SmoothedOrInitialRtt();
4237 EXPECT_EQ(expected_tlp_delay, retransmission_time - clock_.Now());
4238
4239 EXPECT_EQ(QuicPacketNumber(1u), writer_->header().packet_number);
4240 // Simulate firing of the retransmission alarm and retransmit the packet.
4241 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
4242 clock_.AdvanceTime(retransmission_time - clock_.Now());
4243 connection_.GetRetransmissionAlarm()->Fire();
4244 EXPECT_EQ(QuicPacketNumber(2u), writer_->header().packet_number);
4245
4246 // We do not raise the high water mark yet.
4247 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4248}
4249
4250TEST_P(QuicConnectionTest, TailLossProbeDelayForNonStreamDataInTLPR) {
fayangcff885a2019-10-22 07:39:04 -07004251 if (connection_.PtoEnabled()) {
zhongyi1b2f7832019-06-14 13:31:34 -07004252 return;
4253 }
4254
zhongyifbb25772019-04-10 16:54:08 -07004255 // Set TLPR from QuicConfig.
4256 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4257 QuicConfig config;
4258 QuicTagVector options;
4259 options.push_back(kTLPR);
4260 config.SetConnectionOptionsToSend(options);
dschinazif7c6a912020-05-05 11:39:53 -07004261 QuicConfigPeer::SetNegotiated(&config, true);
zhongyifbb25772019-04-10 16:54:08 -07004262 connection_.SetFromConfig(config);
4263 connection_.SetMaxTailLossProbes(1);
4264
4265 // Sets retransmittable on wire.
4266 const QuicTime::Delta retransmittable_on_wire_timeout =
4267 QuicTime::Delta::FromMilliseconds(50);
zhongyi79ace162019-10-21 15:57:09 -07004268 connection_.set_initial_retransmittable_on_wire_timeout(
zhongyifbb25772019-04-10 16:54:08 -07004269 retransmittable_on_wire_timeout);
4270
4271 EXPECT_TRUE(connection_.connected());
4272 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4273 .WillRepeatedly(Return(true));
fayangb59c6f12020-03-23 15:06:14 -07004274 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
zhongyifbb25772019-04-10 16:54:08 -07004275 EXPECT_FALSE(connection_.IsPathDegrading());
4276 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4277
4278 const char data[] = "data";
4279 size_t data_size = strlen(data);
4280 QuicStreamOffset offset = 0;
4281
4282 // Send a data packet.
4283 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
4284 offset += data_size;
4285
4286 // Path degrading alarm should be set when there is a retransmittable packet
4287 // on the wire.
fayangb59c6f12020-03-23 15:06:14 -07004288 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
zhongyifbb25772019-04-10 16:54:08 -07004289
4290 // Verify the path degrading delay.
4291 // First TLP with stream data.
4292 QuicTime::Delta srtt = manager_->GetRttStats()->SmoothedOrInitialRtt();
4293 QuicTime::Delta expected_delay = 0.5 * srtt;
4294 // Add 1st RTO.
4295 QuicTime::Delta retransmission_delay =
4296 QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
4297 expected_delay = expected_delay + retransmission_delay;
4298 // Add 2nd RTO.
4299 expected_delay = expected_delay + retransmission_delay * 2;
4300 EXPECT_EQ(expected_delay,
4301 QuicConnectionPeer::GetSentPacketManager(&connection_)
4302 ->GetPathDegradingDelay());
4303 ASSERT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
4304
4305 // The ping alarm is set for the ping timeout, not the shorter
4306 // retransmittable_on_wire_timeout.
4307 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004308 EXPECT_EQ(connection_.ping_timeout(),
zhongyifbb25772019-04-10 16:54:08 -07004309 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
4310
4311 // Receive an ACK for the data packet.
4312 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4313 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4314 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4315 QuicAckFrame frame =
4316 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
4317 ProcessAckPacket(&frame);
4318
4319 // Path degrading alarm should be cancelled as there is no more
4320 // reretransmittable packets on the wire.
fayangb59c6f12020-03-23 15:06:14 -07004321 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
zhongyifbb25772019-04-10 16:54:08 -07004322 // The ping alarm should be set to the retransmittable_on_wire_timeout.
4323 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4324 EXPECT_EQ(retransmittable_on_wire_timeout,
4325 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
4326
4327 // Simulate firing of the retransmittable on wire and send a PING.
4328 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
4329 clock_.AdvanceTime(retransmittable_on_wire_timeout);
4330 connection_.GetPingAlarm()->Fire();
4331
4332 // The retransmission alarm and the path degrading alarm should be set as
4333 // there is a retransmittable packet (PING) on the wire,
4334 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
fayangb59c6f12020-03-23 15:06:14 -07004335 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
zhongyifbb25772019-04-10 16:54:08 -07004336
4337 // Verify the retransmission delay.
4338 QuicTime::Delta min_rto_timeout =
4339 QuicTime::Delta::FromMilliseconds(kMinRetransmissionTimeMs);
4340 srtt = manager_->GetRttStats()->SmoothedOrInitialRtt();
zhongyi9fa2be32019-09-10 12:39:01 -07004341
4342 // First TLP without unacked stream data will no longer use TLPR.
4343 expected_delay = std::max(2 * srtt, 1.5 * srtt + 0.5 * min_rto_timeout);
zhongyifbb25772019-04-10 16:54:08 -07004344 EXPECT_EQ(expected_delay,
4345 connection_.GetRetransmissionAlarm()->deadline() - clock_.Now());
4346
zhongyi1b2f7832019-06-14 13:31:34 -07004347 // Verify the path degrading delay = TLP delay + 1st RTO + 2nd RTO.
zhongyifbb25772019-04-10 16:54:08 -07004348 // Add 1st RTO.
4349 retransmission_delay =
4350 std::max(manager_->GetRttStats()->smoothed_rtt() +
4351 4 * manager_->GetRttStats()->mean_deviation(),
4352 min_rto_timeout);
4353 expected_delay = expected_delay + retransmission_delay;
4354 // Add 2nd RTO.
4355 expected_delay = expected_delay + retransmission_delay * 2;
4356 EXPECT_EQ(expected_delay,
4357 QuicConnectionPeer::GetSentPacketManager(&connection_)
4358 ->GetPathDegradingDelay());
4359
4360 // The ping alarm is set for the ping timeout, not the shorter
4361 // retransmittable_on_wire_timeout.
4362 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004363 EXPECT_EQ(connection_.ping_timeout(),
zhongyifbb25772019-04-10 16:54:08 -07004364 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
zhongyi1b2f7832019-06-14 13:31:34 -07004365
4366 // Advance a small period of time: 5ms. And receive a retransmitted ACK.
4367 // This will update the retransmission alarm, verify the retransmission delay
4368 // is correct.
4369 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4370 QuicAckFrame ack = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
4371 ProcessAckPacket(&ack);
4372
4373 // Verify the retransmission delay.
zhongyi9fa2be32019-09-10 12:39:01 -07004374 // First TLP without unacked stream data will no longer use TLPR.
4375 expected_delay = std::max(2 * srtt, 1.5 * srtt + 0.5 * min_rto_timeout);
zhongyi1b2f7832019-06-14 13:31:34 -07004376 expected_delay = expected_delay - QuicTime::Delta::FromMilliseconds(5);
4377 EXPECT_EQ(expected_delay,
4378 connection_.GetRetransmissionAlarm()->deadline() - clock_.Now());
zhongyifbb25772019-04-10 16:54:08 -07004379}
4380
QUICHE teama6ef0a62019-03-07 20:34:33 -05004381TEST_P(QuicConnectionTest, RTO) {
fayang5f135052019-08-22 17:59:40 -07004382 if (connection_.PtoEnabled()) {
4383 return;
4384 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004385 connection_.SetMaxTailLossProbes(0);
4386
4387 QuicTime default_retransmission_time =
4388 clock_.ApproximateNow() + DefaultRetransmissionTime();
4389 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
4390 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4391
4392 EXPECT_EQ(QuicPacketNumber(1u), writer_->header().packet_number);
4393 EXPECT_EQ(default_retransmission_time,
4394 connection_.GetRetransmissionAlarm()->deadline());
4395 // Simulate the retransmission alarm firing.
4396 clock_.AdvanceTime(DefaultRetransmissionTime());
4397 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
4398 connection_.GetRetransmissionAlarm()->Fire();
4399 EXPECT_EQ(QuicPacketNumber(2u), writer_->header().packet_number);
4400 // We do not raise the high water mark yet.
4401 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4402}
4403
fayanga29eb242019-07-16 12:25:38 -07004404// Regression test of b/133771183.
4405TEST_P(QuicConnectionTest, RtoWithNoDataToRetransmit) {
fayangcff885a2019-10-22 07:39:04 -07004406 if (connection_.PtoEnabled()) {
fayanga29eb242019-07-16 12:25:38 -07004407 return;
4408 }
4409 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4410 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4411 connection_.SetMaxTailLossProbes(0);
4412
4413 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
4414 // Connection is cwnd limited.
4415 CongestionBlockWrites();
4416 // Stream gets reset.
4417 SendRstStream(3, QUIC_ERROR_PROCESSING_STREAM, 3);
4418 // Simulate the retransmission alarm firing.
4419 clock_.AdvanceTime(DefaultRetransmissionTime());
4420 // RTO fires, but there is no packet to be RTOed.
fayange861aee2019-10-16 13:40:39 -07004421 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
fayanga29eb242019-07-16 12:25:38 -07004422 connection_.GetRetransmissionAlarm()->Fire();
fayange861aee2019-10-16 13:40:39 -07004423 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
fayanga29eb242019-07-16 12:25:38 -07004424
4425 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(40);
4426 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(20);
fayange861aee2019-10-16 13:40:39 -07004427 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(false));
4428 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(1);
fayanga29eb242019-07-16 12:25:38 -07004429 // Receives packets 1 - 40.
4430 for (size_t i = 1; i <= 40; ++i) {
4431 ProcessDataPacket(i);
4432 }
4433}
4434
QUICHE teama6ef0a62019-03-07 20:34:33 -05004435TEST_P(QuicConnectionTest, RetransmitWithSameEncryptionLevel) {
4436 use_tagging_decrypter();
4437
4438 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
4439 // the end of the packet. We can test this to check which encrypter was used.
QUICHE team6987b4a2019-03-15 16:23:04 -07004440 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07004441 std::make_unique<TaggingEncrypter>(0x01));
nharper46833c32019-05-15 21:33:05 -07004442 QuicByteCount packet_size;
4443 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4444 .WillOnce(SaveArg<3>(&packet_size));
4445 connection_.SendCryptoDataWithString("foo", 0);
4446 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004447 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
4448
4449 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004450 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004451 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4452 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
4453 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
4454
4455 {
4456 InSequence s;
4457 EXPECT_CALL(*send_algorithm_,
4458 OnPacketSent(_, _, QuicPacketNumber(3), _, _));
4459 EXPECT_CALL(*send_algorithm_,
4460 OnPacketSent(_, _, QuicPacketNumber(4), _, _));
4461 }
4462
4463 // Manually mark both packets for retransmission.
4464 connection_.RetransmitUnackedPackets(ALL_UNACKED_RETRANSMISSION);
fayang58f71072019-11-05 08:47:02 -08004465 if (!connection_.version().CanSendCoalescedPackets()) {
4466 // Packet should have been sent with ENCRYPTION_INITIAL.
4467 // If connection can send coalesced packet, both retransmissions will be
4468 // coalesced in the same UDP datagram.
4469 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_previous_packet());
4470 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004471
4472 // Packet should have been sent with ENCRYPTION_ZERO_RTT.
4473 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
4474}
4475
4476TEST_P(QuicConnectionTest, SendHandshakeMessages) {
4477 use_tagging_decrypter();
4478 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
4479 // the end of the packet. We can test this to check which encrypter was used.
QUICHE team6987b4a2019-03-15 16:23:04 -07004480 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07004481 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004482
4483 // Attempt to send a handshake message and have the socket block.
4484 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
4485 BlockOnNextWrite();
nharper46833c32019-05-15 21:33:05 -07004486 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004487 // The packet should be serialized, but not queued.
4488 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4489
4490 // Switch to the new encrypter.
4491 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004492 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004493 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4494
4495 // Now become writeable and flush the packets.
4496 writer_->SetWritable();
4497 EXPECT_CALL(visitor_, OnCanWrite());
4498 connection_.OnCanWrite();
4499 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4500
4501 // Verify that the handshake packet went out at the null encryption.
4502 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
4503}
4504
4505TEST_P(QuicConnectionTest,
4506 DropRetransmitsForNullEncryptedPacketAfterForwardSecure) {
4507 use_tagging_decrypter();
QUICHE team6987b4a2019-03-15 16:23:04 -07004508 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07004509 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004510 connection_.SendCryptoStreamData();
4511
4512 // Simulate the retransmission alarm firing and the socket blocking.
4513 BlockOnNextWrite();
4514 clock_.AdvanceTime(DefaultRetransmissionTime());
fayange62e63c2019-12-04 07:16:25 -08004515 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004516 connection_.GetRetransmissionAlarm()->Fire();
fayang2ce66082019-10-02 06:29:04 -07004517 EXPECT_EQ(1u, connection_.NumQueuedPackets());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004518
4519 // Go forward secure.
4520 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07004521 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004522 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4523 notifier_.NeuterUnencryptedData();
4524 connection_.NeuterUnencryptedPackets();
fayang2ce66082019-10-02 06:29:04 -07004525 connection_.OnHandshakeComplete();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004526
4527 EXPECT_EQ(QuicTime::Zero(), connection_.GetRetransmissionAlarm()->deadline());
4528 // Unblock the socket and ensure that no packets are sent.
4529 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4530 writer_->SetWritable();
4531 connection_.OnCanWrite();
4532}
4533
4534TEST_P(QuicConnectionTest, RetransmitPacketsWithInitialEncryption) {
4535 use_tagging_decrypter();
QUICHE team6987b4a2019-03-15 16:23:04 -07004536 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07004537 std::make_unique<TaggingEncrypter>(0x01));
QUICHE team6987b4a2019-03-15 16:23:04 -07004538 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004539
nharper46833c32019-05-15 21:33:05 -07004540 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004541
4542 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004543 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004544 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4545
4546 SendStreamDataToPeer(2, "bar", 0, NO_FIN, nullptr);
4547 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4548
4549 connection_.RetransmitUnackedPackets(ALL_INITIAL_RETRANSMISSION);
4550}
4551
4552TEST_P(QuicConnectionTest, BufferNonDecryptablePackets) {
QUICHE teamcd098022019-03-22 18:49:55 -07004553 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4554 return;
4555 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004556 // SetFromConfig is always called after construction from InitializeSession.
4557 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4558 QuicConfig config;
4559 connection_.SetFromConfig(config);
4560 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4561 use_tagging_decrypter();
4562
4563 const uint8_t tag = 0x07;
4564 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004565 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004566
4567 // Process an encrypted packet which can not yet be decrypted which should
4568 // result in the packet being buffered.
4569 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4570
4571 // Transition to the new encryption state and process another encrypted packet
4572 // which should result in the original packet being processed.
zhongyi546cc452019-04-12 15:27:49 -07004573 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004574 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004575 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4576 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004577 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004578 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(2);
4579 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4580
4581 // Finally, process a third packet and note that we do not reprocess the
4582 // buffered packet.
4583 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4584 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4585}
4586
4587TEST_P(QuicConnectionTest, TestRetransmitOrder) {
fayang5f135052019-08-22 17:59:40 -07004588 if (connection_.PtoEnabled()) {
4589 return;
4590 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004591 connection_.SetMaxTailLossProbes(0);
4592
4593 QuicByteCount first_packet_size;
4594 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4595 .WillOnce(SaveArg<3>(&first_packet_size));
4596
4597 connection_.SendStreamDataWithString(3, "first_packet", 0, NO_FIN);
4598 QuicByteCount second_packet_size;
4599 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4600 .WillOnce(SaveArg<3>(&second_packet_size));
4601 connection_.SendStreamDataWithString(3, "second_packet", 12, NO_FIN);
4602 EXPECT_NE(first_packet_size, second_packet_size);
4603 // Advance the clock by huge time to make sure packets will be retransmitted.
4604 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
4605 {
4606 InSequence s;
4607 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, first_packet_size, _));
4608 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, second_packet_size, _));
4609 }
4610 connection_.GetRetransmissionAlarm()->Fire();
4611
4612 // Advance again and expect the packets to be sent again in the same order.
4613 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(20));
4614 {
4615 InSequence s;
4616 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, first_packet_size, _));
4617 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, second_packet_size, _));
4618 }
4619 connection_.GetRetransmissionAlarm()->Fire();
4620}
4621
4622TEST_P(QuicConnectionTest, Buffer100NonDecryptablePacketsThenKeyChange) {
QUICHE teamcd098022019-03-22 18:49:55 -07004623 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4624 return;
4625 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004626 // SetFromConfig is always called after construction from InitializeSession.
4627 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4628 QuicConfig config;
4629 config.set_max_undecryptable_packets(100);
4630 connection_.SetFromConfig(config);
4631 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4632 use_tagging_decrypter();
4633
4634 const uint8_t tag = 0x07;
4635 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004636 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004637
4638 // Process an encrypted packet which can not yet be decrypted which should
4639 // result in the packet being buffered.
4640 for (uint64_t i = 1; i <= 100; ++i) {
4641 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4642 }
4643
4644 // Transition to the new encryption state and process another encrypted packet
4645 // which should result in the original packets being processed.
4646 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
zhongyi546cc452019-04-12 15:27:49 -07004647 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004648 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004649 EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
4650 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4651 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004652 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004653
4654 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(100);
4655 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
4656
4657 // Finally, process a third packet and note that we do not reprocess the
4658 // buffered packet.
4659 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4660 ProcessDataPacketAtLevel(102, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4661}
4662
4663TEST_P(QuicConnectionTest, SetRTOAfterWritingToSocket) {
4664 BlockOnNextWrite();
fayange62e63c2019-12-04 07:16:25 -08004665 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004666 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
fayange62e63c2019-12-04 07:16:25 -08004667 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004668
4669 // Test that RTO is started once we write to the socket.
4670 writer_->SetWritable();
fayange62e63c2019-12-04 07:16:25 -08004671 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004672 connection_.OnCanWrite();
4673 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4674}
4675
4676TEST_P(QuicConnectionTest, DelayRTOWithAckReceipt) {
fayang5f135052019-08-22 17:59:40 -07004677 if (connection_.PtoEnabled()) {
4678 return;
4679 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004680 connection_.SetMaxTailLossProbes(0);
4681
4682 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4683 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
4684 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
4685 connection_.SendStreamDataWithString(3, "bar", 0, NO_FIN);
4686 QuicAlarm* retransmission_alarm = connection_.GetRetransmissionAlarm();
4687 EXPECT_TRUE(retransmission_alarm->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004688 EXPECT_EQ(DefaultRetransmissionTime(),
4689 retransmission_alarm->deadline() - clock_.Now());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004690
4691 // Advance the time right before the RTO, then receive an ack for the first
4692 // packet to delay the RTO.
4693 clock_.AdvanceTime(DefaultRetransmissionTime());
4694 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4695 QuicAckFrame ack = InitAckFrame(1);
4696 ProcessAckPacket(&ack);
4697 // Now we have an RTT sample of DefaultRetransmissionTime(500ms),
4698 // so the RTO has increased to 2 * SRTT.
4699 EXPECT_TRUE(retransmission_alarm->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004700 EXPECT_EQ(retransmission_alarm->deadline() - clock_.Now(),
4701 2 * DefaultRetransmissionTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004702
4703 // Move forward past the original RTO and ensure the RTO is still pending.
4704 clock_.AdvanceTime(2 * DefaultRetransmissionTime());
4705
4706 // Ensure the second packet gets retransmitted when it finally fires.
4707 EXPECT_TRUE(retransmission_alarm->IsSet());
4708 EXPECT_EQ(retransmission_alarm->deadline(), clock_.ApproximateNow());
4709 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4710 // Manually cancel the alarm to simulate a real test.
4711 connection_.GetRetransmissionAlarm()->Fire();
4712
4713 // The new retransmitted packet number should set the RTO to a larger value
4714 // than previously.
4715 EXPECT_TRUE(retransmission_alarm->IsSet());
4716 QuicTime next_rto_time = retransmission_alarm->deadline();
4717 QuicTime expected_rto_time =
4718 connection_.sent_packet_manager().GetRetransmissionTime();
4719 EXPECT_EQ(next_rto_time, expected_rto_time);
4720}
4721
4722TEST_P(QuicConnectionTest, TestQueued) {
4723 connection_.SetMaxTailLossProbes(0);
4724
4725 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4726 BlockOnNextWrite();
4727 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4728 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4729
4730 // Unblock the writes and actually send.
4731 writer_->SetWritable();
4732 connection_.OnCanWrite();
4733 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4734}
4735
4736TEST_P(QuicConnectionTest, InitialTimeout) {
4737 EXPECT_TRUE(connection_.connected());
4738 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4739 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4740
4741 // SetFromConfig sets the initial timeouts before negotiation.
4742 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4743 QuicConfig config;
4744 connection_.SetFromConfig(config);
4745 // Subtract a second from the idle timeout on the client side.
4746 QuicTime default_timeout =
4747 clock_.ApproximateNow() +
4748 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4749 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
4750
fkastenholz5d880a92019-06-21 09:01:56 -07004751 EXPECT_CALL(visitor_,
4752 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004753 // Simulate the timeout alarm firing.
4754 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1));
4755 connection_.GetTimeoutAlarm()->Fire();
4756
4757 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4758 EXPECT_FALSE(connection_.connected());
4759
4760 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
4761 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4762 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4763 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4764 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
renjietang11e4a3d2019-05-03 11:27:26 -07004765 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07004766 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004767}
4768
4769TEST_P(QuicConnectionTest, IdleTimeoutAfterFirstSentPacket) {
4770 EXPECT_TRUE(connection_.connected());
4771 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4772 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4773
4774 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4775 QuicConfig config;
4776 connection_.SetFromConfig(config);
4777 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4778 QuicTime initial_ddl =
4779 clock_.ApproximateNow() +
4780 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4781 EXPECT_EQ(initial_ddl, connection_.GetTimeoutAlarm()->deadline());
4782 EXPECT_TRUE(connection_.connected());
4783
4784 // Advance the time and send the first packet to the peer.
fayangb9c88442020-03-26 07:03:57 -07004785 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004786 QuicPacketNumber last_packet;
4787 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4788 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4789 // This will be the updated deadline for the connection to idle time out.
4790 QuicTime new_ddl = clock_.ApproximateNow() +
4791 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4792
4793 // Simulate the timeout alarm firing, the connection should not be closed as
4794 // a new packet has been sent.
fkastenholz5d880a92019-06-21 09:01:56 -07004795 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004796 QuicTime::Delta delay = initial_ddl - clock_.ApproximateNow();
4797 clock_.AdvanceTime(delay);
fayangb9c88442020-03-26 07:03:57 -07004798 if (!GetQuicReloadableFlag(quic_use_blackhole_detector) ||
4799 !GetQuicReloadableFlag(quic_use_idle_network_detector)) {
4800 connection_.GetTimeoutAlarm()->Fire();
4801 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004802 // Verify the timeout alarm deadline is updated.
4803 EXPECT_TRUE(connection_.connected());
4804 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4805 EXPECT_EQ(new_ddl, connection_.GetTimeoutAlarm()->deadline());
4806
4807 // Simulate the timeout alarm firing again, the connection now should be
4808 // closed.
fkastenholz5d880a92019-06-21 09:01:56 -07004809 EXPECT_CALL(visitor_,
4810 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004811 clock_.AdvanceTime(new_ddl - clock_.ApproximateNow());
4812 connection_.GetTimeoutAlarm()->Fire();
4813 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4814 EXPECT_FALSE(connection_.connected());
4815
4816 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
4817 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4818 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4819 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4820 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07004821 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004822}
4823
4824TEST_P(QuicConnectionTest, IdleTimeoutAfterSendTwoPackets) {
4825 EXPECT_TRUE(connection_.connected());
4826 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4827 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4828
4829 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4830 QuicConfig config;
4831 connection_.SetFromConfig(config);
4832 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4833 QuicTime initial_ddl =
4834 clock_.ApproximateNow() +
4835 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4836 EXPECT_EQ(initial_ddl, connection_.GetTimeoutAlarm()->deadline());
4837 EXPECT_TRUE(connection_.connected());
4838
4839 // Immediately send the first packet, this is a rare case but test code will
4840 // hit this issue often as MockClock used for tests doesn't move with code
4841 // execution until manually adjusted.
4842 QuicPacketNumber last_packet;
4843 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4844 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4845
4846 // Advance the time and send the second packet to the peer.
4847 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
4848 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4849 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
4850
zhongyic1cab062019-06-19 12:02:24 -07004851 // Simulate the timeout alarm firing, the connection will be closed.
fkastenholz5d880a92019-06-21 09:01:56 -07004852 EXPECT_CALL(visitor_,
4853 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
zhongyic1cab062019-06-19 12:02:24 -07004854 clock_.AdvanceTime(initial_ddl - clock_.ApproximateNow());
4855 connection_.GetTimeoutAlarm()->Fire();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004856
4857 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4858 EXPECT_FALSE(connection_.connected());
4859
4860 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
4861 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4862 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4863 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4864 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07004865 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004866}
4867
4868TEST_P(QuicConnectionTest, HandshakeTimeout) {
4869 // Use a shorter handshake timeout than idle timeout for this test.
4870 const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(5);
4871 connection_.SetNetworkTimeouts(timeout, timeout);
4872 EXPECT_TRUE(connection_.connected());
4873 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4874
4875 QuicTime handshake_timeout =
4876 clock_.ApproximateNow() + timeout - QuicTime::Delta::FromSeconds(1);
4877 EXPECT_EQ(handshake_timeout, connection_.GetTimeoutAlarm()->deadline());
4878 EXPECT_TRUE(connection_.connected());
4879
4880 // Send and ack new data 3 seconds later to lengthen the idle timeout.
4881 SendStreamDataToPeer(
dschinazi552accc2019-06-17 17:07:34 -07004882 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
4883 "GET /", 0, FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004884 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(3));
4885 QuicAckFrame frame = InitAckFrame(1);
4886 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4887 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4888 ProcessAckPacket(&frame);
4889
fayangb9c88442020-03-26 07:03:57 -07004890 if (!GetQuicReloadableFlag(quic_use_blackhole_detector) ||
4891 !GetQuicReloadableFlag(quic_use_idle_network_detector)) {
4892 // Fire early to verify it wouldn't timeout yet.
4893 connection_.GetTimeoutAlarm()->Fire();
4894 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004895 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4896 EXPECT_TRUE(connection_.connected());
4897
4898 clock_.AdvanceTime(timeout - QuicTime::Delta::FromSeconds(2));
4899
fkastenholz5d880a92019-06-21 09:01:56 -07004900 EXPECT_CALL(visitor_,
4901 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004902 // Simulate the timeout alarm firing.
4903 connection_.GetTimeoutAlarm()->Fire();
4904
4905 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4906 EXPECT_FALSE(connection_.connected());
4907
4908 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
4909 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4910 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4911 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07004912 TestConnectionCloseQuicErrorCode(QUIC_HANDSHAKE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004913}
4914
4915TEST_P(QuicConnectionTest, PingAfterSend) {
QUICHE teamcd098022019-03-22 18:49:55 -07004916 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4917 return;
4918 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004919 EXPECT_TRUE(connection_.connected());
4920 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4921 .WillRepeatedly(Return(true));
4922 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4923
4924 // Advance to 5ms, and send a packet to the peer, which will set
4925 // the ping alarm.
4926 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4927 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4928 SendStreamDataToPeer(
dschinazi552accc2019-06-17 17:07:34 -07004929 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
4930 "GET /", 0, FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004931 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004932 EXPECT_EQ(QuicTime::Delta::FromSeconds(15),
4933 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004934
4935 // Now recevie an ACK of the previous packet, which will move the
4936 // ping alarm forward.
4937 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4938 QuicAckFrame frame = InitAckFrame(1);
4939 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4940 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4941 ProcessAckPacket(&frame);
4942 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4943 // The ping timer is set slightly less than 15 seconds in the future, because
4944 // of the 1s ping timer alarm granularity.
zhongyieef848f2019-10-18 07:09:37 -07004945 EXPECT_EQ(
4946 QuicTime::Delta::FromSeconds(15) - QuicTime::Delta::FromMilliseconds(5),
4947 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004948
4949 writer_->Reset();
4950 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15));
zhongyifbb25772019-04-10 16:54:08 -07004951 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004952 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07004953 size_t padding_frame_count = writer_->padding_frames().size();
4954 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004955 ASSERT_EQ(1u, writer_->ping_frames().size());
4956 writer_->Reset();
4957
4958 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4959 .WillRepeatedly(Return(false));
4960 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4961 SendAckPacketToPeer();
4962
4963 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4964}
4965
4966TEST_P(QuicConnectionTest, ReducedPingTimeout) {
QUICHE teamcd098022019-03-22 18:49:55 -07004967 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4968 return;
4969 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004970 EXPECT_TRUE(connection_.connected());
4971 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4972 .WillRepeatedly(Return(true));
4973 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4974
4975 // Use a reduced ping timeout for this connection.
4976 connection_.set_ping_timeout(QuicTime::Delta::FromSeconds(10));
4977
4978 // Advance to 5ms, and send a packet to the peer, which will set
4979 // the ping alarm.
4980 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4981 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4982 SendStreamDataToPeer(
dschinazi552accc2019-06-17 17:07:34 -07004983 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
4984 "GET /", 0, FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004985 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004986 EXPECT_EQ(QuicTime::Delta::FromSeconds(10),
4987 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004988
4989 // Now recevie an ACK of the previous packet, which will move the
4990 // ping alarm forward.
4991 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4992 QuicAckFrame frame = InitAckFrame(1);
4993 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4994 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4995 ProcessAckPacket(&frame);
4996 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4997 // The ping timer is set slightly less than 10 seconds in the future, because
4998 // of the 1s ping timer alarm granularity.
zhongyieef848f2019-10-18 07:09:37 -07004999 EXPECT_EQ(
5000 QuicTime::Delta::FromSeconds(10) - QuicTime::Delta::FromMilliseconds(5),
5001 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005002
5003 writer_->Reset();
5004 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
5005 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
5006 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
5007 }));
5008 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07005009 size_t padding_frame_count = writer_->padding_frames().size();
5010 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005011 ASSERT_EQ(1u, writer_->ping_frames().size());
5012 writer_->Reset();
5013
5014 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
5015 .WillRepeatedly(Return(false));
5016 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
5017 SendAckPacketToPeer();
5018
5019 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
5020}
5021
5022// Tests whether sending an MTU discovery packet to peer successfully causes the
5023// maximum packet size to increase.
5024TEST_P(QuicConnectionTest, SendMtuDiscoveryPacket) {
wub031d47c2019-11-21 08:04:07 -08005025 MtuDiscoveryTestInit();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005026
5027 // Send an MTU probe.
5028 const size_t new_mtu = kDefaultMaxPacketSize + 100;
5029 QuicByteCount mtu_probe_size;
5030 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5031 .WillOnce(SaveArg<3>(&mtu_probe_size));
5032 connection_.SendMtuDiscoveryPacket(new_mtu);
5033 EXPECT_EQ(new_mtu, mtu_probe_size);
5034 EXPECT_EQ(QuicPacketNumber(1u), creator_->packet_number());
5035
5036 // Send more than MTU worth of data. No acknowledgement was received so far,
5037 // so the MTU should be at its old value.
vasilvvc48c8712019-03-11 13:38:16 -07005038 const std::string data(kDefaultMaxPacketSize + 1, '.');
QUICHE teama6ef0a62019-03-07 20:34:33 -05005039 QuicByteCount size_before_mtu_change;
5040 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5041 .Times(2)
5042 .WillOnce(SaveArg<3>(&size_before_mtu_change))
5043 .WillOnce(Return());
5044 connection_.SendStreamDataWithString(3, data, 0, FIN);
5045 EXPECT_EQ(QuicPacketNumber(3u), creator_->packet_number());
5046 EXPECT_EQ(kDefaultMaxPacketSize, size_before_mtu_change);
5047
5048 // Acknowledge all packets so far.
5049 QuicAckFrame probe_ack = InitAckFrame(3);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005050 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5051 ProcessAckPacket(&probe_ack);
5052 EXPECT_EQ(new_mtu, connection_.max_packet_length());
5053
5054 // Send the same data again. Check that it fits into a single packet now.
5055 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
5056 connection_.SendStreamDataWithString(3, data, 0, FIN);
5057 EXPECT_EQ(QuicPacketNumber(4u), creator_->packet_number());
5058}
5059
wubb442b862020-01-31 08:16:21 -08005060// Verifies that when a MTU probe packet is sent and buffered in a batch writer,
5061// the writer is flushed immediately.
5062TEST_P(QuicConnectionTest, BatchWriterFlushedAfterMtuDiscoveryPacket) {
5063 writer_->SetBatchMode(true);
5064 MtuDiscoveryTestInit();
5065
5066 // Send an MTU probe.
5067 const size_t target_mtu = kDefaultMaxPacketSize + 100;
5068 QuicByteCount mtu_probe_size;
5069 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5070 .WillOnce(SaveArg<3>(&mtu_probe_size));
5071 const uint32_t prior_flush_attempts = writer_->flush_attempts();
5072 connection_.SendMtuDiscoveryPacket(target_mtu);
5073 EXPECT_EQ(target_mtu, mtu_probe_size);
wub18f47342020-03-16 15:56:03 -07005074 EXPECT_EQ(writer_->flush_attempts(), prior_flush_attempts + 1);
wubb442b862020-01-31 08:16:21 -08005075}
5076
QUICHE teama6ef0a62019-03-07 20:34:33 -05005077// Tests whether MTU discovery does not happen when it is not explicitly enabled
5078// by the connection options.
5079TEST_P(QuicConnectionTest, MtuDiscoveryDisabled) {
wub031d47c2019-11-21 08:04:07 -08005080 MtuDiscoveryTestInit();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005081
5082 const QuicPacketCount packets_between_probes_base = 10;
5083 set_packets_between_probes_base(packets_between_probes_base);
5084
5085 const QuicPacketCount number_of_packets = packets_between_probes_base * 2;
5086 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
5087 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5088 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5089 EXPECT_EQ(0u, connection_.mtu_probe_count());
5090 }
5091}
5092
wubf76cf2a2019-10-11 18:49:07 -07005093// Tests whether MTU discovery works when all probes are acknowledged on the
QUICHE teama6ef0a62019-03-07 20:34:33 -05005094// first try.
5095TEST_P(QuicConnectionTest, MtuDiscoveryEnabled) {
wub031d47c2019-11-21 08:04:07 -08005096 MtuDiscoveryTestInit();
nharperc6b99512019-09-19 11:13:48 -07005097
QUICHE teama6ef0a62019-03-07 20:34:33 -05005098 const QuicPacketCount packets_between_probes_base = 5;
5099 set_packets_between_probes_base(packets_between_probes_base);
5100
wubf76cf2a2019-10-11 18:49:07 -07005101 connection_.EnablePathMtuDiscovery(send_algorithm_);
5102
QUICHE teama6ef0a62019-03-07 20:34:33 -05005103 // Send enough packets so that the next one triggers path MTU discovery.
5104 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5105 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5106 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5107 }
5108
5109 // Trigger the probe.
5110 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5111 nullptr);
5112 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5113 QuicByteCount probe_size;
5114 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5115 .WillOnce(SaveArg<3>(&probe_size));
5116 connection_.GetMtuDiscoveryAlarm()->Fire();
wub173916e2019-11-27 14:36:24 -08005117
5118 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(),
5119 kMtuDiscoveryTargetPacketSizeHigh));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005120
5121 const QuicPacketNumber probe_packet_number =
5122 FirstSendingPacketNumber() + packets_between_probes_base;
5123 ASSERT_EQ(probe_packet_number, creator_->packet_number());
5124
5125 // Acknowledge all packets sent so far.
5126 QuicAckFrame probe_ack = InitAckFrame(probe_packet_number);
wubf76cf2a2019-10-11 18:49:07 -07005127 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5128 .Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005129 ProcessAckPacket(&probe_ack);
wubf76cf2a2019-10-11 18:49:07 -07005130 EXPECT_EQ(probe_size, connection_.max_packet_length());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005131 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5132
wubf76cf2a2019-10-11 18:49:07 -07005133 EXPECT_EQ(1u, connection_.mtu_probe_count());
5134
wubf76cf2a2019-10-11 18:49:07 -07005135 QuicStreamOffset stream_offset = packets_between_probes_base;
wubecb643f2020-03-19 08:58:46 -07005136 QuicByteCount last_probe_size = 0;
wubf76cf2a2019-10-11 18:49:07 -07005137 for (size_t num_probes = 1; num_probes < kMtuDiscoveryAttempts;
5138 ++num_probes) {
5139 // Send just enough packets without triggering the next probe.
5140 for (QuicPacketCount i = 0;
5141 i < (packets_between_probes_base << num_probes) - 1; ++i) {
5142 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5143 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5144 }
5145
5146 // Trigger the next probe.
5147 SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
5148 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5149 QuicByteCount new_probe_size;
5150 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5151 .WillOnce(SaveArg<3>(&new_probe_size));
5152 connection_.GetMtuDiscoveryAlarm()->Fire();
5153 EXPECT_THAT(new_probe_size,
5154 InRange(probe_size, kMtuDiscoveryTargetPacketSizeHigh));
5155 EXPECT_EQ(num_probes + 1, connection_.mtu_probe_count());
5156
5157 // Acknowledge all packets sent so far.
5158 QuicAckFrame probe_ack = InitAckFrame(creator_->packet_number());
5159 ProcessAckPacket(&probe_ack);
5160 EXPECT_EQ(new_probe_size, connection_.max_packet_length());
5161 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5162
wubecb643f2020-03-19 08:58:46 -07005163 last_probe_size = probe_size;
wubf76cf2a2019-10-11 18:49:07 -07005164 probe_size = new_probe_size;
5165 }
5166
5167 // The last probe size should be equal to the target.
5168 EXPECT_EQ(probe_size, kMtuDiscoveryTargetPacketSizeHigh);
wubecb643f2020-03-19 08:58:46 -07005169
wubae6581a2020-05-04 12:13:05 -07005170 writer_->SetShouldWriteFail();
wubecb643f2020-03-19 08:58:46 -07005171
wubae6581a2020-05-04 12:13:05 -07005172 // Ignore PACKET_WRITE_ERROR once.
5173 SendStreamDataToPeer(3, "(", stream_offset++, NO_FIN, nullptr);
5174 EXPECT_EQ(last_probe_size, connection_.max_packet_length());
5175 EXPECT_TRUE(connection_.connected());
wubecb643f2020-03-19 08:58:46 -07005176
wubae6581a2020-05-04 12:13:05 -07005177 // Close connection on another PACKET_WRITE_ERROR.
5178 EXPECT_CALL(visitor_, OnConnectionClosed(_, _))
5179 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
5180 SendStreamDataToPeer(3, ")", stream_offset++, NO_FIN, nullptr);
5181 EXPECT_EQ(last_probe_size, connection_.max_packet_length());
5182 EXPECT_FALSE(connection_.connected());
5183 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
5184 IsError(QUIC_PACKET_WRITE_ERROR));
wubf76cf2a2019-10-11 18:49:07 -07005185}
5186
wub748e20b2020-03-20 14:33:59 -07005187// After a successful MTU probe, one and only one write error should be ignored
5188// if it happened in QuicConnection::FlushPacket.
5189TEST_P(QuicConnectionTest,
5190 MtuDiscoveryIgnoreOneWriteErrorInFlushAfterSuccessfulProbes) {
5191 MtuDiscoveryTestInit();
5192 writer_->SetBatchMode(true);
5193
5194 const QuicPacketCount packets_between_probes_base = 5;
5195 set_packets_between_probes_base(packets_between_probes_base);
5196
5197 connection_.EnablePathMtuDiscovery(send_algorithm_);
5198
5199 const QuicByteCount original_max_packet_length =
5200 connection_.max_packet_length();
5201 // Send enough packets so that the next one triggers path MTU discovery.
5202 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5203 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5204 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5205 }
5206
5207 // Trigger the probe.
5208 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5209 nullptr);
5210 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5211 QuicByteCount probe_size;
5212 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5213 .WillOnce(SaveArg<3>(&probe_size));
5214 connection_.GetMtuDiscoveryAlarm()->Fire();
5215
5216 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(),
5217 kMtuDiscoveryTargetPacketSizeHigh));
5218
5219 const QuicPacketNumber probe_packet_number =
5220 FirstSendingPacketNumber() + packets_between_probes_base;
5221 ASSERT_EQ(probe_packet_number, creator_->packet_number());
5222
5223 // Acknowledge all packets sent so far.
5224 QuicAckFrame probe_ack = InitAckFrame(probe_packet_number);
5225 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5226 .Times(AnyNumber());
5227 ProcessAckPacket(&probe_ack);
5228 EXPECT_EQ(probe_size, connection_.max_packet_length());
5229 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5230
5231 EXPECT_EQ(1u, connection_.mtu_probe_count());
5232
wubae6581a2020-05-04 12:13:05 -07005233 writer_->SetShouldWriteFail();
wub748e20b2020-03-20 14:33:59 -07005234
wubae6581a2020-05-04 12:13:05 -07005235 // Ignore PACKET_WRITE_ERROR once.
5236 {
5237 QuicConnection::ScopedPacketFlusher flusher(&connection_);
5238 // flusher's destructor will call connection_.FlushPackets, which should
5239 // get a WRITE_STATUS_ERROR from the writer and ignore it.
wub748e20b2020-03-20 14:33:59 -07005240 }
wubae6581a2020-05-04 12:13:05 -07005241 EXPECT_EQ(original_max_packet_length, connection_.max_packet_length());
5242 EXPECT_TRUE(connection_.connected());
5243
5244 // Close connection on another PACKET_WRITE_ERROR.
5245 EXPECT_CALL(visitor_, OnConnectionClosed(_, _))
5246 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
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.
5251 }
5252 EXPECT_EQ(original_max_packet_length, connection_.max_packet_length());
5253 EXPECT_FALSE(connection_.connected());
5254 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
5255 IsError(QUIC_PACKET_WRITE_ERROR));
wub748e20b2020-03-20 14:33:59 -07005256}
5257
wubf76cf2a2019-10-11 18:49:07 -07005258// Simulate the case where the first attempt to send a probe is write blocked,
5259// and after unblock, the second attempt returns a MSG_TOO_BIG error.
5260TEST_P(QuicConnectionTest, MtuDiscoveryWriteBlocked) {
wub031d47c2019-11-21 08:04:07 -08005261 MtuDiscoveryTestInit();
wubf76cf2a2019-10-11 18:49:07 -07005262
5263 const QuicPacketCount packets_between_probes_base = 5;
5264 set_packets_between_probes_base(packets_between_probes_base);
5265
5266 connection_.EnablePathMtuDiscovery(send_algorithm_);
5267
5268 // Send enough packets so that the next one triggers path MTU discovery.
5269 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5270 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005271 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5272 }
5273
wubf76cf2a2019-10-11 18:49:07 -07005274 QuicByteCount original_max_packet_length = connection_.max_packet_length();
5275
5276 // Trigger the probe.
5277 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5278 nullptr);
5279 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
fayange62e63c2019-12-04 07:16:25 -08005280 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
wubf76cf2a2019-10-11 18:49:07 -07005281 BlockOnNextWrite();
5282 EXPECT_EQ(0u, connection_.NumQueuedPackets());
5283 connection_.GetMtuDiscoveryAlarm()->Fire();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005284 EXPECT_EQ(1u, connection_.mtu_probe_count());
wubf76cf2a2019-10-11 18:49:07 -07005285 EXPECT_EQ(1u, connection_.NumQueuedPackets());
5286 ASSERT_TRUE(connection_.connected());
5287
5288 writer_->SetWritable();
5289 SimulateNextPacketTooLarge();
5290 connection_.OnCanWrite();
5291 EXPECT_EQ(0u, connection_.NumQueuedPackets());
5292 EXPECT_EQ(original_max_packet_length, connection_.max_packet_length());
5293 EXPECT_TRUE(connection_.connected());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005294}
5295
5296// Tests whether MTU discovery works correctly when the probes never get
5297// acknowledged.
5298TEST_P(QuicConnectionTest, MtuDiscoveryFailed) {
wub031d47c2019-11-21 08:04:07 -08005299 MtuDiscoveryTestInit();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005300
QUICHE teama6ef0a62019-03-07 20:34:33 -05005301 // Lower the number of probes between packets in order to make the test go
5302 // much faster.
5303 const QuicPacketCount packets_between_probes_base = 5;
5304 set_packets_between_probes_base(packets_between_probes_base);
5305
wubf76cf2a2019-10-11 18:49:07 -07005306 connection_.EnablePathMtuDiscovery(send_algorithm_);
5307
5308 const QuicTime::Delta rtt = QuicTime::Delta::FromMilliseconds(100);
5309
5310 EXPECT_EQ(packets_between_probes_base,
5311 QuicConnectionPeer::GetPacketsBetweenMtuProbes(&connection_));
5312
QUICHE teama6ef0a62019-03-07 20:34:33 -05005313 // This tests sends more packets than strictly necessary to make sure that if
5314 // the connection was to send more discovery packets than needed, those would
5315 // get caught as well.
5316 const QuicPacketCount number_of_packets =
5317 packets_between_probes_base * (1 << (kMtuDiscoveryAttempts + 1));
5318 std::vector<QuicPacketNumber> mtu_discovery_packets;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005319 // Called on many acks.
5320 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5321 .Times(AnyNumber());
5322 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
5323 SendStreamDataToPeer(3, "!", i, NO_FIN, nullptr);
5324 clock_.AdvanceTime(rtt);
5325
5326 // Receive an ACK, which marks all data packets as received, and all MTU
5327 // discovery packets as missing.
5328
5329 QuicAckFrame ack;
5330
5331 if (!mtu_discovery_packets.empty()) {
5332 QuicPacketNumber min_packet = *min_element(mtu_discovery_packets.begin(),
5333 mtu_discovery_packets.end());
5334 QuicPacketNumber max_packet = *max_element(mtu_discovery_packets.begin(),
5335 mtu_discovery_packets.end());
5336 ack.packets.AddRange(QuicPacketNumber(1), min_packet);
5337 ack.packets.AddRange(QuicPacketNumber(max_packet + 1),
5338 creator_->packet_number() + 1);
5339 ack.largest_acked = creator_->packet_number();
5340
5341 } else {
5342 ack.packets.AddRange(QuicPacketNumber(1), creator_->packet_number() + 1);
5343 ack.largest_acked = creator_->packet_number();
5344 }
5345
5346 ProcessAckPacket(&ack);
5347
5348 // Trigger MTU probe if it would be scheduled now.
5349 if (!connection_.GetMtuDiscoveryAlarm()->IsSet()) {
5350 continue;
5351 }
5352
5353 // Fire the alarm. The alarm should cause a packet to be sent.
5354 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5355 connection_.GetMtuDiscoveryAlarm()->Fire();
5356 // Record the packet number of the MTU discovery packet in order to
5357 // mark it as NACK'd.
5358 mtu_discovery_packets.push_back(creator_->packet_number());
5359 }
5360
5361 // Ensure the number of packets between probes grows exponentially by checking
5362 // it against the closed-form expression for the packet number.
5363 ASSERT_EQ(kMtuDiscoveryAttempts, mtu_discovery_packets.size());
5364 for (uint64_t i = 0; i < kMtuDiscoveryAttempts; i++) {
5365 // 2^0 + 2^1 + 2^2 + ... + 2^n = 2^(n + 1) - 1
5366 const QuicPacketCount packets_between_probes =
5367 packets_between_probes_base * ((1 << (i + 1)) - 1);
5368 EXPECT_EQ(QuicPacketNumber(packets_between_probes + (i + 1)),
5369 mtu_discovery_packets[i]);
5370 }
5371
5372 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5373 EXPECT_EQ(kDefaultMaxPacketSize, connection_.max_packet_length());
5374 EXPECT_EQ(kMtuDiscoveryAttempts, connection_.mtu_probe_count());
5375}
5376
wubf76cf2a2019-10-11 18:49:07 -07005377// Probe 3 times, the first one succeeds, then fails, then succeeds again.
5378TEST_P(QuicConnectionTest, MtuDiscoverySecondProbeFailed) {
wub031d47c2019-11-21 08:04:07 -08005379 MtuDiscoveryTestInit();
wubf76cf2a2019-10-11 18:49:07 -07005380
5381 const QuicPacketCount packets_between_probes_base = 5;
5382 set_packets_between_probes_base(packets_between_probes_base);
5383
5384 connection_.EnablePathMtuDiscovery(send_algorithm_);
5385
5386 // Send enough packets so that the next one triggers path MTU discovery.
5387 QuicStreamOffset stream_offset = 0;
5388 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5389 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5390 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5391 }
5392
5393 // Trigger the probe.
5394 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5395 nullptr);
5396 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5397 QuicByteCount probe_size;
5398 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5399 .WillOnce(SaveArg<3>(&probe_size));
5400 connection_.GetMtuDiscoveryAlarm()->Fire();
5401 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(),
5402 kMtuDiscoveryTargetPacketSizeHigh));
5403
5404 const QuicPacketNumber probe_packet_number =
5405 FirstSendingPacketNumber() + packets_between_probes_base;
5406 ASSERT_EQ(probe_packet_number, creator_->packet_number());
5407
5408 // Acknowledge all packets sent so far.
5409 QuicAckFrame first_ack = InitAckFrame(probe_packet_number);
wubf76cf2a2019-10-11 18:49:07 -07005410 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5411 .Times(AnyNumber());
5412 ProcessAckPacket(&first_ack);
5413 EXPECT_EQ(probe_size, connection_.max_packet_length());
5414 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5415
5416 EXPECT_EQ(1u, connection_.mtu_probe_count());
5417
5418 // Send just enough packets without triggering the second probe.
5419 for (QuicPacketCount i = 0; i < (packets_between_probes_base << 1) - 1; ++i) {
5420 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5421 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5422 }
5423
5424 // Trigger the second probe.
5425 SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
5426 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5427 QuicByteCount second_probe_size;
5428 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5429 .WillOnce(SaveArg<3>(&second_probe_size));
5430 connection_.GetMtuDiscoveryAlarm()->Fire();
5431 EXPECT_THAT(second_probe_size,
5432 InRange(probe_size, kMtuDiscoveryTargetPacketSizeHigh));
5433 EXPECT_EQ(2u, connection_.mtu_probe_count());
5434
5435 // Acknowledge all packets sent so far, except the second probe.
5436 QuicPacketNumber second_probe_packet_number = creator_->packet_number();
5437 QuicAckFrame second_ack = InitAckFrame(second_probe_packet_number - 1);
5438 ProcessAckPacket(&first_ack);
5439 EXPECT_EQ(probe_size, connection_.max_packet_length());
5440
5441 // Send just enough packets without triggering the third probe.
5442 for (QuicPacketCount i = 0; i < (packets_between_probes_base << 2) - 1; ++i) {
5443 SendStreamDataToPeer(3, "@", stream_offset++, NO_FIN, nullptr);
5444 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5445 }
5446
5447 // Trigger the third probe.
5448 SendStreamDataToPeer(3, "#", stream_offset++, NO_FIN, nullptr);
5449 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5450 QuicByteCount third_probe_size;
5451 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5452 .WillOnce(SaveArg<3>(&third_probe_size));
5453 connection_.GetMtuDiscoveryAlarm()->Fire();
5454 EXPECT_THAT(third_probe_size, InRange(probe_size, second_probe_size));
5455 EXPECT_EQ(3u, connection_.mtu_probe_count());
5456
5457 // Acknowledge all packets sent so far, except the second probe.
5458 QuicAckFrame third_ack =
5459 ConstructAckFrame(creator_->packet_number(), second_probe_packet_number);
5460 ProcessAckPacket(&third_ack);
5461 EXPECT_EQ(third_probe_size, connection_.max_packet_length());
5462}
5463
QUICHE teama6ef0a62019-03-07 20:34:33 -05005464// Tests whether MTU discovery works when the writer has a limit on how large a
5465// packet can be.
5466TEST_P(QuicConnectionTest, MtuDiscoveryWriterLimited) {
wub031d47c2019-11-21 08:04:07 -08005467 MtuDiscoveryTestInit();
nharperc6b99512019-09-19 11:13:48 -07005468
QUICHE teama6ef0a62019-03-07 20:34:33 -05005469 const QuicByteCount mtu_limit = kMtuDiscoveryTargetPacketSizeHigh - 1;
5470 writer_->set_max_packet_size(mtu_limit);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005471
5472 const QuicPacketCount packets_between_probes_base = 5;
5473 set_packets_between_probes_base(packets_between_probes_base);
5474
wubf76cf2a2019-10-11 18:49:07 -07005475 connection_.EnablePathMtuDiscovery(send_algorithm_);
5476
QUICHE teama6ef0a62019-03-07 20:34:33 -05005477 // Send enough packets so that the next one triggers path MTU discovery.
5478 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5479 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5480 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5481 }
5482
5483 // Trigger the probe.
5484 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5485 nullptr);
5486 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5487 QuicByteCount probe_size;
5488 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5489 .WillOnce(SaveArg<3>(&probe_size));
5490 connection_.GetMtuDiscoveryAlarm()->Fire();
wub173916e2019-11-27 14:36:24 -08005491
5492 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(), mtu_limit));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005493
5494 const QuicPacketNumber probe_sequence_number =
5495 FirstSendingPacketNumber() + packets_between_probes_base;
5496 ASSERT_EQ(probe_sequence_number, creator_->packet_number());
5497
5498 // Acknowledge all packets sent so far.
5499 QuicAckFrame probe_ack = InitAckFrame(probe_sequence_number);
wubf76cf2a2019-10-11 18:49:07 -07005500 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5501 .Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005502 ProcessAckPacket(&probe_ack);
wubf76cf2a2019-10-11 18:49:07 -07005503 EXPECT_EQ(probe_size, connection_.max_packet_length());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005504 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5505
wubf76cf2a2019-10-11 18:49:07 -07005506 EXPECT_EQ(1u, connection_.mtu_probe_count());
5507
wubf76cf2a2019-10-11 18:49:07 -07005508 QuicStreamOffset stream_offset = packets_between_probes_base;
5509 for (size_t num_probes = 1; num_probes < kMtuDiscoveryAttempts;
5510 ++num_probes) {
5511 // Send just enough packets without triggering the next probe.
5512 for (QuicPacketCount i = 0;
5513 i < (packets_between_probes_base << num_probes) - 1; ++i) {
5514 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5515 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5516 }
5517
5518 // Trigger the next probe.
5519 SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
5520 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5521 QuicByteCount new_probe_size;
5522 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5523 .WillOnce(SaveArg<3>(&new_probe_size));
5524 connection_.GetMtuDiscoveryAlarm()->Fire();
5525 EXPECT_THAT(new_probe_size, InRange(probe_size, mtu_limit));
5526 EXPECT_EQ(num_probes + 1, connection_.mtu_probe_count());
5527
5528 // Acknowledge all packets sent so far.
5529 QuicAckFrame probe_ack = InitAckFrame(creator_->packet_number());
5530 ProcessAckPacket(&probe_ack);
5531 EXPECT_EQ(new_probe_size, connection_.max_packet_length());
5532 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5533
5534 probe_size = new_probe_size;
5535 }
5536
5537 // The last probe size should be equal to the target.
5538 EXPECT_EQ(probe_size, mtu_limit);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005539}
5540
5541// Tests whether MTU discovery works when the writer returns an error despite
5542// advertising higher packet length.
5543TEST_P(QuicConnectionTest, MtuDiscoveryWriterFailed) {
wub031d47c2019-11-21 08:04:07 -08005544 MtuDiscoveryTestInit();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005545
5546 const QuicByteCount mtu_limit = kMtuDiscoveryTargetPacketSizeHigh - 1;
5547 const QuicByteCount initial_mtu = connection_.max_packet_length();
5548 EXPECT_LT(initial_mtu, mtu_limit);
5549 writer_->set_max_packet_size(mtu_limit);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005550
5551 const QuicPacketCount packets_between_probes_base = 5;
5552 set_packets_between_probes_base(packets_between_probes_base);
5553
wubf76cf2a2019-10-11 18:49:07 -07005554 connection_.EnablePathMtuDiscovery(send_algorithm_);
5555
QUICHE teama6ef0a62019-03-07 20:34:33 -05005556 // Send enough packets so that the next one triggers path MTU discovery.
5557 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5558 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5559 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5560 }
5561
5562 // Trigger the probe.
5563 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5564 nullptr);
5565 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5566 writer_->SimulateNextPacketTooLarge();
5567 connection_.GetMtuDiscoveryAlarm()->Fire();
5568 ASSERT_TRUE(connection_.connected());
5569
5570 // Send more data.
5571 QuicPacketNumber probe_number = creator_->packet_number();
5572 QuicPacketCount extra_packets = packets_between_probes_base * 3;
5573 for (QuicPacketCount i = 0; i < extra_packets; i++) {
5574 connection_.EnsureWritableAndSendStreamData5();
5575 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5576 }
5577
5578 // Acknowledge all packets sent so far, except for the lost probe.
5579 QuicAckFrame probe_ack =
5580 ConstructAckFrame(creator_->packet_number(), probe_number);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005581 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5582 ProcessAckPacket(&probe_ack);
5583 EXPECT_EQ(initial_mtu, connection_.max_packet_length());
5584
5585 // Send more packets, and ensure that none of them sets the alarm.
5586 for (QuicPacketCount i = 0; i < 4 * packets_between_probes_base; i++) {
5587 connection_.EnsureWritableAndSendStreamData5();
5588 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5589 }
5590
5591 EXPECT_EQ(initial_mtu, connection_.max_packet_length());
5592 EXPECT_EQ(1u, connection_.mtu_probe_count());
5593}
5594
5595TEST_P(QuicConnectionTest, NoMtuDiscoveryAfterConnectionClosed) {
wub031d47c2019-11-21 08:04:07 -08005596 MtuDiscoveryTestInit();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005597
QUICHE teama6ef0a62019-03-07 20:34:33 -05005598 const QuicPacketCount packets_between_probes_base = 10;
5599 set_packets_between_probes_base(packets_between_probes_base);
5600
wubf76cf2a2019-10-11 18:49:07 -07005601 connection_.EnablePathMtuDiscovery(send_algorithm_);
5602
QUICHE teama6ef0a62019-03-07 20:34:33 -05005603 // Send enough packets so that the next one triggers path MTU discovery.
5604 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5605 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5606 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5607 }
5608
5609 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5610 nullptr);
5611 EXPECT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5612
fkastenholz5d880a92019-06-21 09:01:56 -07005613 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005614 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
5615 ConnectionCloseBehavior::SILENT_CLOSE);
5616 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5617}
5618
dschinazi9a6194e2020-04-30 16:21:09 -07005619TEST_P(QuicConnectionTest, TimeoutAfterSendDuringHandshake) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005620 EXPECT_TRUE(connection_.connected());
5621 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5622 QuicConfig config;
5623 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005624
5625 const QuicTime::Delta initial_idle_timeout =
5626 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5627 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5628 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
5629
5630 // When we send a packet, the timeout will change to 5ms +
5631 // kInitialIdleTimeoutSecs.
5632 clock_.AdvanceTime(five_ms);
5633 SendStreamDataToPeer(
5634 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5635 0, FIN, nullptr);
fayangb9c88442020-03-26 07:03:57 -07005636 if (GetQuicReloadableFlag(quic_use_blackhole_detector) &&
5637 GetQuicReloadableFlag(quic_use_idle_network_detector)) {
5638 EXPECT_EQ(default_timeout + five_ms,
5639 connection_.GetTimeoutAlarm()->deadline());
5640 } else {
5641 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5642 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005643
5644 // Now send more data. This will not move the timeout because
5645 // no data has been received since the previous write.
5646 clock_.AdvanceTime(five_ms);
5647 SendStreamDataToPeer(
5648 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5649 3, FIN, nullptr);
fayangb9c88442020-03-26 07:03:57 -07005650 if (GetQuicReloadableFlag(quic_use_blackhole_detector) &&
5651 GetQuicReloadableFlag(quic_use_idle_network_detector)) {
5652 EXPECT_EQ(default_timeout + five_ms,
5653 connection_.GetTimeoutAlarm()->deadline());
5654 } else {
5655 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5656 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005657
5658 // The original alarm will fire. We should not time out because we had a
5659 // network event at t=5ms. The alarm will reregister.
5660 clock_.AdvanceTime(initial_idle_timeout - five_ms - five_ms);
5661 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
fayangb9c88442020-03-26 07:03:57 -07005662 if (!GetQuicReloadableFlag(quic_use_blackhole_detector) ||
5663 !GetQuicReloadableFlag(quic_use_idle_network_detector)) {
5664 connection_.GetTimeoutAlarm()->Fire();
5665 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005666 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5667 EXPECT_TRUE(connection_.connected());
5668 EXPECT_EQ(default_timeout + five_ms,
5669 connection_.GetTimeoutAlarm()->deadline());
5670
5671 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07005672 EXPECT_CALL(visitor_,
5673 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07005674 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005675 clock_.AdvanceTime(five_ms);
5676 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5677 connection_.GetTimeoutAlarm()->Fire();
5678 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5679 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005680 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005681}
5682
5683TEST_P(QuicConnectionTest, TimeoutAfterRetransmission) {
fayang5f135052019-08-22 17:59:40 -07005684 if (connection_.PtoEnabled()) {
5685 return;
5686 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005687 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5688 EXPECT_TRUE(connection_.connected());
5689 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5690 QuicConfig config;
5691 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005692
5693 const QuicTime start_time = clock_.Now();
5694 const QuicTime::Delta initial_idle_timeout =
5695 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5696 QuicTime default_timeout = clock_.Now() + initial_idle_timeout;
5697
5698 connection_.SetMaxTailLossProbes(0);
5699 const QuicTime default_retransmission_time =
5700 start_time + DefaultRetransmissionTime();
5701
5702 ASSERT_LT(default_retransmission_time, default_timeout);
5703
5704 // When we send a packet, the timeout will change to 5 ms +
5705 // kInitialIdleTimeoutSecs (but it will not reschedule the alarm).
5706 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5707 const QuicTime send_time = start_time + five_ms;
5708 clock_.AdvanceTime(five_ms);
5709 ASSERT_EQ(send_time, clock_.Now());
5710 SendStreamDataToPeer(
5711 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5712 0, FIN, nullptr);
fayangb9c88442020-03-26 07:03:57 -07005713 if (GetQuicReloadableFlag(quic_use_blackhole_detector) &&
5714 GetQuicReloadableFlag(quic_use_idle_network_detector)) {
5715 EXPECT_EQ(default_timeout + five_ms,
5716 connection_.GetTimeoutAlarm()->deadline());
5717 } else {
5718 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5719 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005720
5721 // Move forward 5 ms and receive a packet, which will move the timeout
5722 // forward 5 ms more (but will not reschedule the alarm).
5723 const QuicTime receive_time = send_time + five_ms;
5724 clock_.AdvanceTime(receive_time - clock_.Now());
5725 ASSERT_EQ(receive_time, clock_.Now());
5726 ProcessPacket(1);
5727
5728 // Now move forward to the retransmission time and retransmit the
5729 // packet, which should move the timeout forward again (but will not
5730 // reschedule the alarm).
5731 EXPECT_EQ(default_retransmission_time + five_ms,
5732 connection_.GetRetransmissionAlarm()->deadline());
5733 // Simulate the retransmission alarm firing.
5734 const QuicTime rto_time = send_time + DefaultRetransmissionTime();
5735 const QuicTime final_timeout = rto_time + initial_idle_timeout;
5736 clock_.AdvanceTime(rto_time - clock_.Now());
5737 ASSERT_EQ(rto_time, clock_.Now());
5738 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _));
5739 connection_.GetRetransmissionAlarm()->Fire();
5740
5741 // Advance to the original timeout and fire the alarm. The connection should
5742 // timeout, and the alarm should be registered based on the time of the
5743 // retransmission.
5744 clock_.AdvanceTime(default_timeout - clock_.Now());
5745 ASSERT_EQ(default_timeout.ToDebuggingValue(),
5746 clock_.Now().ToDebuggingValue());
5747 EXPECT_EQ(default_timeout, clock_.Now());
fayangb9c88442020-03-26 07:03:57 -07005748 if (!GetQuicReloadableFlag(quic_use_blackhole_detector) ||
5749 !GetQuicReloadableFlag(quic_use_idle_network_detector)) {
5750 connection_.GetTimeoutAlarm()->Fire();
5751 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005752 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5753 EXPECT_TRUE(connection_.connected());
5754 ASSERT_EQ(final_timeout.ToDebuggingValue(),
5755 connection_.GetTimeoutAlarm()->deadline().ToDebuggingValue());
5756
5757 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07005758 EXPECT_CALL(visitor_,
5759 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07005760 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005761 clock_.AdvanceTime(final_timeout - clock_.Now());
5762 EXPECT_EQ(connection_.GetTimeoutAlarm()->deadline(), clock_.Now());
5763 EXPECT_EQ(final_timeout, clock_.Now());
5764 connection_.GetTimeoutAlarm()->Fire();
5765 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5766 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005767 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005768}
5769
dschinazi9a6194e2020-04-30 16:21:09 -07005770TEST_P(QuicConnectionTest, TimeoutAfterSendAfterHandshake) {
5771 // When the idle timeout fires, verify that by default we do not send any
5772 // connection close packets.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005773 EXPECT_TRUE(connection_.connected());
5774 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5775 QuicConfig config;
5776
5777 // Create a handshake message that also enables silent close.
5778 CryptoHandshakeMessage msg;
vasilvvc48c8712019-03-11 13:38:16 -07005779 std::string error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005780 QuicConfig client_config;
5781 client_config.SetInitialStreamFlowControlWindowToSend(
5782 kInitialStreamFlowControlWindowForTest);
5783 client_config.SetInitialSessionFlowControlWindowToSend(
5784 kInitialSessionFlowControlWindowForTest);
5785 client_config.SetIdleNetworkTimeout(
dschinazi027366e2020-05-01 14:31:19 -07005786 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs));
fkastenholzd3a1de92019-05-15 07:00:07 -07005787 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005788 const QuicErrorCode error =
5789 config.ProcessPeerHello(msg, CLIENT, &error_details);
bncf54082a2019-11-27 10:19:47 -08005790 EXPECT_THAT(error, IsQuicNoError());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005791
5792 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005793
5794 const QuicTime::Delta default_idle_timeout =
dschinazi027366e2020-05-01 14:31:19 -07005795 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs - 1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005796 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5797 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5798
5799 // When we send a packet, the timeout will change to 5ms +
5800 // kInitialIdleTimeoutSecs.
5801 clock_.AdvanceTime(five_ms);
5802 SendStreamDataToPeer(
5803 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5804 0, FIN, nullptr);
fayangb9c88442020-03-26 07:03:57 -07005805 if (GetQuicReloadableFlag(quic_use_blackhole_detector) &&
5806 GetQuicReloadableFlag(quic_use_idle_network_detector)) {
5807 EXPECT_EQ(default_timeout + five_ms,
5808 connection_.GetTimeoutAlarm()->deadline());
5809 } else {
5810 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5811 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005812
5813 // Now send more data. This will not move the timeout because
5814 // no data has been received since the previous write.
5815 clock_.AdvanceTime(five_ms);
5816 SendStreamDataToPeer(
5817 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5818 3, FIN, nullptr);
fayangb9c88442020-03-26 07:03:57 -07005819 if (GetQuicReloadableFlag(quic_use_blackhole_detector) &&
5820 GetQuicReloadableFlag(quic_use_idle_network_detector)) {
5821 EXPECT_EQ(default_timeout + five_ms,
5822 connection_.GetTimeoutAlarm()->deadline());
5823 } else {
5824 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5825 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005826
5827 // The original alarm will fire. We should not time out because we had a
5828 // network event at t=5ms. The alarm will reregister.
5829 clock_.AdvanceTime(default_idle_timeout - five_ms - five_ms);
5830 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
fayangb9c88442020-03-26 07:03:57 -07005831 if (!GetQuicReloadableFlag(quic_use_blackhole_detector) ||
5832 !GetQuicReloadableFlag(quic_use_idle_network_detector)) {
5833 connection_.GetTimeoutAlarm()->Fire();
5834 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005835 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5836 EXPECT_TRUE(connection_.connected());
5837 EXPECT_EQ(default_timeout + five_ms,
5838 connection_.GetTimeoutAlarm()->deadline());
5839
5840 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07005841 // This results in a SILENT_CLOSE, so the writer will not be invoked
5842 // and will not save the frame. Grab the frame from OnConnectionClosed
5843 // directly.
5844 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
5845 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
5846
QUICHE teama6ef0a62019-03-07 20:34:33 -05005847 clock_.AdvanceTime(five_ms);
5848 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5849 connection_.GetTimeoutAlarm()->Fire();
5850 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5851 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005852 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08005853 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
5854 IsError(QUIC_NETWORK_IDLE_TIMEOUT));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005855}
5856
5857TEST_P(QuicConnectionTest, TimeoutAfterSendSilentCloseAndTLP) {
fayang5f135052019-08-22 17:59:40 -07005858 if (connection_.PtoEnabled()) {
5859 return;
5860 }
dschinazi9a6194e2020-04-30 16:21:09 -07005861 // Same test as above, but sending TLPs causes a connection close to be sent.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005862 EXPECT_TRUE(connection_.connected());
5863 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5864 QuicConfig config;
5865
5866 // Create a handshake message that also enables silent close.
5867 CryptoHandshakeMessage msg;
vasilvvc48c8712019-03-11 13:38:16 -07005868 std::string error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005869 QuicConfig client_config;
5870 client_config.SetInitialStreamFlowControlWindowToSend(
5871 kInitialStreamFlowControlWindowForTest);
5872 client_config.SetInitialSessionFlowControlWindowToSend(
5873 kInitialSessionFlowControlWindowForTest);
5874 client_config.SetIdleNetworkTimeout(
dschinazi027366e2020-05-01 14:31:19 -07005875 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs));
fkastenholzd3a1de92019-05-15 07:00:07 -07005876 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005877 const QuicErrorCode error =
5878 config.ProcessPeerHello(msg, CLIENT, &error_details);
bncf54082a2019-11-27 10:19:47 -08005879 EXPECT_THAT(error, IsQuicNoError());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005880
5881 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005882
5883 const QuicTime::Delta default_idle_timeout =
dschinazi027366e2020-05-01 14:31:19 -07005884 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs - 1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005885 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5886 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5887
5888 // When we send a packet, the timeout will change to 5ms +
5889 // kInitialIdleTimeoutSecs.
5890 clock_.AdvanceTime(five_ms);
5891 SendStreamDataToPeer(
5892 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5893 0, FIN, nullptr);
fayangb9c88442020-03-26 07:03:57 -07005894 if (GetQuicReloadableFlag(quic_use_blackhole_detector) &&
5895 GetQuicReloadableFlag(quic_use_idle_network_detector)) {
5896 EXPECT_EQ(default_timeout + five_ms,
5897 connection_.GetTimeoutAlarm()->deadline());
5898 } else {
5899 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5900 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005901
5902 // Retransmit the packet via tail loss probe.
5903 clock_.AdvanceTime(connection_.GetRetransmissionAlarm()->deadline() -
5904 clock_.Now());
5905 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _));
5906 connection_.GetRetransmissionAlarm()->Fire();
5907
5908 // This time, we should time out and send a connection close due to the TLP.
fkastenholz5d880a92019-06-21 09:01:56 -07005909 EXPECT_CALL(visitor_,
5910 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07005911 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005912 clock_.AdvanceTime(connection_.GetTimeoutAlarm()->deadline() -
5913 clock_.ApproximateNow() + five_ms);
5914 connection_.GetTimeoutAlarm()->Fire();
5915 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5916 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005917 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005918}
5919
5920TEST_P(QuicConnectionTest, TimeoutAfterSendSilentCloseWithOpenStreams) {
dschinazi9a6194e2020-04-30 16:21:09 -07005921 // Same test as above, but having open streams causes a connection close
5922 // to be sent.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005923 EXPECT_TRUE(connection_.connected());
5924 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5925 QuicConfig config;
5926
5927 // Create a handshake message that also enables silent close.
5928 CryptoHandshakeMessage msg;
vasilvvc48c8712019-03-11 13:38:16 -07005929 std::string error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005930 QuicConfig client_config;
5931 client_config.SetInitialStreamFlowControlWindowToSend(
5932 kInitialStreamFlowControlWindowForTest);
5933 client_config.SetInitialSessionFlowControlWindowToSend(
5934 kInitialSessionFlowControlWindowForTest);
5935 client_config.SetIdleNetworkTimeout(
dschinazi027366e2020-05-01 14:31:19 -07005936 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs));
fkastenholzd3a1de92019-05-15 07:00:07 -07005937 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005938 const QuicErrorCode error =
5939 config.ProcessPeerHello(msg, CLIENT, &error_details);
bncf54082a2019-11-27 10:19:47 -08005940 EXPECT_THAT(error, IsQuicNoError());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005941
5942 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005943
5944 const QuicTime::Delta default_idle_timeout =
dschinazi027366e2020-05-01 14:31:19 -07005945 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs - 1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005946 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5947 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5948
5949 // When we send a packet, the timeout will change to 5ms +
5950 // kInitialIdleTimeoutSecs.
5951 clock_.AdvanceTime(five_ms);
5952 SendStreamDataToPeer(
5953 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5954 0, FIN, nullptr);
fayangb9c88442020-03-26 07:03:57 -07005955 if (GetQuicReloadableFlag(quic_use_blackhole_detector) &&
5956 GetQuicReloadableFlag(quic_use_idle_network_detector)) {
5957 EXPECT_EQ(default_timeout + five_ms,
5958 connection_.GetTimeoutAlarm()->deadline());
5959 } else {
5960 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5961 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005962
5963 // Indicate streams are still open.
5964 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
5965 .WillRepeatedly(Return(true));
5966
5967 // This time, we should time out and send a connection close due to the TLP.
fkastenholz5d880a92019-06-21 09:01:56 -07005968 EXPECT_CALL(visitor_,
5969 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07005970 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005971 clock_.AdvanceTime(connection_.GetTimeoutAlarm()->deadline() -
5972 clock_.ApproximateNow() + five_ms);
5973 connection_.GetTimeoutAlarm()->Fire();
5974 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5975 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005976 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005977}
5978
5979TEST_P(QuicConnectionTest, TimeoutAfterReceive) {
5980 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5981 EXPECT_TRUE(connection_.connected());
5982 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5983 QuicConfig config;
5984 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005985
5986 const QuicTime::Delta initial_idle_timeout =
5987 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5988 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5989 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
5990
5991 connection_.SendStreamDataWithString(
5992 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5993 0, NO_FIN);
5994 connection_.SendStreamDataWithString(
5995 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5996 3, NO_FIN);
5997
5998 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5999 clock_.AdvanceTime(five_ms);
6000
6001 // When we receive a packet, the timeout will change to 5ms +
6002 // kInitialIdleTimeoutSecs.
6003 QuicAckFrame ack = InitAckFrame(2);
6004 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
6005 ProcessAckPacket(&ack);
6006
6007 // The original alarm will fire. We should not time out because we had a
6008 // network event at t=5ms. The alarm will reregister.
6009 clock_.AdvanceTime(initial_idle_timeout - five_ms);
6010 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
fayangb9c88442020-03-26 07:03:57 -07006011 if (!GetQuicReloadableFlag(quic_use_blackhole_detector) ||
6012 !GetQuicReloadableFlag(quic_use_idle_network_detector)) {
6013 connection_.GetTimeoutAlarm()->Fire();
6014 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006015 EXPECT_TRUE(connection_.connected());
6016 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
6017 EXPECT_EQ(default_timeout + five_ms,
6018 connection_.GetTimeoutAlarm()->deadline());
6019
6020 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07006021 EXPECT_CALL(visitor_,
6022 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07006023 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006024 clock_.AdvanceTime(five_ms);
6025 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
6026 connection_.GetTimeoutAlarm()->Fire();
6027 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
6028 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07006029 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006030}
6031
6032TEST_P(QuicConnectionTest, TimeoutAfterReceiveNotSendWhenUnacked) {
6033 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6034 EXPECT_TRUE(connection_.connected());
6035 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6036 QuicConfig config;
6037 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006038
6039 const QuicTime::Delta initial_idle_timeout =
6040 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
6041 connection_.SetNetworkTimeouts(
6042 QuicTime::Delta::Infinite(),
6043 initial_idle_timeout + QuicTime::Delta::FromSeconds(1));
6044 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
6045 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
6046
6047 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
6048 connection_.SendStreamDataWithString(
6049 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6050 0, NO_FIN);
6051 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
6052 connection_.SendStreamDataWithString(
6053 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6054 3, NO_FIN);
6055
6056 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
6057
6058 clock_.AdvanceTime(five_ms);
6059
6060 // When we receive a packet, the timeout will change to 5ms +
6061 // kInitialIdleTimeoutSecs.
6062 QuicAckFrame ack = InitAckFrame(2);
6063 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
6064 ProcessAckPacket(&ack);
6065
6066 // The original alarm will fire. We should not time out because we had a
6067 // network event at t=5ms. The alarm will reregister.
6068 clock_.AdvanceTime(initial_idle_timeout - five_ms);
6069 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
fayangb9c88442020-03-26 07:03:57 -07006070 if (!GetQuicReloadableFlag(quic_use_blackhole_detector) ||
6071 !GetQuicReloadableFlag(quic_use_idle_network_detector)) {
6072 connection_.GetTimeoutAlarm()->Fire();
6073 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006074 EXPECT_TRUE(connection_.connected());
6075 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
6076 EXPECT_EQ(default_timeout + five_ms,
6077 connection_.GetTimeoutAlarm()->deadline());
6078
6079 // Now, send packets while advancing the time and verify that the connection
6080 // eventually times out.
fkastenholz5d880a92019-06-21 09:01:56 -07006081 EXPECT_CALL(visitor_,
6082 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006083 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
6084 for (int i = 0; i < 100 && connection_.connected(); ++i) {
6085 QUIC_LOG(INFO) << "sending data packet";
6086 connection_.SendStreamDataWithString(
6087 GetNthClientInitiatedStreamId(1, connection_.transport_version()),
6088 "foo", 0, NO_FIN);
6089 connection_.GetTimeoutAlarm()->Fire();
6090 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
6091 }
6092 EXPECT_FALSE(connection_.connected());
6093 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07006094 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006095}
6096
6097TEST_P(QuicConnectionTest, TimeoutAfter5ClientRTOs) {
fayang5f135052019-08-22 17:59:40 -07006098 if (connection_.PtoEnabled()) {
6099 return;
6100 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006101 connection_.SetMaxTailLossProbes(2);
6102 EXPECT_TRUE(connection_.connected());
6103 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6104 QuicConfig config;
6105 QuicTagVector connection_options;
6106 connection_options.push_back(k5RTO);
6107 config.SetConnectionOptionsToSend(connection_options);
dschinazif7c6a912020-05-05 11:39:53 -07006108 QuicConfigPeer::SetNegotiated(&config, true);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006109 connection_.SetFromConfig(config);
6110
6111 // Send stream data.
6112 SendStreamDataToPeer(
6113 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6114 0, FIN, nullptr);
6115
6116 // Fire the retransmission alarm 6 times, twice for TLP and 4 times for RTO.
6117 for (int i = 0; i < 6; ++i) {
6118 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
6119 connection_.GetRetransmissionAlarm()->Fire();
6120 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
6121 EXPECT_TRUE(connection_.connected());
6122 }
fayangb59c6f12020-03-23 15:06:14 -07006123 if (GetQuicReloadableFlag(quic_use_blackhole_detector)) {
6124 EXPECT_CALL(visitor_, OnPathDegrading());
6125 connection_.PathDegradingTimeout();
6126 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006127
6128 EXPECT_EQ(2u, connection_.sent_packet_manager().GetConsecutiveTlpCount());
6129 EXPECT_EQ(4u, connection_.sent_packet_manager().GetConsecutiveRtoCount());
6130 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07006131 EXPECT_CALL(visitor_,
6132 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07006133 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
fayangb59c6f12020-03-23 15:06:14 -07006134 if (GetQuicReloadableFlag(quic_use_blackhole_detector)) {
6135 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
6136 connection_.GetBlackholeDetectorAlarm()->Fire();
6137 } else {
6138 connection_.GetRetransmissionAlarm()->Fire();
6139 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006140 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
6141 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07006142 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006143}
6144
6145TEST_P(QuicConnectionTest, SendScheduler) {
6146 // Test that if we send a packet without delay, it is not queued.
6147 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
QUICHE team8c1daa22019-03-13 08:33:41 -07006148 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07006149 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006150 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
6151 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
QUICHE team6987b4a2019-03-15 16:23:04 -07006152 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05006153 HAS_RETRANSMITTABLE_DATA, false, false);
6154 EXPECT_EQ(0u, connection_.NumQueuedPackets());
6155}
6156
6157TEST_P(QuicConnectionTest, FailToSendFirstPacket) {
6158 // Test that the connection does not crash when it fails to send the first
6159 // packet at which point self_address_ might be uninitialized.
6160 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
fkastenholz5d880a92019-06-21 09:01:56 -07006161 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
QUICHE team8c1daa22019-03-13 08:33:41 -07006162 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07006163 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006164 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
6165 writer_->SetShouldWriteFail();
QUICHE team6987b4a2019-03-15 16:23:04 -07006166 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05006167 HAS_RETRANSMITTABLE_DATA, false, false);
6168}
6169
6170TEST_P(QuicConnectionTest, SendSchedulerEAGAIN) {
6171 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
QUICHE team8c1daa22019-03-13 08:33:41 -07006172 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07006173 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006174 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
6175 BlockOnNextWrite();
6176 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _))
6177 .Times(0);
QUICHE team6987b4a2019-03-15 16:23:04 -07006178 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05006179 HAS_RETRANSMITTABLE_DATA, false, false);
6180 EXPECT_EQ(1u, connection_.NumQueuedPackets());
6181}
6182
6183TEST_P(QuicConnectionTest, TestQueueLimitsOnSendStreamData) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006184 // Queue the first packet.
ianswett3085da82019-04-04 07:24:24 -07006185 size_t payload_length = connection_.max_packet_length();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006186 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(testing::Return(false));
vasilvvc48c8712019-03-11 13:38:16 -07006187 const std::string payload(payload_length, 'a');
ianswett3085da82019-04-04 07:24:24 -07006188 QuicStreamId first_bidi_stream_id(QuicUtils::GetFirstBidirectionalStreamId(
6189 connection_.version().transport_version, Perspective::IS_CLIENT));
6190 EXPECT_EQ(0u, connection_
6191 .SendStreamDataWithString(first_bidi_stream_id, payload, 0,
6192 NO_FIN)
QUICHE teama6ef0a62019-03-07 20:34:33 -05006193 .bytes_consumed);
6194 EXPECT_EQ(0u, connection_.NumQueuedPackets());
6195}
6196
ianswett3085da82019-04-04 07:24:24 -07006197TEST_P(QuicConnectionTest, SendingThreePackets) {
ianswett3085da82019-04-04 07:24:24 -07006198 // Make the payload twice the size of the packet, so 3 packets are written.
6199 size_t total_payload_length = 2 * connection_.max_packet_length();
vasilvvc48c8712019-03-11 13:38:16 -07006200 const std::string payload(total_payload_length, 'a');
ianswett3085da82019-04-04 07:24:24 -07006201 QuicStreamId first_bidi_stream_id(QuicUtils::GetFirstBidirectionalStreamId(
6202 connection_.version().transport_version, Perspective::IS_CLIENT));
6203 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
6204 EXPECT_EQ(payload.size(), connection_
6205 .SendStreamDataWithString(first_bidi_stream_id,
6206 payload, 0, NO_FIN)
6207 .bytes_consumed);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006208}
6209
6210TEST_P(QuicConnectionTest, LoopThroughSendingPacketsWithTruncation) {
6211 set_perspective(Perspective::IS_SERVER);
fayangd4291e42019-05-30 10:31:21 -07006212 if (!VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006213 // For IETF QUIC, encryption level will be switched to FORWARD_SECURE in
6214 // SendStreamDataWithString.
6215 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
6216 }
6217 // Set up a larger payload than will fit in one packet.
vasilvvc48c8712019-03-11 13:38:16 -07006218 const std::string payload(connection_.max_packet_length(), 'a');
QUICHE teama6ef0a62019-03-07 20:34:33 -05006219 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
6220
6221 // Now send some packets with no truncation.
6222 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
6223 EXPECT_EQ(payload.size(),
6224 connection_.SendStreamDataWithString(3, payload, 0, NO_FIN)
6225 .bytes_consumed);
6226 // Track the size of the second packet here. The overhead will be the largest
6227 // we see in this test, due to the non-truncated connection id.
6228 size_t non_truncated_packet_size = writer_->last_packet_size();
6229
6230 // Change to a 0 byte connection id.
6231 QuicConfig config;
6232 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
6233 connection_.SetFromConfig(config);
6234 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
6235 EXPECT_EQ(payload.size(),
6236 connection_.SendStreamDataWithString(3, payload, 1350, NO_FIN)
6237 .bytes_consumed);
fayangd4291e42019-05-30 10:31:21 -07006238 if (VersionHasIetfInvariantHeader(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006239 // Short header packets sent from server omit connection ID already, and
6240 // stream offset size increases from 0 to 2.
6241 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() - 2);
6242 } else {
6243 // Just like above, we save 8 bytes on payload, and 8 on truncation. -2
6244 // because stream offset size is 2 instead of 0.
6245 EXPECT_EQ(non_truncated_packet_size,
6246 writer_->last_packet_size() + 8 * 2 - 2);
6247 }
6248}
6249
6250TEST_P(QuicConnectionTest, SendDelayedAck) {
6251 QuicTime ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6252 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6253 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6254 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006255 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006256 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006257 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006258 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006259 // Process a packet from the non-crypto stream.
6260 frame1_.stream_id = 3;
6261
6262 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006263 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006264 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6265 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6266
6267 // Check if delayed ack timer is running for the expected interval.
6268 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6269 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6270 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07006271 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006272 connection_.GetAckAlarm()->Fire();
6273 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006274 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006275 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006276 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006277 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6278 } else {
nharper55fa6132019-05-07 19:37:21 -07006279 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006280 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6281 }
6282 EXPECT_FALSE(writer_->ack_frames().empty());
6283 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6284}
6285
6286TEST_P(QuicConnectionTest, SendDelayedAfterQuiescence) {
6287 QuicConnectionPeer::SetFastAckAfterQuiescence(&connection_, true);
6288
6289 // The beginning of the connection counts as quiescence.
ianswett8f90e512019-12-18 10:50:27 -08006290 QuicTime ack_time = clock_.ApproximateNow() + kAlarmGranularity;
QUICHE teama6ef0a62019-03-07 20:34:33 -05006291 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6292 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6293 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006294 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006295 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006296 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006297 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006298 // Process a packet from the non-crypto stream.
6299 frame1_.stream_id = 3;
6300
6301 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006302 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006303 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6304 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6305
6306 // Check if delayed ack timer is running for the expected interval.
6307 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6308 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6309 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07006310 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006311 connection_.GetAckAlarm()->Fire();
6312 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006313 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006314 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006315 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006316 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6317 } else {
nharper55fa6132019-05-07 19:37:21 -07006318 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006319 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6320 }
6321 EXPECT_FALSE(writer_->ack_frames().empty());
6322 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6323
6324 // Process another packet immedately after sending the ack and expect the
6325 // ack alarm to be set delayed ack time in the future.
6326 ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6327 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6328 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6329
6330 // Check if delayed ack timer is running for the expected interval.
6331 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6332 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6333 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07006334 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006335 connection_.GetAckAlarm()->Fire();
6336 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006337 padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006338 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006339 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006340 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6341 } else {
nharper55fa6132019-05-07 19:37:21 -07006342 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006343 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6344 }
6345 EXPECT_FALSE(writer_->ack_frames().empty());
6346 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6347
ianswett8f90e512019-12-18 10:50:27 -08006348 // Wait 1 second and ensure the ack alarm is set to 1ms in the future.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006349 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
6350 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
6351 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6352 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6353
6354 // Check if delayed ack timer is running for the expected interval.
6355 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6356 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6357}
6358
6359TEST_P(QuicConnectionTest, SendDelayedAckDecimation) {
6360 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6361 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION);
6362
6363 const size_t kMinRttMs = 40;
6364 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6365 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6366 QuicTime::Delta::Zero(), QuicTime::Zero());
6367 // The ack time should be based on min_rtt/4, since it's less than the
6368 // default delayed ack time.
6369 QuicTime ack_time = clock_.ApproximateNow() +
6370 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6371 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6372 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6373 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006374 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006375 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006376 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006377 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006378 // Process a packet from the non-crypto stream.
6379 frame1_.stream_id = 3;
6380
6381 // Process all the initial packets in order so there aren't missing packets.
6382 uint64_t kFirstDecimatedPacket = 101;
6383 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6384 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6385 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6386 }
6387 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6388 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006389 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006390 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6391 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6392 ENCRYPTION_ZERO_RTT);
6393
6394 // Check if delayed ack timer is running for the expected interval.
6395 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6396 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6397
6398 // The 10th received packet causes an ack to be sent.
6399 for (int i = 0; i < 9; ++i) {
6400 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6401 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6402 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6403 ENCRYPTION_ZERO_RTT);
6404 }
6405 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07006406 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006407 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07006408 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006409 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6410 } else {
nharperc32d8ab2019-10-09 11:09:06 -07006411 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006412 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6413 }
6414 EXPECT_FALSE(writer_->ack_frames().empty());
6415 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6416}
6417
6418TEST_P(QuicConnectionTest, SendDelayedAckAckDecimationAfterQuiescence) {
6419 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6420 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION);
6421 QuicConnectionPeer::SetFastAckAfterQuiescence(&connection_, true);
6422
6423 const size_t kMinRttMs = 40;
6424 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6425 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6426 QuicTime::Delta::Zero(), QuicTime::Zero());
6427
6428 // The beginning of the connection counts as quiescence.
6429 QuicTime ack_time =
6430 clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
6431 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6432 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6433 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006434 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006435 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006436 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006437 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006438 // Process a packet from the non-crypto stream.
6439 frame1_.stream_id = 3;
6440
6441 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006442 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006443 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6444 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6445
6446 // Check if delayed ack timer is running for the expected interval.
6447 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6448 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6449 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07006450 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006451 connection_.GetAckAlarm()->Fire();
6452 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006453 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006454 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006455 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006456 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6457 } else {
nharper55fa6132019-05-07 19:37:21 -07006458 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006459 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6460 }
6461 EXPECT_FALSE(writer_->ack_frames().empty());
6462 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6463
6464 // Process another packet immedately after sending the ack and expect the
6465 // ack alarm to be set delayed ack time in the future.
6466 ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6467 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6468 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6469
6470 // Check if delayed ack timer is running for the expected interval.
6471 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6472 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6473 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07006474 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006475 connection_.GetAckAlarm()->Fire();
6476 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006477 padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006478 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006479 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006480 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6481 } else {
nharper55fa6132019-05-07 19:37:21 -07006482 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006483 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6484 }
6485 EXPECT_FALSE(writer_->ack_frames().empty());
6486 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6487
6488 // Wait 1 second and enesure the ack alarm is set to 1ms in the future.
6489 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
6490 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
6491 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6492 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6493
6494 // Check if delayed ack timer is running for the expected interval.
6495 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6496 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6497
6498 // Process enough packets to get into ack decimation behavior.
6499 // The ack time should be based on min_rtt/4, since it's less than the
6500 // default delayed ack time.
6501 ack_time = clock_.ApproximateNow() +
6502 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6503 uint64_t kFirstDecimatedPacket = 101;
6504 for (unsigned int i = 0; i < kFirstDecimatedPacket - 4; ++i) {
6505 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6506 ProcessDataPacketAtLevel(4 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6507 }
6508 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6509 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006510 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006511 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6512 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6513 ENCRYPTION_ZERO_RTT);
6514
6515 // Check if delayed ack timer is running for the expected interval.
6516 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6517 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6518
6519 // The 10th received packet causes an ack to be sent.
6520 for (int i = 0; i < 9; ++i) {
6521 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6522 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6523 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6524 ENCRYPTION_ZERO_RTT);
6525 }
6526 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07006527 padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006528 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07006529 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006530 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6531 } else {
nharperc32d8ab2019-10-09 11:09:06 -07006532 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006533 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6534 }
6535 EXPECT_FALSE(writer_->ack_frames().empty());
6536 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6537
6538 // Wait 1 second and enesure the ack alarm is set to 1ms in the future.
6539 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
6540 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
6541 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6542 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 10, !kHasStopWaiting,
6543 ENCRYPTION_ZERO_RTT);
6544
6545 // Check if delayed ack timer is running for the expected interval.
6546 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6547 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6548}
6549
6550TEST_P(QuicConnectionTest, SendDelayedAckDecimationUnlimitedAggregation) {
6551 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6552 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6553 QuicConfig config;
6554 QuicTagVector connection_options;
6555 connection_options.push_back(kACKD);
6556 // No limit on the number of packets received before sending an ack.
6557 connection_options.push_back(kAKDU);
6558 config.SetConnectionOptionsToSend(connection_options);
6559 connection_.SetFromConfig(config);
6560
6561 const size_t kMinRttMs = 40;
6562 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6563 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6564 QuicTime::Delta::Zero(), QuicTime::Zero());
6565 // The ack time should be based on min_rtt/4, since it's less than the
6566 // default delayed ack time.
6567 QuicTime ack_time = clock_.ApproximateNow() +
6568 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6569 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6570 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6571 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006572 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006573 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006574 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006575 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006576 // Process a packet from the non-crypto stream.
6577 frame1_.stream_id = 3;
6578
6579 // Process all the initial packets in order so there aren't missing packets.
6580 uint64_t kFirstDecimatedPacket = 101;
6581 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6582 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6583 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6584 }
6585 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6586 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006587 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006588 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6589 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6590 ENCRYPTION_ZERO_RTT);
6591
6592 // Check if delayed ack timer is running for the expected interval.
6593 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6594 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6595
6596 // 18 packets will not cause an ack to be sent. 19 will because when
6597 // stop waiting frames are in use, we ack every 20 packets no matter what.
6598 for (int i = 0; i < 18; ++i) {
6599 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6600 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6601 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6602 ENCRYPTION_ZERO_RTT);
6603 }
6604 // The delayed ack timer should still be set to the expected deadline.
6605 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6606 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6607}
6608
6609TEST_P(QuicConnectionTest, SendDelayedAckDecimationEighthRtt) {
6610 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6611 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION);
6612 QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
6613
6614 const size_t kMinRttMs = 40;
6615 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6616 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6617 QuicTime::Delta::Zero(), QuicTime::Zero());
6618 // The ack time should be based on min_rtt/8, since it's less than the
6619 // default delayed ack time.
6620 QuicTime ack_time = clock_.ApproximateNow() +
6621 QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
6622 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6623 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6624 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006625 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006626 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006627 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006628 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006629 // Process a packet from the non-crypto stream.
6630 frame1_.stream_id = 3;
6631
6632 // Process all the initial packets in order so there aren't missing packets.
6633 uint64_t kFirstDecimatedPacket = 101;
6634 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6635 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6636 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6637 }
6638 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6639 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006640 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006641 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6642 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6643 ENCRYPTION_ZERO_RTT);
6644
6645 // Check if delayed ack timer is running for the expected interval.
6646 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6647 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6648
6649 // The 10th received packet causes an ack to be sent.
6650 for (int i = 0; i < 9; ++i) {
6651 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6652 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6653 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6654 ENCRYPTION_ZERO_RTT);
6655 }
6656 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07006657 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006658 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07006659 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006660 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6661 } else {
nharperc32d8ab2019-10-09 11:09:06 -07006662 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006663 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6664 }
6665 EXPECT_FALSE(writer_->ack_frames().empty());
6666 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6667}
6668
6669TEST_P(QuicConnectionTest, SendDelayedAckDecimationWithReordering) {
6670 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6671 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6672
6673 const size_t kMinRttMs = 40;
6674 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6675 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6676 QuicTime::Delta::Zero(), QuicTime::Zero());
6677 // The ack time should be based on min_rtt/4, since it's less than the
6678 // default delayed ack time.
6679 QuicTime ack_time = clock_.ApproximateNow() +
6680 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6681 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6682 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6683 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006684 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006685 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006686 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006687 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006688 // Process a packet from the non-crypto stream.
6689 frame1_.stream_id = 3;
6690
6691 // Process all the initial packets in order so there aren't missing packets.
6692 uint64_t kFirstDecimatedPacket = 101;
6693 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6694 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6695 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6696 }
6697 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6698
6699 // Receive one packet out of order and then the rest in order.
6700 // The loop leaves a one packet gap between acks sent to simulate some loss.
6701 for (int j = 0; j < 3; ++j) {
6702 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6703 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6704 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 9 + (j * 11),
6705 !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6706 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
6707 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6708 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6709
6710 // The 10th received packet causes an ack to be sent.
6711 writer_->Reset();
6712 for (int i = 0; i < 9; ++i) {
6713 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6714 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6715 // The ACK shouldn't be sent until the 10th packet is processed.
6716 EXPECT_TRUE(writer_->ack_frames().empty());
6717 ProcessDataPacketAtLevel(kFirstDecimatedPacket + i + (j * 11),
6718 !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6719 }
6720 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07006721 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006722 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07006723 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006724 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6725 } else {
nharperc32d8ab2019-10-09 11:09:06 -07006726 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006727 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6728 }
6729 EXPECT_FALSE(writer_->ack_frames().empty());
6730 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6731 }
6732}
6733
6734TEST_P(QuicConnectionTest, SendDelayedAckDecimationWithLargeReordering) {
6735 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6736 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6737
6738 const size_t kMinRttMs = 40;
6739 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6740 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6741 QuicTime::Delta::Zero(), QuicTime::Zero());
6742 // The ack time should be based on min_rtt/4, since it's less than the
6743 // default delayed ack time.
6744 QuicTime ack_time = clock_.ApproximateNow() +
6745 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6746 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6747 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6748 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006749 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006750 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006751 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006752 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006753 // Process a packet from the non-crypto stream.
6754 frame1_.stream_id = 3;
6755
6756 // Process all the initial packets in order so there aren't missing packets.
6757 uint64_t kFirstDecimatedPacket = 101;
6758 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6759 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6760 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6761 }
6762 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6763 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006764 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006765 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6766 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6767 ENCRYPTION_ZERO_RTT);
6768
6769 // Check if delayed ack timer is running for the expected interval.
6770 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6771 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6772
6773 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6774 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6775 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 19, !kHasStopWaiting,
6776 ENCRYPTION_ZERO_RTT);
6777 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
6778 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6779 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6780
6781 // The 10th received packet causes an ack to be sent.
6782 for (int i = 0; i < 8; ++i) {
6783 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6784 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6785 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6786 ENCRYPTION_ZERO_RTT);
6787 }
6788 // Check that ack is sent and that delayed ack alarm is reset.
6789 if (GetParam().no_stop_waiting) {
fayang58f71072019-11-05 08:47:02 -08006790 EXPECT_EQ(writer_->padding_frames().size() + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006791 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6792 } else {
6793 EXPECT_EQ(2u, writer_->frame_count());
6794 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6795 }
6796 EXPECT_FALSE(writer_->ack_frames().empty());
6797 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6798
6799 // The next packet received in order will cause an immediate ack,
6800 // because it fills a hole.
6801 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6802 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6803 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 10, !kHasStopWaiting,
6804 ENCRYPTION_ZERO_RTT);
6805 // Check that ack is sent and that delayed ack alarm is reset.
6806 if (GetParam().no_stop_waiting) {
fayang58f71072019-11-05 08:47:02 -08006807 EXPECT_EQ(writer_->padding_frames().size() + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006808 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6809 } else {
6810 EXPECT_EQ(2u, writer_->frame_count());
6811 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6812 }
6813 EXPECT_FALSE(writer_->ack_frames().empty());
6814 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6815}
6816
6817TEST_P(QuicConnectionTest, SendDelayedAckDecimationWithReorderingEighthRtt) {
6818 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6819 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6820 QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
6821
6822 const size_t kMinRttMs = 40;
6823 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6824 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6825 QuicTime::Delta::Zero(), QuicTime::Zero());
6826 // The ack time should be based on min_rtt/8, since it's less than the
6827 // default delayed ack time.
6828 QuicTime ack_time = clock_.ApproximateNow() +
6829 QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
6830 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6831 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6832 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006833 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006834 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006835 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006836 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006837 // Process a packet from the non-crypto stream.
6838 frame1_.stream_id = 3;
6839
6840 // Process all the initial packets in order so there aren't missing packets.
6841 uint64_t kFirstDecimatedPacket = 101;
6842 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6843 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6844 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6845 }
6846 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6847 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006848 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006849 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6850 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6851 ENCRYPTION_ZERO_RTT);
6852
6853 // Check if delayed ack timer is running for the expected interval.
6854 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6855 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6856
6857 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6858 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6859 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 9, !kHasStopWaiting,
6860 ENCRYPTION_ZERO_RTT);
6861 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
6862 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6863 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6864
6865 // The 10th received packet causes an ack to be sent.
6866 for (int i = 0; i < 8; ++i) {
6867 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6868 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6869 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6870 ENCRYPTION_ZERO_RTT);
6871 }
6872 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07006873 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006874 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07006875 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006876 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6877 } else {
nharperc32d8ab2019-10-09 11:09:06 -07006878 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006879 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6880 }
6881 EXPECT_FALSE(writer_->ack_frames().empty());
6882 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6883}
6884
6885TEST_P(QuicConnectionTest,
6886 SendDelayedAckDecimationWithLargeReorderingEighthRtt) {
6887 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6888 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6889 QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
6890
6891 const size_t kMinRttMs = 40;
6892 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6893 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6894 QuicTime::Delta::Zero(), QuicTime::Zero());
6895 // The ack time should be based on min_rtt/8, since it's less than the
6896 // default delayed ack time.
6897 QuicTime ack_time = clock_.ApproximateNow() +
6898 QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
6899 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6900 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6901 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006902 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006903 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006904 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006905 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006906 // Process a packet from the non-crypto stream.
6907 frame1_.stream_id = 3;
6908
6909 // Process all the initial packets in order so there aren't missing packets.
6910 uint64_t kFirstDecimatedPacket = 101;
6911 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6912 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6913 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6914 }
6915 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6916 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006917 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006918 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6919 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6920 ENCRYPTION_ZERO_RTT);
6921
6922 // Check if delayed ack timer is running for the expected interval.
6923 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6924 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6925
6926 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6927 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6928 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 19, !kHasStopWaiting,
6929 ENCRYPTION_ZERO_RTT);
6930 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
6931 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6932 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6933
6934 // The 10th received packet causes an ack to be sent.
6935 for (int i = 0; i < 8; ++i) {
6936 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6937 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6938 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6939 ENCRYPTION_ZERO_RTT);
6940 }
6941 // Check that ack is sent and that delayed ack alarm is reset.
6942 if (GetParam().no_stop_waiting) {
fayang58f71072019-11-05 08:47:02 -08006943 EXPECT_EQ(writer_->padding_frames().size() + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006944 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6945 } else {
6946 EXPECT_EQ(2u, writer_->frame_count());
6947 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6948 }
6949 EXPECT_FALSE(writer_->ack_frames().empty());
6950 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6951
6952 // The next packet received in order will cause an immediate ack,
6953 // because it fills a hole.
6954 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6955 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6956 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 10, !kHasStopWaiting,
6957 ENCRYPTION_ZERO_RTT);
6958 // Check that ack is sent and that delayed ack alarm is reset.
6959 if (GetParam().no_stop_waiting) {
fayang58f71072019-11-05 08:47:02 -08006960 EXPECT_EQ(writer_->padding_frames().size() + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006961 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6962 } else {
6963 EXPECT_EQ(2u, writer_->frame_count());
6964 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6965 }
6966 EXPECT_FALSE(writer_->ack_frames().empty());
6967 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6968}
6969
6970TEST_P(QuicConnectionTest, SendDelayedAckOnHandshakeConfirmed) {
6971 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6972 ProcessPacket(1);
6973 // Check that ack is sent and that delayed ack alarm is set.
6974 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6975 QuicTime ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6976 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6977
6978 // Completing the handshake as the server does nothing.
6979 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_SERVER);
6980 connection_.OnHandshakeComplete();
6981 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6982 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6983
6984 // Complete the handshake as the client decreases the delayed ack time to 0ms.
6985 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_CLIENT);
6986 connection_.OnHandshakeComplete();
6987 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
fayangb296fb82020-02-11 08:14:28 -08006988 if (connection_.SupportsMultiplePacketNumberSpaces()) {
6989 EXPECT_EQ(clock_.ApproximateNow() + DefaultDelayedAckTime(),
6990 connection_.GetAckAlarm()->deadline());
6991 } else {
6992 EXPECT_EQ(clock_.ApproximateNow(), connection_.GetAckAlarm()->deadline());
6993 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006994}
6995
6996TEST_P(QuicConnectionTest, SendDelayedAckOnSecondPacket) {
6997 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6998 ProcessPacket(1);
6999 ProcessPacket(2);
7000 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07007001 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05007002 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07007003 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007004 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
7005 } else {
nharper55fa6132019-05-07 19:37:21 -07007006 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007007 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
7008 }
7009 EXPECT_FALSE(writer_->ack_frames().empty());
7010 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
7011}
7012
7013TEST_P(QuicConnectionTest, NoAckOnOldNacks) {
7014 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang6dba4902019-06-17 10:04:23 -07007015 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007016 ProcessPacket(2);
7017 size_t frames_per_ack = GetParam().no_stop_waiting ? 1 : 2;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007018
7019 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7020 ProcessPacket(3);
nharper55fa6132019-05-07 19:37:21 -07007021 size_t padding_frame_count = writer_->padding_frames().size();
7022 EXPECT_EQ(padding_frame_count + frames_per_ack, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007023 EXPECT_FALSE(writer_->ack_frames().empty());
7024 writer_->Reset();
7025
fayang6dba4902019-06-17 10:04:23 -07007026 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007027 ProcessPacket(4);
fayang6dba4902019-06-17 10:04:23 -07007028 EXPECT_EQ(0u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007029
7030 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7031 ProcessPacket(5);
nharper55fa6132019-05-07 19:37:21 -07007032 padding_frame_count = writer_->padding_frames().size();
7033 EXPECT_EQ(padding_frame_count + frames_per_ack, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007034 EXPECT_FALSE(writer_->ack_frames().empty());
7035 writer_->Reset();
7036
7037 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
7038 // Now only set the timer on the 6th packet, instead of sending another ack.
7039 ProcessPacket(6);
nharper55fa6132019-05-07 19:37:21 -07007040 padding_frame_count = writer_->padding_frames().size();
7041 EXPECT_EQ(padding_frame_count, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007042 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
7043}
7044
7045TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingPacket) {
7046 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
QUICHE team8c1daa22019-03-13 08:33:41 -07007047 EXPECT_CALL(visitor_, OnStreamFrame(_));
7048 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07007049 std::make_unique<TaggingEncrypter>(0x01));
zhongyi546cc452019-04-12 15:27:49 -07007050 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07007051 std::make_unique<StrictTaggingDecrypter>(0x01));
nharper2c9f02a2019-05-08 10:25:50 -07007052 ProcessDataPacket(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007053 connection_.SendStreamDataWithString(
7054 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
7055 0, NO_FIN);
7056 // Check that ack is bundled with outgoing data and that delayed ack
7057 // alarm is reset.
7058 if (GetParam().no_stop_waiting) {
7059 EXPECT_EQ(2u, writer_->frame_count());
7060 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
7061 } else {
7062 EXPECT_EQ(3u, writer_->frame_count());
7063 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
7064 }
7065 EXPECT_FALSE(writer_->ack_frames().empty());
7066 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
7067}
7068
7069TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingCryptoPacket) {
7070 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayangc31c9952019-06-05 13:54:48 -07007071 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
7072 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
7073 } else {
7074 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7075 }
7076 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
nharper46833c32019-05-15 21:33:05 -07007077 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007078 // Check that ack is bundled with outgoing crypto data.
7079 if (GetParam().no_stop_waiting) {
7080 EXPECT_EQ(3u, writer_->frame_count());
7081 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
7082 } else {
7083 EXPECT_EQ(4u, writer_->frame_count());
7084 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
7085 }
7086 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
7087}
7088
7089TEST_P(QuicConnectionTest, BlockAndBufferOnFirstCHLOPacketOfTwo) {
7090 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7091 ProcessPacket(1);
7092 BlockOnNextWrite();
7093 writer_->set_is_write_blocked_data_buffered(true);
nharper46833c32019-05-15 21:33:05 -07007094 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007095 EXPECT_TRUE(writer_->IsWriteBlocked());
7096 EXPECT_FALSE(connection_.HasQueuedData());
nharper46833c32019-05-15 21:33:05 -07007097 connection_.SendCryptoDataWithString("bar", 3);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007098 EXPECT_TRUE(writer_->IsWriteBlocked());
7099 EXPECT_TRUE(connection_.HasQueuedData());
7100}
7101
7102TEST_P(QuicConnectionTest, BundleAckForSecondCHLO) {
7103 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7104 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
7105 EXPECT_CALL(visitor_, OnCanWrite())
7106 .WillOnce(IgnoreResult(InvokeWithoutArgs(
7107 &connection_, &TestConnection::SendCryptoStreamData)));
7108 // Process a packet from the crypto stream, which is frame1_'s default.
7109 // Receiving the CHLO as packet 2 first will cause the connection to
7110 // immediately send an ack, due to the packet gap.
fayangc31c9952019-06-05 13:54:48 -07007111 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
7112 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
7113 } else {
7114 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7115 }
7116 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007117 // Check that ack is sent and that delayed ack alarm is reset.
7118 if (GetParam().no_stop_waiting) {
7119 EXPECT_EQ(3u, writer_->frame_count());
7120 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
7121 } else {
7122 EXPECT_EQ(4u, writer_->frame_count());
7123 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
7124 }
QUICHE teamea740082019-03-11 17:58:43 -07007125 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007126 EXPECT_EQ(1u, writer_->stream_frames().size());
7127 } else {
7128 EXPECT_EQ(1u, writer_->crypto_frames().size());
7129 }
7130 EXPECT_EQ(1u, writer_->padding_frames().size());
7131 ASSERT_FALSE(writer_->ack_frames().empty());
7132 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(writer_->ack_frames().front()));
7133 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
7134}
7135
7136TEST_P(QuicConnectionTest, BundleAckForSecondCHLOTwoPacketReject) {
7137 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7138 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
7139
7140 // Process two packets from the crypto stream, which is frame1_'s default,
7141 // simulating a 2 packet reject.
7142 {
fayangc31c9952019-06-05 13:54:48 -07007143 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
7144 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
7145 } else {
7146 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7147 }
7148 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007149 // Send the new CHLO when the REJ is processed.
fayangc31c9952019-06-05 13:54:48 -07007150 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
7151 EXPECT_CALL(visitor_, OnCryptoFrame(_))
7152 .WillOnce(IgnoreResult(InvokeWithoutArgs(
7153 &connection_, &TestConnection::SendCryptoStreamData)));
7154 } else {
7155 EXPECT_CALL(visitor_, OnStreamFrame(_))
7156 .WillOnce(IgnoreResult(InvokeWithoutArgs(
7157 &connection_, &TestConnection::SendCryptoStreamData)));
7158 }
7159 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007160 }
7161 // Check that ack is sent and that delayed ack alarm is reset.
7162 if (GetParam().no_stop_waiting) {
7163 EXPECT_EQ(3u, writer_->frame_count());
7164 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
7165 } else {
7166 EXPECT_EQ(4u, writer_->frame_count());
7167 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
7168 }
QUICHE teamea740082019-03-11 17:58:43 -07007169 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007170 EXPECT_EQ(1u, writer_->stream_frames().size());
7171 } else {
7172 EXPECT_EQ(1u, writer_->crypto_frames().size());
7173 }
7174 EXPECT_EQ(1u, writer_->padding_frames().size());
7175 ASSERT_FALSE(writer_->ack_frames().empty());
7176 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(writer_->ack_frames().front()));
7177 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
7178}
7179
7180TEST_P(QuicConnectionTest, BundleAckWithDataOnIncomingAck) {
7181 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7182 connection_.SendStreamDataWithString(
7183 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
7184 0, NO_FIN);
7185 connection_.SendStreamDataWithString(
7186 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
7187 3, NO_FIN);
7188 // Ack the second packet, which will retransmit the first packet.
7189 QuicAckFrame ack = ConstructAckFrame(2, 1);
7190 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07007191 lost_packets.push_back(
7192 LostPacket(QuicPacketNumber(1), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007193 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
7194 .WillOnce(SetArgPointee<5>(lost_packets));
7195 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7196 ProcessAckPacket(&ack);
nharper55fa6132019-05-07 19:37:21 -07007197 size_t padding_frame_count = writer_->padding_frames().size();
7198 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007199 EXPECT_EQ(1u, writer_->stream_frames().size());
7200 writer_->Reset();
7201
7202 // Now ack the retransmission, which will both raise the high water mark
7203 // and see if there is more data to send.
7204 ack = ConstructAckFrame(3, 1);
7205 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
7206 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7207 ProcessAckPacket(&ack);
7208
7209 // Check that no packet is sent and the ack alarm isn't set.
7210 EXPECT_EQ(0u, writer_->frame_count());
7211 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
7212 writer_->Reset();
7213
7214 // Send the same ack, but send both data and an ack together.
7215 ack = ConstructAckFrame(3, 1);
7216 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
7217 EXPECT_CALL(visitor_, OnCanWrite())
7218 .WillOnce(IgnoreResult(InvokeWithoutArgs(
7219 &connection_, &TestConnection::EnsureWritableAndSendStreamData5)));
7220 ProcessAckPacket(&ack);
7221
7222 // Check that ack is bundled with outgoing data and the delayed ack
7223 // alarm is reset.
7224 if (GetParam().no_stop_waiting) {
fayang8a27b0f2019-11-04 11:27:40 -08007225 // Do not ACK acks.
7226 EXPECT_EQ(1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007227 } else {
7228 EXPECT_EQ(3u, writer_->frame_count());
7229 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
7230 }
fayang8a27b0f2019-11-04 11:27:40 -08007231 if (GetParam().no_stop_waiting) {
fayang03916692019-05-22 17:57:18 -07007232 EXPECT_TRUE(writer_->ack_frames().empty());
7233 } else {
7234 EXPECT_FALSE(writer_->ack_frames().empty());
7235 EXPECT_EQ(QuicPacketNumber(3u),
7236 LargestAcked(writer_->ack_frames().front()));
7237 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007238 EXPECT_EQ(1u, writer_->stream_frames().size());
7239 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
7240}
7241
7242TEST_P(QuicConnectionTest, NoAckSentForClose) {
7243 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7244 ProcessPacket(1);
fkastenholz5d880a92019-06-21 09:01:56 -07007245 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
7246 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007247 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
7248 ProcessClosePacket(2);
fkastenholz5d880a92019-06-21 09:01:56 -07007249 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007250 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7251 IsError(QUIC_PEER_GOING_AWAY));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007252}
7253
7254TEST_P(QuicConnectionTest, SendWhenDisconnected) {
7255 EXPECT_TRUE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07007256 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7257 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007258 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
7259 ConnectionCloseBehavior::SILENT_CLOSE);
7260 EXPECT_FALSE(connection_.connected());
7261 EXPECT_FALSE(connection_.CanWriteStreamData());
QUICHE team8c1daa22019-03-13 08:33:41 -07007262 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07007263 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007264 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
7265 .Times(0);
QUICHE team6987b4a2019-03-15 16:23:04 -07007266 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05007267 HAS_RETRANSMITTABLE_DATA, false, false);
fkastenholz5d880a92019-06-21 09:01:56 -07007268 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007269 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7270 IsError(QUIC_PEER_GOING_AWAY));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007271}
7272
7273TEST_P(QuicConnectionTest, SendConnectivityProbingWhenDisconnected) {
7274 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
fayangc31c9952019-06-05 13:54:48 -07007275 if (!IsDefaultTestConfiguration()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007276 return;
7277 }
7278
7279 EXPECT_TRUE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07007280 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7281 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007282 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
7283 ConnectionCloseBehavior::SILENT_CLOSE);
7284 EXPECT_FALSE(connection_.connected());
7285 EXPECT_FALSE(connection_.CanWriteStreamData());
7286
7287 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
7288 .Times(0);
7289
7290 EXPECT_QUIC_BUG(connection_.SendConnectivityProbingPacket(
7291 writer_.get(), connection_.peer_address()),
7292 "Not sending connectivity probing packet as connection is "
7293 "disconnected.");
fkastenholz5d880a92019-06-21 09:01:56 -07007294 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007295 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7296 IsError(QUIC_PEER_GOING_AWAY));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007297}
7298
7299TEST_P(QuicConnectionTest, WriteBlockedAfterClientSendsConnectivityProbe) {
7300 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
7301 TestPacketWriter probing_writer(version(), &clock_);
7302 // Block next write so that sending connectivity probe will encounter a
7303 // blocked write when send a connectivity probe to the peer.
7304 probing_writer.BlockOnNextWrite();
7305 // Connection will not be marked as write blocked as connectivity probe only
7306 // affects the probing_writer which is not the default.
7307 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
7308
7309 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
7310 .Times(1);
7311 connection_.SendConnectivityProbingPacket(&probing_writer,
7312 connection_.peer_address());
7313}
7314
7315TEST_P(QuicConnectionTest, WriterBlockedAfterServerSendsConnectivityProbe) {
7316 set_perspective(Perspective::IS_SERVER);
7317 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
7318
7319 // Block next write so that sending connectivity probe will encounter a
7320 // blocked write when send a connectivity probe to the peer.
7321 writer_->BlockOnNextWrite();
7322 // Connection will be marked as write blocked as server uses the default
7323 // writer to send connectivity probes.
7324 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
7325
7326 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
7327 .Times(1);
7328 connection_.SendConnectivityProbingPacket(writer_.get(),
7329 connection_.peer_address());
7330}
7331
7332TEST_P(QuicConnectionTest, WriterErrorWhenClientSendsConnectivityProbe) {
7333 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
7334 TestPacketWriter probing_writer(version(), &clock_);
7335 probing_writer.SetShouldWriteFail();
7336
7337 // Connection should not be closed if a connectivity probe is failed to be
7338 // sent.
fkastenholz5d880a92019-06-21 09:01:56 -07007339 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007340
7341 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
7342 .Times(0);
7343 connection_.SendConnectivityProbingPacket(&probing_writer,
7344 connection_.peer_address());
7345}
7346
7347TEST_P(QuicConnectionTest, WriterErrorWhenServerSendsConnectivityProbe) {
7348 set_perspective(Perspective::IS_SERVER);
7349 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
7350
7351 writer_->SetShouldWriteFail();
7352 // Connection should not be closed if a connectivity probe is failed to be
7353 // sent.
fkastenholz5d880a92019-06-21 09:01:56 -07007354 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007355
7356 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
7357 .Times(0);
7358 connection_.SendConnectivityProbingPacket(writer_.get(),
7359 connection_.peer_address());
7360}
7361
7362TEST_P(QuicConnectionTest, PublicReset) {
fayangc31c9952019-06-05 13:54:48 -07007363 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007364 return;
7365 }
7366 QuicPublicResetPacket header;
7367 // Public reset packet in only built by server.
7368 header.connection_id = connection_id_;
7369 std::unique_ptr<QuicEncryptedPacket> packet(
7370 framer_.BuildPublicResetPacket(header));
7371 std::unique_ptr<QuicReceivedPacket> received(
7372 ConstructReceivedPacket(*packet, QuicTime::Zero()));
fkastenholz5d880a92019-06-21 09:01:56 -07007373 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
7374 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007375 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
fkastenholz5d880a92019-06-21 09:01:56 -07007376 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007377 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7378 IsError(QUIC_PUBLIC_RESET));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007379}
7380
7381TEST_P(QuicConnectionTest, IetfStatelessReset) {
fayangc31c9952019-06-05 13:54:48 -07007382 if (!VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007383 return;
7384 }
7385 const QuicUint128 kTestStatelessResetToken = 1010101;
7386 QuicConfig config;
7387 QuicConfigPeer::SetReceivedStatelessResetToken(&config,
7388 kTestStatelessResetToken);
7389 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7390 connection_.SetFromConfig(config);
7391 std::unique_ptr<QuicEncryptedPacket> packet(
7392 QuicFramer::BuildIetfStatelessResetPacket(connection_id_,
7393 kTestStatelessResetToken));
7394 std::unique_ptr<QuicReceivedPacket> received(
7395 ConstructReceivedPacket(*packet, QuicTime::Zero()));
fkastenholz5d880a92019-06-21 09:01:56 -07007396 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
7397 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007398 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
fkastenholz5d880a92019-06-21 09:01:56 -07007399 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007400 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7401 IsError(QUIC_PUBLIC_RESET));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007402}
7403
7404TEST_P(QuicConnectionTest, GoAway) {
fkastenholz305e1732019-06-18 05:01:22 -07007405 if (VersionHasIetfQuicFrames(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007406 // GoAway is not available in version 99.
7407 return;
7408 }
7409
7410 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7411
7412 QuicGoAwayFrame goaway;
7413 goaway.last_good_stream_id = 1;
7414 goaway.error_code = QUIC_PEER_GOING_AWAY;
7415 goaway.reason_phrase = "Going away.";
7416 EXPECT_CALL(visitor_, OnGoAway(_));
7417 ProcessGoAwayPacket(&goaway);
7418}
7419
7420TEST_P(QuicConnectionTest, WindowUpdate) {
7421 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7422
7423 QuicWindowUpdateFrame window_update;
7424 window_update.stream_id = 3;
renjietangd088eab2019-11-21 14:54:41 -08007425 window_update.max_data = 1234;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007426 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
7427 ProcessFramePacket(QuicFrame(&window_update));
7428}
7429
7430TEST_P(QuicConnectionTest, Blocked) {
7431 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7432
7433 QuicBlockedFrame blocked;
7434 blocked.stream_id = 3;
7435 EXPECT_CALL(visitor_, OnBlockedFrame(_));
7436 ProcessFramePacket(QuicFrame(&blocked));
7437 EXPECT_EQ(1u, connection_.GetStats().blocked_frames_received);
7438 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7439}
7440
7441TEST_P(QuicConnectionTest, ZeroBytePacket) {
7442 // Don't close the connection for zero byte packets.
fkastenholz5d880a92019-06-21 09:01:56 -07007443 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007444 QuicReceivedPacket encrypted(nullptr, 0, QuicTime::Zero());
7445 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, encrypted);
7446}
7447
7448TEST_P(QuicConnectionTest, MissingPacketsBeforeLeastUnacked) {
fayangd4291e42019-05-30 10:31:21 -07007449 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007450 return;
7451 }
7452 // Set the packet number of the ack packet to be least unacked (4).
7453 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 3);
7454 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7455 ProcessStopWaitingPacket(InitStopWaitingFrame(4));
fayangc31c9952019-06-05 13:54:48 -07007456 EXPECT_FALSE(connection_.ack_frame().packets.Empty());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007457}
7458
QUICHE teama6ef0a62019-03-07 20:34:33 -05007459TEST_P(QuicConnectionTest, ClientHandlesVersionNegotiation) {
dschinazi48ac9192019-07-31 00:07:26 -07007460 // All supported versions except the one the connection supports.
7461 ParsedQuicVersionVector versions;
7462 for (auto version : AllSupportedVersions()) {
7463 if (version != connection_.version()) {
7464 versions.push_back(version);
7465 }
7466 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007467
7468 // Send a version negotiation packet.
7469 std::unique_ptr<QuicEncryptedPacket> encrypted(
dschinazib417d602019-05-29 13:08:45 -07007470 QuicFramer::BuildVersionNegotiationPacket(
7471 connection_id_, EmptyQuicConnectionId(),
fayangd4291e42019-05-30 10:31:21 -07007472 VersionHasIetfInvariantHeader(connection_.transport_version()),
dschinazi48ac9192019-07-31 00:07:26 -07007473 connection_.version().HasLengthPrefixedConnectionIds(), versions));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007474 std::unique_ptr<QuicReceivedPacket> received(
7475 ConstructReceivedPacket(*encrypted, QuicTime::Zero()));
fkastenholz5d880a92019-06-21 09:01:56 -07007476 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7477 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
fayang95cef072019-10-10 12:44:14 -07007478 // Verify no connection close packet gets sent.
7479 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007480 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
fayang9ed391a2019-06-20 11:16:59 -07007481 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07007482 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007483 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7484 IsError(QUIC_INVALID_VERSION));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007485}
7486
7487TEST_P(QuicConnectionTest, BadVersionNegotiation) {
7488 // Send a version negotiation packet with the version the client started with.
7489 // It should be rejected.
fkastenholz5d880a92019-06-21 09:01:56 -07007490 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7491 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007492 std::unique_ptr<QuicEncryptedPacket> encrypted(
dschinazib417d602019-05-29 13:08:45 -07007493 QuicFramer::BuildVersionNegotiationPacket(
7494 connection_id_, EmptyQuicConnectionId(),
fayangd4291e42019-05-30 10:31:21 -07007495 VersionHasIetfInvariantHeader(connection_.transport_version()),
dschinazi48ac9192019-07-31 00:07:26 -07007496 connection_.version().HasLengthPrefixedConnectionIds(),
QUICHE teama6ef0a62019-03-07 20:34:33 -05007497 AllSupportedVersions()));
7498 std::unique_ptr<QuicReceivedPacket> received(
7499 ConstructReceivedPacket(*encrypted, QuicTime::Zero()));
7500 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
fkastenholz5d880a92019-06-21 09:01:56 -07007501 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007502 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7503 IsError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007504}
7505
7506TEST_P(QuicConnectionTest, CheckSendStats) {
fayang5f135052019-08-22 17:59:40 -07007507 if (connection_.PtoEnabled()) {
7508 return;
7509 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007510 connection_.SetMaxTailLossProbes(0);
7511
7512 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7513 connection_.SendStreamDataWithString(3, "first", 0, NO_FIN);
7514 size_t first_packet_size = writer_->last_packet_size();
7515
7516 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7517 connection_.SendStreamDataWithString(5, "second", 0, NO_FIN);
7518 size_t second_packet_size = writer_->last_packet_size();
7519
7520 // 2 retransmissions due to rto, 1 due to explicit nack.
7521 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
7522 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
7523
7524 // Retransmit due to RTO.
7525 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
7526 connection_.GetRetransmissionAlarm()->Fire();
7527
7528 // Retransmit due to explicit nacks.
7529 QuicAckFrame nack_three =
7530 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)},
7531 {QuicPacketNumber(4), QuicPacketNumber(5)}});
7532
7533 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07007534 lost_packets.push_back(
7535 LostPacket(QuicPacketNumber(1), kMaxOutgoingPacketSize));
7536 lost_packets.push_back(
7537 LostPacket(QuicPacketNumber(3), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007538 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
7539 .WillOnce(SetArgPointee<5>(lost_packets));
7540 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007541 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7542 ProcessAckPacket(&nack_three);
7543
7544 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
7545 .WillOnce(Return(QuicBandwidth::Zero()));
7546
7547 const QuicConnectionStats& stats = connection_.GetStats();
7548 // For IETF QUIC, version is not included as the encryption level switches to
7549 // FORWARD_SECURE in SendStreamDataWithString.
7550 size_t save_on_version =
fayangd4291e42019-05-30 10:31:21 -07007551 VersionHasIetfInvariantHeader(GetParam().version.transport_version)
7552 ? 0
7553 : kQuicVersionSize;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007554 EXPECT_EQ(3 * first_packet_size + 2 * second_packet_size - save_on_version,
7555 stats.bytes_sent);
7556 EXPECT_EQ(5u, stats.packets_sent);
7557 EXPECT_EQ(2 * first_packet_size + second_packet_size - save_on_version,
7558 stats.bytes_retransmitted);
7559 EXPECT_EQ(3u, stats.packets_retransmitted);
7560 EXPECT_EQ(1u, stats.rto_count);
7561 EXPECT_EQ(kDefaultMaxPacketSize, stats.max_packet_size);
7562}
7563
7564TEST_P(QuicConnectionTest, ProcessFramesIfPacketClosedConnection) {
7565 // Construct a packet with stream frame and connection close frame.
7566 QuicPacketHeader header;
dschinazi5e1a7b22019-07-31 12:23:21 -07007567 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
QUICHE team2252b702019-05-14 23:55:14 -04007568 header.source_connection_id = connection_id_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007569 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
fayangd4291e42019-05-30 10:31:21 -07007570 if (!VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04007571 header.source_connection_id_included = CONNECTION_ID_PRESENT;
7572 }
7573 } else {
7574 header.destination_connection_id = connection_id_;
fayangd4291e42019-05-30 10:31:21 -07007575 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04007576 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
7577 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007578 }
7579 header.packet_number = QuicPacketNumber(1);
7580 header.version_flag = false;
7581
fkastenholz488a4622019-08-26 06:24:46 -07007582 QuicErrorCode kQuicErrorCode = QUIC_PEER_GOING_AWAY;
7583 // This QuicConnectionCloseFrame will default to being for a Google QUIC
7584 // close. If doing IETF QUIC then set fields appropriately for CC/T or CC/A,
7585 // depending on the mapping.
fkastenholz591814c2019-09-06 12:11:46 -07007586 QuicConnectionCloseFrame qccf(peer_framer_.transport_version(),
7587 kQuicErrorCode, "",
7588 /*transport_close_frame_type=*/0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007589 QuicFrames frames;
7590 frames.push_back(QuicFrame(frame1_));
7591 frames.push_back(QuicFrame(&qccf));
7592 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
7593 EXPECT_TRUE(nullptr != packet);
dschinazi66dea072019-04-09 11:41:06 -07007594 char buffer[kMaxOutgoingPacketSize];
nharperc6b99512019-09-19 11:13:48 -07007595 size_t encrypted_length = peer_framer_.EncryptPayload(
7596 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
7597 kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007598
fkastenholz5d880a92019-06-21 09:01:56 -07007599 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
7600 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007601 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7602 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7603
7604 connection_.ProcessUdpPacket(
7605 kSelfAddress, kPeerAddress,
7606 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
fkastenholz5d880a92019-06-21 09:01:56 -07007607 EXPECT_EQ(1, connection_close_frame_count_);
bnc77e77b82020-04-05 10:36:49 -07007608 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
bncf54082a2019-11-27 10:19:47 -08007609 IsError(QUIC_PEER_GOING_AWAY));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007610}
7611
7612TEST_P(QuicConnectionTest, SelectMutualVersion) {
7613 connection_.SetSupportedVersions(AllSupportedVersions());
7614 // Set the connection to speak the lowest quic version.
7615 connection_.set_version(QuicVersionMin());
7616 EXPECT_EQ(QuicVersionMin(), connection_.version());
7617
7618 // Pass in available versions which includes a higher mutually supported
7619 // version. The higher mutually supported version should be selected.
7620 ParsedQuicVersionVector supported_versions = AllSupportedVersions();
7621 EXPECT_TRUE(connection_.SelectMutualVersion(supported_versions));
7622 EXPECT_EQ(QuicVersionMax(), connection_.version());
7623
7624 // Expect that the lowest version is selected.
7625 // Ensure the lowest supported version is less than the max, unless they're
7626 // the same.
7627 ParsedQuicVersionVector lowest_version_vector;
7628 lowest_version_vector.push_back(QuicVersionMin());
7629 EXPECT_TRUE(connection_.SelectMutualVersion(lowest_version_vector));
7630 EXPECT_EQ(QuicVersionMin(), connection_.version());
7631
7632 // Shouldn't be able to find a mutually supported version.
7633 ParsedQuicVersionVector unsupported_version;
7634 unsupported_version.push_back(UnsupportedQuicVersion());
7635 EXPECT_FALSE(connection_.SelectMutualVersion(unsupported_version));
7636}
7637
7638TEST_P(QuicConnectionTest, ConnectionCloseWhenWritable) {
7639 EXPECT_FALSE(writer_->IsWriteBlocked());
7640
7641 // Send a packet.
7642 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7643 EXPECT_EQ(0u, connection_.NumQueuedPackets());
7644 EXPECT_EQ(1u, writer_->packets_write_attempts());
7645
7646 TriggerConnectionClose();
rch39c88ab2019-10-16 19:24:40 -07007647 EXPECT_LE(2u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007648}
7649
7650TEST_P(QuicConnectionTest, ConnectionCloseGettingWriteBlocked) {
7651 BlockOnNextWrite();
7652 TriggerConnectionClose();
7653 EXPECT_EQ(1u, writer_->packets_write_attempts());
7654 EXPECT_TRUE(writer_->IsWriteBlocked());
7655}
7656
7657TEST_P(QuicConnectionTest, ConnectionCloseWhenWriteBlocked) {
7658 BlockOnNextWrite();
7659 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7660 EXPECT_EQ(1u, connection_.NumQueuedPackets());
7661 EXPECT_EQ(1u, writer_->packets_write_attempts());
7662 EXPECT_TRUE(writer_->IsWriteBlocked());
7663 TriggerConnectionClose();
7664 EXPECT_EQ(1u, writer_->packets_write_attempts());
7665}
7666
7667TEST_P(QuicConnectionTest, OnPacketSentDebugVisitor) {
7668 MockQuicConnectionDebugVisitor debug_visitor;
7669 connection_.set_debug_visitor(&debug_visitor);
7670
fayangcff885a2019-10-22 07:39:04 -07007671 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007672 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7673
fayangcff885a2019-10-22 07:39:04 -07007674 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007675 connection_.SendConnectivityProbingPacket(writer_.get(),
7676 connection_.peer_address());
7677}
7678
7679TEST_P(QuicConnectionTest, OnPacketHeaderDebugVisitor) {
7680 QuicPacketHeader header;
7681 header.packet_number = QuicPacketNumber(1);
fayangd4291e42019-05-30 10:31:21 -07007682 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007683 header.form = IETF_QUIC_LONG_HEADER_PACKET;
7684 }
7685
7686 MockQuicConnectionDebugVisitor debug_visitor;
7687 connection_.set_debug_visitor(&debug_visitor);
7688 EXPECT_CALL(debug_visitor, OnPacketHeader(Ref(header))).Times(1);
7689 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(1);
7690 EXPECT_CALL(debug_visitor, OnSuccessfulVersionNegotiation(_)).Times(1);
7691 connection_.OnPacketHeader(header);
7692}
7693
7694TEST_P(QuicConnectionTest, Pacing) {
7695 TestConnection server(connection_id_, kSelfAddress, helper_.get(),
7696 alarm_factory_.get(), writer_.get(),
7697 Perspective::IS_SERVER, version());
7698 TestConnection client(connection_id_, kPeerAddress, helper_.get(),
7699 alarm_factory_.get(), writer_.get(),
7700 Perspective::IS_CLIENT, version());
7701 EXPECT_FALSE(QuicSentPacketManagerPeer::UsingPacing(
7702 static_cast<const QuicSentPacketManager*>(
7703 &client.sent_packet_manager())));
7704 EXPECT_FALSE(QuicSentPacketManagerPeer::UsingPacing(
7705 static_cast<const QuicSentPacketManager*>(
7706 &server.sent_packet_manager())));
7707}
7708
7709TEST_P(QuicConnectionTest, WindowUpdateInstigateAcks) {
7710 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7711
7712 // Send a WINDOW_UPDATE frame.
7713 QuicWindowUpdateFrame window_update;
7714 window_update.stream_id = 3;
renjietangd088eab2019-11-21 14:54:41 -08007715 window_update.max_data = 1234;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007716 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
7717 ProcessFramePacket(QuicFrame(&window_update));
7718
7719 // Ensure that this has caused the ACK alarm to be set.
7720 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
7721 EXPECT_TRUE(ack_alarm->IsSet());
7722}
7723
7724TEST_P(QuicConnectionTest, BlockedFrameInstigateAcks) {
7725 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7726
7727 // Send a BLOCKED frame.
7728 QuicBlockedFrame blocked;
7729 blocked.stream_id = 3;
7730 EXPECT_CALL(visitor_, OnBlockedFrame(_));
7731 ProcessFramePacket(QuicFrame(&blocked));
7732
7733 // Ensure that this has caused the ACK alarm to be set.
7734 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
7735 EXPECT_TRUE(ack_alarm->IsSet());
7736}
7737
7738TEST_P(QuicConnectionTest, ReevaluateTimeUntilSendOnAck) {
7739 // Enable pacing.
7740 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7741 QuicConfig config;
7742 connection_.SetFromConfig(config);
7743
7744 // Send two packets. One packet is not sufficient because if it gets acked,
7745 // there will be no packets in flight after that and the pacer will always
7746 // allow the next packet in that situation.
7747 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7748 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
7749 connection_.SendStreamDataWithString(
7750 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
7751 0, NO_FIN);
7752 connection_.SendStreamDataWithString(
7753 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "bar",
7754 3, NO_FIN);
7755 connection_.OnCanWrite();
7756
7757 // Schedule the next packet for a few milliseconds in future.
7758 QuicSentPacketManagerPeer::DisablePacerBursts(manager_);
7759 QuicTime scheduled_pacing_time =
7760 clock_.Now() + QuicTime::Delta::FromMilliseconds(5);
7761 QuicSentPacketManagerPeer::SetNextPacedPacketTime(manager_,
7762 scheduled_pacing_time);
7763
7764 // Send a packet and have it be blocked by congestion control.
7765 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(false));
7766 connection_.SendStreamDataWithString(
7767 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "baz",
7768 6, NO_FIN);
7769 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
7770
7771 // Process an ack and the send alarm will be set to the new 5ms delay.
7772 QuicAckFrame ack = InitAckFrame(1);
7773 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
7774 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7775 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
7776 ProcessAckPacket(&ack);
nharper55fa6132019-05-07 19:37:21 -07007777 size_t padding_frame_count = writer_->padding_frames().size();
7778 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007779 EXPECT_EQ(1u, writer_->stream_frames().size());
7780 EXPECT_TRUE(connection_.GetSendAlarm()->IsSet());
7781 EXPECT_EQ(scheduled_pacing_time, connection_.GetSendAlarm()->deadline());
7782 writer_->Reset();
7783}
7784
7785TEST_P(QuicConnectionTest, SendAcksImmediately) {
QUICHE teamcd098022019-03-22 18:49:55 -07007786 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7787 return;
7788 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007789 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7790 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7791 ProcessDataPacket(1);
7792 CongestionBlockWrites();
7793 SendAckPacketToPeer();
7794}
7795
7796TEST_P(QuicConnectionTest, SendPingImmediately) {
7797 MockQuicConnectionDebugVisitor debug_visitor;
7798 connection_.set_debug_visitor(&debug_visitor);
7799
7800 CongestionBlockWrites();
fayang93cc53a2019-08-22 12:47:30 -07007801 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007802 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
fayangcff885a2019-10-22 07:39:04 -07007803 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007804 EXPECT_CALL(debug_visitor, OnPingSent()).Times(1);
7805 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
7806 EXPECT_FALSE(connection_.HasQueuedData());
7807}
7808
7809TEST_P(QuicConnectionTest, SendBlockedImmediately) {
7810 MockQuicConnectionDebugVisitor debug_visitor;
7811 connection_.set_debug_visitor(&debug_visitor);
7812
fayang93cc53a2019-08-22 12:47:30 -07007813 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007814 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
fayangcff885a2019-10-22 07:39:04 -07007815 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007816 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7817 connection_.SendControlFrame(QuicFrame(new QuicBlockedFrame(1, 3)));
7818 EXPECT_EQ(1u, connection_.GetStats().blocked_frames_sent);
7819 EXPECT_FALSE(connection_.HasQueuedData());
7820}
7821
fayang93cc53a2019-08-22 12:47:30 -07007822TEST_P(QuicConnectionTest, FailedToSendBlockedFrames) {
7823 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
7824 return;
7825 }
7826 MockQuicConnectionDebugVisitor debug_visitor;
7827 connection_.set_debug_visitor(&debug_visitor);
7828 QuicBlockedFrame blocked(1, 3);
7829
7830 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
fayangcff885a2019-10-22 07:39:04 -07007831 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(0);
fayang93cc53a2019-08-22 12:47:30 -07007832 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7833 connection_.SendControlFrame(QuicFrame(&blocked));
7834 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7835 EXPECT_FALSE(connection_.HasQueuedData());
7836}
7837
QUICHE teama6ef0a62019-03-07 20:34:33 -05007838TEST_P(QuicConnectionTest, SendingUnencryptedStreamDataFails) {
7839 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
7840 if (!IsDefaultTestConfiguration()) {
7841 return;
7842 }
7843
fkastenholz5d880a92019-06-21 09:01:56 -07007844 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7845 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007846 struct iovec iov;
7847 MakeIOVector("", &iov);
7848 EXPECT_QUIC_BUG(connection_.SaveAndSendStreamData(3, &iov, 1, 0, 0, FIN),
fayang49523232019-05-03 06:28:22 -07007849 "Cannot send stream data with level: ENCRYPTION_INITIAL");
QUICHE teama6ef0a62019-03-07 20:34:33 -05007850 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07007851 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007852 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7853 IsError(QUIC_ATTEMPT_TO_SEND_UNENCRYPTED_STREAM_DATA));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007854}
7855
7856TEST_P(QuicConnectionTest, SetRetransmissionAlarmForCryptoPacket) {
7857 EXPECT_TRUE(connection_.connected());
7858 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
7859
7860 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7861 connection_.SendCryptoStreamData();
7862
7863 // Verify retransmission timer is correctly set after crypto packet has been
7864 // sent.
7865 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
7866 QuicTime retransmission_time =
7867 QuicConnectionPeer::GetSentPacketManager(&connection_)
7868 ->GetRetransmissionTime();
7869 EXPECT_NE(retransmission_time, clock_.ApproximateNow());
7870 EXPECT_EQ(retransmission_time,
7871 connection_.GetRetransmissionAlarm()->deadline());
7872
7873 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7874 connection_.GetRetransmissionAlarm()->Fire();
7875}
7876
7877TEST_P(QuicConnectionTest, PathDegradingAlarmForCryptoPacket) {
7878 EXPECT_TRUE(connection_.connected());
fayangb59c6f12020-03-23 15:06:14 -07007879 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007880 EXPECT_FALSE(connection_.IsPathDegrading());
7881
7882 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7883 connection_.SendCryptoStreamData();
7884
fayangb59c6f12020-03-23 15:06:14 -07007885 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007886 EXPECT_FALSE(connection_.IsPathDegrading());
7887 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7888 ->GetPathDegradingDelay();
fayangb59c6f12020-03-23 15:06:14 -07007889 if (GetQuicReloadableFlag(quic_use_blackhole_detector)) {
7890 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7891 clock_.ApproximateNow());
7892 } else {
7893 EXPECT_EQ(delay, connection_.GetPathDegradingAlarm()->deadline() -
7894 clock_.ApproximateNow());
7895 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007896
7897 // Fire the path degrading alarm, path degrading signal should be sent to
7898 // the visitor.
7899 EXPECT_CALL(visitor_, OnPathDegrading());
7900 clock_.AdvanceTime(delay);
fayangb59c6f12020-03-23 15:06:14 -07007901 connection_.PathDegradingTimeout();
QUICHE teama6ef0a62019-03-07 20:34:33 -05007902 EXPECT_TRUE(connection_.IsPathDegrading());
fayangb59c6f12020-03-23 15:06:14 -07007903 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007904}
7905
vasilvv693d5b02019-04-09 21:58:56 -07007906// Includes regression test for b/69979024.
QUICHE teama6ef0a62019-03-07 20:34:33 -05007907TEST_P(QuicConnectionTest, PathDegradingAlarmForNonCryptoPackets) {
7908 EXPECT_TRUE(connection_.connected());
fayangb59c6f12020-03-23 15:06:14 -07007909 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007910 EXPECT_FALSE(connection_.IsPathDegrading());
7911
7912 const char data[] = "data";
7913 size_t data_size = strlen(data);
7914 QuicStreamOffset offset = 0;
7915
7916 for (int i = 0; i < 2; ++i) {
7917 // Send a packet. Now there's a retransmittable packet on the wire, so the
7918 // path degrading alarm should be set.
7919 connection_.SendStreamDataWithString(
7920 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
7921 offset, NO_FIN);
7922 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07007923 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007924 // Check the deadline of the path degrading alarm.
7925 QuicTime::Delta delay =
7926 QuicConnectionPeer::GetSentPacketManager(&connection_)
7927 ->GetPathDegradingDelay();
fayangb59c6f12020-03-23 15:06:14 -07007928 if (GetQuicReloadableFlag(quic_use_blackhole_detector)) {
7929 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7930 clock_.ApproximateNow());
7931 } else {
7932 EXPECT_EQ(delay, connection_.GetPathDegradingAlarm()->deadline() -
7933 clock_.ApproximateNow());
7934 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007935
7936 // Send a second packet. The path degrading alarm's deadline should remain
7937 // the same.
vasilvv693d5b02019-04-09 21:58:56 -07007938 // Regression test for b/69979024.
QUICHE teama6ef0a62019-03-07 20:34:33 -05007939 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7940 QuicTime prev_deadline = connection_.GetPathDegradingAlarm()->deadline();
fayangb59c6f12020-03-23 15:06:14 -07007941 if (GetQuicReloadableFlag(quic_use_blackhole_detector)) {
7942 prev_deadline = connection_.GetBlackholeDetectorAlarm()->deadline();
7943 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007944 connection_.SendStreamDataWithString(
7945 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
7946 offset, NO_FIN);
7947 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07007948 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7949 if (GetQuicReloadableFlag(quic_use_blackhole_detector)) {
7950 EXPECT_EQ(prev_deadline,
7951 connection_.GetBlackholeDetectorAlarm()->deadline());
7952 } else {
7953 EXPECT_EQ(prev_deadline, connection_.GetPathDegradingAlarm()->deadline());
7954 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007955
7956 // Now receive an ACK of the first packet. This should advance the path
7957 // degrading alarm's deadline since forward progress has been made.
7958 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7959 if (i == 0) {
7960 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7961 }
7962 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7963 QuicAckFrame frame = InitAckFrame(
7964 {{QuicPacketNumber(1u + 2u * i), QuicPacketNumber(2u + 2u * i)}});
7965 ProcessAckPacket(&frame);
fayangb59c6f12020-03-23 15:06:14 -07007966 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007967 // Check the deadline of the path degrading alarm.
7968 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7969 ->GetPathDegradingDelay();
fayangb59c6f12020-03-23 15:06:14 -07007970 if (GetQuicReloadableFlag(quic_use_blackhole_detector)) {
7971 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7972 clock_.ApproximateNow());
7973 } else {
7974 EXPECT_EQ(delay, connection_.GetPathDegradingAlarm()->deadline() -
7975 clock_.ApproximateNow());
7976 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007977
7978 if (i == 0) {
7979 // Now receive an ACK of the second packet. Since there are no more
7980 // retransmittable packets on the wire, this should cancel the path
7981 // degrading alarm.
7982 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7983 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7984 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
7985 ProcessAckPacket(&frame);
fayangb59c6f12020-03-23 15:06:14 -07007986 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007987 } else {
7988 // Advance time to the path degrading alarm's deadline and simulate
7989 // firing the alarm.
7990 clock_.AdvanceTime(delay);
7991 EXPECT_CALL(visitor_, OnPathDegrading());
fayangb59c6f12020-03-23 15:06:14 -07007992 connection_.PathDegradingTimeout();
7993 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007994 }
7995 }
7996 EXPECT_TRUE(connection_.IsPathDegrading());
7997}
7998
7999TEST_P(QuicConnectionTest, RetransmittableOnWireSetsPingAlarm) {
8000 const QuicTime::Delta retransmittable_on_wire_timeout =
8001 QuicTime::Delta::FromMilliseconds(50);
zhongyi79ace162019-10-21 15:57:09 -07008002 connection_.set_initial_retransmittable_on_wire_timeout(
QUICHE teama6ef0a62019-03-07 20:34:33 -05008003 retransmittable_on_wire_timeout);
8004
8005 EXPECT_TRUE(connection_.connected());
8006 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8007 .WillRepeatedly(Return(true));
8008
fayangb59c6f12020-03-23 15:06:14 -07008009 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008010 EXPECT_FALSE(connection_.IsPathDegrading());
8011 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8012
8013 const char data[] = "data";
8014 size_t data_size = strlen(data);
8015 QuicStreamOffset offset = 0;
8016
8017 // Send a packet.
8018 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8019 offset += data_size;
8020 // Now there's a retransmittable packet on the wire, so the path degrading
8021 // alarm should be set.
8022 // The retransmittable-on-wire alarm should not be set.
fayangb59c6f12020-03-23 15:06:14 -07008023 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008024 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
8025 ->GetPathDegradingDelay();
fayangb59c6f12020-03-23 15:06:14 -07008026 if (GetQuicReloadableFlag(quic_use_blackhole_detector)) {
8027 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
8028 clock_.ApproximateNow());
8029 } else {
8030 EXPECT_EQ(delay, connection_.GetPathDegradingAlarm()->deadline() -
8031 clock_.ApproximateNow());
8032 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008033 ASSERT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8034 // The ping alarm is set for the ping timeout, not the shorter
8035 // retransmittable_on_wire_timeout.
8036 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8037 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
zhongyieef848f2019-10-18 07:09:37 -07008038 EXPECT_EQ(ping_delay,
8039 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008040
8041 // Now receive an ACK of the packet.
8042 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8043 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8044 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8045 QuicAckFrame frame =
8046 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8047 ProcessAckPacket(&frame);
8048 // No more retransmittable packets on the wire, so the path degrading alarm
8049 // should be cancelled, and the ping alarm should be set to the
8050 // retransmittable_on_wire_timeout.
fayangb59c6f12020-03-23 15:06:14 -07008051 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008052 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07008053 EXPECT_EQ(retransmittable_on_wire_timeout,
8054 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008055
8056 // Simulate firing the ping alarm and sending a PING.
8057 clock_.AdvanceTime(retransmittable_on_wire_timeout);
8058 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8059 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
8060 }));
8061 connection_.GetPingAlarm()->Fire();
8062
8063 // Now there's a retransmittable packet (PING) on the wire, so the path
8064 // degrading alarm should be set.
fayangb59c6f12020-03-23 15:06:14 -07008065 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008066 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
8067 ->GetPathDegradingDelay();
fayangb59c6f12020-03-23 15:06:14 -07008068 if (GetQuicReloadableFlag(quic_use_blackhole_detector)) {
8069 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
8070 clock_.ApproximateNow());
8071 } else {
8072 EXPECT_EQ(delay, connection_.GetPathDegradingAlarm()->deadline() -
8073 clock_.ApproximateNow());
8074 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008075}
8076
8077// This test verifies that the connection marks path as degrading and does not
8078// spin timer to detect path degrading when a new packet is sent on the
8079// degraded path.
8080TEST_P(QuicConnectionTest, NoPathDegradingAlarmIfPathIsDegrading) {
8081 EXPECT_TRUE(connection_.connected());
fayangb59c6f12020-03-23 15:06:14 -07008082 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008083 EXPECT_FALSE(connection_.IsPathDegrading());
8084
8085 const char data[] = "data";
8086 size_t data_size = strlen(data);
8087 QuicStreamOffset offset = 0;
8088
8089 // Send the first packet. Now there's a retransmittable packet on the wire, so
8090 // the path degrading alarm should be set.
8091 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8092 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07008093 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008094 // Check the deadline of the path degrading alarm.
8095 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
8096 ->GetPathDegradingDelay();
fayangb59c6f12020-03-23 15:06:14 -07008097 if (GetQuicReloadableFlag(quic_use_blackhole_detector)) {
8098 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
8099 clock_.ApproximateNow());
8100 } else {
8101 EXPECT_EQ(delay, connection_.GetPathDegradingAlarm()->deadline() -
8102 clock_.ApproximateNow());
8103 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008104
8105 // Send a second packet. The path degrading alarm's deadline should remain
8106 // the same.
8107 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8108 QuicTime prev_deadline = connection_.GetPathDegradingAlarm()->deadline();
fayangb59c6f12020-03-23 15:06:14 -07008109 if (GetQuicReloadableFlag(quic_use_blackhole_detector)) {
8110 prev_deadline = connection_.GetBlackholeDetectorAlarm()->deadline();
8111 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008112 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8113 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07008114 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
8115 if (GetQuicReloadableFlag(quic_use_blackhole_detector)) {
8116 EXPECT_EQ(prev_deadline,
8117 connection_.GetBlackholeDetectorAlarm()->deadline());
8118 } else {
8119 EXPECT_EQ(prev_deadline, connection_.GetPathDegradingAlarm()->deadline());
8120 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008121
8122 // Now receive an ACK of the first packet. This should advance the path
8123 // degrading alarm's deadline since forward progress has been made.
8124 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8125 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8126 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8127 QuicAckFrame frame =
8128 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
8129 ProcessAckPacket(&frame);
fayangb59c6f12020-03-23 15:06:14 -07008130 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008131 // Check the deadline of the path degrading alarm.
8132 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
8133 ->GetPathDegradingDelay();
fayangb59c6f12020-03-23 15:06:14 -07008134 if (GetQuicReloadableFlag(quic_use_blackhole_detector)) {
8135 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
8136 clock_.ApproximateNow());
8137 } else {
8138 EXPECT_EQ(delay, connection_.GetPathDegradingAlarm()->deadline() -
8139 clock_.ApproximateNow());
8140 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008141
8142 // Advance time to the path degrading alarm's deadline and simulate
8143 // firing the path degrading alarm. This path will be considered as
8144 // degrading.
8145 clock_.AdvanceTime(delay);
8146 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
fayangb59c6f12020-03-23 15:06:14 -07008147 connection_.PathDegradingTimeout();
8148 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008149 EXPECT_TRUE(connection_.IsPathDegrading());
8150
8151 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
fayangb59c6f12020-03-23 15:06:14 -07008152 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008153 // Send a third packet. The path degrading alarm is no longer set but path
8154 // should still be marked as degrading.
8155 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8156 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07008157 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008158 EXPECT_TRUE(connection_.IsPathDegrading());
8159}
8160
8161// This test verifies that the connection unmarks path as degrarding and spins
8162// the timer to detect future path degrading when forward progress is made
8163// after path has been marked degrading.
8164TEST_P(QuicConnectionTest, UnmarkPathDegradingOnForwardProgress) {
8165 EXPECT_TRUE(connection_.connected());
fayangb59c6f12020-03-23 15:06:14 -07008166 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008167 EXPECT_FALSE(connection_.IsPathDegrading());
8168
8169 const char data[] = "data";
8170 size_t data_size = strlen(data);
8171 QuicStreamOffset offset = 0;
8172
8173 // Send the first packet. Now there's a retransmittable packet on the wire, so
8174 // the path degrading alarm should be set.
8175 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8176 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07008177 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008178 // Check the deadline of the path degrading alarm.
8179 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
8180 ->GetPathDegradingDelay();
fayangb59c6f12020-03-23 15:06:14 -07008181 if (GetQuicReloadableFlag(quic_use_blackhole_detector)) {
8182 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
8183 clock_.ApproximateNow());
8184 } else {
8185 EXPECT_EQ(delay, connection_.GetPathDegradingAlarm()->deadline() -
8186 clock_.ApproximateNow());
8187 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008188
8189 // Send a second packet. The path degrading alarm's deadline should remain
8190 // the same.
8191 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8192 QuicTime prev_deadline = connection_.GetPathDegradingAlarm()->deadline();
fayangb59c6f12020-03-23 15:06:14 -07008193 if (GetQuicReloadableFlag(quic_use_blackhole_detector)) {
8194 prev_deadline = connection_.GetBlackholeDetectorAlarm()->deadline();
8195 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008196 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8197 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07008198 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
8199 if (GetQuicReloadableFlag(quic_use_blackhole_detector)) {
8200 EXPECT_EQ(prev_deadline,
8201 connection_.GetBlackholeDetectorAlarm()->deadline());
8202 } else {
8203 EXPECT_EQ(prev_deadline, connection_.GetPathDegradingAlarm()->deadline());
8204 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008205
8206 // Now receive an ACK of the first packet. This should advance the path
8207 // degrading alarm's deadline since forward progress has been made.
8208 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8209 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8210 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8211 QuicAckFrame frame =
8212 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
8213 ProcessAckPacket(&frame);
fayangb59c6f12020-03-23 15:06:14 -07008214 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008215 // Check the deadline of the path degrading alarm.
8216 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
8217 ->GetPathDegradingDelay();
fayangb59c6f12020-03-23 15:06:14 -07008218 if (GetQuicReloadableFlag(quic_use_blackhole_detector)) {
8219 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
8220 clock_.ApproximateNow());
8221 } else {
8222 EXPECT_EQ(delay, connection_.GetPathDegradingAlarm()->deadline() -
8223 clock_.ApproximateNow());
8224 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008225
8226 // Advance time to the path degrading alarm's deadline and simulate
8227 // firing the alarm.
8228 clock_.AdvanceTime(delay);
8229 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
fayangb59c6f12020-03-23 15:06:14 -07008230 connection_.PathDegradingTimeout();
8231 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008232 EXPECT_TRUE(connection_.IsPathDegrading());
8233
8234 // Send a third packet. The path degrading alarm is no longer set but path
8235 // should still be marked as degrading.
8236 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
fayangb59c6f12020-03-23 15:06:14 -07008237 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008238 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8239 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07008240 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008241 EXPECT_TRUE(connection_.IsPathDegrading());
8242
8243 // Now receive an ACK of the second packet. This should unmark the path as
8244 // degrading. And will set a timer to detect new path degrading.
8245 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8246 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8247 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8248 ProcessAckPacket(&frame);
8249 EXPECT_FALSE(connection_.IsPathDegrading());
fayangb59c6f12020-03-23 15:06:14 -07008250 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008251}
8252
8253TEST_P(QuicConnectionTest, NoPathDegradingOnServer) {
QUICHE teamcd098022019-03-22 18:49:55 -07008254 if (connection_.SupportsMultiplePacketNumberSpaces()) {
8255 return;
8256 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008257 set_perspective(Perspective::IS_SERVER);
8258 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
8259
8260 EXPECT_FALSE(connection_.IsPathDegrading());
fayangb59c6f12020-03-23 15:06:14 -07008261 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008262
8263 // Send data.
8264 const char data[] = "data";
8265 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
8266 EXPECT_FALSE(connection_.IsPathDegrading());
fayangb59c6f12020-03-23 15:06:14 -07008267 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008268
8269 // Ack data.
8270 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
QUICHE teama6ef0a62019-03-07 20:34:33 -05008271 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8272 QuicAckFrame frame =
8273 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
8274 ProcessAckPacket(&frame);
8275 EXPECT_FALSE(connection_.IsPathDegrading());
fayangb59c6f12020-03-23 15:06:14 -07008276 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008277}
8278
8279TEST_P(QuicConnectionTest, NoPathDegradingAfterSendingAck) {
QUICHE teamcd098022019-03-22 18:49:55 -07008280 if (connection_.SupportsMultiplePacketNumberSpaces()) {
8281 return;
8282 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008283 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8284 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
8285 ProcessDataPacket(1);
8286 SendAckPacketToPeer();
8287 EXPECT_FALSE(connection_.sent_packet_manager().unacked_packets().empty());
8288 EXPECT_FALSE(connection_.sent_packet_manager().HasInFlightPackets());
8289 EXPECT_FALSE(connection_.IsPathDegrading());
fayangb59c6f12020-03-23 15:06:14 -07008290 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008291}
8292
8293TEST_P(QuicConnectionTest, MultipleCallsToCloseConnection) {
8294 // Verifies that multiple calls to CloseConnection do not
8295 // result in multiple attempts to close the connection - it will be marked as
8296 // disconnected after the first call.
fkastenholz5d880a92019-06-21 09:01:56 -07008297 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008298 connection_.CloseConnection(QUIC_NO_ERROR, "no reason",
8299 ConnectionCloseBehavior::SILENT_CLOSE);
8300 connection_.CloseConnection(QUIC_NO_ERROR, "no reason",
8301 ConnectionCloseBehavior::SILENT_CLOSE);
8302}
8303
8304TEST_P(QuicConnectionTest, ServerReceivesChloOnNonCryptoStream) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008305 set_perspective(Perspective::IS_SERVER);
8306 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
8307
8308 CryptoHandshakeMessage message;
8309 CryptoFramer framer;
8310 message.set_tag(kCHLO);
QUICHE team3fe6a8b2019-03-14 09:10:38 -07008311 std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008312 frame1_.stream_id = 10;
8313 frame1_.data_buffer = data->data();
8314 frame1_.data_length = data->length();
8315
fkastenholz5d880a92019-06-21 09:01:56 -07008316 EXPECT_CALL(visitor_,
8317 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05008318 ForceProcessFramePacket(QuicFrame(frame1_));
fkastenholz5d880a92019-06-21 09:01:56 -07008319 TestConnectionCloseQuicErrorCode(QUIC_MAYBE_CORRUPTED_MEMORY);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008320}
8321
8322TEST_P(QuicConnectionTest, ClientReceivesRejOnNonCryptoStream) {
8323 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8324
8325 CryptoHandshakeMessage message;
8326 CryptoFramer framer;
8327 message.set_tag(kREJ);
QUICHE team3fe6a8b2019-03-14 09:10:38 -07008328 std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008329 frame1_.stream_id = 10;
8330 frame1_.data_buffer = data->data();
8331 frame1_.data_length = data->length();
8332
fkastenholz5d880a92019-06-21 09:01:56 -07008333 EXPECT_CALL(visitor_,
8334 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05008335 ForceProcessFramePacket(QuicFrame(frame1_));
fkastenholz5d880a92019-06-21 09:01:56 -07008336 TestConnectionCloseQuicErrorCode(QUIC_MAYBE_CORRUPTED_MEMORY);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008337}
8338
8339TEST_P(QuicConnectionTest, CloseConnectionOnPacketTooLarge) {
8340 SimulateNextPacketTooLarge();
8341 // A connection close packet is sent
fkastenholz5d880a92019-06-21 09:01:56 -07008342 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
QUICHE teama6ef0a62019-03-07 20:34:33 -05008343 .Times(1);
8344 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
fkastenholz5d880a92019-06-21 09:01:56 -07008345 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008346}
8347
8348TEST_P(QuicConnectionTest, AlwaysGetPacketTooLarge) {
8349 // Test even we always get packet too large, we do not infinitely try to send
8350 // close packet.
8351 AlwaysGetPacketTooLarge();
fkastenholz5d880a92019-06-21 09:01:56 -07008352 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
QUICHE teama6ef0a62019-03-07 20:34:33 -05008353 .Times(1);
8354 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
fkastenholz5d880a92019-06-21 09:01:56 -07008355 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008356}
8357
nharperef468962019-07-02 14:15:38 -07008358TEST_P(QuicConnectionTest, CloseConnectionOnQueuedWriteError) {
nharperef468962019-07-02 14:15:38 -07008359 // Regression test for crbug.com/979507.
8360 //
8361 // If we get a write error when writing queued packets, we should attempt to
8362 // send a connection close packet, but if sending that fails, it shouldn't get
8363 // queued.
8364
8365 // Queue a packet to write.
8366 BlockOnNextWrite();
8367 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
8368 EXPECT_EQ(1u, connection_.NumQueuedPackets());
8369
8370 // Configure writer to always fail.
8371 AlwaysGetPacketTooLarge();
8372
8373 // Expect that we attempt to close the connection exactly once.
8374 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
8375 .Times(1);
8376
8377 // Unblock the writes and actually send.
8378 writer_->SetWritable();
8379 connection_.OnCanWrite();
8380 EXPECT_EQ(0u, connection_.NumQueuedPackets());
8381
8382 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
8383}
8384
QUICHE teama6ef0a62019-03-07 20:34:33 -05008385// Verify that if connection has no outstanding data, it notifies the send
8386// algorithm after the write.
8387TEST_P(QuicConnectionTest, SendDataAndBecomeApplicationLimited) {
8388 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
8389 {
8390 InSequence seq;
8391 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
8392 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
8393 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
8394 .WillRepeatedly(Return(false));
8395 }
8396
8397 connection_.SendStreamData3();
8398}
8399
8400// Verify that the connection does not become app-limited if there is
8401// outstanding data to send after the write.
8402TEST_P(QuicConnectionTest, NotBecomeApplicationLimitedIfMoreDataAvailable) {
8403 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
8404 {
8405 InSequence seq;
8406 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
8407 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
8408 }
8409
8410 connection_.SendStreamData3();
8411}
8412
8413// Verify that the connection does not become app-limited after blocked write
8414// even if there is outstanding data to send after the write.
8415TEST_P(QuicConnectionTest, NotBecomeApplicationLimitedDueToWriteBlock) {
8416 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
8417 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
8418 BlockOnNextWrite();
8419
fayange62e63c2019-12-04 07:16:25 -08008420 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008421 connection_.SendStreamData3();
8422
8423 // Now unblock the writer, become congestion control blocked,
8424 // and ensure we become app-limited after writing.
8425 writer_->SetWritable();
8426 CongestionBlockWrites();
8427 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(false));
fayange62e63c2019-12-04 07:16:25 -08008428 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
fayang2ce66082019-10-02 06:29:04 -07008429 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008430 connection_.OnCanWrite();
8431}
8432
8433// Test the mode in which the link is filled up with probing retransmissions if
8434// the connection becomes application-limited.
8435TEST_P(QuicConnectionTest, SendDataWhenApplicationLimited) {
8436 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8437 EXPECT_CALL(*send_algorithm_, ShouldSendProbingPacket())
8438 .WillRepeatedly(Return(true));
8439 {
8440 InSequence seq;
8441 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
8442 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
8443 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
8444 .WillRepeatedly(Return(false));
8445 }
QUICHE teamb8343252019-04-29 13:58:01 -07008446 EXPECT_CALL(visitor_, SendProbingData()).WillRepeatedly([this] {
8447 return connection_.sent_packet_manager().MaybeRetransmitOldestPacket(
8448 PROBING_RETRANSMISSION);
8449 });
QUICHE teama6ef0a62019-03-07 20:34:33 -05008450 // Fix congestion window to be 20,000 bytes.
8451 EXPECT_CALL(*send_algorithm_, CanSend(Ge(20000u)))
8452 .WillRepeatedly(Return(false));
8453 EXPECT_CALL(*send_algorithm_, CanSend(Lt(20000u)))
8454 .WillRepeatedly(Return(true));
8455
8456 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
8457 ASSERT_EQ(0u, connection_.GetStats().packets_sent);
8458 connection_.set_fill_up_link_during_probing(true);
fayangedf9ad52020-03-05 13:49:18 -08008459 EXPECT_CALL(visitor_, GetHandshakeState())
8460 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
QUICHE teama6ef0a62019-03-07 20:34:33 -05008461 connection_.OnHandshakeComplete();
8462 connection_.SendStreamData3();
8463
8464 // We expect a lot of packets from a 20 kbyte window.
8465 EXPECT_GT(connection_.GetStats().packets_sent, 10u);
8466 // Ensure that the packets are padded.
8467 QuicByteCount average_packet_size =
8468 connection_.GetStats().bytes_sent / connection_.GetStats().packets_sent;
8469 EXPECT_GT(average_packet_size, 1000u);
8470
8471 // Acknowledge all packets sent, except for the last one.
8472 QuicAckFrame ack = InitAckFrame(
8473 connection_.sent_packet_manager().GetLargestSentPacket() - 1);
8474 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
8475 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8476
8477 // Ensure that since we no longer have retransmittable bytes in flight, this
8478 // will not cause any responses to be sent.
8479 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8480 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
8481 ProcessAckPacket(&ack);
8482}
8483
rchd672c6d2019-11-27 15:30:54 -08008484TEST_P(QuicConnectionTest, DoNotForceSendingAckOnPacketTooLarge) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008485 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8486 // Send an ack by simulating delayed ack alarm firing.
8487 ProcessPacket(1);
8488 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
8489 EXPECT_TRUE(ack_alarm->IsSet());
8490 connection_.GetAckAlarm()->Fire();
8491 // Simulate data packet causes write error.
fkastenholz5d880a92019-06-21 09:01:56 -07008492 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05008493 SimulateNextPacketTooLarge();
8494 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
rchd672c6d2019-11-27 15:30:54 -08008495 EXPECT_EQ(1u, writer_->connection_close_frames().size());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008496 // Ack frame is not bundled in connection close packet.
8497 EXPECT_TRUE(writer_->ack_frames().empty());
rchd672c6d2019-11-27 15:30:54 -08008498 if (writer_->padding_frames().empty()) {
8499 EXPECT_EQ(1u, writer_->frame_count());
8500 } else {
8501 EXPECT_EQ(2u, writer_->frame_count());
8502 }
8503
fkastenholz5d880a92019-06-21 09:01:56 -07008504 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008505}
8506
rchd672c6d2019-11-27 15:30:54 -08008507TEST_P(QuicConnectionTest, CloseConnectionAllLevels) {
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
8523 if (!connection_.version().CanSendCoalescedPackets()) {
8524 // Each connection close packet should be sent in distinct UDP packets.
8525 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
8526 writer_->connection_close_packets());
8527 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
8528 writer_->packets_write_attempts());
8529 return;
8530 }
8531
8532 // A single UDP packet should be sent with multiple connection close packets
8533 // coalesced together.
8534 EXPECT_EQ(1u, writer_->packets_write_attempts());
8535
8536 // Only the first packet has been processed yet.
8537 EXPECT_EQ(1u, writer_->connection_close_packets());
8538
8539 // ProcessPacket resets the visitor and frees the coalesced packet.
8540 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
8541 auto packet = writer_->coalesced_packet()->Clone();
8542 writer_->framer()->ProcessPacket(*packet);
8543 EXPECT_EQ(1u, writer_->connection_close_packets());
8544 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
8545}
8546
8547TEST_P(QuicConnectionTest, CloseConnectionOneLevel) {
fayangc303bfd2020-02-11 09:19:54 -08008548 if (connection_.SupportsMultiplePacketNumberSpaces()) {
8549 return;
8550 }
rchd672c6d2019-11-27 15:30:54 -08008551
8552 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
8553 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
8554 connection_.CloseConnection(
8555 kQuicErrorCode, "Some random error message",
8556 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
8557
8558 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
8559
8560 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
8561 EXPECT_EQ(1u, writer_->connection_close_frames().size());
8562 EXPECT_EQ(1u, writer_->connection_close_packets());
8563 EXPECT_EQ(1u, writer_->packets_write_attempts());
8564 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
8565}
8566
fayang9abdfec2020-02-13 12:34:58 -08008567TEST_P(QuicConnectionTest, DoNotPadServerInitialConnectionClose) {
8568 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8569 return;
8570 }
8571 set_perspective(Perspective::IS_SERVER);
8572
8573 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
8574 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
8575 connection_.CloseConnection(
8576 kQuicErrorCode, "Some random error message",
8577 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
8578
8579 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
8580
8581 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
8582 EXPECT_EQ(1u, writer_->connection_close_frames().size());
8583 EXPECT_TRUE(writer_->padding_frames().empty());
8584 EXPECT_EQ(ENCRYPTION_INITIAL, writer_->framer()->last_decrypted_level());
8585}
8586
QUICHE teama6ef0a62019-03-07 20:34:33 -05008587// Regression test for b/63620844.
8588TEST_P(QuicConnectionTest, FailedToWriteHandshakePacket) {
8589 SimulateNextPacketTooLarge();
fkastenholz5d880a92019-06-21 09:01:56 -07008590 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
QUICHE teama6ef0a62019-03-07 20:34:33 -05008591 .Times(1);
fkastenholz5d880a92019-06-21 09:01:56 -07008592
QUICHE teama6ef0a62019-03-07 20:34:33 -05008593 connection_.SendCryptoStreamData();
fkastenholz5d880a92019-06-21 09:01:56 -07008594 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008595}
8596
8597TEST_P(QuicConnectionTest, MaxPacingRate) {
8598 EXPECT_EQ(0, connection_.MaxPacingRate().ToBytesPerSecond());
8599 connection_.SetMaxPacingRate(QuicBandwidth::FromBytesPerSecond(100));
8600 EXPECT_EQ(100, connection_.MaxPacingRate().ToBytesPerSecond());
8601}
8602
8603TEST_P(QuicConnectionTest, ClientAlwaysSendConnectionId) {
8604 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
8605 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8606 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
8607 EXPECT_EQ(CONNECTION_ID_PRESENT,
8608 writer_->last_packet_header().destination_connection_id_included);
8609
8610 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8611 QuicConfig config;
8612 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
8613 connection_.SetFromConfig(config);
8614
8615 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8616 connection_.SendStreamDataWithString(3, "bar", 3, NO_FIN);
8617 // Verify connection id is still sent in the packet.
8618 EXPECT_EQ(CONNECTION_ID_PRESENT,
8619 writer_->last_packet_header().destination_connection_id_included);
8620}
8621
8622TEST_P(QuicConnectionTest, SendProbingRetransmissions) {
8623 MockQuicConnectionDebugVisitor debug_visitor;
8624 connection_.set_debug_visitor(&debug_visitor);
8625
8626 const QuicStreamId stream_id = 2;
8627 QuicPacketNumber last_packet;
8628 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
8629 SendStreamDataToPeer(stream_id, "bar", 3, NO_FIN, &last_packet);
8630 SendStreamDataToPeer(stream_id, "test", 6, NO_FIN, &last_packet);
8631
8632 const QuicByteCount old_bytes_in_flight =
8633 connection_.sent_packet_manager().GetBytesInFlight();
8634
8635 // Allow 9 probing retransmissions to be sent.
8636 {
8637 InSequence seq;
8638 EXPECT_CALL(*send_algorithm_, CanSend(_))
8639 .Times(9 * 2)
8640 .WillRepeatedly(Return(true));
8641 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(Return(false));
8642 }
8643 // Expect them retransmitted in cyclic order (foo, bar, test, foo, bar...).
8644 QuicPacketCount sent_count = 0;
fayangcff885a2019-10-22 07:39:04 -07008645 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _))
QUICHE teama6ef0a62019-03-07 20:34:33 -05008646 .WillRepeatedly(Invoke([this, &sent_count](const SerializedPacket&,
QUICHE teama6ef0a62019-03-07 20:34:33 -05008647 TransmissionType, QuicTime) {
8648 ASSERT_EQ(1u, writer_->stream_frames().size());
fayang58f71072019-11-05 08:47:02 -08008649 if (connection_.version().CanSendCoalescedPackets()) {
8650 // There is a delay of sending coalesced packet, so (6, 0, 3, 6,
8651 // 0...).
8652 EXPECT_EQ(3 * ((sent_count + 2) % 3),
8653 writer_->stream_frames()[0]->offset);
8654 } else {
8655 // Identify the frames by stream offset (0, 3, 6, 0, 3...).
8656 EXPECT_EQ(3 * (sent_count % 3), writer_->stream_frames()[0]->offset);
8657 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008658 sent_count++;
8659 }));
8660 EXPECT_CALL(*send_algorithm_, ShouldSendProbingPacket())
8661 .WillRepeatedly(Return(true));
QUICHE teamb8343252019-04-29 13:58:01 -07008662 EXPECT_CALL(visitor_, SendProbingData()).WillRepeatedly([this] {
8663 return connection_.sent_packet_manager().MaybeRetransmitOldestPacket(
8664 PROBING_RETRANSMISSION);
8665 });
QUICHE teama6ef0a62019-03-07 20:34:33 -05008666
8667 connection_.SendProbingRetransmissions();
8668
8669 // Ensure that the in-flight has increased.
8670 const QuicByteCount new_bytes_in_flight =
8671 connection_.sent_packet_manager().GetBytesInFlight();
8672 EXPECT_GT(new_bytes_in_flight, old_bytes_in_flight);
8673}
8674
8675// Ensure that SendProbingRetransmissions() does not retransmit anything when
8676// there are no outstanding packets.
8677TEST_P(QuicConnectionTest,
8678 SendProbingRetransmissionsFailsWhenNothingToRetransmit) {
8679 ASSERT_TRUE(connection_.sent_packet_manager().unacked_packets().empty());
8680
8681 MockQuicConnectionDebugVisitor debug_visitor;
8682 connection_.set_debug_visitor(&debug_visitor);
fayangcff885a2019-10-22 07:39:04 -07008683 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008684 EXPECT_CALL(*send_algorithm_, ShouldSendProbingPacket())
8685 .WillRepeatedly(Return(true));
QUICHE teamb8343252019-04-29 13:58:01 -07008686 EXPECT_CALL(visitor_, SendProbingData()).WillRepeatedly([this] {
8687 return connection_.sent_packet_manager().MaybeRetransmitOldestPacket(
8688 PROBING_RETRANSMISSION);
8689 });
QUICHE teama6ef0a62019-03-07 20:34:33 -05008690
8691 connection_.SendProbingRetransmissions();
8692}
8693
8694TEST_P(QuicConnectionTest, PingAfterLastRetransmittablePacketAcked) {
8695 const QuicTime::Delta retransmittable_on_wire_timeout =
8696 QuicTime::Delta::FromMilliseconds(50);
zhongyi79ace162019-10-21 15:57:09 -07008697 connection_.set_initial_retransmittable_on_wire_timeout(
QUICHE teama6ef0a62019-03-07 20:34:33 -05008698 retransmittable_on_wire_timeout);
8699
8700 EXPECT_TRUE(connection_.connected());
8701 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8702 .WillRepeatedly(Return(true));
8703
8704 const char data[] = "data";
8705 size_t data_size = strlen(data);
8706 QuicStreamOffset offset = 0;
8707
8708 // Advance 5ms, send a retransmittable packet to the peer.
8709 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8710 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8711 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8712 offset += data_size;
8713 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8714 // The ping alarm is set for the ping timeout, not the shorter
8715 // retransmittable_on_wire_timeout.
8716 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8717 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
zhongyieef848f2019-10-18 07:09:37 -07008718 EXPECT_EQ(ping_delay,
8719 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008720
8721 // Advance 5ms, send a second retransmittable packet to the peer.
8722 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8723 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8724 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8725 offset += data_size;
8726 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8727
8728 // Now receive an ACK of the first packet. This should not set the
8729 // retransmittable-on-wire alarm since packet 2 is still on the wire.
8730 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8731 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8732 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8733 QuicAckFrame frame =
8734 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8735 ProcessAckPacket(&frame);
8736 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8737 // The ping alarm is set for the ping timeout, not the shorter
8738 // retransmittable_on_wire_timeout.
8739 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8740 // The ping alarm has a 1 second granularity, and the clock has been advanced
8741 // 10ms since it was originally set.
zhongyieef848f2019-10-18 07:09:37 -07008742 EXPECT_EQ(ping_delay - QuicTime::Delta::FromMilliseconds(10),
8743 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008744
8745 // Now receive an ACK of the second packet. This should set the
8746 // retransmittable-on-wire alarm now that no retransmittable packets are on
8747 // the wire.
8748 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8749 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8750 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8751 ProcessAckPacket(&frame);
8752 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07008753 EXPECT_EQ(retransmittable_on_wire_timeout,
8754 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008755
8756 // Now receive a duplicate ACK of the second packet. This should not update
8757 // the ping alarm.
8758 QuicTime prev_deadline = connection_.GetPingAlarm()->deadline();
8759 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8760 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8761 ProcessAckPacket(&frame);
8762 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8763 EXPECT_EQ(prev_deadline, connection_.GetPingAlarm()->deadline());
8764
8765 // Now receive a non-ACK packet. This should not update the ping alarm.
8766 prev_deadline = connection_.GetPingAlarm()->deadline();
8767 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8768 ProcessPacket(4);
8769 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8770 EXPECT_EQ(prev_deadline, connection_.GetPingAlarm()->deadline());
8771
8772 // Simulate the alarm firing and check that a PING is sent.
8773 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8774 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
8775 }));
8776 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07008777 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05008778 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07008779 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008780 } else {
nharper55fa6132019-05-07 19:37:21 -07008781 EXPECT_EQ(padding_frame_count + 3u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008782 }
8783 ASSERT_EQ(1u, writer_->ping_frames().size());
8784}
8785
8786TEST_P(QuicConnectionTest, NoPingIfRetransmittablePacketSent) {
8787 const QuicTime::Delta retransmittable_on_wire_timeout =
8788 QuicTime::Delta::FromMilliseconds(50);
zhongyi79ace162019-10-21 15:57:09 -07008789 connection_.set_initial_retransmittable_on_wire_timeout(
QUICHE teama6ef0a62019-03-07 20:34:33 -05008790 retransmittable_on_wire_timeout);
8791
8792 EXPECT_TRUE(connection_.connected());
8793 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8794 .WillRepeatedly(Return(true));
8795
8796 const char data[] = "data";
8797 size_t data_size = strlen(data);
8798 QuicStreamOffset offset = 0;
8799
8800 // Advance 5ms, send a retransmittable packet to the peer.
8801 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8802 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8803 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8804 offset += data_size;
8805 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8806 // The ping alarm is set for the ping timeout, not the shorter
8807 // retransmittable_on_wire_timeout.
8808 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8809 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
zhongyieef848f2019-10-18 07:09:37 -07008810 EXPECT_EQ(ping_delay,
8811 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008812
8813 // Now receive an ACK of the first packet. This should set the
8814 // retransmittable-on-wire alarm now that no retransmittable packets are on
8815 // the wire.
8816 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8817 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8818 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8819 QuicAckFrame frame =
8820 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8821 ProcessAckPacket(&frame);
8822 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07008823 EXPECT_EQ(retransmittable_on_wire_timeout,
8824 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008825
8826 // Before the alarm fires, send another retransmittable packet. This should
8827 // cancel the retransmittable-on-wire alarm since now there's a
8828 // retransmittable packet on the wire.
8829 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8830 offset += data_size;
8831 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8832
8833 // Now receive an ACK of the second packet. This should set the
8834 // retransmittable-on-wire alarm now that no retransmittable packets are on
8835 // the wire.
8836 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8837 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8838 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8839 ProcessAckPacket(&frame);
8840 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07008841 EXPECT_EQ(retransmittable_on_wire_timeout,
8842 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008843
8844 // Simulate the alarm firing and check that a PING is sent.
8845 writer_->Reset();
8846 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8847 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
8848 }));
8849 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07008850 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05008851 if (GetParam().no_stop_waiting) {
fayang8a27b0f2019-11-04 11:27:40 -08008852 // Do not ACK acks.
8853 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008854 } else {
nharper55fa6132019-05-07 19:37:21 -07008855 EXPECT_EQ(padding_frame_count + 3u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008856 }
8857 ASSERT_EQ(1u, writer_->ping_frames().size());
8858}
8859
zhongyi79ace162019-10-21 15:57:09 -07008860// When there is no stream data received but are open streams, send the
8861// first few consecutive pings with aggressive retransmittable-on-wire
8862// timeout. Exponentially back off the retransmittable-on-wire ping timeout
8863// afterwards until it exceeds the default ping timeout.
8864TEST_P(QuicConnectionTest, BackOffRetransmittableOnWireTimeout) {
8865 int max_aggressive_retransmittable_on_wire_ping_count = 5;
8866 SetQuicFlag(FLAGS_quic_max_aggressive_retransmittable_on_wire_ping_count,
8867 max_aggressive_retransmittable_on_wire_ping_count);
8868 const QuicTime::Delta initial_retransmittable_on_wire_timeout =
8869 QuicTime::Delta::FromMilliseconds(200);
8870 connection_.set_initial_retransmittable_on_wire_timeout(
8871 initial_retransmittable_on_wire_timeout);
8872
8873 EXPECT_TRUE(connection_.connected());
8874 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8875 .WillRepeatedly(Return(true));
8876
8877 const char data[] = "data";
8878 // Advance 5ms, send a retransmittable data packet to the peer.
8879 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8880 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8881 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
8882 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8883 // The ping alarm is set for the ping timeout, not the shorter
8884 // retransmittable_on_wire_timeout.
8885 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8886 EXPECT_EQ(connection_.ping_timeout(),
8887 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8888
8889 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
8890 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
8891 .Times(AnyNumber());
8892
8893 // Verify that the first few consecutive retransmittable on wire pings are
8894 // sent with aggressive timeout.
8895 for (int i = 0; i <= max_aggressive_retransmittable_on_wire_ping_count; i++) {
8896 // Receive an ACK of the previous packet. This should set the ping alarm
8897 // with the initial retransmittable-on-wire timeout.
8898 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8899 QuicPacketNumber ack_num = creator_->packet_number();
8900 QuicAckFrame frame = InitAckFrame(
8901 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8902 ProcessAckPacket(&frame);
8903 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8904 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8905 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8906 // Simulate the alarm firing and check that a PING is sent.
8907 writer_->Reset();
8908 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8909 SendPing();
8910 }));
8911 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8912 connection_.GetPingAlarm()->Fire();
8913 }
8914
8915 QuicTime::Delta retransmittable_on_wire_timeout =
8916 initial_retransmittable_on_wire_timeout;
8917
8918 // Verify subsequent pings are sent with timeout that is exponentially backed
8919 // off.
8920 while (retransmittable_on_wire_timeout * 2 < connection_.ping_timeout()) {
8921 // Receive an ACK for the previous PING. This should set the
8922 // ping alarm with backed off retransmittable-on-wire timeout.
8923 retransmittable_on_wire_timeout = retransmittable_on_wire_timeout * 2;
8924 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8925 QuicPacketNumber ack_num = creator_->packet_number();
8926 QuicAckFrame frame = InitAckFrame(
8927 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8928 ProcessAckPacket(&frame);
8929 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8930 EXPECT_EQ(retransmittable_on_wire_timeout,
8931 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8932
8933 // Simulate the alarm firing and check that a PING is sent.
8934 writer_->Reset();
8935 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8936 SendPing();
8937 }));
8938 clock_.AdvanceTime(retransmittable_on_wire_timeout);
8939 connection_.GetPingAlarm()->Fire();
8940 }
8941
8942 // The ping alarm is set with default ping timeout.
8943 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8944 EXPECT_EQ(connection_.ping_timeout(),
8945 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8946
8947 // Receive an ACK for the previous PING. The ping alarm is set with an
8948 // earlier deadline.
8949 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8950 QuicPacketNumber ack_num = creator_->packet_number();
8951 QuicAckFrame frame = InitAckFrame(
8952 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8953 ProcessAckPacket(&frame);
8954 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8955 EXPECT_EQ(connection_.ping_timeout() - QuicTime::Delta::FromMilliseconds(5),
8956 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8957}
8958
8959// This test verify that the count of consecutive aggressive pings is reset
8960// when new data is received. And it also verifies the connection resets
8961// the exponential back-off of the retransmittable-on-wire ping timeout
8962// after receiving new stream data.
8963TEST_P(QuicConnectionTest, ResetBackOffRetransmitableOnWireTimeout) {
8964 int max_aggressive_retransmittable_on_wire_ping_count = 3;
8965 SetQuicFlag(FLAGS_quic_max_aggressive_retransmittable_on_wire_ping_count, 3);
8966 const QuicTime::Delta initial_retransmittable_on_wire_timeout =
8967 QuicTime::Delta::FromMilliseconds(200);
8968 connection_.set_initial_retransmittable_on_wire_timeout(
8969 initial_retransmittable_on_wire_timeout);
8970
8971 EXPECT_TRUE(connection_.connected());
8972 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8973 .WillRepeatedly(Return(true));
8974 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
8975 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
8976 .Times(AnyNumber());
8977
8978 const char data[] = "data";
8979 // Advance 5ms, send a retransmittable data packet to the peer.
8980 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8981 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8982 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
8983 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8984 // The ping alarm is set for the ping timeout, not the shorter
8985 // retransmittable_on_wire_timeout.
8986 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8987 EXPECT_EQ(connection_.ping_timeout(),
8988 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8989
8990 // Receive an ACK of the first packet. This should set the ping alarm with
8991 // initial retransmittable-on-wire timeout since there is no retransmittable
8992 // packet on the wire.
8993 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8994 QuicAckFrame frame =
8995 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8996 ProcessAckPacket(&frame);
8997 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8998 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8999 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
9000
9001 // Simulate the alarm firing and check that a PING is sent.
9002 writer_->Reset();
9003 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
9004 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
9005 connection_.GetPingAlarm()->Fire();
9006
9007 // Receive an ACK for the previous PING. Ping alarm will be set with
9008 // aggressive timeout.
9009 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
9010 QuicPacketNumber 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,
9016 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
9017
9018 // Process a data packet.
9019 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
9020 ProcessDataPacket(peer_creator_.packet_number() + 1);
9021 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_,
9022 peer_creator_.packet_number() + 1);
9023 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
9024 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
9025
9026 // Verify the count of consecutive aggressive pings is reset.
9027 for (int i = 0; i < max_aggressive_retransmittable_on_wire_ping_count; i++) {
9028 // Receive an ACK of the previous packet. This should set the ping alarm
9029 // with the initial retransmittable-on-wire timeout.
9030 QuicPacketNumber ack_num = creator_->packet_number();
9031 QuicAckFrame 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 // Simulate the alarm firing and check that a PING is sent.
9038 writer_->Reset();
9039 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
9040 SendPing();
9041 }));
9042 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
9043 connection_.GetPingAlarm()->Fire();
9044 // Advance 5ms to receive next packet.
9045 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
9046 }
9047
9048 // Receive another ACK for the previous PING. This should set the
9049 // ping alarm with backed off retransmittable-on-wire timeout.
9050 ack_num = creator_->packet_number();
9051 frame = InitAckFrame(
9052 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
9053 ProcessAckPacket(&frame);
9054 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
9055 EXPECT_EQ(initial_retransmittable_on_wire_timeout * 2,
9056 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
9057
9058 writer_->Reset();
9059 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
9060 clock_.AdvanceTime(2 * initial_retransmittable_on_wire_timeout);
9061 connection_.GetPingAlarm()->Fire();
9062
9063 // Process another data packet and a new ACK packet. The ping alarm is set
9064 // with aggressive ping timeout again.
9065 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
9066 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
9067 ProcessDataPacket(peer_creator_.packet_number() + 1);
9068 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_,
9069 peer_creator_.packet_number() + 1);
9070 ack_num = creator_->packet_number();
9071 frame = InitAckFrame(
9072 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
9073 ProcessAckPacket(&frame);
9074 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
9075 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
9076 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
9077}
9078
QUICHE teama6ef0a62019-03-07 20:34:33 -05009079TEST_P(QuicConnectionTest, OnForwardProgressConfirmed) {
9080 EXPECT_CALL(visitor_, OnForwardProgressConfirmed()).Times(Exactly(0));
9081 EXPECT_TRUE(connection_.connected());
9082
9083 const char data[] = "data";
9084 size_t data_size = strlen(data);
9085 QuicStreamOffset offset = 0;
9086
9087 // Send two packets.
9088 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
9089 offset += data_size;
9090 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
9091 offset += data_size;
9092
9093 // Ack packet 1. This increases the largest_acked to 1, so
9094 // OnForwardProgressConfirmed() should be called
9095 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
9096 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9097 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
9098 EXPECT_CALL(visitor_, OnForwardProgressConfirmed());
9099 QuicAckFrame frame =
9100 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
9101 ProcessAckPacket(&frame);
9102
9103 // Ack packet 1 again. largest_acked remains at 1, so
9104 // OnForwardProgressConfirmed() should not be called.
9105 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
9106 frame = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
9107 ProcessAckPacket(&frame);
9108
9109 // Ack packet 2. This increases the largest_acked to 2, so
9110 // OnForwardProgressConfirmed() should be called.
9111 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
9112 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
9113 EXPECT_CALL(visitor_, OnForwardProgressConfirmed());
9114 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
9115 ProcessAckPacket(&frame);
9116}
9117
9118TEST_P(QuicConnectionTest, ValidStatelessResetToken) {
9119 const QuicUint128 kTestToken = 1010101;
9120 const QuicUint128 kWrongTestToken = 1010100;
9121 QuicConfig config;
9122 // No token has been received.
9123 EXPECT_FALSE(connection_.IsValidStatelessResetToken(kTestToken));
9124
9125 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(2);
9126 // Token is different from received token.
9127 QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestToken);
9128 connection_.SetFromConfig(config);
9129 EXPECT_FALSE(connection_.IsValidStatelessResetToken(kWrongTestToken));
9130
9131 QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestToken);
9132 connection_.SetFromConfig(config);
9133 EXPECT_TRUE(connection_.IsValidStatelessResetToken(kTestToken));
9134}
9135
9136TEST_P(QuicConnectionTest, WriteBlockedWithInvalidAck) {
9137 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayange62e63c2019-12-04 07:16:25 -08009138 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05009139 BlockOnNextWrite();
fayange62e63c2019-12-04 07:16:25 -08009140 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05009141 connection_.SendStreamDataWithString(5, "foo", 0, FIN);
9142 // This causes connection to be closed because packet 1 has not been sent yet.
9143 QuicAckFrame frame = InitAckFrame(1);
fayange62e63c2019-12-04 07:16:25 -08009144 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05009145 ProcessAckPacket(1, &frame);
fayange62e63c2019-12-04 07:16:25 -08009146 EXPECT_EQ(0, connection_close_frame_count_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05009147}
9148
9149TEST_P(QuicConnectionTest, SendMessage) {
fayangc31c9952019-06-05 13:54:48 -07009150 if (!VersionSupportsMessageFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05009151 return;
9152 }
dschinazied459c02020-05-07 16:12:23 -07009153 if (connection_.version().UsesTls()) {
9154 QuicConfig config;
9155 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
9156 &config, kMaxAcceptedDatagramFrameSize);
9157 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9158 connection_.SetFromConfig(config);
9159 }
ianswettb239f862019-04-05 09:15:06 -07009160 std::string message(connection_.GetCurrentLargestMessagePayload() * 2, 'a');
dmcardlecf0bfcf2019-12-13 08:08:21 -08009161 quiche::QuicheStringPiece message_data(message);
QUICHE teama6ef0a62019-03-07 20:34:33 -05009162 QuicMemSliceStorage storage(nullptr, 0, nullptr, 0);
9163 {
fayanga4b37b22019-06-18 13:37:47 -07009164 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05009165 connection_.SendStreamData3();
9166 // Send a message which cannot fit into current open packet, and 2 packets
9167 // get sent, one contains stream frame, and the other only contains the
9168 // message frame.
9169 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
QUICHE team350e9e62019-11-19 13:16:24 -08009170 EXPECT_EQ(MESSAGE_STATUS_SUCCESS,
9171 connection_.SendMessage(
9172 1,
9173 MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(),
dmcardlecf0bfcf2019-12-13 08:08:21 -08009174 quiche::QuicheStringPiece(
QUICHE team350e9e62019-11-19 13:16:24 -08009175 message_data.data(),
9176 connection_.GetCurrentLargestMessagePayload()),
9177 &storage),
9178 false));
QUICHE teama6ef0a62019-03-07 20:34:33 -05009179 }
9180 // Fail to send a message if connection is congestion control blocked.
9181 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(Return(false));
QUICHE team350e9e62019-11-19 13:16:24 -08009182 EXPECT_EQ(MESSAGE_STATUS_BLOCKED,
9183 connection_.SendMessage(
9184 2,
9185 MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(),
9186 "message", &storage),
9187 false));
QUICHE teama6ef0a62019-03-07 20:34:33 -05009188
9189 // Always fail to send a message which cannot fit into one packet.
9190 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE team350e9e62019-11-19 13:16:24 -08009191 EXPECT_EQ(MESSAGE_STATUS_TOO_LARGE,
9192 connection_.SendMessage(
9193 3,
9194 MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(),
dmcardlecf0bfcf2019-12-13 08:08:21 -08009195 quiche::QuicheStringPiece(
QUICHE team350e9e62019-11-19 13:16:24 -08009196 message_data.data(),
9197 connection_.GetCurrentLargestMessagePayload() + 1),
9198 &storage),
9199 false));
QUICHE teama6ef0a62019-03-07 20:34:33 -05009200}
9201
dschinazied459c02020-05-07 16:12:23 -07009202TEST_P(QuicConnectionTest, GetCurrentLargestMessagePayload) {
9203 if (!connection_.version().SupportsMessageFrames()) {
9204 return;
9205 }
9206 // Force use of this encrypter to simplify test expectations by making sure
9207 // that the encryption overhead is constant across versions.
9208 connection_.SetEncrypter(ENCRYPTION_INITIAL,
9209 std::make_unique<TaggingEncrypter>(0x00));
9210 QuicPacketLength expected_largest_payload = 1319;
9211 if (connection_.version().SendsVariableLengthPacketNumberInLongHeader()) {
9212 expected_largest_payload += 3;
9213 }
9214 if (connection_.version().HasLongHeaderLengths()) {
9215 expected_largest_payload -= 2;
9216 }
9217 if (connection_.version().HasLengthPrefixedConnectionIds()) {
9218 expected_largest_payload -= 1;
9219 }
9220 if (connection_.version().UsesTls()) {
9221 // QUIC+TLS disallows DATAGRAM/MESSAGE frames before the handshake.
9222 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), 0);
9223 QuicConfig config;
9224 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
9225 &config, kMaxAcceptedDatagramFrameSize);
9226 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9227 connection_.SetFromConfig(config);
9228 // Verify the value post-handshake.
9229 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(),
9230 expected_largest_payload);
9231 } else {
9232 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(),
9233 expected_largest_payload);
9234 }
9235}
9236
9237TEST_P(QuicConnectionTest, GetGuaranteedLargestMessagePayload) {
9238 if (!connection_.version().SupportsMessageFrames()) {
9239 return;
9240 }
9241 // Force use of this encrypter to simplify test expectations by making sure
9242 // that the encryption overhead is constant across versions.
9243 connection_.SetEncrypter(ENCRYPTION_INITIAL,
9244 std::make_unique<TaggingEncrypter>(0x00));
9245 QuicPacketLength expected_largest_payload = 1319;
9246 if (connection_.version().HasLongHeaderLengths()) {
9247 expected_largest_payload -= 2;
9248 }
9249 if (connection_.version().HasLengthPrefixedConnectionIds()) {
9250 expected_largest_payload -= 1;
9251 }
9252 if (connection_.version().UsesTls()) {
9253 // QUIC+TLS disallows DATAGRAM/MESSAGE frames before the handshake.
9254 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(), 0);
9255 QuicConfig config;
9256 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
9257 &config, kMaxAcceptedDatagramFrameSize);
9258 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9259 connection_.SetFromConfig(config);
9260 // Verify the value post-handshake.
9261 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(),
9262 expected_largest_payload);
9263 } else {
9264 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(),
9265 expected_largest_payload);
9266 }
9267}
9268
9269TEST_P(QuicConnectionTest, LimitedLargestMessagePayload) {
9270 if (!connection_.version().SupportsMessageFrames() ||
9271 !connection_.version().UsesTls()) {
9272 return;
9273 }
9274 constexpr QuicPacketLength kFrameSizeLimit = 1000;
9275 constexpr QuicPacketLength kPayloadSizeLimit =
9276 kFrameSizeLimit - kQuicFrameTypeSize;
9277 // QUIC+TLS disallows DATAGRAM/MESSAGE frames before the handshake.
9278 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), 0);
9279 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(), 0);
9280 QuicConfig config;
9281 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(&config, kFrameSizeLimit);
9282 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9283 connection_.SetFromConfig(config);
9284 // Verify the value post-handshake.
9285 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), kPayloadSizeLimit);
9286 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(),
9287 kPayloadSizeLimit);
9288}
9289
QUICHE teama6ef0a62019-03-07 20:34:33 -05009290// Test to check that the path challenge/path response logic works
9291// correctly. This test is only for version-99
9292TEST_P(QuicConnectionTest, PathChallengeResponse) {
fkastenholz305e1732019-06-18 05:01:22 -07009293 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05009294 return;
9295 }
9296 // First check if we can probe from server to client and back
9297 set_perspective(Perspective::IS_SERVER);
9298 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
9299
9300 // Create and send the probe request (PATH_CHALLENGE frame).
9301 // SendConnectivityProbingPacket ends up calling
9302 // TestPacketWriter::WritePacket() which in turns receives and parses the
9303 // packet by calling framer_.ProcessPacket() -- which in turn calls
9304 // SimpleQuicFramer::OnPathChallengeFrame(). SimpleQuicFramer saves
9305 // the packet in writer_->path_challenge_frames()
9306 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9307 connection_.SendConnectivityProbingPacket(writer_.get(),
9308 connection_.peer_address());
9309 // Save the random contents of the challenge for later comparison to the
9310 // response.
nharper55fa6132019-05-07 19:37:21 -07009311 ASSERT_GE(writer_->path_challenge_frames().size(), 1u);
QUICHE teama6ef0a62019-03-07 20:34:33 -05009312 QuicPathFrameBuffer challenge_data =
9313 writer_->path_challenge_frames().front().data_buffer;
9314
9315 // Normally, QuicConnection::OnPathChallengeFrame and OnPaddingFrame would be
9316 // called and it will perform actions to ensure that the rest of the protocol
9317 // is performed (specifically, call UpdatePacketContent to say that this is a
9318 // path challenge so that when QuicConnection::OnPacketComplete is called
9319 // (again, out of the framer), the response is generated). Simulate those
9320 // calls so that the right internal state is set up for generating
9321 // the response.
9322 EXPECT_TRUE(connection_.OnPathChallengeFrame(
9323 writer_->path_challenge_frames().front()));
9324 EXPECT_TRUE(connection_.OnPaddingFrame(writer_->padding_frames().front()));
9325 // Cause the response to be created and sent. Result is that the response
9326 // should be stashed in writer's path_response_frames.
9327 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9328 connection_.SendConnectivityProbingResponsePacket(connection_.peer_address());
9329
9330 // The final check is to ensure that the random data in the response matches
9331 // the random data from the challenge.
9332 EXPECT_EQ(0, memcmp(&challenge_data,
9333 &(writer_->path_response_frames().front().data_buffer),
9334 sizeof(challenge_data)));
9335}
9336
9337// Regression test for b/110259444
9338TEST_P(QuicConnectionTest, DoNotScheduleSpuriousAckAlarm) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05009339 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9340 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
9341 writer_->SetWriteBlocked();
9342
9343 ProcessPacket(1);
9344 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
9345 // Verify ack alarm is set.
9346 EXPECT_TRUE(ack_alarm->IsSet());
9347 // Fire the ack alarm, verify no packet is sent because the writer is blocked.
9348 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9349 connection_.GetAckAlarm()->Fire();
9350
9351 writer_->SetWritable();
9352 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9353 ProcessPacket(2);
9354 // Verify ack alarm is not set.
9355 EXPECT_FALSE(ack_alarm->IsSet());
9356}
9357
9358TEST_P(QuicConnectionTest, DisablePacingOffloadConnectionOptions) {
9359 EXPECT_FALSE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
9360 writer_->set_supports_release_time(true);
9361 QuicConfig config;
9362 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9363 connection_.SetFromConfig(config);
9364 EXPECT_TRUE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
9365
9366 QuicTagVector connection_options;
9367 connection_options.push_back(kNPCO);
9368 config.SetConnectionOptionsToSend(connection_options);
9369 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9370 connection_.SetFromConfig(config);
9371 // Verify pacing offload is disabled.
9372 EXPECT_FALSE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
9373}
9374
9375// Regression test for b/110259444
9376// Get a path response without having issued a path challenge...
9377TEST_P(QuicConnectionTest, OrphanPathResponse) {
9378 QuicPathFrameBuffer data = {{0, 1, 2, 3, 4, 5, 6, 7}};
9379
9380 QuicPathResponseFrame frame(99, data);
9381 EXPECT_TRUE(connection_.OnPathResponseFrame(frame));
9382 // If PATH_RESPONSE was accepted (payload matches the payload saved
9383 // in QuicConnection::transmitted_connectivity_probe_payload_) then
9384 // current_packet_content_ would be set to FIRST_FRAME_IS_PING.
9385 // Since this PATH_RESPONSE does not match, current_packet_content_
9386 // must not be FIRST_FRAME_IS_PING.
9387 EXPECT_NE(QuicConnection::FIRST_FRAME_IS_PING,
9388 QuicConnectionPeer::GetCurrentPacketContent(&connection_));
9389}
9390
9391// Regression test for b/120791670
9392TEST_P(QuicConnectionTest, StopProcessingGQuicPacketInIetfQuicConnection) {
9393 // This test mimics a problematic scenario where an IETF QUIC connection
9394 // receives a Google QUIC packet and continue processing it using Google QUIC
9395 // wire format.
fayangd4291e42019-05-30 10:31:21 -07009396 if (!VersionHasIetfInvariantHeader(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05009397 return;
9398 }
9399 set_perspective(Perspective::IS_SERVER);
nharper46833c32019-05-15 21:33:05 -07009400 QuicFrame frame;
9401 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9402 frame = QuicFrame(&crypto_frame_);
9403 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
9404 } else {
9405 frame = QuicFrame(QuicStreamFrame(
9406 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
dmcardlecf0bfcf2019-12-13 08:08:21 -08009407 0u, quiche::QuicheStringPiece()));
nharper46833c32019-05-15 21:33:05 -07009408 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
9409 }
nharper46833c32019-05-15 21:33:05 -07009410 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05009411
9412 // Let connection process a Google QUIC packet.
9413 peer_framer_.set_version_for_tests(
9414 ParsedQuicVersion(PROTOCOL_QUIC_CRYPTO, QUIC_VERSION_43));
QUICHE team8c1daa22019-03-13 08:33:41 -07009415 std::unique_ptr<QuicPacket> packet(
QUICHE team6987b4a2019-03-15 16:23:04 -07009416 ConstructDataPacket(2, !kHasStopWaiting, ENCRYPTION_INITIAL));
dschinazi66dea072019-04-09 11:41:06 -07009417 char buffer[kMaxOutgoingPacketSize];
9418 size_t encrypted_length =
9419 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(2),
9420 *packet, buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05009421 // Make sure no stream frame is processed.
9422 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(0);
9423 connection_.ProcessUdpPacket(
9424 kSelfAddress, kPeerAddress,
9425 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
9426
9427 EXPECT_EQ(2u, connection_.GetStats().packets_received);
9428 EXPECT_EQ(1u, connection_.GetStats().packets_processed);
9429}
9430
9431TEST_P(QuicConnectionTest, AcceptPacketNumberZero) {
fkastenholz305e1732019-06-18 05:01:22 -07009432 if (!VersionHasIetfQuicFrames(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05009433 return;
9434 }
9435 // Set first_sending_packet_number to be 0 to allow successfully processing
9436 // acks which ack packet number 0.
9437 QuicFramerPeer::SetFirstSendingPacketNumber(writer_->framer()->framer(), 0);
9438 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9439
9440 ProcessPacket(0);
fayangc31c9952019-06-05 13:54:48 -07009441 EXPECT_EQ(QuicPacketNumber(0), LargestAcked(connection_.ack_frame()));
9442 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05009443
9444 ProcessPacket(1);
fayangc31c9952019-06-05 13:54:48 -07009445 EXPECT_EQ(QuicPacketNumber(1), LargestAcked(connection_.ack_frame()));
9446 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05009447
9448 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07009449 EXPECT_EQ(QuicPacketNumber(2), LargestAcked(connection_.ack_frame()));
9450 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05009451}
9452
QUICHE teamcd098022019-03-22 18:49:55 -07009453TEST_P(QuicConnectionTest, MultiplePacketNumberSpacesBasicSending) {
9454 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
9455 return;
9456 }
9457 use_tagging_decrypter();
9458 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07009459 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teamcd098022019-03-22 18:49:55 -07009460
9461 connection_.SendCryptoStreamData();
9462 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9463 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
9464 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
9465 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9466 QuicAckFrame frame1 = InitAckFrame(1);
9467 // Received ACK for packet 1.
9468 ProcessFramePacketAtLevel(30, QuicFrame(&frame1), ENCRYPTION_INITIAL);
9469
9470 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(4);
9471 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
9472 NO_FIN);
9473 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 4,
9474 NO_FIN);
9475 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
9476 8, NO_FIN);
9477 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
9478 12, FIN);
9479 // Received ACK for packets 2, 4, 5.
9480 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
9481 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
9482 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9483 QuicAckFrame frame2 =
9484 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)},
9485 {QuicPacketNumber(4), QuicPacketNumber(6)}});
9486 // Make sure although the same packet number is used, but they are in
9487 // different packet number spaces.
9488 ProcessFramePacketAtLevel(30, QuicFrame(&frame2), ENCRYPTION_FORWARD_SECURE);
9489}
9490
9491TEST_P(QuicConnectionTest, PeerAcksPacketsInWrongPacketNumberSpace) {
9492 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
9493 return;
9494 }
9495 use_tagging_decrypter();
9496 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07009497 std::make_unique<TaggingEncrypter>(0x01));
rch39c88ab2019-10-16 19:24:40 -07009498 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
9499 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teamcd098022019-03-22 18:49:55 -07009500
9501 connection_.SendCryptoStreamData();
9502 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9503 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
9504 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
9505 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9506 QuicAckFrame frame1 = InitAckFrame(1);
9507 // Received ACK for packet 1.
9508 ProcessFramePacketAtLevel(30, QuicFrame(&frame1), ENCRYPTION_INITIAL);
9509
9510 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
9511 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
9512 NO_FIN);
9513 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 4,
9514 NO_FIN);
9515
9516 // Received ACK for packets 2 and 3 in wrong packet number space.
9517 QuicAckFrame invalid_ack =
9518 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(4)}});
fkastenholz5d880a92019-06-21 09:01:56 -07009519 EXPECT_CALL(visitor_,
9520 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07009521 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teamcd098022019-03-22 18:49:55 -07009522 ProcessFramePacketAtLevel(300, QuicFrame(&invalid_ack), ENCRYPTION_INITIAL);
fkastenholz5d880a92019-06-21 09:01:56 -07009523 TestConnectionCloseQuicErrorCode(QUIC_INVALID_ACK_DATA);
QUICHE teamcd098022019-03-22 18:49:55 -07009524}
9525
9526TEST_P(QuicConnectionTest, MultiplePacketNumberSpacesBasicReceiving) {
9527 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
9528 return;
9529 }
9530 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
nharper46833c32019-05-15 21:33:05 -07009531 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9532 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9533 }
QUICHE teamcd098022019-03-22 18:49:55 -07009534 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
9535 use_tagging_decrypter();
9536 // Receives packet 1000 in initial data.
nharper46833c32019-05-15 21:33:05 -07009537 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
QUICHE teamcd098022019-03-22 18:49:55 -07009538 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
9539 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07009540 std::make_unique<TaggingEncrypter>(0x02));
zhongyi546cc452019-04-12 15:27:49 -07009541 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07009542 std::make_unique<StrictTaggingDecrypter>(0x02));
QUICHE teamcd098022019-03-22 18:49:55 -07009543 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07009544 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teamcd098022019-03-22 18:49:55 -07009545 // Receives packet 1000 in application data.
9546 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
9547 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
9548 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
9549 NO_FIN);
9550 // Verify application data ACK gets bundled with outgoing data.
9551 EXPECT_EQ(2u, writer_->frame_count());
9552 // Make sure ACK alarm is still set because initial data is not ACKed.
9553 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
9554 // Receive packet 1001 in application data.
9555 ProcessDataPacketAtLevel(1001, false, ENCRYPTION_ZERO_RTT);
9556 clock_.AdvanceTime(DefaultRetransmissionTime());
9557 // Simulates ACK alarm fires and verify two ACKs are flushed.
9558 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
9559 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07009560 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teamcd098022019-03-22 18:49:55 -07009561 connection_.GetAckAlarm()->Fire();
9562 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
9563 // Receives more packets in application data.
9564 ProcessDataPacketAtLevel(1002, false, ENCRYPTION_ZERO_RTT);
9565 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
9566
9567 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07009568 std::make_unique<TaggingEncrypter>(0x02));
zhongyi546cc452019-04-12 15:27:49 -07009569 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07009570 std::make_unique<StrictTaggingDecrypter>(0x02));
QUICHE teamcd098022019-03-22 18:49:55 -07009571 // Verify zero rtt and forward secure packets get acked in the same packet.
9572 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
nharper2c9f02a2019-05-08 10:25:50 -07009573 ProcessDataPacket(1003);
QUICHE teamcd098022019-03-22 18:49:55 -07009574 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
9575}
9576
QUICHE team552f71f2019-03-23 15:37:59 -07009577TEST_P(QuicConnectionTest, CancelAckAlarmOnWriteBlocked) {
9578 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
9579 return;
9580 }
9581 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
nharper46833c32019-05-15 21:33:05 -07009582 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9583 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9584 }
QUICHE team552f71f2019-03-23 15:37:59 -07009585 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
9586 use_tagging_decrypter();
9587 // Receives packet 1000 in initial data.
nharper46833c32019-05-15 21:33:05 -07009588 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
QUICHE team552f71f2019-03-23 15:37:59 -07009589 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
9590 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07009591 std::make_unique<TaggingEncrypter>(0x02));
zhongyi546cc452019-04-12 15:27:49 -07009592 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07009593 std::make_unique<StrictTaggingDecrypter>(0x02));
QUICHE team552f71f2019-03-23 15:37:59 -07009594 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07009595 std::make_unique<TaggingEncrypter>(0x02));
QUICHE team552f71f2019-03-23 15:37:59 -07009596 // Receives packet 1000 in application data.
9597 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
9598 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
9599
9600 writer_->SetWriteBlocked();
9601 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AnyNumber());
9602 // Simulates ACK alarm fires and verify no ACK is flushed because of write
9603 // blocked.
9604 clock_.AdvanceTime(DefaultDelayedAckTime());
9605 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9606 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07009607 std::make_unique<TaggingEncrypter>(0x02));
QUICHE team552f71f2019-03-23 15:37:59 -07009608 connection_.GetAckAlarm()->Fire();
9609 // Verify ACK alarm is not set.
9610 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
9611
9612 writer_->SetWritable();
9613 // Verify 2 ACKs are sent when connection gets unblocked.
9614 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
9615 connection_.OnCanWrite();
9616 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
9617}
9618
dschinazi346b7ce2019-06-05 01:38:18 -07009619// Make sure a packet received with the right client connection ID is processed.
9620TEST_P(QuicConnectionTest, ValidClientConnectionId) {
dschinazi346b7ce2019-06-05 01:38:18 -07009621 if (!framer_.version().SupportsClientConnectionIds()) {
9622 return;
9623 }
9624 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9625 connection_.set_client_connection_id(TestConnectionId(0x33));
9626 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_FORWARD_SECURE);
9627 header.destination_connection_id = TestConnectionId(0x33);
9628 header.destination_connection_id_included = CONNECTION_ID_PRESENT;
9629 header.source_connection_id_included = CONNECTION_ID_ABSENT;
9630 QuicFrames frames;
9631 QuicPingFrame ping_frame;
9632 QuicPaddingFrame padding_frame;
9633 frames.push_back(QuicFrame(ping_frame));
9634 frames.push_back(QuicFrame(padding_frame));
9635 std::unique_ptr<QuicPacket> packet =
9636 BuildUnsizedDataPacket(&framer_, header, frames);
9637 char buffer[kMaxOutgoingPacketSize];
9638 size_t encrypted_length = peer_framer_.EncryptPayload(
9639 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
9640 kMaxOutgoingPacketSize);
9641 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9642 false);
9643 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9644 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9645 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9646}
9647
9648// Make sure a packet received with a different client connection ID is dropped.
9649TEST_P(QuicConnectionTest, InvalidClientConnectionId) {
dschinazi346b7ce2019-06-05 01:38:18 -07009650 if (!framer_.version().SupportsClientConnectionIds()) {
9651 return;
9652 }
9653 connection_.set_client_connection_id(TestConnectionId(0x33));
9654 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_FORWARD_SECURE);
9655 header.destination_connection_id = TestConnectionId(0xbad);
9656 header.destination_connection_id_included = CONNECTION_ID_PRESENT;
9657 header.source_connection_id_included = CONNECTION_ID_ABSENT;
9658 QuicFrames frames;
9659 QuicPingFrame ping_frame;
9660 QuicPaddingFrame padding_frame;
9661 frames.push_back(QuicFrame(ping_frame));
9662 frames.push_back(QuicFrame(padding_frame));
9663 std::unique_ptr<QuicPacket> packet =
9664 BuildUnsizedDataPacket(&framer_, header, frames);
9665 char buffer[kMaxOutgoingPacketSize];
9666 size_t encrypted_length = peer_framer_.EncryptPayload(
9667 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
9668 kMaxOutgoingPacketSize);
9669 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9670 false);
9671 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9672 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9673 EXPECT_EQ(1u, connection_.GetStats().packets_dropped);
9674}
9675
9676// Make sure the first packet received with a different client connection ID on
9677// the server is processed and it changes the client connection ID.
9678TEST_P(QuicConnectionTest, UpdateClientConnectionIdFromFirstPacket) {
dschinazi346b7ce2019-06-05 01:38:18 -07009679 if (!framer_.version().SupportsClientConnectionIds()) {
9680 return;
9681 }
dschinazi346b7ce2019-06-05 01:38:18 -07009682 set_perspective(Perspective::IS_SERVER);
9683 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_INITIAL);
9684 header.source_connection_id = TestConnectionId(0x33);
9685 header.source_connection_id_included = CONNECTION_ID_PRESENT;
9686 QuicFrames frames;
9687 QuicPingFrame ping_frame;
9688 QuicPaddingFrame padding_frame;
9689 frames.push_back(QuicFrame(ping_frame));
9690 frames.push_back(QuicFrame(padding_frame));
9691 std::unique_ptr<QuicPacket> packet =
9692 BuildUnsizedDataPacket(&framer_, header, frames);
9693 char buffer[kMaxOutgoingPacketSize];
nharperc6b99512019-09-19 11:13:48 -07009694 size_t encrypted_length =
9695 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(1),
9696 *packet, buffer, kMaxOutgoingPacketSize);
dschinazi346b7ce2019-06-05 01:38:18 -07009697 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9698 false);
9699 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9700 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9701 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9702 EXPECT_EQ(TestConnectionId(0x33), connection_.client_connection_id());
9703}
9704
fayang40ec3ac2019-06-05 09:07:54 -07009705// Regression test for b/134416344.
9706TEST_P(QuicConnectionTest, CheckConnectedBeforeFlush) {
9707 // This test mimics a scenario where a connection processes 2 packets and the
9708 // 2nd packet contains connection close frame. When the 2nd flusher goes out
9709 // of scope, a delayed ACK is pending, and ACK alarm should not be scheduled
9710 // because connection is disconnected.
9711 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fkastenholz5d880a92019-06-21 09:01:56 -07009712 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
fayang40ec3ac2019-06-05 09:07:54 -07009713 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
fkastenholz88d08f42019-09-06 07:38:04 -07009714 const QuicErrorCode kErrorCode = QUIC_INTERNAL_ERROR;
fayang40ec3ac2019-06-05 09:07:54 -07009715 std::unique_ptr<QuicConnectionCloseFrame> connection_close_frame(
fkastenholz591814c2019-09-06 12:11:46 -07009716 new QuicConnectionCloseFrame(connection_.transport_version(), kErrorCode,
9717 "",
9718 /*transport_close_frame_type=*/0));
9719
fayang40ec3ac2019-06-05 09:07:54 -07009720 // Received 2 packets.
9721 QuicFrame frame;
9722 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9723 frame = QuicFrame(&crypto_frame_);
9724 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9725 } else {
9726 frame = QuicFrame(QuicStreamFrame(
9727 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
dmcardlecf0bfcf2019-12-13 08:08:21 -08009728 0u, quiche::QuicheStringPiece()));
fayang40ec3ac2019-06-05 09:07:54 -07009729 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
9730 }
9731 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
9732 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
9733 EXPECT_TRUE(ack_alarm->IsSet());
9734 ProcessFramePacketWithAddresses(QuicFrame(connection_close_frame.get()),
9735 kSelfAddress, kPeerAddress);
fayang0f0c4e62019-07-16 08:55:54 -07009736 // Verify ack alarm is not set.
9737 EXPECT_FALSE(ack_alarm->IsSet());
fayang40ec3ac2019-06-05 09:07:54 -07009738}
9739
dschinazi8d551132019-08-02 19:17:16 -07009740// Verify that a packet containing three coalesced packets is parsed correctly.
9741TEST_P(QuicConnectionTest, CoalescedPacket) {
9742 if (!QuicVersionHasLongHeaderLengths(connection_.transport_version())) {
9743 // Coalesced packets can only be encoded using long header lengths.
9744 return;
9745 }
9746 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9747 EXPECT_TRUE(connection_.connected());
9748 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9749 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(3);
9750 } else {
9751 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(3);
9752 }
9753
9754 uint64_t packet_numbers[3] = {1, 2, 3};
9755 EncryptionLevel encryption_levels[3] = {
9756 ENCRYPTION_INITIAL, ENCRYPTION_INITIAL, ENCRYPTION_FORWARD_SECURE};
9757 char buffer[kMaxOutgoingPacketSize] = {};
9758 size_t total_encrypted_length = 0;
9759 for (int i = 0; i < 3; i++) {
9760 QuicPacketHeader header =
9761 ConstructPacketHeader(packet_numbers[i], encryption_levels[i]);
9762 QuicFrames frames;
9763 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9764 frames.push_back(QuicFrame(&crypto_frame_));
9765 } else {
9766 frames.push_back(QuicFrame(frame1_));
9767 }
9768 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
9769 peer_creator_.set_encryption_level(encryption_levels[i]);
9770 size_t encrypted_length = peer_framer_.EncryptPayload(
9771 encryption_levels[i], QuicPacketNumber(packet_numbers[i]), *packet,
9772 buffer + total_encrypted_length,
9773 sizeof(buffer) - total_encrypted_length);
9774 EXPECT_GT(encrypted_length, 0u);
9775 total_encrypted_length += encrypted_length;
9776 }
9777 connection_.ProcessUdpPacket(
9778 kSelfAddress, kPeerAddress,
9779 QuicReceivedPacket(buffer, total_encrypted_length, clock_.Now(), false));
9780 if (connection_.GetSendAlarm()->IsSet()) {
9781 connection_.GetSendAlarm()->Fire();
9782 }
9783
9784 EXPECT_TRUE(connection_.connected());
9785}
9786
dschinazi66fc0242019-08-16 10:00:25 -07009787// Regression test for crbug.com/992831.
9788TEST_P(QuicConnectionTest, CoalescedPacketThatSavesFrames) {
9789 if (!QuicVersionHasLongHeaderLengths(connection_.transport_version())) {
9790 // Coalesced packets can only be encoded using long header lengths.
9791 return;
9792 }
9793 if (connection_.SupportsMultiplePacketNumberSpaces()) {
9794 // TODO(b/129151114) Enable this test with multiple packet number spaces.
9795 return;
9796 }
9797 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9798 EXPECT_TRUE(connection_.connected());
9799 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9800 EXPECT_CALL(visitor_, OnCryptoFrame(_))
9801 .Times(3)
9802 .WillRepeatedly([this](const QuicCryptoFrame& /*frame*/) {
9803 // QuicFrame takes ownership of the QuicBlockedFrame.
9804 connection_.SendControlFrame(QuicFrame(new QuicBlockedFrame(1, 3)));
9805 });
9806 } else {
9807 EXPECT_CALL(visitor_, OnStreamFrame(_))
9808 .Times(3)
9809 .WillRepeatedly([this](const QuicStreamFrame& /*frame*/) {
9810 // QuicFrame takes ownership of the QuicBlockedFrame.
9811 connection_.SendControlFrame(QuicFrame(new QuicBlockedFrame(1, 3)));
9812 });
9813 }
9814
9815 uint64_t packet_numbers[3] = {1, 2, 3};
9816 EncryptionLevel encryption_levels[3] = {
9817 ENCRYPTION_INITIAL, ENCRYPTION_INITIAL, ENCRYPTION_FORWARD_SECURE};
9818 char buffer[kMaxOutgoingPacketSize] = {};
9819 size_t total_encrypted_length = 0;
9820 for (int i = 0; i < 3; i++) {
9821 QuicPacketHeader header =
9822 ConstructPacketHeader(packet_numbers[i], encryption_levels[i]);
9823 QuicFrames frames;
9824 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9825 frames.push_back(QuicFrame(&crypto_frame_));
9826 } else {
9827 frames.push_back(QuicFrame(frame1_));
9828 }
9829 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
9830 peer_creator_.set_encryption_level(encryption_levels[i]);
9831 size_t encrypted_length = peer_framer_.EncryptPayload(
9832 encryption_levels[i], QuicPacketNumber(packet_numbers[i]), *packet,
9833 buffer + total_encrypted_length,
9834 sizeof(buffer) - total_encrypted_length);
9835 EXPECT_GT(encrypted_length, 0u);
9836 total_encrypted_length += encrypted_length;
9837 }
9838 connection_.ProcessUdpPacket(
9839 kSelfAddress, kPeerAddress,
9840 QuicReceivedPacket(buffer, total_encrypted_length, clock_.Now(), false));
9841 if (connection_.GetSendAlarm()->IsSet()) {
9842 connection_.GetSendAlarm()->Fire();
9843 }
9844
9845 EXPECT_TRUE(connection_.connected());
9846
9847 SendAckPacketToPeer();
9848}
9849
fayangd3016832019-08-08 07:24:45 -07009850// Regresstion test for b/138962304.
9851TEST_P(QuicConnectionTest, RtoAndWriteBlocked) {
fayangd3016832019-08-08 07:24:45 -07009852 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9853
9854 QuicStreamId stream_id = 2;
9855 QuicPacketNumber last_data_packet;
9856 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
9857 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9858
9859 // Writer gets blocked.
9860 writer_->SetWriteBlocked();
9861
9862 // Cancel the stream.
9863 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9864 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
fayang67f82272019-08-14 16:08:45 -07009865 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
9866 .WillRepeatedly(
9867 Invoke(&notifier_, &SimpleSessionNotifier::WillingToWrite));
fayangd3016832019-08-08 07:24:45 -07009868 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9869
9870 // Retransmission timer fires in RTO mode.
9871 connection_.GetRetransmissionAlarm()->Fire();
9872 // Verify no packets get flushed when writer is blocked.
9873 EXPECT_EQ(0u, connection_.NumQueuedPackets());
9874}
9875
9876// Regresstion test for b/138962304.
9877TEST_P(QuicConnectionTest, TlpAndWriteBlocked) {
fayangd3016832019-08-08 07:24:45 -07009878 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9879 connection_.SetMaxTailLossProbes(1);
9880
9881 QuicStreamId stream_id = 2;
9882 QuicPacketNumber last_data_packet;
9883 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
9884 SendStreamDataToPeer(4, "foo", 0, NO_FIN, &last_data_packet);
9885 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9886
9887 // Writer gets blocked.
9888 writer_->SetWriteBlocked();
9889
9890 // Cancel stream 2.
9891 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9892 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
9893 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9894
fayange62e63c2019-12-04 07:16:25 -08009895 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
fayangd3016832019-08-08 07:24:45 -07009896 // Retransmission timer fires in TLP mode.
9897 connection_.GetRetransmissionAlarm()->Fire();
9898 // Verify one packets is forced flushed when writer is blocked.
9899 EXPECT_EQ(1u, connection_.NumQueuedPackets());
9900}
9901
fayang67f82272019-08-14 16:08:45 -07009902// Regresstion test for b/139375344.
9903TEST_P(QuicConnectionTest, RtoForcesSendingPing) {
fayangcff885a2019-10-22 07:39:04 -07009904 if (connection_.PtoEnabled()) {
fayang67f82272019-08-14 16:08:45 -07009905 return;
9906 }
9907 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9908 connection_.SetMaxTailLossProbes(2);
9909 EXPECT_EQ(0u, connection_.GetStats().tlp_count);
9910 EXPECT_EQ(0u, connection_.GetStats().rto_count);
9911
9912 SendStreamDataToPeer(2, "foo", 0, NO_FIN, nullptr);
9913 QuicTime retransmission_time =
9914 connection_.GetRetransmissionAlarm()->deadline();
9915 EXPECT_NE(QuicTime::Zero(), retransmission_time);
9916 // TLP fires.
9917 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
9918 clock_.AdvanceTime(retransmission_time - clock_.Now());
9919 connection_.GetRetransmissionAlarm()->Fire();
9920 EXPECT_EQ(1u, connection_.GetStats().tlp_count);
9921 EXPECT_EQ(0u, connection_.GetStats().rto_count);
9922 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9923
9924 // Packet 1 gets acked.
9925 QuicAckFrame frame = InitAckFrame(1);
9926 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
9927 ProcessAckPacket(1, &frame);
9928 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9929 retransmission_time = connection_.GetRetransmissionAlarm()->deadline();
9930
9931 // RTO fires, verify a PING packet gets sent because there is no data to send.
9932 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(3), _, _));
9933 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
9934 clock_.AdvanceTime(retransmission_time - clock_.Now());
9935 connection_.GetRetransmissionAlarm()->Fire();
9936 EXPECT_EQ(1u, connection_.GetStats().tlp_count);
9937 EXPECT_EQ(1u, connection_.GetStats().rto_count);
9938 EXPECT_EQ(1u, writer_->ping_frames().size());
9939}
9940
fayangce0a3162019-08-15 09:05:36 -07009941TEST_P(QuicConnectionTest, ProbeTimeout) {
fayangce0a3162019-08-15 09:05:36 -07009942 QuicConfig config;
9943 QuicTagVector connection_options;
9944 connection_options.push_back(k2PTO);
9945 config.SetConnectionOptionsToSend(connection_options);
9946 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9947 connection_.SetFromConfig(config);
9948 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9949
9950 QuicStreamId stream_id = 2;
9951 QuicPacketNumber last_packet;
9952 SendStreamDataToPeer(stream_id, "foooooo", 0, NO_FIN, &last_packet);
9953 SendStreamDataToPeer(stream_id, "foooooo", 7, NO_FIN, &last_packet);
9954 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9955
9956 // Reset stream.
9957 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9958 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9959
9960 // Fire the PTO and verify only the RST_STREAM is resent, not stream data.
9961 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9962 connection_.GetRetransmissionAlarm()->Fire();
9963 EXPECT_EQ(0u, writer_->stream_frames().size());
9964 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
9965 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9966}
9967
fayang97ce41e2019-10-07 08:37:29 -07009968TEST_P(QuicConnectionTest, CloseConnectionAfter6ClientPTOs) {
fayang97ce41e2019-10-07 08:37:29 -07009969 QuicConfig config;
9970 QuicTagVector connection_options;
9971 connection_options.push_back(k1PTO);
9972 connection_options.push_back(k6PTO);
9973 config.SetConnectionOptionsToSend(connection_options);
dschinazif7c6a912020-05-05 11:39:53 -07009974 QuicConfigPeer::SetNegotiated(&config, true);
fayang97ce41e2019-10-07 08:37:29 -07009975 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9976 connection_.SetFromConfig(config);
9977 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9978
9979 // Send stream data.
9980 SendStreamDataToPeer(
9981 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
9982 0, FIN, nullptr);
9983
9984 // 5PTO + 1 connection close.
rch39c88ab2019-10-16 19:24:40 -07009985 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(6));
fayang97ce41e2019-10-07 08:37:29 -07009986
9987 // Fire the retransmission alarm 5 times.
9988 for (int i = 0; i < 5; ++i) {
9989 connection_.GetRetransmissionAlarm()->Fire();
9990 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
9991 EXPECT_TRUE(connection_.connected());
9992 }
fayangb59c6f12020-03-23 15:06:14 -07009993 if (GetQuicReloadableFlag(quic_use_blackhole_detector)) {
9994 EXPECT_CALL(visitor_, OnPathDegrading());
9995 connection_.PathDegradingTimeout();
9996 }
fayang97ce41e2019-10-07 08:37:29 -07009997
9998 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveTlpCount());
9999 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveRtoCount());
10000 EXPECT_EQ(5u, connection_.sent_packet_manager().GetConsecutivePtoCount());
10001 // Closes connection on 6th PTO.
10002 EXPECT_CALL(visitor_,
10003 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
fayangb59c6f12020-03-23 15:06:14 -070010004 if (GetQuicReloadableFlag(quic_use_blackhole_detector)) {
10005 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
10006 connection_.GetBlackholeDetectorAlarm()->Fire();
10007 } else {
10008 connection_.GetRetransmissionAlarm()->Fire();
10009 }
fayang97ce41e2019-10-07 08:37:29 -070010010 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
10011 EXPECT_FALSE(connection_.connected());
10012 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
10013}
10014
fayangce0a3162019-08-15 09:05:36 -070010015TEST_P(QuicConnectionTest, CloseConnectionAfter7ClientPTOs) {
fayangce0a3162019-08-15 09:05:36 -070010016 QuicConfig config;
10017 QuicTagVector connection_options;
10018 connection_options.push_back(k2PTO);
10019 connection_options.push_back(k7PTO);
10020 config.SetConnectionOptionsToSend(connection_options);
dschinazif7c6a912020-05-05 11:39:53 -070010021 QuicConfigPeer::SetNegotiated(&config, true);
fayangce0a3162019-08-15 09:05:36 -070010022 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10023 connection_.SetFromConfig(config);
10024 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
10025
10026 // Send stream data.
10027 SendStreamDataToPeer(
10028 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
10029 0, FIN, nullptr);
10030
10031 // Fire the retransmission alarm 6 times.
10032 for (int i = 0; i < 6; ++i) {
10033 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
10034 connection_.GetRetransmissionAlarm()->Fire();
10035 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
10036 EXPECT_TRUE(connection_.connected());
10037 }
fayangb59c6f12020-03-23 15:06:14 -070010038 if (GetQuicReloadableFlag(quic_use_blackhole_detector)) {
10039 EXPECT_CALL(visitor_, OnPathDegrading());
10040 connection_.PathDegradingTimeout();
10041 }
fayangce0a3162019-08-15 09:05:36 -070010042
10043 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveTlpCount());
10044 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveRtoCount());
10045 EXPECT_EQ(6u, connection_.sent_packet_manager().GetConsecutivePtoCount());
10046 // Closes connection on 7th PTO.
10047 EXPECT_CALL(visitor_,
10048 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -070010049 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
fayangb59c6f12020-03-23 15:06:14 -070010050 if (GetQuicReloadableFlag(quic_use_blackhole_detector)) {
10051 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
10052 connection_.GetBlackholeDetectorAlarm()->Fire();
10053 } else {
10054 connection_.GetRetransmissionAlarm()->Fire();
10055 }
fayangce0a3162019-08-15 09:05:36 -070010056 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
10057 EXPECT_FALSE(connection_.connected());
10058 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
10059}
10060
10061TEST_P(QuicConnectionTest, CloseConnectionAfter8ClientPTOs) {
fayangce0a3162019-08-15 09:05:36 -070010062 QuicConfig config;
10063 QuicTagVector connection_options;
10064 connection_options.push_back(k2PTO);
10065 connection_options.push_back(k8PTO);
dschinazif7c6a912020-05-05 11:39:53 -070010066 QuicConfigPeer::SetNegotiated(&config, true);
fayangce0a3162019-08-15 09:05:36 -070010067 config.SetConnectionOptionsToSend(connection_options);
10068 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10069 connection_.SetFromConfig(config);
10070 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
10071
10072 // Send stream data.
10073 SendStreamDataToPeer(
10074 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
10075 0, FIN, nullptr);
10076
10077 // Fire the retransmission alarm 7 times.
10078 for (int i = 0; i < 7; ++i) {
10079 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
10080 connection_.GetRetransmissionAlarm()->Fire();
10081 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
10082 EXPECT_TRUE(connection_.connected());
10083 }
fayangb59c6f12020-03-23 15:06:14 -070010084 if (GetQuicReloadableFlag(quic_use_blackhole_detector)) {
10085 EXPECT_CALL(visitor_, OnPathDegrading());
10086 connection_.PathDegradingTimeout();
10087 }
fayangce0a3162019-08-15 09:05:36 -070010088
10089 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveTlpCount());
10090 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveRtoCount());
10091 EXPECT_EQ(7u, connection_.sent_packet_manager().GetConsecutivePtoCount());
10092 // Closes connection on 8th PTO.
10093 EXPECT_CALL(visitor_,
10094 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -070010095 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
fayangb59c6f12020-03-23 15:06:14 -070010096 if (GetQuicReloadableFlag(quic_use_blackhole_detector)) {
10097 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
10098 connection_.GetBlackholeDetectorAlarm()->Fire();
10099 } else {
10100 connection_.GetRetransmissionAlarm()->Fire();
10101 }
fayangce0a3162019-08-15 09:05:36 -070010102 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
10103 EXPECT_FALSE(connection_.connected());
10104 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
10105}
10106
fayang5f135052019-08-22 17:59:40 -070010107TEST_P(QuicConnectionTest, DeprecateHandshakeMode) {
10108 if (!connection_.version().SupportsAntiAmplificationLimit()) {
10109 return;
10110 }
10111 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10112 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
10113
10114 // Send CHLO.
10115 connection_.SendCryptoStreamData();
10116 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
10117
10118 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
10119 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
10120 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
10121 QuicAckFrame frame1 = InitAckFrame(1);
10122 // Received ACK for packet 1.
10123 ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL);
10124
10125 // Verify retransmission alarm is still set because handshake is not
10126 // confirmed although there is nothing in flight.
10127 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
10128 EXPECT_EQ(0u, connection_.GetStats().pto_count);
10129 EXPECT_EQ(0u, connection_.GetStats().crypto_retransmit_count);
10130
10131 // PTO fires, verify a PING packet gets sent because there is no data to send.
fayang1c2d1ab2020-03-11 12:08:41 -070010132 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(3), _, _));
fayang5f135052019-08-22 17:59:40 -070010133 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
10134 connection_.GetRetransmissionAlarm()->Fire();
10135 EXPECT_EQ(1u, connection_.GetStats().pto_count);
10136 EXPECT_EQ(0u, connection_.GetStats().crypto_retransmit_count);
10137 EXPECT_EQ(1u, writer_->ping_frames().size());
10138}
10139
10140TEST_P(QuicConnectionTest, AntiAmplificationLimit) {
10141 if (!connection_.version().SupportsAntiAmplificationLimit()) {
10142 return;
10143 }
fayang5f135052019-08-22 17:59:40 -070010144 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10145
10146 set_perspective(Perspective::IS_SERVER);
10147 // Verify no data can be sent at the beginning because bytes received is 0.
10148 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
10149 connection_.SendCryptoDataWithString("foo", 0);
10150 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
10151
10152 // Receives packet 1.
10153 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
10154
10155 const size_t anti_amplification_factor =
10156 GetQuicFlag(FLAGS_quic_anti_amplification_factor);
10157 // Verify now packets can be sent.
10158 for (size_t i = 0; i < anti_amplification_factor; ++i) {
10159 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10160 connection_.SendCryptoDataWithString("foo", i * 3);
10161 // Verify retransmission alarm is not set if throttled by anti-amplification
10162 // limit.
10163 EXPECT_EQ(i != anti_amplification_factor - 1,
10164 connection_.GetRetransmissionAlarm()->IsSet());
10165 }
10166 // Verify server is throttled by anti-amplification limit.
10167 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
10168 connection_.SendCryptoDataWithString("foo", anti_amplification_factor * 3);
10169
10170 // Receives packet 2.
10171 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
10172 // Verify more packets can be sent.
10173 for (size_t i = anti_amplification_factor; i < anti_amplification_factor * 2;
10174 ++i) {
10175 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10176 connection_.SendCryptoDataWithString("foo", i * 3);
10177 }
10178 // Verify server is throttled by anti-amplification limit.
10179 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
10180 connection_.SendCryptoDataWithString("foo",
10181 2 * anti_amplification_factor * 3);
10182
10183 ProcessPacket(3);
10184 // Verify anti-amplification limit is gone after address validation.
10185 for (size_t i = 0; i < 100; ++i) {
10186 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10187 connection_.SendStreamDataWithString(3, "first", i * 0, NO_FIN);
10188 }
10189}
10190
fkastenholza3660102019-08-28 05:19:24 -070010191TEST_P(QuicConnectionTest, ConnectionCloseFrameType) {
10192 if (!VersionHasIetfQuicFrames(version().transport_version)) {
10193 // Test relevent only for IETF QUIC.
10194 return;
10195 }
10196 const QuicErrorCode kQuicErrorCode = IETF_QUIC_PROTOCOL_VIOLATION;
10197 // Use the (unknown) frame type of 9999 to avoid triggering any logic
10198 // which might be associated with the processing of a known frame type.
10199 const uint64_t kTransportCloseFrameType = 9999u;
10200 QuicFramerPeer::set_current_received_frame_type(
10201 QuicConnectionPeer::GetFramer(&connection_), kTransportCloseFrameType);
10202 // Do a transport connection close
10203 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10204 connection_.CloseConnection(
10205 kQuicErrorCode, "Some random error message",
10206 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10207 const std::vector<QuicConnectionCloseFrame>& connection_close_frames =
10208 writer_->connection_close_frames();
10209 ASSERT_EQ(1u, connection_close_frames.size());
10210 EXPECT_EQ(IETF_QUIC_TRANSPORT_CONNECTION_CLOSE,
10211 connection_close_frames[0].close_type);
bnc77e77b82020-04-05 10:36:49 -070010212 EXPECT_EQ(kQuicErrorCode, connection_close_frames[0].quic_error_code);
fkastenholza3660102019-08-28 05:19:24 -070010213 EXPECT_EQ(kTransportCloseFrameType,
10214 connection_close_frames[0].transport_close_frame_type);
10215}
10216
fayang0fcbf352019-08-30 11:15:58 -070010217// Regression test for b/137401387 and b/138962304.
10218TEST_P(QuicConnectionTest, RtoPacketAsTwo) {
fayangcff885a2019-10-22 07:39:04 -070010219 if (connection_.PtoEnabled()) {
fayang0fcbf352019-08-30 11:15:58 -070010220 return;
10221 }
10222 connection_.SetMaxTailLossProbes(1);
10223 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10224 std::string stream_data(3000, 's');
10225 // Send packets 1 - 66 and exhaust cwnd.
10226 for (size_t i = 0; i < 22; ++i) {
10227 // 3 packets for each stream, the first 2 are guaranteed to be full packets.
10228 SendStreamDataToPeer(i + 2, stream_data, 0, FIN, nullptr);
10229 }
10230 CongestionBlockWrites();
10231
10232 // Fires TLP. Please note, this tail loss probe has 1 byte less stream data
10233 // compared to packet 1 because packet number length increases.
10234 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(67), _, _));
10235 connection_.GetRetransmissionAlarm()->Fire();
10236 // Fires RTO. Please note, although packets 2 and 3 *should* be RTOed, but
10237 // packet 2 gets RTOed to two packets because packet number length increases.
10238 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(68), _, _));
10239 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(69), _, _));
10240 connection_.GetRetransmissionAlarm()->Fire();
10241
10242 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10243 // Resets all streams except 2 and ack packets 1 and 2. Now, packet 3 is the
10244 // only one containing retransmittable frames.
10245 for (size_t i = 1; i < 22; ++i) {
10246 notifier_.OnStreamReset(i + 2, QUIC_STREAM_CANCELLED);
10247 }
10248 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
10249 QuicAckFrame frame =
10250 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(3)}});
10251 ProcessAckPacket(1, &frame);
10252 CongestionUnblockWrites();
10253
10254 // Fires TLP, verify a PING gets sent because packet 3 is marked
10255 // RTO_RETRANSMITTED.
10256 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(70), _, _));
10257 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
10258 connection_.GetRetransmissionAlarm()->Fire();
10259}
10260
fayang4c1c2362019-09-13 07:20:01 -070010261TEST_P(QuicConnectionTest, PtoSkipsPacketNumber) {
fayang4c1c2362019-09-13 07:20:01 -070010262 QuicConfig config;
10263 QuicTagVector connection_options;
10264 connection_options.push_back(k1PTO);
10265 connection_options.push_back(kPTOS);
10266 config.SetConnectionOptionsToSend(connection_options);
10267 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10268 connection_.SetFromConfig(config);
10269 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
10270
10271 QuicStreamId stream_id = 2;
10272 QuicPacketNumber last_packet;
10273 SendStreamDataToPeer(stream_id, "foooooo", 0, NO_FIN, &last_packet);
10274 SendStreamDataToPeer(stream_id, "foooooo", 7, NO_FIN, &last_packet);
10275 EXPECT_EQ(QuicPacketNumber(2), last_packet);
10276 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
10277
10278 // Fire PTO and verify the PTO retransmission skips one packet number.
10279 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10280 connection_.GetRetransmissionAlarm()->Fire();
10281 EXPECT_EQ(1u, writer_->stream_frames().size());
10282 EXPECT_EQ(QuicPacketNumber(4), writer_->last_packet_header().packet_number);
10283 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
10284}
10285
fayang58f71072019-11-05 08:47:02 -080010286TEST_P(QuicConnectionTest, SendCoalescedPackets) {
10287 if (!connection_.version().CanSendCoalescedPackets()) {
10288 return;
10289 }
fayang6100ab72020-03-18 13:16:25 -070010290 MockQuicConnectionDebugVisitor debug_visitor;
10291 connection_.set_debug_visitor(&debug_visitor);
10292 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(3);
10293 EXPECT_CALL(debug_visitor, OnCoalescedPacketSent(_, _)).Times(1);
fayang44ae4e92020-04-28 13:09:42 -070010294 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
fayang58f71072019-11-05 08:47:02 -080010295 {
10296 QuicConnection::ScopedPacketFlusher flusher(&connection_);
10297 use_tagging_decrypter();
10298 connection_.SetEncrypter(ENCRYPTION_INITIAL,
10299 std::make_unique<TaggingEncrypter>(0x01));
10300 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10301 connection_.SendCryptoDataWithString("foo", 0);
10302 // Verify this packet is on hold.
10303 EXPECT_EQ(0u, writer_->packets_write_attempts());
10304
10305 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10306 std::make_unique<TaggingEncrypter>(0x02));
10307 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10308 connection_.SendCryptoDataWithString("bar", 3);
10309 EXPECT_EQ(0u, writer_->packets_write_attempts());
10310
10311 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
10312 std::make_unique<TaggingEncrypter>(0x03));
10313 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10314 SendStreamDataToPeer(2, "baz", 3, NO_FIN, nullptr);
10315 }
10316 // Verify all 3 packets are coalesced in the same UDP datagram.
10317 EXPECT_EQ(1u, writer_->packets_write_attempts());
10318 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
10319 // Verify the packet is padded to full.
10320 EXPECT_EQ(connection_.max_packet_length(), writer_->last_packet_size());
10321
10322 // Verify packet process.
10323 EXPECT_EQ(1u, writer_->crypto_frames().size());
10324 EXPECT_EQ(0u, writer_->stream_frames().size());
10325 // Verify there is coalesced packet.
10326 EXPECT_NE(nullptr, writer_->coalesced_packet());
10327}
10328
fayang01062942020-01-22 07:23:23 -080010329TEST_P(QuicConnectionTest, ClientReceivedHandshakeDone) {
10330 if (!connection_.version().HasHandshakeDone()) {
10331 return;
10332 }
10333 EXPECT_CALL(visitor_, OnHandshakeDoneReceived());
10334 QuicFrames frames;
10335 frames.push_back(QuicFrame(QuicHandshakeDoneFrame()));
10336 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10337 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10338}
10339
10340TEST_P(QuicConnectionTest, ServerReceivedHandshakeDone) {
10341 if (!connection_.version().HasHandshakeDone()) {
10342 return;
10343 }
10344 set_perspective(Perspective::IS_SERVER);
10345 EXPECT_CALL(visitor_, OnHandshakeDoneReceived()).Times(0);
10346 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10347 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
10348 QuicFrames frames;
10349 frames.push_back(QuicFrame(QuicHandshakeDoneFrame()));
10350 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10351 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10352 EXPECT_EQ(1, connection_close_frame_count_);
10353 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
10354 IsError(IETF_QUIC_PROTOCOL_VIOLATION));
10355}
10356
fayang18ff23b2020-01-28 09:19:00 -080010357TEST_P(QuicConnectionTest, MultiplePacketNumberSpacePto) {
10358 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10359 return;
10360 }
10361 use_tagging_decrypter();
10362 // Send handshake packet.
10363 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10364 std::make_unique<TaggingEncrypter>(0x02));
10365 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
fayang44ae4e92020-04-28 13:09:42 -070010366 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
fayang18ff23b2020-01-28 09:19:00 -080010367 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
10368 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
10369
10370 // Send application data.
10371 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
10372 0, NO_FIN);
10373 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
10374 QuicTime retransmission_time =
10375 connection_.GetRetransmissionAlarm()->deadline();
10376 EXPECT_NE(QuicTime::Zero(), retransmission_time);
10377
10378 // Retransmit handshake data.
10379 clock_.AdvanceTime(retransmission_time - clock_.Now());
fayang1c2d1ab2020-03-11 12:08:41 -070010380 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _));
fayang44ae4e92020-04-28 13:09:42 -070010381 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
fayang18ff23b2020-01-28 09:19:00 -080010382 connection_.GetRetransmissionAlarm()->Fire();
10383 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
10384
10385 // Send application data.
10386 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
10387 4, NO_FIN);
10388 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
10389 retransmission_time = connection_.GetRetransmissionAlarm()->deadline();
10390 EXPECT_NE(QuicTime::Zero(), retransmission_time);
10391
10392 // Retransmit handshake data again.
10393 clock_.AdvanceTime(retransmission_time - clock_.Now());
fayang1c2d1ab2020-03-11 12:08:41 -070010394 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(7), _, _));
fayang44ae4e92020-04-28 13:09:42 -070010395 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
fayang18ff23b2020-01-28 09:19:00 -080010396 connection_.GetRetransmissionAlarm()->Fire();
10397 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
10398
10399 // Discard handshake key.
10400 connection_.OnHandshakeComplete();
10401 retransmission_time = connection_.GetRetransmissionAlarm()->deadline();
10402 EXPECT_NE(QuicTime::Zero(), retransmission_time);
10403
10404 // Retransmit application data.
10405 clock_.AdvanceTime(retransmission_time - clock_.Now());
fayang1c2d1ab2020-03-11 12:08:41 -070010406 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(9), _, _));
fayang18ff23b2020-01-28 09:19:00 -080010407 connection_.GetRetransmissionAlarm()->Fire();
10408 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
10409}
10410
dschinazi39e5e552020-05-06 13:55:24 -070010411void QuicConnectionTest::TestClientRetryHandling(bool invalid_retry_tag,
10412 bool missing_id_in_config,
10413 bool wrong_id_in_config) {
10414 if (invalid_retry_tag) {
10415 ASSERT_FALSE(missing_id_in_config);
10416 ASSERT_FALSE(wrong_id_in_config);
10417 } else {
10418 ASSERT_FALSE(missing_id_in_config && wrong_id_in_config);
10419 }
dschinazi278efae2020-01-28 17:03:09 -080010420 if (!version().HasRetryIntegrityTag()) {
10421 return;
10422 }
dschinazi39e5e552020-05-06 13:55:24 -070010423
10424 // These values come from draft-ietf-quic-tls Appendix A.4.
10425 char retry_packet25[] = {
10426 0xff, 0xff, 0x00, 0x00, 0x19, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a,
10427 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x1e, 0x5e, 0xc5, 0xb0,
10428 0x14, 0xcb, 0xb1, 0xf0, 0xfd, 0x93, 0xdf, 0x40, 0x48, 0xc4, 0x46, 0xa6};
10429 char retry_packet27[] = {
10430 0xff, 0xff, 0x00, 0x00, 0x1b, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a,
10431 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0xa5, 0x23, 0xcb, 0x5b,
10432 0xa5, 0x24, 0x69, 0x5f, 0x65, 0x69, 0xf2, 0x93, 0xa1, 0x35, 0x9d, 0x8e};
10433
10434 char* retry_packet;
10435 size_t retry_packet_length;
10436 if (version() ==
10437 ParsedQuicVersion(PROTOCOL_TLS1_3, QUIC_VERSION_IETF_DRAFT_27)) {
10438 retry_packet = retry_packet27;
10439 retry_packet_length = QUICHE_ARRAYSIZE(retry_packet27);
10440 } else if (version() ==
10441 ParsedQuicVersion(PROTOCOL_TLS1_3, QUIC_VERSION_IETF_DRAFT_25)) {
10442 retry_packet = retry_packet25;
10443 retry_packet_length = QUICHE_ARRAYSIZE(retry_packet25);
10444 } else {
dschinazi278efae2020-01-28 17:03:09 -080010445 // TODO(dschinazi) generate retry packets for all versions once we have
10446 // server-side support for generating these programmatically.
10447 return;
10448 }
10449
dschinazi278efae2020-01-28 17:03:09 -080010450 char original_connection_id_bytes[] = {0x83, 0x94, 0xc8, 0xf0,
10451 0x3e, 0x51, 0x57, 0x08};
10452 char new_connection_id_bytes[] = {0xf0, 0x67, 0xa5, 0x50,
10453 0x2a, 0x42, 0x62, 0xb5};
10454 char retry_token_bytes[] = {0x74, 0x6f, 0x6b, 0x65, 0x6e};
10455
10456 QuicConnectionId original_connection_id(
10457 original_connection_id_bytes,
10458 QUICHE_ARRAYSIZE(original_connection_id_bytes));
10459 QuicConnectionId new_connection_id(new_connection_id_bytes,
10460 QUICHE_ARRAYSIZE(new_connection_id_bytes));
10461
10462 std::string retry_token(retry_token_bytes,
10463 QUICHE_ARRAYSIZE(retry_token_bytes));
10464
dschinazi39e5e552020-05-06 13:55:24 -070010465 if (invalid_retry_tag) {
10466 // Flip the last bit of the retry packet to prevent the integrity tag
10467 // from validating correctly.
10468 retry_packet[retry_packet_length - 1] ^= 1;
dschinazi278efae2020-01-28 17:03:09 -080010469 }
10470
dschinazi39e5e552020-05-06 13:55:24 -070010471 QuicConnectionId config_original_connection_id = original_connection_id;
10472 if (wrong_id_in_config) {
10473 // Flip the first bit of the connection ID.
10474 ASSERT_FALSE(config_original_connection_id.IsEmpty());
10475 config_original_connection_id.mutable_data()[0] ^= 0x80;
10476 }
dschinazi278efae2020-01-28 17:03:09 -080010477
dschinazi39e5e552020-05-06 13:55:24 -070010478 // Make sure the connection uses the connection ID from the test vectors,
10479 QuicConnectionPeer::SetServerConnectionId(&connection_,
10480 original_connection_id);
dschinazi278efae2020-01-28 17:03:09 -080010481
dschinazi39e5e552020-05-06 13:55:24 -070010482 // Process the RETRY packet.
10483 connection_.ProcessUdpPacket(
10484 kSelfAddress, kPeerAddress,
10485 QuicReceivedPacket(retry_packet, retry_packet_length, clock_.Now()));
10486
10487 if (invalid_retry_tag) {
10488 // Make sure we refuse to process a RETRY with invalid tag.
10489 EXPECT_FALSE(connection_.GetStats().retry_packet_processed);
10490 EXPECT_EQ(connection_.connection_id(), original_connection_id);
dschinazi278efae2020-01-28 17:03:09 -080010491 EXPECT_TRUE(QuicPacketCreatorPeer::GetRetryToken(
dschinazi39e5e552020-05-06 13:55:24 -070010492 QuicConnectionPeer::GetPacketCreator(&connection_))
dschinazi278efae2020-01-28 17:03:09 -080010493 .empty());
dschinazi39e5e552020-05-06 13:55:24 -070010494 return;
dschinazi278efae2020-01-28 17:03:09 -080010495 }
dschinazi39e5e552020-05-06 13:55:24 -070010496
10497 // Make sure we correctly parsed the RETRY.
10498 EXPECT_TRUE(connection_.GetStats().retry_packet_processed);
10499 EXPECT_EQ(connection_.connection_id(), new_connection_id);
10500 EXPECT_EQ(QuicPacketCreatorPeer::GetRetryToken(
10501 QuicConnectionPeer::GetPacketCreator(&connection_)),
10502 retry_token);
10503 // Make sure our fake framer has the new post-retry INITIAL keys.
10504 writer_->framer()->framer()->SetInitialObfuscators(new_connection_id);
10505
10506 // Test validating the original_connection_id from the config.
10507 QuicConfig received_config;
10508 QuicConfigPeer::SetNegotiated(&received_config, true);
10509 if (!missing_id_in_config) {
10510 QuicConfigPeer::SetReceivedOriginalConnectionId(
10511 &received_config, config_original_connection_id);
10512 }
10513 if (missing_id_in_config || wrong_id_in_config) {
10514 EXPECT_CALL(visitor_,
10515 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10516 .Times(1);
10517 } else {
10518 EXPECT_CALL(visitor_,
10519 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10520 .Times(0);
10521 }
10522 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
10523 connection_.SetFromConfig(received_config);
10524 if (missing_id_in_config || wrong_id_in_config) {
10525 EXPECT_FALSE(connection_.connected());
10526 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
10527 } else {
10528 EXPECT_TRUE(connection_.connected());
10529 }
10530}
10531
10532TEST_P(QuicConnectionTest, ClientParsesRetry) {
10533 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10534 /*missing_id_in_config=*/false,
10535 /*wrong_id_in_config=*/false);
10536}
10537
10538TEST_P(QuicConnectionTest, ClientParsesInvalidRetry) {
10539 TestClientRetryHandling(/*invalid_retry_tag=*/true,
10540 /*missing_id_in_config=*/false,
10541 /*wrong_id_in_config=*/false);
10542}
10543
10544TEST_P(QuicConnectionTest, ClientParsesRetryMissingId) {
10545 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10546 /*missing_id_in_config=*/true,
10547 /*wrong_id_in_config=*/false);
10548}
10549
10550TEST_P(QuicConnectionTest, ClientParsesRetryWrongId) {
10551 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10552 /*missing_id_in_config=*/false,
10553 /*wrong_id_in_config=*/true);
10554}
10555
10556TEST_P(QuicConnectionTest, ClientReceivesOriginalConnectionIdWithoutRetry) {
10557 // Make sure that receiving the original_connection_id transport parameter
10558 // fails the handshake when no RETRY packet was received before it.
10559 QuicConfig received_config;
10560 QuicConfigPeer::SetNegotiated(&received_config, true);
10561 QuicConfigPeer::SetReceivedOriginalConnectionId(&received_config,
10562 TestConnectionId(0x12345));
10563 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
10564 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10565 .Times(1);
10566 connection_.SetFromConfig(received_config);
10567 EXPECT_FALSE(connection_.connected());
10568 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
dschinazi278efae2020-01-28 17:03:09 -080010569}
10570
fayang0e3035e2020-02-03 13:30:36 -080010571// Regression test for http://crbug/1047977
10572TEST_P(QuicConnectionTest, MaxStreamsFrameCausesConnectionClose) {
10573 if (!VersionHasIetfQuicFrames(connection_.transport_version())) {
10574 return;
10575 }
10576 // Received frame causes connection close.
10577 EXPECT_CALL(visitor_, OnMaxStreamsFrame(_))
10578 .WillOnce(InvokeWithoutArgs([this]() {
10579 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10580 connection_.CloseConnection(
10581 QUIC_TOO_MANY_BUFFERED_CONTROL_FRAMES, "error",
10582 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10583 return true;
10584 }));
10585 QuicFrames frames;
10586 frames.push_back(QuicFrame(QuicMaxStreamsFrame()));
10587 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10588 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10589}
10590
10591TEST_P(QuicConnectionTest, StreamsBlockedFrameCausesConnectionClose) {
10592 if (!VersionHasIetfQuicFrames(connection_.transport_version())) {
10593 return;
10594 }
10595 // Received frame causes connection close.
10596 EXPECT_CALL(visitor_, OnStreamsBlockedFrame(_))
10597 .WillOnce(InvokeWithoutArgs([this]() {
10598 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10599 connection_.CloseConnection(
10600 QUIC_TOO_MANY_BUFFERED_CONTROL_FRAMES, "error",
10601 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10602 return true;
10603 }));
10604 QuicFrames frames;
10605 frames.push_back(
10606 QuicFrame(QuicStreamsBlockedFrame(kInvalidControlFrameId, 10, false)));
10607 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10608 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10609}
10610
fayang79400d52020-02-13 10:13:05 -080010611TEST_P(QuicConnectionTest,
10612 BundleAckWithConnectionCloseMultiplePacketNumberSpace) {
10613 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10614 return;
10615 }
10616 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10617 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10618 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
10619 // Receives packet 1000 in initial data.
10620 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
10621 // Receives packet 2000 in application data.
10622 ProcessDataPacketAtLevel(2000, false, ENCRYPTION_FORWARD_SECURE);
10623 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10624 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
10625 connection_.CloseConnection(
10626 kQuicErrorCode, "Some random error message",
10627 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10628
10629 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
10630
10631 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
10632 EXPECT_EQ(1u, writer_->connection_close_frames().size());
10633 // Verify ack is bundled.
10634 EXPECT_EQ(1u, writer_->ack_frames().size());
10635
10636 if (!connection_.version().CanSendCoalescedPackets()) {
10637 // Each connection close packet should be sent in distinct UDP packets.
10638 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
10639 writer_->connection_close_packets());
10640 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
10641 writer_->packets_write_attempts());
10642 return;
10643 }
10644
10645 // A single UDP packet should be sent with multiple connection close packets
10646 // coalesced together.
10647 EXPECT_EQ(1u, writer_->packets_write_attempts());
10648
10649 // Only the first packet has been processed yet.
10650 EXPECT_EQ(1u, writer_->connection_close_packets());
10651
10652 // ProcessPacket resets the visitor and frees the coalesced packet.
10653 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
10654 auto packet = writer_->coalesced_packet()->Clone();
10655 writer_->framer()->ProcessPacket(*packet);
10656 EXPECT_EQ(1u, writer_->connection_close_packets());
10657 EXPECT_EQ(1u, writer_->connection_close_frames().size());
10658 // Verify ack is bundled.
10659 EXPECT_EQ(1u, writer_->ack_frames().size());
10660 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
10661}
10662
fayang61453cb2020-03-11 11:32:26 -070010663// Regression test for b/151220135.
10664TEST_P(QuicConnectionTest, SendPingWhenSkipPacketNumberForPto) {
10665 if (!VersionSupportsMessageFrames(connection_.transport_version())) {
10666 return;
10667 }
10668 QuicConfig config;
10669 QuicTagVector connection_options;
10670 connection_options.push_back(kPTOS);
10671 connection_options.push_back(k1PTO);
10672 config.SetConnectionOptionsToSend(connection_options);
dschinazied459c02020-05-07 16:12:23 -070010673 if (connection_.version().UsesTls()) {
10674 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
10675 &config, kMaxAcceptedDatagramFrameSize);
10676 }
fayang61453cb2020-03-11 11:32:26 -070010677 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10678 connection_.SetFromConfig(config);
10679 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
10680
10681 EXPECT_EQ(MESSAGE_STATUS_SUCCESS, SendMessage("message"));
10682 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
10683
fayang80f9cc62020-04-22 08:08:20 -070010684 // PTO fires, verify a PING packet gets sent because there is no data to
10685 // send.
10686 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(3), _, _));
10687 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
fayang61453cb2020-03-11 11:32:26 -070010688 connection_.GetRetransmissionAlarm()->Fire();
fayang80f9cc62020-04-22 08:08:20 -070010689 EXPECT_EQ(1u, connection_.GetStats().pto_count);
10690 EXPECT_EQ(0u, connection_.GetStats().crypto_retransmit_count);
10691 EXPECT_EQ(1u, writer_->ping_frames().size());
fayang61453cb2020-03-11 11:32:26 -070010692}
10693
fayangcc210e72020-05-05 14:41:34 -070010694// Regression test for b/155757133
10695TEST_P(QuicConnectionTest, DonotChangeQueuedAcks) {
10696 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10697 return;
10698 }
10699 const size_t kMinRttMs = 40;
10700 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
10701 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
10702 QuicTime::Delta::Zero(), QuicTime::Zero());
10703 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10704 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
10705 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10706
10707 ProcessPacket(2);
10708 ProcessPacket(3);
10709 ProcessPacket(4);
10710 // Process a packet containing stream frame followed by ACK of packets 1.
10711 QuicFrames frames;
10712 frames.push_back(QuicFrame(QuicStreamFrame(
10713 QuicUtils::GetFirstBidirectionalStreamId(
10714 connection_.version().transport_version, Perspective::IS_CLIENT),
10715 false, 0u, quiche::QuicheStringPiece())));
10716 QuicAckFrame ack_frame = InitAckFrame(1);
10717 frames.push_back(QuicFrame(&ack_frame));
10718 // Receiving stream frame causes something to send.
10719 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([this]() {
10720 connection_.SendControlFrame(QuicFrame(new QuicWindowUpdateFrame(1, 0, 0)));
10721 // Verify now the queued ACK contains packet number 2.
10722 EXPECT_TRUE(QuicPacketCreatorPeer::QueuedFrames(
10723 QuicConnectionPeer::GetPacketCreator(&connection_))[0]
10724 .ack_frame->packets.Contains(QuicPacketNumber(2)));
10725 }));
10726 ProcessFramesPacketAtLevel(9, frames, ENCRYPTION_FORWARD_SECURE);
10727 if (GetQuicReloadableFlag(quic_donot_change_queued_ack)) {
10728 EXPECT_TRUE(writer_->ack_frames()[0].packets.Contains(QuicPacketNumber(2)));
10729 } else {
10730 // ACK frame changes mid packet serialiation!
10731 EXPECT_FALSE(
10732 writer_->ack_frames()[0].packets.Contains(QuicPacketNumber(2)));
10733 }
10734}
10735
fayange9304002020-05-07 11:57:48 -070010736TEST_P(QuicConnectionTest, DonotExtendIdleTimeOnUndecryptablePackets) {
10737 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10738 QuicConfig config;
10739 connection_.SetFromConfig(config);
10740 // Subtract a second from the idle timeout on the client side.
10741 QuicTime initial_deadline =
10742 clock_.ApproximateNow() +
10743 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
10744 EXPECT_EQ(initial_deadline, connection_.GetTimeoutAlarm()->deadline());
10745
10746 // Received an undecryptable packet.
10747 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
10748 const uint8_t tag = 0x07;
10749 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
10750 std::make_unique<TaggingEncrypter>(tag));
10751 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
10752 if (GetQuicReloadableFlag(quic_extend_idle_time_on_decryptable_packets) ||
10753 !GetQuicReloadableFlag(quic_use_blackhole_detector)) {
10754 // Verify deadline does not get extended.
10755 EXPECT_EQ(initial_deadline, connection_.GetTimeoutAlarm()->deadline());
10756 }
10757 if (GetQuicReloadableFlag(quic_extend_idle_time_on_decryptable_packets)) {
10758 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
10759 } else {
10760 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
10761 }
10762 QuicTime::Delta delay = initial_deadline - clock_.ApproximateNow();
10763 clock_.AdvanceTime(delay);
10764 if (GetQuicReloadableFlag(quic_extend_idle_time_on_decryptable_packets) ||
10765 !GetQuicReloadableFlag(quic_use_blackhole_detector)) {
10766 connection_.GetTimeoutAlarm()->Fire();
10767 }
10768 if (GetQuicReloadableFlag(quic_extend_idle_time_on_decryptable_packets)) {
10769 // Verify connection gets closed.
10770 EXPECT_FALSE(connection_.connected());
10771 } else {
10772 // Verify the timeout alarm deadline is updated.
10773 EXPECT_TRUE(connection_.connected());
10774 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
10775 }
10776}
10777
QUICHE teama6ef0a62019-03-07 20:34:33 -050010778} // namespace
10779} // namespace test
10780} // namespace quic