blob: 60c6e1b0429d60cbb73595b0d0e54ce054d60ccb [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"
25#include "net/third_party/quiche/src/quic/platform/api/quic_error_code_wrappers.h"
26#include "net/third_party/quiche/src/quic/platform/api/quic_expect_bug.h"
27#include "net/third_party/quiche/src/quic/platform/api/quic_flags.h"
28#include "net/third_party/quiche/src/quic/platform/api/quic_logging.h"
29#include "net/third_party/quiche/src/quic/platform/api/quic_ptr_util.h"
30#include "net/third_party/quiche/src/quic/platform/api/quic_reference_counted.h"
31#include "net/third_party/quiche/src/quic/platform/api/quic_str_cat.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050032#include "net/third_party/quiche/src/quic/platform/api/quic_string_piece.h"
33#include "net/third_party/quiche/src/quic/platform/api/quic_test.h"
34#include "net/third_party/quiche/src/quic/test_tools/mock_clock.h"
35#include "net/third_party/quiche/src/quic/test_tools/mock_random.h"
36#include "net/third_party/quiche/src/quic/test_tools/quic_config_peer.h"
37#include "net/third_party/quiche/src/quic/test_tools/quic_connection_peer.h"
38#include "net/third_party/quiche/src/quic/test_tools/quic_framer_peer.h"
39#include "net/third_party/quiche/src/quic/test_tools/quic_packet_creator_peer.h"
40#include "net/third_party/quiche/src/quic/test_tools/quic_packet_generator_peer.h"
41#include "net/third_party/quiche/src/quic/test_tools/quic_sent_packet_manager_peer.h"
42#include "net/third_party/quiche/src/quic/test_tools/quic_test_utils.h"
43#include "net/third_party/quiche/src/quic/test_tools/simple_data_producer.h"
44#include "net/third_party/quiche/src/quic/test_tools/simple_quic_framer.h"
45#include "net/third_party/quiche/src/quic/test_tools/simple_session_notifier.h"
46
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.
dschinazi17d42422019-06-18 16:35:07 -0700122 bool SetKey(QuicStringPiece /*key*/) override { return true; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500123
dschinazi17d42422019-06-18 16:35:07 -0700124 bool SetNoncePrefix(QuicStringPiece /*nonce_prefix*/) override {
125 return true;
126 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500127
dschinazi17d42422019-06-18 16:35:07 -0700128 bool SetIV(QuicStringPiece /*iv*/) override { return true; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500129
dschinazi17d42422019-06-18 16:35:07 -0700130 bool SetHeaderProtectionKey(QuicStringPiece /*key*/) override { return true; }
QUICHE team2d187972019-03-19 16:23:47 -0700131
dschinazi17d42422019-06-18 16:35:07 -0700132 bool EncryptPacket(uint64_t /*packet_number*/,
133 QuicStringPiece /*associated_data*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500134 QuicStringPiece plaintext,
135 char* output,
136 size_t* output_length,
137 size_t max_output_length) override {
138 const size_t len = plaintext.size() + kTagSize;
139 if (max_output_length < len) {
140 return false;
141 }
142 // Memmove is safe for inplace encryption.
143 memmove(output, plaintext.data(), plaintext.size());
144 output += plaintext.size();
145 memset(output, tag_, kTagSize);
146 *output_length = len;
147 return true;
148 }
149
dschinazi17d42422019-06-18 16:35:07 -0700150 std::string GenerateHeaderProtectionMask(
151 QuicStringPiece /*sample*/) override {
QUICHE team2d187972019-03-19 16:23:47 -0700152 return std::string(5, 0);
153 }
154
QUICHE teama6ef0a62019-03-07 20:34:33 -0500155 size_t GetKeySize() const override { return 0; }
156 size_t GetNoncePrefixSize() const override { return 0; }
157 size_t GetIVSize() const override { return 0; }
158
159 size_t GetMaxPlaintextSize(size_t ciphertext_size) const override {
160 return ciphertext_size - kTagSize;
161 }
162
163 size_t GetCiphertextSize(size_t plaintext_size) const override {
164 return plaintext_size + kTagSize;
165 }
166
167 QuicStringPiece GetKey() const override { return QuicStringPiece(); }
168
169 QuicStringPiece GetNoncePrefix() const override { return QuicStringPiece(); }
170
171 private:
172 enum {
173 kTagSize = 12,
174 };
175
176 const uint8_t tag_;
177};
178
179// TaggingDecrypter ensures that the final kTagSize bytes of the message all
180// have the same value and then removes them.
181class TaggingDecrypter : public QuicDecrypter {
182 public:
183 ~TaggingDecrypter() override {}
184
185 // QuicDecrypter interface
dschinazi17d42422019-06-18 16:35:07 -0700186 bool SetKey(QuicStringPiece /*key*/) override { return true; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500187
dschinazi17d42422019-06-18 16:35:07 -0700188 bool SetNoncePrefix(QuicStringPiece /*nonce_prefix*/) override {
189 return true;
190 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500191
dschinazi17d42422019-06-18 16:35:07 -0700192 bool SetIV(QuicStringPiece /*iv*/) override { return true; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500193
dschinazi17d42422019-06-18 16:35:07 -0700194 bool SetHeaderProtectionKey(QuicStringPiece /*key*/) override { return true; }
QUICHE team2d187972019-03-19 16:23:47 -0700195
dschinazi17d42422019-06-18 16:35:07 -0700196 bool SetPreliminaryKey(QuicStringPiece /*key*/) override {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500197 QUIC_BUG << "should not be called";
198 return false;
199 }
200
dschinazi17d42422019-06-18 16:35:07 -0700201 bool SetDiversificationNonce(const DiversificationNonce& /*key*/) override {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500202 return true;
203 }
204
dschinazi17d42422019-06-18 16:35:07 -0700205 bool DecryptPacket(uint64_t /*packet_number*/,
206 QuicStringPiece /*associated_data*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500207 QuicStringPiece ciphertext,
208 char* output,
209 size_t* output_length,
dschinazi17d42422019-06-18 16:35:07 -0700210 size_t /*max_output_length*/) override {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500211 if (ciphertext.size() < kTagSize) {
212 return false;
213 }
214 if (!CheckTag(ciphertext, GetTag(ciphertext))) {
215 return false;
216 }
217 *output_length = ciphertext.size() - kTagSize;
218 memcpy(output, ciphertext.data(), *output_length);
219 return true;
220 }
221
QUICHE team2d187972019-03-19 16:23:47 -0700222 std::string GenerateHeaderProtectionMask(
dschinazi17d42422019-06-18 16:35:07 -0700223 QuicDataReader* /*sample_reader*/) override {
QUICHE team2d187972019-03-19 16:23:47 -0700224 return std::string(5, 0);
225 }
226
QUICHE teama6ef0a62019-03-07 20:34:33 -0500227 size_t GetKeySize() const override { return 0; }
nharper965e5922019-09-23 22:33:54 -0700228 size_t GetNoncePrefixSize() const override { return 0; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500229 size_t GetIVSize() const override { return 0; }
230 QuicStringPiece GetKey() const override { return QuicStringPiece(); }
231 QuicStringPiece GetNoncePrefix() const override { return QuicStringPiece(); }
232 // Use a distinct value starting with 0xFFFFFF, which is never used by TLS.
233 uint32_t cipher_id() const override { return 0xFFFFFFF0; }
234
235 protected:
236 virtual uint8_t GetTag(QuicStringPiece ciphertext) {
237 return ciphertext.data()[ciphertext.size() - 1];
238 }
239
240 private:
241 enum {
242 kTagSize = 12,
243 };
244
245 bool CheckTag(QuicStringPiece ciphertext, uint8_t tag) {
246 for (size_t i = ciphertext.size() - kTagSize; i < ciphertext.size(); i++) {
247 if (ciphertext.data()[i] != tag) {
248 return false;
249 }
250 }
251
252 return true;
253 }
254};
255
256// StringTaggingDecrypter ensures that the final kTagSize bytes of the message
257// match the expected value.
258class StrictTaggingDecrypter : public TaggingDecrypter {
259 public:
260 explicit StrictTaggingDecrypter(uint8_t tag) : tag_(tag) {}
261 ~StrictTaggingDecrypter() override {}
262
263 // TaggingQuicDecrypter
dschinazi17d42422019-06-18 16:35:07 -0700264 uint8_t GetTag(QuicStringPiece /*ciphertext*/) override { return tag_; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500265
266 // Use a distinct value starting with 0xFFFFFF, which is never used by TLS.
267 uint32_t cipher_id() const override { return 0xFFFFFFF1; }
268
269 private:
270 const uint8_t tag_;
271};
272
273class TestConnectionHelper : public QuicConnectionHelperInterface {
274 public:
275 TestConnectionHelper(MockClock* clock, MockRandom* random_generator)
276 : clock_(clock), random_generator_(random_generator) {
277 clock_->AdvanceTime(QuicTime::Delta::FromSeconds(1));
278 }
279 TestConnectionHelper(const TestConnectionHelper&) = delete;
280 TestConnectionHelper& operator=(const TestConnectionHelper&) = delete;
281
282 // QuicConnectionHelperInterface
283 const QuicClock* GetClock() const override { return clock_; }
284
285 QuicRandom* GetRandomGenerator() override { return random_generator_; }
286
287 QuicBufferAllocator* GetStreamSendBufferAllocator() override {
288 return &buffer_allocator_;
289 }
290
291 private:
292 MockClock* clock_;
293 MockRandom* random_generator_;
294 SimpleBufferAllocator buffer_allocator_;
295};
296
297class TestAlarmFactory : public QuicAlarmFactory {
298 public:
299 class TestAlarm : public QuicAlarm {
300 public:
301 explicit TestAlarm(QuicArenaScopedPtr<QuicAlarm::Delegate> delegate)
302 : QuicAlarm(std::move(delegate)) {}
303
304 void SetImpl() override {}
305 void CancelImpl() override {}
306 using QuicAlarm::Fire;
307 };
308
309 TestAlarmFactory() {}
310 TestAlarmFactory(const TestAlarmFactory&) = delete;
311 TestAlarmFactory& operator=(const TestAlarmFactory&) = delete;
312
313 QuicAlarm* CreateAlarm(QuicAlarm::Delegate* delegate) override {
314 return new TestAlarm(QuicArenaScopedPtr<QuicAlarm::Delegate>(delegate));
315 }
316
317 QuicArenaScopedPtr<QuicAlarm> CreateAlarm(
318 QuicArenaScopedPtr<QuicAlarm::Delegate> delegate,
319 QuicConnectionArena* arena) override {
320 return arena->New<TestAlarm>(std::move(delegate));
321 }
322};
323
324class TestPacketWriter : public QuicPacketWriter {
325 public:
326 TestPacketWriter(ParsedQuicVersion version, MockClock* clock)
327 : version_(version),
328 framer_(SupportedVersions(version_), Perspective::IS_SERVER),
329 last_packet_size_(0),
330 write_blocked_(false),
331 write_should_fail_(false),
332 block_on_next_flush_(false),
333 block_on_next_write_(false),
334 next_packet_too_large_(false),
335 always_get_packet_too_large_(false),
336 is_write_blocked_data_buffered_(false),
337 is_batch_mode_(false),
338 final_bytes_of_last_packet_(0),
339 final_bytes_of_previous_packet_(0),
340 use_tagging_decrypter_(false),
341 packets_write_attempts_(0),
342 clock_(clock),
343 write_pause_time_delta_(QuicTime::Delta::Zero()),
dschinazi66dea072019-04-09 11:41:06 -0700344 max_packet_size_(kMaxOutgoingPacketSize),
dschinazib953d022019-08-01 18:05:58 -0700345 supports_release_time_(false) {
346 QuicFramerPeer::SetLastSerializedServerConnectionId(framer_.framer(),
347 TestConnectionId());
nharperc6b99512019-09-19 11:13:48 -0700348 framer_.framer()->SetInitialObfuscators(TestConnectionId());
dschinazib953d022019-08-01 18:05:58 -0700349 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500350 TestPacketWriter(const TestPacketWriter&) = delete;
351 TestPacketWriter& operator=(const TestPacketWriter&) = delete;
352
353 // QuicPacketWriter interface
354 WriteResult WritePacket(const char* buffer,
355 size_t buf_len,
dschinazi17d42422019-06-18 16:35:07 -0700356 const QuicIpAddress& /*self_address*/,
357 const QuicSocketAddress& /*peer_address*/,
358 PerPacketOptions* /*options*/) override {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500359 QuicEncryptedPacket packet(buffer, buf_len);
360 ++packets_write_attempts_;
361
362 if (packet.length() >= sizeof(final_bytes_of_last_packet_)) {
363 final_bytes_of_previous_packet_ = final_bytes_of_last_packet_;
364 memcpy(&final_bytes_of_last_packet_, packet.data() + packet.length() - 4,
365 sizeof(final_bytes_of_last_packet_));
366 }
367
368 if (use_tagging_decrypter_) {
zhongyi546cc452019-04-12 15:27:49 -0700369 if (framer_.framer()->version().KnowsWhichDecrypterToUse()) {
vasilvv0fc587f2019-09-06 13:33:08 -0700370 framer_.framer()->InstallDecrypter(
371 ENCRYPTION_INITIAL, std::make_unique<TaggingDecrypter>());
372 framer_.framer()->InstallDecrypter(
373 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 }
385 EXPECT_TRUE(framer_.ProcessPacket(packet));
386 if (block_on_next_write_) {
387 write_blocked_ = true;
388 block_on_next_write_ = false;
389 }
390 if (next_packet_too_large_) {
391 next_packet_too_large_ = false;
392 return WriteResult(WRITE_STATUS_ERROR, QUIC_EMSGSIZE);
393 }
394 if (always_get_packet_too_large_) {
395 return WriteResult(WRITE_STATUS_ERROR, QUIC_EMSGSIZE);
396 }
397 if (IsWriteBlocked()) {
398 return WriteResult(is_write_blocked_data_buffered_
399 ? WRITE_STATUS_BLOCKED_DATA_BUFFERED
400 : WRITE_STATUS_BLOCKED,
401 0);
402 }
403
404 if (ShouldWriteFail()) {
405 return WriteResult(WRITE_STATUS_ERROR, 0);
406 }
407
408 last_packet_size_ = packet.length();
409 last_packet_header_ = framer_.header();
410
411 if (!write_pause_time_delta_.IsZero()) {
412 clock_->AdvanceTime(write_pause_time_delta_);
413 }
414 return WriteResult(WRITE_STATUS_OK, last_packet_size_);
415 }
416
417 bool ShouldWriteFail() { return write_should_fail_; }
418
419 bool IsWriteBlocked() const override { return write_blocked_; }
420
421 void SetWriteBlocked() { write_blocked_ = true; }
422
423 void SetWritable() override { write_blocked_ = false; }
424
425 void SetShouldWriteFail() { write_should_fail_ = true; }
426
427 QuicByteCount GetMaxPacketSize(
428 const QuicSocketAddress& /*peer_address*/) const override {
429 return max_packet_size_;
430 }
431
dschinazi61eb6432019-06-14 16:27:16 -0700432 bool SupportsReleaseTime() const override { return supports_release_time_; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500433
434 bool IsBatchMode() const override { return is_batch_mode_; }
435
dschinazi17d42422019-06-18 16:35:07 -0700436 char* GetNextWriteLocation(
437 const QuicIpAddress& /*self_address*/,
438 const QuicSocketAddress& /*peer_address*/) override {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500439 return nullptr;
440 }
441
442 WriteResult Flush() override {
443 if (block_on_next_flush_) {
444 block_on_next_flush_ = false;
445 SetWriteBlocked();
446 return WriteResult(WRITE_STATUS_BLOCKED, /*errno*/ -1);
447 }
448 return WriteResult(WRITE_STATUS_OK, 0);
449 }
450
451 void BlockOnNextFlush() { block_on_next_flush_ = true; }
452
453 void BlockOnNextWrite() { block_on_next_write_ = true; }
454
455 void SimulateNextPacketTooLarge() { next_packet_too_large_ = true; }
456
457 void AlwaysGetPacketTooLarge() { always_get_packet_too_large_ = true; }
458
459 // Sets the amount of time that the writer should before the actual write.
460 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
461 write_pause_time_delta_ = delta;
462 }
463
464 void SetBatchMode(bool new_value) { is_batch_mode_ = new_value; }
465
466 const QuicPacketHeader& header() { return framer_.header(); }
467
468 size_t frame_count() const { return framer_.num_frames(); }
469
470 const std::vector<QuicAckFrame>& ack_frames() const {
471 return framer_.ack_frames();
472 }
473
474 const std::vector<QuicStopWaitingFrame>& stop_waiting_frames() const {
475 return framer_.stop_waiting_frames();
476 }
477
478 const std::vector<QuicConnectionCloseFrame>& connection_close_frames() const {
479 return framer_.connection_close_frames();
480 }
481
482 const std::vector<QuicRstStreamFrame>& rst_stream_frames() const {
483 return framer_.rst_stream_frames();
484 }
485
486 const std::vector<std::unique_ptr<QuicStreamFrame>>& stream_frames() const {
487 return framer_.stream_frames();
488 }
489
490 const std::vector<std::unique_ptr<QuicCryptoFrame>>& crypto_frames() const {
491 return framer_.crypto_frames();
492 }
493
494 const std::vector<QuicPingFrame>& ping_frames() const {
495 return framer_.ping_frames();
496 }
497
498 const std::vector<QuicMessageFrame>& message_frames() const {
499 return framer_.message_frames();
500 }
501
502 const std::vector<QuicWindowUpdateFrame>& window_update_frames() const {
503 return framer_.window_update_frames();
504 }
505
506 const std::vector<QuicPaddingFrame>& padding_frames() const {
507 return framer_.padding_frames();
508 }
509
510 const std::vector<QuicPathChallengeFrame>& path_challenge_frames() const {
511 return framer_.path_challenge_frames();
512 }
513
514 const std::vector<QuicPathResponseFrame>& path_response_frames() const {
515 return framer_.path_response_frames();
516 }
517
518 size_t last_packet_size() { return last_packet_size_; }
519
520 const QuicPacketHeader& last_packet_header() const {
521 return last_packet_header_;
522 }
523
524 const QuicVersionNegotiationPacket* version_negotiation_packet() {
525 return framer_.version_negotiation_packet();
526 }
527
528 void set_is_write_blocked_data_buffered(bool buffered) {
529 is_write_blocked_data_buffered_ = buffered;
530 }
531
532 void set_perspective(Perspective perspective) {
533 // We invert perspective here, because the framer needs to parse packets
534 // we send.
535 QuicFramerPeer::SetPerspective(framer_.framer(),
nharper4eba09b2019-06-26 20:17:25 -0700536 QuicUtils::InvertPerspective(perspective));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500537 }
538
539 // final_bytes_of_last_packet_ returns the last four bytes of the previous
540 // packet as a little-endian, uint32_t. This is intended to be used with a
541 // TaggingEncrypter so that tests can determine which encrypter was used for
542 // a given packet.
543 uint32_t final_bytes_of_last_packet() { return final_bytes_of_last_packet_; }
544
545 // Returns the final bytes of the second to last packet.
546 uint32_t final_bytes_of_previous_packet() {
547 return final_bytes_of_previous_packet_;
548 }
549
550 void use_tagging_decrypter() { use_tagging_decrypter_ = true; }
551
552 uint32_t packets_write_attempts() { return packets_write_attempts_; }
553
554 void Reset() { framer_.Reset(); }
555
556 void SetSupportedVersions(const ParsedQuicVersionVector& versions) {
557 framer_.SetSupportedVersions(versions);
558 }
559
560 void set_max_packet_size(QuicByteCount max_packet_size) {
561 max_packet_size_ = max_packet_size;
562 }
563
564 void set_supports_release_time(bool supports_release_time) {
565 supports_release_time_ = supports_release_time;
566 }
567
568 SimpleQuicFramer* framer() { return &framer_; }
569
570 private:
571 ParsedQuicVersion version_;
572 SimpleQuicFramer framer_;
573 size_t last_packet_size_;
574 QuicPacketHeader last_packet_header_;
575 bool write_blocked_;
576 bool write_should_fail_;
577 bool block_on_next_flush_;
578 bool block_on_next_write_;
579 bool next_packet_too_large_;
580 bool always_get_packet_too_large_;
581 bool is_write_blocked_data_buffered_;
582 bool is_batch_mode_;
583 uint32_t final_bytes_of_last_packet_;
584 uint32_t final_bytes_of_previous_packet_;
585 bool use_tagging_decrypter_;
586 uint32_t packets_write_attempts_;
587 MockClock* clock_;
588 // If non-zero, the clock will pause during WritePacket for this amount of
589 // time.
590 QuicTime::Delta write_pause_time_delta_;
591 QuicByteCount max_packet_size_;
592 bool supports_release_time_;
593};
594
595class TestConnection : public QuicConnection {
596 public:
597 TestConnection(QuicConnectionId connection_id,
598 QuicSocketAddress address,
599 TestConnectionHelper* helper,
600 TestAlarmFactory* alarm_factory,
601 TestPacketWriter* writer,
602 Perspective perspective,
603 ParsedQuicVersion version)
604 : QuicConnection(connection_id,
605 address,
606 helper,
607 alarm_factory,
608 writer,
609 /* owns_writer= */ false,
610 perspective,
611 SupportedVersions(version)),
612 notifier_(nullptr) {
613 writer->set_perspective(perspective);
614 SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -0700615 std::make_unique<NullEncrypter>(perspective));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500616 SetDataProducer(&producer_);
617 }
618 TestConnection(const TestConnection&) = delete;
619 TestConnection& operator=(const TestConnection&) = delete;
620
QUICHE teama6ef0a62019-03-07 20:34:33 -0500621 void SetSendAlgorithm(SendAlgorithmInterface* send_algorithm) {
622 QuicConnectionPeer::SetSendAlgorithm(this, send_algorithm);
623 }
624
625 void SetLossAlgorithm(LossDetectionInterface* loss_algorithm) {
626 QuicConnectionPeer::SetLossAlgorithm(this, loss_algorithm);
627 }
628
dschinazi17d42422019-06-18 16:35:07 -0700629 void SendPacket(EncryptionLevel /*level*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500630 uint64_t packet_number,
631 std::unique_ptr<QuicPacket> packet,
632 HasRetransmittableData retransmittable,
633 bool has_ack,
634 bool has_pending_frames) {
dschinazi66dea072019-04-09 11:41:06 -0700635 char buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -0500636 size_t encrypted_length =
637 QuicConnectionPeer::GetFramer(this)->EncryptPayload(
QUICHE team6987b4a2019-03-15 16:23:04 -0700638 ENCRYPTION_INITIAL, QuicPacketNumber(packet_number), *packet,
dschinazi66dea072019-04-09 11:41:06 -0700639 buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500640 SerializedPacket serialized_packet(
641 QuicPacketNumber(packet_number), PACKET_4BYTE_PACKET_NUMBER, buffer,
642 encrypted_length, has_ack, has_pending_frames);
643 if (retransmittable == HAS_RETRANSMITTABLE_DATA) {
644 serialized_packet.retransmittable_frames.push_back(
645 QuicFrame(QuicStreamFrame()));
646 }
647 OnSerializedPacket(&serialized_packet);
648 }
649
650 QuicConsumedData SaveAndSendStreamData(QuicStreamId id,
651 const struct iovec* iov,
652 int iov_count,
653 size_t total_length,
654 QuicStreamOffset offset,
655 StreamSendingState state) {
fayanga4b37b22019-06-18 13:37:47 -0700656 ScopedPacketFlusher flusher(this);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500657 producer_.SaveStreamData(id, iov, iov_count, 0u, total_length);
658 if (notifier_ != nullptr) {
659 return notifier_->WriteOrBufferData(id, total_length, state);
660 }
661 return QuicConnection::SendStreamData(id, total_length, offset, state);
662 }
663
664 QuicConsumedData SendStreamDataWithString(QuicStreamId id,
665 QuicStringPiece data,
666 QuicStreamOffset offset,
667 StreamSendingState state) {
fayanga4b37b22019-06-18 13:37:47 -0700668 ScopedPacketFlusher flusher(this);
nharper46833c32019-05-15 21:33:05 -0700669 if (!QuicUtils::IsCryptoStreamId(transport_version(), id) &&
QUICHE team6987b4a2019-03-15 16:23:04 -0700670 this->encryption_level() == ENCRYPTION_INITIAL) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500671 this->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
fayang5f135052019-08-22 17:59:40 -0700672 if (perspective() == Perspective::IS_CLIENT && !IsHandshakeConfirmed()) {
673 OnHandshakeComplete();
674 }
675 if (version().SupportsAntiAmplificationLimit()) {
676 QuicConnectionPeer::SetAddressValidated(this);
677 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500678 }
679 struct iovec iov;
680 MakeIOVector(data, &iov);
681 return SaveAndSendStreamData(id, &iov, 1, data.length(), offset, state);
682 }
683
QUICHE teamcd098022019-03-22 18:49:55 -0700684 QuicConsumedData SendApplicationDataAtLevel(EncryptionLevel encryption_level,
685 QuicStreamId id,
686 QuicStringPiece data,
687 QuicStreamOffset offset,
688 StreamSendingState state) {
fayanga4b37b22019-06-18 13:37:47 -0700689 ScopedPacketFlusher flusher(this);
QUICHE teamcd098022019-03-22 18:49:55 -0700690 DCHECK(encryption_level >= ENCRYPTION_ZERO_RTT);
vasilvv0fc587f2019-09-06 13:33:08 -0700691 SetEncrypter(encryption_level, std::make_unique<TaggingEncrypter>(0x01));
QUICHE teamcd098022019-03-22 18:49:55 -0700692 SetDefaultEncryptionLevel(encryption_level);
693 struct iovec iov;
694 MakeIOVector(data, &iov);
695 return SaveAndSendStreamData(id, &iov, 1, data.length(), offset, state);
696 }
697
QUICHE teama6ef0a62019-03-07 20:34:33 -0500698 QuicConsumedData SendStreamData3() {
699 return SendStreamDataWithString(
700 GetNthClientInitiatedStreamId(1, transport_version()), "food", 0,
701 NO_FIN);
702 }
703
704 QuicConsumedData SendStreamData5() {
705 return SendStreamDataWithString(
706 GetNthClientInitiatedStreamId(2, transport_version()), "food2", 0,
707 NO_FIN);
708 }
709
710 // Ensures the connection can write stream data before writing.
711 QuicConsumedData EnsureWritableAndSendStreamData5() {
712 EXPECT_TRUE(CanWriteStreamData());
713 return SendStreamData5();
714 }
715
716 // The crypto stream has special semantics so that it is not blocked by a
717 // congestion window limitation, and also so that it gets put into a separate
718 // packet (so that it is easier to reason about a crypto frame not being
719 // split needlessly across packet boundaries). As a result, we have separate
720 // tests for some cases for this stream.
721 QuicConsumedData SendCryptoStreamData() {
722 QuicStreamOffset offset = 0;
723 QuicStringPiece data("chlo");
fayang2ce66082019-10-02 06:29:04 -0700724 if (!QuicVersionUsesCryptoFrames(transport_version())) {
725 return SendCryptoDataWithString(data, offset);
726 }
727 producer_.SaveCryptoData(ENCRYPTION_INITIAL, offset, data);
728 size_t bytes_written;
729 if (notifier_) {
730 bytes_written =
731 notifier_->WriteCryptoData(ENCRYPTION_INITIAL, data.length(), offset);
732 } else {
733 bytes_written = QuicConnection::SendCryptoData(ENCRYPTION_INITIAL,
734 data.length(), offset);
735 }
736 return QuicConsumedData(bytes_written, /*fin_consumed*/ false);
nharper46833c32019-05-15 21:33:05 -0700737 }
738
739 QuicConsumedData SendCryptoDataWithString(QuicStringPiece data,
740 QuicStreamOffset offset) {
QUICHE teamea740082019-03-11 17:58:43 -0700741 if (!QuicVersionUsesCryptoFrames(transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500742 return SendStreamDataWithString(
743 QuicUtils::GetCryptoStreamId(transport_version()), data, offset,
744 NO_FIN);
745 }
QUICHE team6987b4a2019-03-15 16:23:04 -0700746 producer_.SaveCryptoData(ENCRYPTION_INITIAL, offset, data);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500747 size_t bytes_written;
748 if (notifier_) {
749 bytes_written =
QUICHE team6987b4a2019-03-15 16:23:04 -0700750 notifier_->WriteCryptoData(ENCRYPTION_INITIAL, data.length(), offset);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500751 } else {
QUICHE team6987b4a2019-03-15 16:23:04 -0700752 bytes_written = QuicConnection::SendCryptoData(ENCRYPTION_INITIAL,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500753 data.length(), offset);
754 }
755 return QuicConsumedData(bytes_written, /*fin_consumed*/ false);
756 }
757
758 void set_version(ParsedQuicVersion version) {
759 QuicConnectionPeer::GetFramer(this)->set_version(version);
760 }
761
762 void SetSupportedVersions(const ParsedQuicVersionVector& versions) {
763 QuicConnectionPeer::GetFramer(this)->SetSupportedVersions(versions);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500764 writer()->SetSupportedVersions(versions);
765 }
766
767 void set_perspective(Perspective perspective) {
768 writer()->set_perspective(perspective);
769 QuicConnectionPeer::SetPerspective(this, perspective);
770 }
771
772 // Enable path MTU discovery. Assumes that the test is performed from the
773 // client perspective and the higher value of MTU target is used.
774 void EnablePathMtuDiscovery(MockSendAlgorithm* send_algorithm) {
775 ASSERT_EQ(Perspective::IS_CLIENT, perspective());
776
777 QuicConfig config;
778 QuicTagVector connection_options;
779 connection_options.push_back(kMTUH);
780 config.SetConnectionOptionsToSend(connection_options);
781 EXPECT_CALL(*send_algorithm, SetFromConfig(_, _));
782 SetFromConfig(config);
783
784 // Normally, the pacing would be disabled in the test, but calling
785 // SetFromConfig enables it. Set nearly-infinite bandwidth to make the
786 // pacing algorithm work.
787 EXPECT_CALL(*send_algorithm, PacingRate(_))
788 .WillRepeatedly(Return(QuicBandwidth::Infinite()));
789 }
790
791 TestAlarmFactory::TestAlarm* GetAckAlarm() {
792 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
793 QuicConnectionPeer::GetAckAlarm(this));
794 }
795
796 TestAlarmFactory::TestAlarm* GetPingAlarm() {
797 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
798 QuicConnectionPeer::GetPingAlarm(this));
799 }
800
801 TestAlarmFactory::TestAlarm* GetRetransmissionAlarm() {
802 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
803 QuicConnectionPeer::GetRetransmissionAlarm(this));
804 }
805
806 TestAlarmFactory::TestAlarm* GetSendAlarm() {
807 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
808 QuicConnectionPeer::GetSendAlarm(this));
809 }
810
811 TestAlarmFactory::TestAlarm* GetTimeoutAlarm() {
812 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
813 QuicConnectionPeer::GetTimeoutAlarm(this));
814 }
815
816 TestAlarmFactory::TestAlarm* GetMtuDiscoveryAlarm() {
817 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
818 QuicConnectionPeer::GetMtuDiscoveryAlarm(this));
819 }
820
821 TestAlarmFactory::TestAlarm* GetPathDegradingAlarm() {
822 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
823 QuicConnectionPeer::GetPathDegradingAlarm(this));
824 }
825
826 TestAlarmFactory::TestAlarm* GetProcessUndecryptablePacketsAlarm() {
827 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
828 QuicConnectionPeer::GetProcessUndecryptablePacketsAlarm(this));
829 }
830
831 void SetMaxTailLossProbes(size_t max_tail_loss_probes) {
832 QuicSentPacketManagerPeer::SetMaxTailLossProbes(
833 QuicConnectionPeer::GetSentPacketManager(this), max_tail_loss_probes);
834 }
835
836 QuicByteCount GetBytesInFlight() {
ianswett9f459cb2019-04-21 06:39:59 -0700837 return QuicConnectionPeer::GetSentPacketManager(this)->GetBytesInFlight();
QUICHE teama6ef0a62019-03-07 20:34:33 -0500838 }
839
840 void set_notifier(SimpleSessionNotifier* notifier) { notifier_ = notifier; }
841
842 void ReturnEffectivePeerAddressForNextPacket(const QuicSocketAddress& addr) {
vasilvv0fc587f2019-09-06 13:33:08 -0700843 next_effective_peer_addr_ = std::make_unique<QuicSocketAddress>(addr);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500844 }
845
fayang5f135052019-08-22 17:59:40 -0700846 bool PtoEnabled() {
847 if (QuicConnectionPeer::GetSentPacketManager(this)->pto_enabled()) {
848 // PTO mode is default enabled for T099. And TLP/RTO related tests are
849 // stale.
850 DCHECK_EQ(ParsedQuicVersion(PROTOCOL_TLS1_3, QUIC_VERSION_99), version());
851 return true;
852 }
853 return false;
854 }
855
nharper46833c32019-05-15 21:33:05 -0700856 SimpleDataProducer* producer() { return &producer_; }
857
QUICHE teama6ef0a62019-03-07 20:34:33 -0500858 using QuicConnection::active_effective_peer_migration_type;
859 using QuicConnection::IsCurrentPacketConnectivityProbing;
860 using QuicConnection::SelectMutualVersion;
861 using QuicConnection::SendProbingRetransmissions;
862 using QuicConnection::set_defer_send_in_response_to_packets;
863
864 protected:
865 QuicSocketAddress GetEffectivePeerAddressFromCurrentPacket() const override {
866 if (next_effective_peer_addr_) {
867 return *std::move(next_effective_peer_addr_);
868 }
869 return QuicConnection::GetEffectivePeerAddressFromCurrentPacket();
870 }
871
872 private:
873 TestPacketWriter* writer() {
874 return static_cast<TestPacketWriter*>(QuicConnection::writer());
875 }
876
877 SimpleDataProducer producer_;
878
879 SimpleSessionNotifier* notifier_;
880
881 std::unique_ptr<QuicSocketAddress> next_effective_peer_addr_;
882};
883
884enum class AckResponse { kDefer, kImmediate };
885
886// Run tests with combinations of {ParsedQuicVersion, AckResponse}.
887struct TestParams {
888 TestParams(ParsedQuicVersion version,
889 AckResponse ack_response,
890 bool no_stop_waiting)
891 : version(version),
892 ack_response(ack_response),
893 no_stop_waiting(no_stop_waiting) {}
894
QUICHE teama6ef0a62019-03-07 20:34:33 -0500895 ParsedQuicVersion version;
896 AckResponse ack_response;
897 bool no_stop_waiting;
898};
899
dschinazi142051a2019-09-18 18:17:29 -0700900// Used by ::testing::PrintToStringParamName().
901std::string PrintToString(const TestParams& p) {
902 return QuicStrCat(
903 ParsedQuicVersionToString(p.version), "_",
904 (p.ack_response == AckResponse::kDefer ? "defer" : "immediate"), "_",
905 (p.no_stop_waiting ? "No" : ""), "StopWaiting");
906}
907
QUICHE teama6ef0a62019-03-07 20:34:33 -0500908// Constructs various test permutations.
909std::vector<TestParams> GetTestParams() {
910 QuicFlagSaver flags;
rch16df2a52019-09-10 10:50:09 -0700911 SetQuicReloadableFlag(quic_supports_tls_handshake, true);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500912 std::vector<TestParams> params;
913 ParsedQuicVersionVector all_supported_versions = AllSupportedVersions();
914 for (size_t i = 0; i < all_supported_versions.size(); ++i) {
915 for (AckResponse ack_response :
916 {AckResponse::kDefer, AckResponse::kImmediate}) {
dschinazi142051a2019-09-18 18:17:29 -0700917 params.push_back(
918 TestParams(all_supported_versions[i], ack_response, true));
919 if (!VersionHasIetfInvariantHeader(
920 all_supported_versions[i].transport_version)) {
fayangd4291e42019-05-30 10:31:21 -0700921 params.push_back(
dschinazi142051a2019-09-18 18:17:29 -0700922 TestParams(all_supported_versions[i], ack_response, false));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500923 }
924 }
925 }
926 return params;
927}
928
929class QuicConnectionTest : public QuicTestWithParam<TestParams> {
fkastenholz5d880a92019-06-21 09:01:56 -0700930 public:
931 // For tests that do silent connection closes, no such packet is generated. In
932 // order to verify the contents of the OnConnectionClosed upcall, EXPECTs
933 // should invoke this method, saving the frame, and then the test can verify
934 // the contents.
935 void SaveConnectionCloseFrame(const QuicConnectionCloseFrame& frame,
936 ConnectionCloseSource /*source*/) {
937 saved_connection_close_frame_ = frame;
938 connection_close_frame_count_++;
939 }
940
QUICHE teama6ef0a62019-03-07 20:34:33 -0500941 protected:
942 QuicConnectionTest()
943 : connection_id_(TestConnectionId()),
944 framer_(SupportedVersions(version()),
945 QuicTime::Zero(),
946 Perspective::IS_CLIENT,
947 connection_id_.length()),
948 send_algorithm_(new StrictMock<MockSendAlgorithm>),
949 loss_algorithm_(new MockLossAlgorithm()),
950 helper_(new TestConnectionHelper(&clock_, &random_generator_)),
951 alarm_factory_(new TestAlarmFactory()),
952 peer_framer_(SupportedVersions(version()),
953 QuicTime::Zero(),
954 Perspective::IS_SERVER,
955 connection_id_.length()),
956 peer_creator_(connection_id_,
957 &peer_framer_,
958 /*delegate=*/nullptr),
959 writer_(new TestPacketWriter(version(), &clock_)),
960 connection_(connection_id_,
961 kPeerAddress,
962 helper_.get(),
963 alarm_factory_.get(),
964 writer_.get(),
965 Perspective::IS_CLIENT,
966 version()),
967 creator_(QuicConnectionPeer::GetPacketCreator(&connection_)),
968 generator_(QuicConnectionPeer::GetPacketGenerator(&connection_)),
969 manager_(QuicConnectionPeer::GetSentPacketManager(&connection_)),
nharper46833c32019-05-15 21:33:05 -0700970 frame1_(0, false, 0, QuicStringPiece(data1)),
971 frame2_(0, false, 3, QuicStringPiece(data2)),
972 crypto_frame_(ENCRYPTION_INITIAL, 0, QuicStringPiece(data1)),
QUICHE teama6ef0a62019-03-07 20:34:33 -0500973 packet_number_length_(PACKET_4BYTE_PACKET_NUMBER),
974 connection_id_included_(CONNECTION_ID_PRESENT),
fkastenholz5d880a92019-06-21 09:01:56 -0700975 notifier_(&connection_),
976 connection_close_frame_count_(0) {
dschinazi142051a2019-09-18 18:17:29 -0700977 QUIC_DVLOG(2) << "QuicConnectionTest(" << PrintToString(GetParam()) << ")";
rch16df2a52019-09-10 10:50:09 -0700978 SetQuicReloadableFlag(quic_supports_tls_handshake, true);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500979 connection_.set_defer_send_in_response_to_packets(GetParam().ack_response ==
980 AckResponse::kDefer);
nharperc6b99512019-09-19 11:13:48 -0700981 framer_.SetInitialObfuscators(TestConnectionId());
982 connection_.InstallInitialCrypters(TestConnectionId());
983 CrypterPair crypters;
984 CryptoUtils::CreateInitialObfuscators(Perspective::IS_SERVER, version(),
985 TestConnectionId(), &crypters);
986 peer_creator_.SetEncrypter(ENCRYPTION_INITIAL,
987 std::move(crypters.encrypter));
988 if (version().KnowsWhichDecrypterToUse()) {
989 peer_framer_.InstallDecrypter(ENCRYPTION_INITIAL,
990 std::move(crypters.decrypter));
991 } else {
992 peer_framer_.SetDecrypter(ENCRYPTION_INITIAL,
993 std::move(crypters.decrypter));
994 }
nharper2c9f02a2019-05-08 10:25:50 -0700995 for (EncryptionLevel level :
996 {ENCRYPTION_ZERO_RTT, ENCRYPTION_FORWARD_SECURE}) {
997 peer_creator_.SetEncrypter(
vasilvv0fc587f2019-09-06 13:33:08 -0700998 level, std::make_unique<NullEncrypter>(peer_framer_.perspective()));
nharper2c9f02a2019-05-08 10:25:50 -0700999 }
dschinazi7b9278c2019-05-20 07:36:21 -07001000 QuicFramerPeer::SetLastSerializedServerConnectionId(
QUICHE teama6ef0a62019-03-07 20:34:33 -05001001 QuicConnectionPeer::GetFramer(&connection_), connection_id_);
nharperc6b99512019-09-19 11:13:48 -07001002 QuicFramerPeer::SetLastWrittenPacketNumberLength(
1003 QuicConnectionPeer::GetFramer(&connection_), packet_number_length_);
fayangd4291e42019-05-30 10:31:21 -07001004 if (VersionHasIetfInvariantHeader(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001005 EXPECT_TRUE(QuicConnectionPeer::GetNoStopWaitingFrames(&connection_));
1006 } else {
1007 QuicConnectionPeer::SetNoStopWaitingFrames(&connection_,
1008 GetParam().no_stop_waiting);
1009 }
nharper46833c32019-05-15 21:33:05 -07001010 QuicStreamId stream_id;
1011 if (QuicVersionUsesCryptoFrames(version().transport_version)) {
1012 stream_id = QuicUtils::GetFirstBidirectionalStreamId(
1013 version().transport_version, Perspective::IS_CLIENT);
1014 } else {
1015 stream_id = QuicUtils::GetCryptoStreamId(version().transport_version);
1016 }
1017 frame1_.stream_id = stream_id;
1018 frame2_.stream_id = stream_id;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001019 connection_.set_visitor(&visitor_);
1020 if (connection_.session_decides_what_to_write()) {
1021 connection_.SetSessionNotifier(&notifier_);
1022 connection_.set_notifier(&notifier_);
1023 }
1024 connection_.SetSendAlgorithm(send_algorithm_);
1025 connection_.SetLossAlgorithm(loss_algorithm_.get());
1026 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
1027 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1028 .Times(AnyNumber());
1029 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
1030 .WillRepeatedly(Return(kDefaultTCPMSS));
1031 EXPECT_CALL(*send_algorithm_, PacingRate(_))
1032 .WillRepeatedly(Return(QuicBandwidth::Zero()));
1033 EXPECT_CALL(*send_algorithm_, HasReliableBandwidthEstimate())
1034 .Times(AnyNumber());
1035 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
1036 .Times(AnyNumber())
1037 .WillRepeatedly(Return(QuicBandwidth::Zero()));
1038 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
1039 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
1040 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
1041 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).Times(AnyNumber());
1042 EXPECT_CALL(visitor_, HasPendingHandshake()).Times(AnyNumber());
1043 if (connection_.session_decides_what_to_write()) {
1044 EXPECT_CALL(visitor_, OnCanWrite())
1045 .WillRepeatedly(
1046 Invoke(&notifier_, &SimpleSessionNotifier::OnCanWrite));
1047 } else {
1048 EXPECT_CALL(visitor_, OnCanWrite()).Times(AnyNumber());
1049 }
1050 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
1051 .WillRepeatedly(Return(false));
1052 EXPECT_CALL(visitor_, OnCongestionWindowChange(_)).Times(AnyNumber());
zhongyi83161e42019-08-19 09:06:25 -07001053 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -05001054 EXPECT_CALL(visitor_, OnForwardProgressConfirmed()).Times(AnyNumber());
1055
1056 EXPECT_CALL(*loss_algorithm_, GetLossTimeout())
1057 .WillRepeatedly(Return(QuicTime::Zero()));
1058 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
1059 .Times(AnyNumber());
zhongyi546cc452019-04-12 15:27:49 -07001060
1061 if (connection_.version().KnowsWhichDecrypterToUse()) {
1062 connection_.InstallDecrypter(
1063 ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07001064 std::make_unique<NullDecrypter>(Perspective::IS_CLIENT));
zhongyi546cc452019-04-12 15:27:49 -07001065 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001066 }
1067
1068 QuicConnectionTest(const QuicConnectionTest&) = delete;
1069 QuicConnectionTest& operator=(const QuicConnectionTest&) = delete;
1070
1071 ParsedQuicVersion version() { return GetParam().version; }
1072
QUICHE teama6ef0a62019-03-07 20:34:33 -05001073 QuicStopWaitingFrame* stop_waiting() {
1074 QuicConnectionPeer::PopulateStopWaitingFrame(&connection_, &stop_waiting_);
1075 return &stop_waiting_;
1076 }
1077
1078 QuicPacketNumber least_unacked() {
1079 if (writer_->stop_waiting_frames().empty()) {
1080 return QuicPacketNumber();
1081 }
1082 return writer_->stop_waiting_frames()[0].least_unacked;
1083 }
1084
1085 void use_tagging_decrypter() { writer_->use_tagging_decrypter(); }
1086
zhongyi546cc452019-04-12 15:27:49 -07001087 void SetDecrypter(EncryptionLevel level,
1088 std::unique_ptr<QuicDecrypter> decrypter) {
1089 if (connection_.version().KnowsWhichDecrypterToUse()) {
1090 connection_.InstallDecrypter(level, std::move(decrypter));
1091 connection_.RemoveDecrypter(ENCRYPTION_INITIAL);
1092 } else {
1093 connection_.SetDecrypter(level, std::move(decrypter));
1094 }
1095 }
1096
QUICHE teama6ef0a62019-03-07 20:34:33 -05001097 void ProcessPacket(uint64_t number) {
1098 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
1099 ProcessDataPacket(number);
1100 if (connection_.GetSendAlarm()->IsSet()) {
1101 connection_.GetSendAlarm()->Fire();
1102 }
1103 }
1104
1105 void ProcessReceivedPacket(const QuicSocketAddress& self_address,
1106 const QuicSocketAddress& peer_address,
1107 const QuicReceivedPacket& packet) {
1108 connection_.ProcessUdpPacket(self_address, peer_address, packet);
1109 if (connection_.GetSendAlarm()->IsSet()) {
1110 connection_.GetSendAlarm()->Fire();
1111 }
1112 }
1113
1114 void ProcessFramePacket(QuicFrame frame) {
1115 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
1116 }
1117
1118 void ProcessFramePacketWithAddresses(QuicFrame frame,
1119 QuicSocketAddress self_address,
1120 QuicSocketAddress peer_address) {
1121 QuicFrames frames;
1122 frames.push_back(QuicFrame(frame));
1123 QuicPacketCreatorPeer::SetSendVersionInPacket(
1124 &peer_creator_, connection_.perspective() == Perspective::IS_SERVER);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001125
dschinazi66dea072019-04-09 11:41:06 -07001126 char buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05001127 SerializedPacket serialized_packet =
dschinazi66dea072019-04-09 11:41:06 -07001128 QuicPacketCreatorPeer::SerializeAllFrames(
1129 &peer_creator_, frames, buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001130 connection_.ProcessUdpPacket(
1131 self_address, peer_address,
1132 QuicReceivedPacket(serialized_packet.encrypted_buffer,
1133 serialized_packet.encrypted_length, clock_.Now()));
1134 if (connection_.GetSendAlarm()->IsSet()) {
1135 connection_.GetSendAlarm()->Fire();
1136 }
1137 }
1138
1139 // Bypassing the packet creator is unrealistic, but allows us to process
1140 // packets the QuicPacketCreator won't allow us to create.
1141 void ForceProcessFramePacket(QuicFrame frame) {
1142 QuicFrames frames;
1143 frames.push_back(QuicFrame(frame));
zhongyi546cc452019-04-12 15:27:49 -07001144 bool send_version = connection_.perspective() == Perspective::IS_SERVER;
1145 if (connection_.version().KnowsWhichDecrypterToUse()) {
1146 send_version = true;
1147 }
1148 QuicPacketCreatorPeer::SetSendVersionInPacket(&peer_creator_, send_version);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001149 QuicPacketHeader header;
1150 QuicPacketCreatorPeer::FillPacketHeader(&peer_creator_, &header);
dschinazi66dea072019-04-09 11:41:06 -07001151 char encrypted_buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05001152 size_t length = peer_framer_.BuildDataPacket(
dschinazi66dea072019-04-09 11:41:06 -07001153 header, frames, encrypted_buffer, kMaxOutgoingPacketSize,
1154 ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001155 DCHECK_GT(length, 0u);
1156
1157 const size_t encrypted_length = peer_framer_.EncryptInPlace(
QUICHE team6987b4a2019-03-15 16:23:04 -07001158 ENCRYPTION_INITIAL, header.packet_number,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001159 GetStartOfEncryptedData(peer_framer_.version().transport_version,
1160 header),
dschinazi66dea072019-04-09 11:41:06 -07001161 length, kMaxOutgoingPacketSize, encrypted_buffer);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001162 DCHECK_GT(encrypted_length, 0u);
1163
1164 connection_.ProcessUdpPacket(
1165 kSelfAddress, kPeerAddress,
1166 QuicReceivedPacket(encrypted_buffer, encrypted_length, clock_.Now()));
1167 }
1168
1169 size_t ProcessFramePacketAtLevel(uint64_t number,
1170 QuicFrame frame,
1171 EncryptionLevel level) {
1172 QuicPacketHeader header;
1173 header.destination_connection_id = connection_id_;
1174 header.packet_number_length = packet_number_length_;
1175 header.destination_connection_id_included = connection_id_included_;
dschinazi5e1a7b22019-07-31 12:23:21 -07001176 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001177 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1178 }
zhongyi546cc452019-04-12 15:27:49 -07001179 if (level == ENCRYPTION_INITIAL &&
1180 peer_framer_.version().KnowsWhichDecrypterToUse()) {
1181 header.version_flag = true;
nharperd43f1d62019-07-01 15:18:20 -07001182 if (QuicVersionHasLongHeaderLengths(peer_framer_.transport_version())) {
1183 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
1184 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
1185 }
QUICHE team2252b702019-05-14 23:55:14 -04001186 }
dschinazi5e1a7b22019-07-31 12:23:21 -07001187 if (header.version_flag &&
QUICHE team2252b702019-05-14 23:55:14 -04001188 peer_framer_.perspective() == Perspective::IS_SERVER) {
1189 header.source_connection_id = connection_id_;
1190 header.source_connection_id_included = CONNECTION_ID_PRESENT;
zhongyi546cc452019-04-12 15:27:49 -07001191 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001192 header.packet_number = QuicPacketNumber(number);
1193 QuicFrames frames;
1194 frames.push_back(frame);
1195 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
QUICHE teamcd098022019-03-22 18:49:55 -07001196 // Set the correct encryption level and encrypter on peer_creator and
1197 // peer_framer, respectively.
1198 peer_creator_.set_encryption_level(level);
1199 if (QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_) >
1200 ENCRYPTION_INITIAL) {
1201 peer_framer_.SetEncrypter(
1202 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
vasilvv0fc587f2019-09-06 13:33:08 -07001203 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teamcd098022019-03-22 18:49:55 -07001204 // Set the corresponding decrypter.
zhongyi546cc452019-04-12 15:27:49 -07001205 if (connection_.version().KnowsWhichDecrypterToUse()) {
1206 connection_.InstallDecrypter(
1207 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
vasilvv0fc587f2019-09-06 13:33:08 -07001208 std::make_unique<StrictTaggingDecrypter>(0x01));
zhongyi546cc452019-04-12 15:27:49 -07001209 connection_.RemoveDecrypter(ENCRYPTION_INITIAL);
1210 } else {
1211 connection_.SetDecrypter(
1212 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
vasilvv0fc587f2019-09-06 13:33:08 -07001213 std::make_unique<StrictTaggingDecrypter>(0x01));
zhongyi546cc452019-04-12 15:27:49 -07001214 }
QUICHE teamcd098022019-03-22 18:49:55 -07001215 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001216
dschinazi66dea072019-04-09 11:41:06 -07001217 char buffer[kMaxOutgoingPacketSize];
1218 size_t encrypted_length =
1219 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
1220 buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001221 connection_.ProcessUdpPacket(
1222 kSelfAddress, kPeerAddress,
QUICHE teamcd098022019-03-22 18:49:55 -07001223 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1224 if (connection_.GetSendAlarm()->IsSet()) {
1225 connection_.GetSendAlarm()->Fire();
1226 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001227 return encrypted_length;
1228 }
1229
1230 size_t ProcessDataPacket(uint64_t number) {
nharper2c9f02a2019-05-08 10:25:50 -07001231 return ProcessDataPacketAtLevel(number, false, ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001232 }
1233
1234 size_t ProcessDataPacket(QuicPacketNumber packet_number) {
nharper2c9f02a2019-05-08 10:25:50 -07001235 return ProcessDataPacketAtLevel(packet_number, false,
1236 ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001237 }
1238
1239 size_t ProcessDataPacketAtLevel(QuicPacketNumber packet_number,
1240 bool has_stop_waiting,
1241 EncryptionLevel level) {
1242 return ProcessDataPacketAtLevel(packet_number.ToUint64(), has_stop_waiting,
1243 level);
1244 }
1245
dschinazi17d42422019-06-18 16:35:07 -07001246 size_t ProcessCryptoPacketAtLevel(uint64_t number,
1247 EncryptionLevel /*level*/) {
fayangc31c9952019-06-05 13:54:48 -07001248 QuicPacketHeader header = ConstructPacketHeader(number, ENCRYPTION_INITIAL);
nharper46833c32019-05-15 21:33:05 -07001249 QuicFrames frames;
1250 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1251 frames.push_back(QuicFrame(&crypto_frame_));
1252 } else {
1253 frames.push_back(QuicFrame(frame1_));
1254 }
fayang5f135052019-08-22 17:59:40 -07001255 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
nharper46833c32019-05-15 21:33:05 -07001256 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
1257 char buffer[kMaxOutgoingPacketSize];
1258 peer_creator_.set_encryption_level(ENCRYPTION_INITIAL);
fayangc31c9952019-06-05 13:54:48 -07001259 size_t encrypted_length = peer_framer_.EncryptPayload(
1260 ENCRYPTION_INITIAL, QuicPacketNumber(number), *packet, buffer,
1261 kMaxOutgoingPacketSize);
nharper46833c32019-05-15 21:33:05 -07001262 connection_.ProcessUdpPacket(
1263 kSelfAddress, kPeerAddress,
1264 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1265 if (connection_.GetSendAlarm()->IsSet()) {
1266 connection_.GetSendAlarm()->Fire();
1267 }
1268 return encrypted_length;
1269 }
1270
QUICHE teama6ef0a62019-03-07 20:34:33 -05001271 size_t ProcessDataPacketAtLevel(uint64_t number,
1272 bool has_stop_waiting,
1273 EncryptionLevel level) {
1274 std::unique_ptr<QuicPacket> packet(
QUICHE team8c1daa22019-03-13 08:33:41 -07001275 ConstructDataPacket(number, has_stop_waiting, level));
dschinazi66dea072019-04-09 11:41:06 -07001276 char buffer[kMaxOutgoingPacketSize];
QUICHE teamcd098022019-03-22 18:49:55 -07001277 peer_creator_.set_encryption_level(level);
dschinazi66dea072019-04-09 11:41:06 -07001278 size_t encrypted_length =
1279 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
1280 buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001281 connection_.ProcessUdpPacket(
1282 kSelfAddress, kPeerAddress,
1283 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1284 if (connection_.GetSendAlarm()->IsSet()) {
1285 connection_.GetSendAlarm()->Fire();
1286 }
1287 return encrypted_length;
1288 }
1289
1290 void ProcessClosePacket(uint64_t number) {
1291 std::unique_ptr<QuicPacket> packet(ConstructClosePacket(number));
dschinazi66dea072019-04-09 11:41:06 -07001292 char buffer[kMaxOutgoingPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07001293 size_t encrypted_length = peer_framer_.EncryptPayload(
nharperc6b99512019-09-19 11:13:48 -07001294 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(number), *packet, buffer,
dschinazi66dea072019-04-09 11:41:06 -07001295 kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001296 connection_.ProcessUdpPacket(
1297 kSelfAddress, kPeerAddress,
1298 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
1299 }
1300
1301 QuicByteCount SendStreamDataToPeer(QuicStreamId id,
1302 QuicStringPiece data,
1303 QuicStreamOffset offset,
1304 StreamSendingState state,
1305 QuicPacketNumber* last_packet) {
1306 QuicByteCount packet_size;
fayang0fcbf352019-08-30 11:15:58 -07001307 // Save the last packet's size.
QUICHE teama6ef0a62019-03-07 20:34:33 -05001308 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
fayang0fcbf352019-08-30 11:15:58 -07001309 .Times(AnyNumber())
1310 .WillRepeatedly(SaveArg<3>(&packet_size));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001311 connection_.SendStreamDataWithString(id, data, offset, state);
1312 if (last_packet != nullptr) {
1313 *last_packet = creator_->packet_number();
1314 }
1315 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1316 .Times(AnyNumber());
1317 return packet_size;
1318 }
1319
1320 void SendAckPacketToPeer() {
1321 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1322 {
fayanga4b37b22019-06-18 13:37:47 -07001323 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001324 connection_.SendAck();
1325 }
1326 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1327 .Times(AnyNumber());
1328 }
1329
1330 void SendRstStream(QuicStreamId id,
1331 QuicRstStreamErrorCode error,
1332 QuicStreamOffset bytes_written) {
1333 if (connection_.session_decides_what_to_write()) {
1334 notifier_.WriteOrBufferRstStream(id, error, bytes_written);
1335 connection_.OnStreamReset(id, error);
1336 return;
1337 }
1338 std::unique_ptr<QuicRstStreamFrame> rst_stream =
vasilvv0fc587f2019-09-06 13:33:08 -07001339 std::make_unique<QuicRstStreamFrame>(1, id, error, bytes_written);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001340 if (connection_.SendControlFrame(QuicFrame(rst_stream.get()))) {
1341 rst_stream.release();
1342 }
1343 connection_.OnStreamReset(id, error);
1344 }
1345
zhongyifbb25772019-04-10 16:54:08 -07001346 void SendPing() {
1347 if (connection_.session_decides_what_to_write()) {
1348 notifier_.WriteOrBufferPing();
1349 } else {
1350 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
1351 }
1352 }
1353
QUICHE teama6ef0a62019-03-07 20:34:33 -05001354 void ProcessAckPacket(uint64_t packet_number, QuicAckFrame* frame) {
1355 if (packet_number > 1) {
1356 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, packet_number - 1);
1357 } else {
1358 QuicPacketCreatorPeer::ClearPacketNumber(&peer_creator_);
1359 }
1360 ProcessFramePacket(QuicFrame(frame));
1361 }
1362
1363 void ProcessAckPacket(QuicAckFrame* frame) {
1364 ProcessFramePacket(QuicFrame(frame));
1365 }
1366
1367 void ProcessStopWaitingPacket(QuicStopWaitingFrame frame) {
1368 ProcessFramePacket(QuicFrame(frame));
1369 }
1370
1371 size_t ProcessStopWaitingPacketAtLevel(uint64_t number,
1372 QuicStopWaitingFrame frame,
dschinazi17d42422019-06-18 16:35:07 -07001373 EncryptionLevel /*level*/) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001374 return ProcessFramePacketAtLevel(number, QuicFrame(frame),
1375 ENCRYPTION_ZERO_RTT);
1376 }
1377
1378 void ProcessGoAwayPacket(QuicGoAwayFrame* frame) {
1379 ProcessFramePacket(QuicFrame(frame));
1380 }
1381
1382 bool IsMissing(uint64_t number) {
fayangc31c9952019-06-05 13:54:48 -07001383 return IsAwaitingPacket(connection_.ack_frame(), QuicPacketNumber(number),
QUICHE teama6ef0a62019-03-07 20:34:33 -05001384 QuicPacketNumber());
1385 }
1386
1387 std::unique_ptr<QuicPacket> ConstructPacket(const QuicPacketHeader& header,
1388 const QuicFrames& frames) {
1389 auto packet = BuildUnsizedDataPacket(&peer_framer_, header, frames);
1390 EXPECT_NE(nullptr, packet.get());
1391 return packet;
1392 }
1393
nharper46833c32019-05-15 21:33:05 -07001394 QuicPacketHeader ConstructPacketHeader(uint64_t number,
1395 EncryptionLevel level) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001396 QuicPacketHeader header;
fayangd4291e42019-05-30 10:31:21 -07001397 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version()) &&
QUICHE team8c1daa22019-03-13 08:33:41 -07001398 level < ENCRYPTION_FORWARD_SECURE) {
1399 // Set long header type accordingly.
1400 header.version_flag = true;
nharperc6b99512019-09-19 11:13:48 -07001401 header.form = IETF_QUIC_LONG_HEADER_PACKET;
QUICHE team8c1daa22019-03-13 08:33:41 -07001402 header.long_packet_type = EncryptionlevelToLongHeaderType(level);
1403 if (QuicVersionHasLongHeaderLengths(
1404 peer_framer_.version().transport_version)) {
1405 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
1406 if (header.long_packet_type == INITIAL) {
1407 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
1408 }
1409 }
1410 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001411 // Set connection_id to peer's in memory representation as this data packet
1412 // is created by peer_framer.
dschinazi5e1a7b22019-07-31 12:23:21 -07001413 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
QUICHE team2252b702019-05-14 23:55:14 -04001414 header.source_connection_id = connection_id_;
1415 header.source_connection_id_included = connection_id_included_;
1416 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1417 } else {
1418 header.destination_connection_id = connection_id_;
1419 header.destination_connection_id_included = connection_id_included_;
1420 }
fayangd4291e42019-05-30 10:31:21 -07001421 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version()) &&
QUICHE teama6ef0a62019-03-07 20:34:33 -05001422 peer_framer_.perspective() == Perspective::IS_SERVER) {
1423 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
QUICHE team8c1daa22019-03-13 08:33:41 -07001424 if (header.version_flag) {
1425 header.source_connection_id = connection_id_;
1426 header.source_connection_id_included = CONNECTION_ID_PRESENT;
1427 if (GetParam().version.handshake_protocol == PROTOCOL_QUIC_CRYPTO &&
1428 header.long_packet_type == ZERO_RTT_PROTECTED) {
QUICHE team548d51b2019-03-14 10:06:54 -07001429 header.nonce = &kTestDiversificationNonce;
QUICHE team8c1daa22019-03-13 08:33:41 -07001430 }
1431 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001432 }
QUICHE team2252b702019-05-14 23:55:14 -04001433 header.packet_number_length = packet_number_length_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001434 header.packet_number = QuicPacketNumber(number);
nharper46833c32019-05-15 21:33:05 -07001435 return header;
1436 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001437
nharper46833c32019-05-15 21:33:05 -07001438 std::unique_ptr<QuicPacket> ConstructDataPacket(uint64_t number,
1439 bool has_stop_waiting,
1440 EncryptionLevel level) {
1441 QuicPacketHeader header = ConstructPacketHeader(number, level);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001442 QuicFrames frames;
1443 frames.push_back(QuicFrame(frame1_));
1444 if (has_stop_waiting) {
1445 frames.push_back(QuicFrame(stop_waiting_));
1446 }
1447 return ConstructPacket(header, frames);
1448 }
1449
1450 OwningSerializedPacketPointer ConstructProbingPacket() {
fkastenholz305e1732019-06-18 05:01:22 -07001451 if (VersionHasIetfQuicFrames(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001452 QuicPathFrameBuffer payload = {
1453 {0xde, 0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xfe}};
1454 return QuicPacketCreatorPeer::
1455 SerializePathChallengeConnectivityProbingPacket(&peer_creator_,
1456 &payload);
1457 }
1458 return QuicPacketCreatorPeer::SerializeConnectivityProbingPacket(
1459 &peer_creator_);
1460 }
1461
1462 std::unique_ptr<QuicPacket> ConstructClosePacket(uint64_t number) {
1463 QuicPacketHeader header;
1464 // Set connection_id to peer's in memory representation as this connection
1465 // close packet is created by peer_framer.
dschinazi5e1a7b22019-07-31 12:23:21 -07001466 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
QUICHE team2252b702019-05-14 23:55:14 -04001467 header.source_connection_id = connection_id_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001468 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
fayangd4291e42019-05-30 10:31:21 -07001469 if (!VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04001470 header.source_connection_id_included = CONNECTION_ID_PRESENT;
1471 }
1472 } else {
1473 header.destination_connection_id = connection_id_;
fayangd4291e42019-05-30 10:31:21 -07001474 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04001475 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1476 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001477 }
1478
QUICHE team2252b702019-05-14 23:55:14 -04001479 header.packet_number = QuicPacketNumber(number);
1480
fkastenholz0d6554a2019-08-05 12:20:35 -07001481 QuicErrorCode kQuicErrorCode = QUIC_PEER_GOING_AWAY;
fkastenholz591814c2019-09-06 12:11:46 -07001482 QuicConnectionCloseFrame qccf(peer_framer_.transport_version(),
1483 kQuicErrorCode, "",
1484 /*transport_close_frame_type=*/0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001485 QuicFrames frames;
1486 frames.push_back(QuicFrame(&qccf));
1487 return ConstructPacket(header, frames);
1488 }
1489
1490 QuicTime::Delta DefaultRetransmissionTime() {
1491 return QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
1492 }
1493
1494 QuicTime::Delta DefaultDelayedAckTime() {
1495 return QuicTime::Delta::FromMilliseconds(kDefaultDelayedAckTimeMs);
1496 }
1497
1498 const QuicStopWaitingFrame InitStopWaitingFrame(uint64_t least_unacked) {
1499 QuicStopWaitingFrame frame;
1500 frame.least_unacked = QuicPacketNumber(least_unacked);
1501 return frame;
1502 }
1503
1504 // Construct a ack_frame that acks all packet numbers between 1 and
1505 // |largest_acked|, except |missing|.
1506 // REQUIRES: 1 <= |missing| < |largest_acked|
1507 QuicAckFrame ConstructAckFrame(uint64_t largest_acked, uint64_t missing) {
1508 return ConstructAckFrame(QuicPacketNumber(largest_acked),
1509 QuicPacketNumber(missing));
1510 }
1511
1512 QuicAckFrame ConstructAckFrame(QuicPacketNumber largest_acked,
1513 QuicPacketNumber missing) {
1514 if (missing == QuicPacketNumber(1)) {
1515 return InitAckFrame({{missing + 1, largest_acked + 1}});
1516 }
1517 return InitAckFrame(
1518 {{QuicPacketNumber(1), missing}, {missing + 1, largest_acked + 1}});
1519 }
1520
1521 // Undo nacking a packet within the frame.
1522 void AckPacket(QuicPacketNumber arrived, QuicAckFrame* frame) {
1523 EXPECT_FALSE(frame->packets.Contains(arrived));
1524 frame->packets.Add(arrived);
1525 }
1526
1527 void TriggerConnectionClose() {
1528 // Send an erroneous packet to close the connection.
fkastenholz5d880a92019-06-21 09:01:56 -07001529 EXPECT_CALL(visitor_,
1530 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
1531 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
1532
QUICHE teamcd098022019-03-22 18:49:55 -07001533 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1534 // Triggers a connection by receiving ACK of unsent packet.
1535 QuicAckFrame frame = InitAckFrame(10000);
1536 ProcessAckPacket(1, &frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001537 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1538 nullptr);
fkastenholz5d880a92019-06-21 09:01:56 -07001539 EXPECT_EQ(1, connection_close_frame_count_);
1540 EXPECT_EQ(QUIC_INVALID_ACK_DATA,
1541 saved_connection_close_frame_.quic_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001542 }
1543
1544 void BlockOnNextWrite() {
1545 writer_->BlockOnNextWrite();
1546 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
1547 }
1548
1549 void SimulateNextPacketTooLarge() { writer_->SimulateNextPacketTooLarge(); }
1550
1551 void AlwaysGetPacketTooLarge() { writer_->AlwaysGetPacketTooLarge(); }
1552
1553 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
1554 writer_->SetWritePauseTimeDelta(delta);
1555 }
1556
1557 void CongestionBlockWrites() {
1558 EXPECT_CALL(*send_algorithm_, CanSend(_))
1559 .WillRepeatedly(testing::Return(false));
1560 }
1561
1562 void CongestionUnblockWrites() {
1563 EXPECT_CALL(*send_algorithm_, CanSend(_))
1564 .WillRepeatedly(testing::Return(true));
1565 }
1566
1567 void set_perspective(Perspective perspective) {
1568 connection_.set_perspective(perspective);
1569 if (perspective == Perspective::IS_SERVER) {
1570 connection_.set_can_truncate_connection_ids(true);
1571 }
1572 QuicFramerPeer::SetPerspective(&peer_framer_,
nharper4eba09b2019-06-26 20:17:25 -07001573 QuicUtils::InvertPerspective(perspective));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001574 }
1575
1576 void set_packets_between_probes_base(
1577 const QuicPacketCount packets_between_probes_base) {
1578 QuicConnectionPeer::SetPacketsBetweenMtuProbes(&connection_,
1579 packets_between_probes_base);
1580 QuicConnectionPeer::SetNextMtuProbeAt(
1581 &connection_, QuicPacketNumber(packets_between_probes_base));
1582 }
1583
1584 bool IsDefaultTestConfiguration() {
1585 TestParams p = GetParam();
1586 return p.ack_response == AckResponse::kImmediate &&
1587 p.version == AllSupportedVersions()[0] && p.no_stop_waiting;
1588 }
1589
fkastenholz5d880a92019-06-21 09:01:56 -07001590 void TestConnectionCloseQuicErrorCode(QuicErrorCode expected_code) {
1591 // Not strictly needed for this test, but is commonly done.
1592 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1593 nullptr);
1594 const std::vector<QuicConnectionCloseFrame>& connection_close_frames =
1595 writer_->connection_close_frames();
1596 ASSERT_EQ(1u, connection_close_frames.size());
fkastenholz0d6554a2019-08-05 12:20:35 -07001597 if (!VersionHasIetfQuicFrames(version().transport_version)) {
1598 EXPECT_EQ(expected_code, connection_close_frames[0].quic_error_code);
1599 EXPECT_EQ(GOOGLE_QUIC_CONNECTION_CLOSE,
1600 connection_close_frames[0].close_type);
1601 return;
1602 }
1603
1604 QuicErrorCodeToIetfMapping mapping =
1605 QuicErrorCodeToTransportErrorCode(expected_code);
1606
1607 if (mapping.is_transport_close_) {
1608 // This Google QUIC Error Code maps to a transport close,
1609 EXPECT_EQ(IETF_QUIC_TRANSPORT_CONNECTION_CLOSE,
1610 connection_close_frames[0].close_type);
1611 EXPECT_EQ(mapping.transport_error_code_,
1612 connection_close_frames[0].transport_error_code);
1613 // TODO(fkastenholz): when the extracted error code CL lands,
1614 // need to test that extracted==expected.
1615 } else {
1616 // This maps to an application close.
1617 EXPECT_EQ(expected_code, connection_close_frames[0].quic_error_code);
1618 EXPECT_EQ(IETF_QUIC_APPLICATION_CONNECTION_CLOSE,
1619 connection_close_frames[0].close_type);
1620 // TODO(fkastenholz): when the extracted error code CL lands,
1621 // need to test that extracted==expected.
1622 }
fkastenholz5d880a92019-06-21 09:01:56 -07001623 }
1624
QUICHE teama6ef0a62019-03-07 20:34:33 -05001625 QuicConnectionId connection_id_;
1626 QuicFramer framer_;
1627
1628 MockSendAlgorithm* send_algorithm_;
1629 std::unique_ptr<MockLossAlgorithm> loss_algorithm_;
1630 MockClock clock_;
1631 MockRandom random_generator_;
1632 SimpleBufferAllocator buffer_allocator_;
1633 std::unique_ptr<TestConnectionHelper> helper_;
1634 std::unique_ptr<TestAlarmFactory> alarm_factory_;
1635 QuicFramer peer_framer_;
1636 QuicPacketCreator peer_creator_;
1637 std::unique_ptr<TestPacketWriter> writer_;
1638 TestConnection connection_;
1639 QuicPacketCreator* creator_;
1640 QuicPacketGenerator* generator_;
1641 QuicSentPacketManager* manager_;
1642 StrictMock<MockQuicConnectionVisitor> visitor_;
1643
1644 QuicStreamFrame frame1_;
1645 QuicStreamFrame frame2_;
nharper46833c32019-05-15 21:33:05 -07001646 QuicCryptoFrame crypto_frame_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001647 QuicAckFrame ack_;
1648 QuicStopWaitingFrame stop_waiting_;
1649 QuicPacketNumberLength packet_number_length_;
1650 QuicConnectionIdIncluded connection_id_included_;
1651
1652 SimpleSessionNotifier notifier_;
fkastenholz5d880a92019-06-21 09:01:56 -07001653
1654 QuicConnectionCloseFrame saved_connection_close_frame_;
1655 int connection_close_frame_count_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001656};
1657
1658// Run all end to end tests with all supported versions.
1659INSTANTIATE_TEST_SUITE_P(SupportedVersion,
1660 QuicConnectionTest,
dschinazi142051a2019-09-18 18:17:29 -07001661 ::testing::ValuesIn(GetTestParams()),
1662 ::testing::PrintToStringParamName());
QUICHE teama6ef0a62019-03-07 20:34:33 -05001663
fkastenholz0d6554a2019-08-05 12:20:35 -07001664// These two tests ensure that the QuicErrorCode mapping works correctly.
1665// Both tests expect to see a Google QUIC close if not running IETF QUIC.
1666// If running IETF QUIC, the first will generate a transport connection
1667// close, the second an application connection close.
1668// The connection close codes for the two tests are manually chosen;
1669// they are expected to always map to transport- and application-
1670// closes, respectively. If that changes, mew codes should be chosen.
1671TEST_P(QuicConnectionTest, CloseErrorCodeTestTransport) {
1672 EXPECT_TRUE(connection_.connected());
1673 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
1674 connection_.CloseConnection(
1675 IETF_QUIC_PROTOCOL_VIOLATION, "Should be transport close",
1676 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1677 EXPECT_FALSE(connection_.connected());
1678 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
1679}
1680
1681// Test that the IETF QUIC Error code mapping function works
1682// properly for application connection close codes.
1683TEST_P(QuicConnectionTest, CloseErrorCodeTestApplication) {
1684 EXPECT_TRUE(connection_.connected());
1685 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
1686 connection_.CloseConnection(
1687 QUIC_HEADERS_STREAM_DATA_DECOMPRESS_FAILURE,
1688 "Should be application close",
1689 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1690 EXPECT_FALSE(connection_.connected());
1691 TestConnectionCloseQuicErrorCode(QUIC_HEADERS_STREAM_DATA_DECOMPRESS_FAILURE);
1692}
1693
QUICHE teama6ef0a62019-03-07 20:34:33 -05001694TEST_P(QuicConnectionTest, SelfAddressChangeAtClient) {
1695 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1696
1697 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
1698 EXPECT_TRUE(connection_.connected());
1699
nharper46833c32019-05-15 21:33:05 -07001700 QuicFrame frame;
1701 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1702 frame = QuicFrame(&crypto_frame_);
1703 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1704 } else {
1705 frame = QuicFrame(QuicStreamFrame(
1706 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
1707 0u, QuicStringPiece()));
1708 EXPECT_CALL(visitor_, OnStreamFrame(_));
1709 }
1710 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001711 // Cause change in self_address.
1712 QuicIpAddress host;
1713 host.FromString("1.1.1.1");
1714 QuicSocketAddress self_address(host, 123);
nharper46833c32019-05-15 21:33:05 -07001715 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1716 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1717 } else {
1718 EXPECT_CALL(visitor_, OnStreamFrame(_));
1719 }
1720 ProcessFramePacketWithAddresses(frame, self_address, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001721 EXPECT_TRUE(connection_.connected());
1722}
1723
1724TEST_P(QuicConnectionTest, SelfAddressChangeAtServer) {
1725 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1726
1727 set_perspective(Perspective::IS_SERVER);
1728 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1729
1730 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1731 EXPECT_TRUE(connection_.connected());
1732
nharper46833c32019-05-15 21:33:05 -07001733 QuicFrame frame;
1734 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1735 frame = QuicFrame(&crypto_frame_);
1736 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1737 } else {
1738 frame = QuicFrame(QuicStreamFrame(
1739 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
1740 0u, QuicStringPiece()));
1741 EXPECT_CALL(visitor_, OnStreamFrame(_));
1742 }
1743 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001744 // Cause change in self_address.
1745 QuicIpAddress host;
1746 host.FromString("1.1.1.1");
1747 QuicSocketAddress self_address(host, 123);
1748 EXPECT_CALL(visitor_, AllowSelfAddressChange()).WillOnce(Return(false));
fkastenholz5d880a92019-06-21 09:01:56 -07001749 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
nharper46833c32019-05-15 21:33:05 -07001750 ProcessFramePacketWithAddresses(frame, self_address, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001751 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07001752 TestConnectionCloseQuicErrorCode(QUIC_ERROR_MIGRATING_ADDRESS);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001753}
1754
1755TEST_P(QuicConnectionTest, AllowSelfAddressChangeToMappedIpv4AddressAtServer) {
1756 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1757
1758 set_perspective(Perspective::IS_SERVER);
1759 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1760
1761 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1762 EXPECT_TRUE(connection_.connected());
1763
nharper46833c32019-05-15 21:33:05 -07001764 QuicFrame frame;
1765 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1766 frame = QuicFrame(&crypto_frame_);
1767 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(3);
1768 } else {
1769 frame = QuicFrame(QuicStreamFrame(
1770 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
1771 0u, QuicStringPiece()));
1772 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(3);
1773 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001774 QuicIpAddress host;
1775 host.FromString("1.1.1.1");
1776 QuicSocketAddress self_address1(host, 443);
nharper46833c32019-05-15 21:33:05 -07001777 ProcessFramePacketWithAddresses(frame, self_address1, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001778 // Cause self_address change to mapped Ipv4 address.
1779 QuicIpAddress host2;
1780 host2.FromString(
1781 QuicStrCat("::ffff:", connection_.self_address().host().ToString()));
1782 QuicSocketAddress self_address2(host2, connection_.self_address().port());
nharper46833c32019-05-15 21:33:05 -07001783 ProcessFramePacketWithAddresses(frame, self_address2, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001784 EXPECT_TRUE(connection_.connected());
1785 // self_address change back to Ipv4 address.
nharper46833c32019-05-15 21:33:05 -07001786 ProcessFramePacketWithAddresses(frame, self_address1, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001787 EXPECT_TRUE(connection_.connected());
1788}
1789
1790TEST_P(QuicConnectionTest, ClientAddressChangeAndPacketReordered) {
1791 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1792 set_perspective(Perspective::IS_SERVER);
1793 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1794
1795 // Clear direct_peer_address.
1796 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1797 // Clear effective_peer_address, it is the same as direct_peer_address for
1798 // this test.
1799 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1800 QuicSocketAddress());
1801
nharper46833c32019-05-15 21:33:05 -07001802 QuicFrame frame;
1803 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1804 frame = QuicFrame(&crypto_frame_);
1805 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1806 } else {
1807 frame = QuicFrame(QuicStreamFrame(
1808 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
1809 0u, QuicStringPiece()));
1810 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1811 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001812 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001813 const QuicSocketAddress kNewPeerAddress =
1814 QuicSocketAddress(QuicIpAddress::Loopback6(),
1815 /*port=*/23456);
nharper46833c32019-05-15 21:33:05 -07001816 ProcessFramePacketWithAddresses(frame, kSelfAddress, kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001817 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1818 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1819
1820 // Decrease packet number to simulate out-of-order packets.
1821 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 4);
1822 // This is an old packet, do not migrate.
1823 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
nharper46833c32019-05-15 21:33:05 -07001824 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001825 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1826 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1827}
1828
1829TEST_P(QuicConnectionTest, PeerAddressChangeAtServer) {
1830 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1831 set_perspective(Perspective::IS_SERVER);
1832 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1833 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1834
1835 // Clear direct_peer_address.
1836 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1837 // Clear effective_peer_address, it is the same as direct_peer_address for
1838 // this test.
1839 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1840 QuicSocketAddress());
1841 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1842
nharper46833c32019-05-15 21:33:05 -07001843 QuicFrame frame;
1844 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1845 frame = QuicFrame(&crypto_frame_);
1846 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1847 } else {
1848 frame = QuicFrame(QuicStreamFrame(
1849 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
1850 0u, QuicStringPiece()));
1851 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1852 }
1853 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001854 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1855 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1856
1857 // Process another packet with a different peer address on server side will
1858 // start connection migration.
1859 const QuicSocketAddress kNewPeerAddress =
1860 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
1861 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
nharper46833c32019-05-15 21:33:05 -07001862 ProcessFramePacketWithAddresses(frame, kSelfAddress, kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001863 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1864 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1865}
1866
1867TEST_P(QuicConnectionTest, EffectivePeerAddressChangeAtServer) {
1868 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1869 set_perspective(Perspective::IS_SERVER);
1870 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1871 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1872
1873 // Clear direct_peer_address.
1874 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1875 // Clear effective_peer_address, it is different from direct_peer_address for
1876 // this test.
1877 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1878 QuicSocketAddress());
1879 const QuicSocketAddress kEffectivePeerAddress =
1880 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/43210);
1881 connection_.ReturnEffectivePeerAddressForNextPacket(kEffectivePeerAddress);
1882
nharper46833c32019-05-15 21:33:05 -07001883 QuicFrame frame;
1884 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1885 frame = QuicFrame(&crypto_frame_);
1886 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1887 } else {
1888 frame = QuicFrame(QuicStreamFrame(
1889 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
1890 0u, QuicStringPiece()));
1891 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1892 }
1893 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001894 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1895 EXPECT_EQ(kEffectivePeerAddress, connection_.effective_peer_address());
1896
1897 // Process another packet with the same direct peer address and different
1898 // effective peer address on server side will start connection migration.
1899 const QuicSocketAddress kNewEffectivePeerAddress =
1900 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/54321);
1901 connection_.ReturnEffectivePeerAddressForNextPacket(kNewEffectivePeerAddress);
1902 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
nharper46833c32019-05-15 21:33:05 -07001903 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001904 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1905 EXPECT_EQ(kNewEffectivePeerAddress, connection_.effective_peer_address());
1906
1907 // Process another packet with a different direct peer address and the same
1908 // effective peer address on server side will not start connection migration.
1909 const QuicSocketAddress kNewPeerAddress =
1910 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
1911 connection_.ReturnEffectivePeerAddressForNextPacket(kNewEffectivePeerAddress);
1912 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
1913 // ack_frame is used to complete the migration started by the last packet, we
1914 // need to make sure a new migration does not start after the previous one is
1915 // completed.
1916 QuicAckFrame ack_frame = InitAckFrame(1);
1917 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
1918 ProcessFramePacketWithAddresses(QuicFrame(&ack_frame), kSelfAddress,
1919 kNewPeerAddress);
1920 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1921 EXPECT_EQ(kNewEffectivePeerAddress, connection_.effective_peer_address());
1922
1923 // Process another packet with different direct peer address and different
1924 // effective peer address on server side will start connection migration.
1925 const QuicSocketAddress kNewerEffectivePeerAddress =
1926 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/65432);
1927 const QuicSocketAddress kFinalPeerAddress =
1928 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/34567);
1929 connection_.ReturnEffectivePeerAddressForNextPacket(
1930 kNewerEffectivePeerAddress);
1931 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
nharper46833c32019-05-15 21:33:05 -07001932 ProcessFramePacketWithAddresses(frame, kSelfAddress, kFinalPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001933 EXPECT_EQ(kFinalPeerAddress, connection_.peer_address());
1934 EXPECT_EQ(kNewerEffectivePeerAddress, connection_.effective_peer_address());
1935 EXPECT_EQ(PORT_CHANGE, connection_.active_effective_peer_migration_type());
1936
1937 // While the previous migration is ongoing, process another packet with the
1938 // same direct peer address and different effective peer address on server
1939 // side will start a new connection migration.
1940 const QuicSocketAddress kNewestEffectivePeerAddress =
1941 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/65430);
1942 connection_.ReturnEffectivePeerAddressForNextPacket(
1943 kNewestEffectivePeerAddress);
1944 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
1945 EXPECT_CALL(*send_algorithm_, OnConnectionMigration()).Times(1);
nharper46833c32019-05-15 21:33:05 -07001946 ProcessFramePacketWithAddresses(frame, kSelfAddress, kFinalPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001947 EXPECT_EQ(kFinalPeerAddress, connection_.peer_address());
1948 EXPECT_EQ(kNewestEffectivePeerAddress, connection_.effective_peer_address());
1949 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
1950 connection_.active_effective_peer_migration_type());
1951}
1952
1953TEST_P(QuicConnectionTest, ReceivePaddedPingAtServer) {
1954 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1955 set_perspective(Perspective::IS_SERVER);
1956 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1957 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1958
1959 // Clear direct_peer_address.
1960 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1961 // Clear effective_peer_address, it is the same as direct_peer_address for
1962 // this test.
1963 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1964 QuicSocketAddress());
1965 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1966
nharper46833c32019-05-15 21:33:05 -07001967 QuicFrame frame;
1968 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1969 frame = QuicFrame(&crypto_frame_);
1970 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1971 } else {
1972 frame = QuicFrame(QuicStreamFrame(
1973 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
1974 0u, QuicStringPiece()));
1975 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1976 }
1977 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001978 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1979 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1980
1981 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyi83161e42019-08-19 09:06:25 -07001982 EXPECT_CALL(visitor_, OnPacketReceived(_, _, false)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001983
1984 // Process a padded PING or PATH CHALLENGE packet with no peer address change
1985 // on server side will be ignored.
1986 OwningSerializedPacketPointer probing_packet;
fkastenholz305e1732019-06-18 05:01:22 -07001987 if (VersionHasIetfQuicFrames(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001988 QuicPathFrameBuffer payload = {
1989 {0xde, 0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xfe}};
1990 probing_packet =
1991 QuicPacketCreatorPeer::SerializePathChallengeConnectivityProbingPacket(
1992 &peer_creator_, &payload);
1993 } else {
1994 probing_packet = QuicPacketCreatorPeer::SerializeConnectivityProbingPacket(
1995 &peer_creator_);
1996 }
1997 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
1998 QuicEncryptedPacket(probing_packet->encrypted_buffer,
1999 probing_packet->encrypted_length),
2000 clock_.Now()));
2001
2002 uint64_t num_probing_received =
2003 connection_.GetStats().num_connectivity_probing_received;
2004 ProcessReceivedPacket(kSelfAddress, kPeerAddress, *received);
2005
2006 EXPECT_EQ(num_probing_received,
2007 connection_.GetStats().num_connectivity_probing_received);
2008 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2009 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2010}
2011
2012TEST_P(QuicConnectionTest, WriteOutOfOrderQueuedPackets) {
2013 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
fayangc31c9952019-06-05 13:54:48 -07002014 if (!IsDefaultTestConfiguration()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002015 return;
2016 }
2017
2018 set_perspective(Perspective::IS_CLIENT);
2019
2020 BlockOnNextWrite();
2021
2022 QuicStreamId stream_id = 2;
2023 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
2024
2025 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2026
2027 writer_->SetWritable();
2028 connection_.SendConnectivityProbingPacket(writer_.get(),
2029 connection_.peer_address());
fayang2ce66082019-10-02 06:29:04 -07002030 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
2031 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
2032 connection_.OnCanWrite();
2033 return;
2034 }
fkastenholz5d880a92019-06-21 09:01:56 -07002035 EXPECT_CALL(visitor_,
2036 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002037 EXPECT_QUIC_BUG(connection_.OnCanWrite(),
2038 "Attempt to write packet:1 after:2");
2039 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07002040 TestConnectionCloseQuicErrorCode(QUIC_INTERNAL_ERROR);
2041 const std::vector<QuicConnectionCloseFrame>& connection_close_frames =
2042 writer_->connection_close_frames();
fkastenholz488a4622019-08-26 06:24:46 -07002043 EXPECT_EQ("Packet written out of order.",
2044 connection_close_frames[0].error_details);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002045}
2046
2047TEST_P(QuicConnectionTest, DiscardQueuedPacketsAfterConnectionClose) {
2048 // Regression test for b/74073386.
2049 {
2050 InSequence seq;
2051 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
fkastenholz5d880a92019-06-21 09:01:56 -07002052 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002053 }
2054
2055 set_perspective(Perspective::IS_CLIENT);
2056
2057 writer_->SimulateNextPacketTooLarge();
2058
2059 // This packet write should fail, which should cause the connection to close
2060 // after sending a connection close packet, then the failed packet should be
2061 // queued.
2062 connection_.SendStreamDataWithString(/*id=*/2, "foo", 0, NO_FIN);
2063
2064 EXPECT_FALSE(connection_.connected());
fayang2ce66082019-10-02 06:29:04 -07002065 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
2066 // No need to buffer packets.
2067 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2068 } else {
2069 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2070 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002071
2072 EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
2073 connection_.OnCanWrite();
fayang0f0c4e62019-07-16 08:55:54 -07002074 EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002075}
2076
2077TEST_P(QuicConnectionTest, ReceiveConnectivityProbingAtServer) {
2078 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2079 set_perspective(Perspective::IS_SERVER);
2080 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2081 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2082
2083 // Clear direct_peer_address.
2084 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2085 // Clear effective_peer_address, it is the same as direct_peer_address for
2086 // this test.
2087 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2088 QuicSocketAddress());
2089 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2090
nharper46833c32019-05-15 21:33:05 -07002091 QuicFrame frame;
2092 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2093 frame = QuicFrame(&crypto_frame_);
2094 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2095 } else {
2096 frame = QuicFrame(QuicStreamFrame(
2097 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
2098 0u, QuicStringPiece()));
2099 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2100 }
2101 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002102 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2103 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2104
2105 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyi83161e42019-08-19 09:06:25 -07002106 EXPECT_CALL(visitor_, OnPacketReceived(_, _, true)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002107
2108 // Process a padded PING packet from a new peer address on server side
2109 // is effectively receiving a connectivity probing.
2110 const QuicSocketAddress kNewPeerAddress =
2111 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2112
2113 OwningSerializedPacketPointer probing_packet = ConstructProbingPacket();
2114 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2115 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2116 probing_packet->encrypted_length),
2117 clock_.Now()));
2118
2119 uint64_t num_probing_received =
2120 connection_.GetStats().num_connectivity_probing_received;
2121 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2122
2123 EXPECT_EQ(num_probing_received + 1,
2124 connection_.GetStats().num_connectivity_probing_received);
2125 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2126 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2127
2128 // Process another packet with the old peer address on server side will not
2129 // start peer migration.
2130 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
nharper46833c32019-05-15 21:33:05 -07002131 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002132 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2133 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2134}
2135
2136TEST_P(QuicConnectionTest, ReceiveReorderedConnectivityProbingAtServer) {
2137 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2138 set_perspective(Perspective::IS_SERVER);
2139 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2140 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2141
2142 // Clear direct_peer_address.
2143 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2144 // Clear effective_peer_address, it is the same as direct_peer_address for
2145 // this test.
2146 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2147 QuicSocketAddress());
2148 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2149
nharper46833c32019-05-15 21:33:05 -07002150 QuicFrame frame;
2151 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2152 frame = QuicFrame(&crypto_frame_);
2153 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2154 } else {
2155 frame = QuicFrame(QuicStreamFrame(
2156 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
2157 0u, QuicStringPiece()));
2158 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2159 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002160 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
nharper46833c32019-05-15 21:33:05 -07002161 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002162 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2163 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2164
2165 // Decrease packet number to simulate out-of-order packets.
2166 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 4);
2167
2168 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyi83161e42019-08-19 09:06:25 -07002169 EXPECT_CALL(visitor_, OnPacketReceived(_, _, true)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002170
2171 // Process a padded PING packet from a new peer address on server side
2172 // is effectively receiving a connectivity probing, even if a newer packet has
2173 // been received before this one.
2174 const QuicSocketAddress kNewPeerAddress =
2175 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2176
2177 OwningSerializedPacketPointer probing_packet = ConstructProbingPacket();
2178 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2179 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2180 probing_packet->encrypted_length),
2181 clock_.Now()));
2182
2183 uint64_t num_probing_received =
2184 connection_.GetStats().num_connectivity_probing_received;
2185 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2186
2187 EXPECT_EQ(num_probing_received + 1,
2188 connection_.GetStats().num_connectivity_probing_received);
2189 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2190 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2191}
2192
2193TEST_P(QuicConnectionTest, MigrateAfterProbingAtServer) {
2194 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2195 set_perspective(Perspective::IS_SERVER);
2196 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2197 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2198
2199 // Clear direct_peer_address.
2200 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2201 // Clear effective_peer_address, it is the same as direct_peer_address for
2202 // this test.
2203 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2204 QuicSocketAddress());
2205 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2206
nharper46833c32019-05-15 21:33:05 -07002207 QuicFrame frame;
2208 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2209 frame = QuicFrame(&crypto_frame_);
2210 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2211 } else {
2212 frame = QuicFrame(QuicStreamFrame(
2213 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
2214 0u, QuicStringPiece()));
2215 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2216 }
2217 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002218 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2219 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2220
2221 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyi83161e42019-08-19 09:06:25 -07002222 EXPECT_CALL(visitor_, OnPacketReceived(_, _, true)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002223
2224 // Process a padded PING packet from a new peer address on server side
2225 // is effectively receiving a connectivity probing.
2226 const QuicSocketAddress kNewPeerAddress =
2227 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2228
2229 OwningSerializedPacketPointer probing_packet = ConstructProbingPacket();
2230 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2231 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2232 probing_packet->encrypted_length),
2233 clock_.Now()));
2234 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2235 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2236 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2237
2238 // Process another non-probing packet with the new peer address on server
2239 // side will start peer migration.
2240 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2241
nharper46833c32019-05-15 21:33:05 -07002242 ProcessFramePacketWithAddresses(frame, kSelfAddress, kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002243 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2244 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2245}
2246
2247TEST_P(QuicConnectionTest, ReceivePaddedPingAtClient) {
2248 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2249 set_perspective(Perspective::IS_CLIENT);
2250 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2251
2252 // Clear direct_peer_address.
2253 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2254 // Clear effective_peer_address, it is the same as direct_peer_address for
2255 // this test.
2256 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2257 QuicSocketAddress());
2258 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2259
nharper46833c32019-05-15 21:33:05 -07002260 QuicFrame frame;
2261 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2262 frame = QuicFrame(&crypto_frame_);
2263 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2264 } else {
2265 frame = QuicFrame(QuicStreamFrame(
2266 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
2267 0u, QuicStringPiece()));
2268 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2269 }
2270 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002271 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2272 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2273
2274 // Client takes all padded PING packet as speculative connectivity
2275 // probing packet, and reports to visitor.
2276 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyi83161e42019-08-19 09:06:25 -07002277 EXPECT_CALL(visitor_, OnPacketReceived(_, _, false)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002278
2279 OwningSerializedPacketPointer probing_packet = ConstructProbingPacket();
2280 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2281 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2282 probing_packet->encrypted_length),
2283 clock_.Now()));
2284 uint64_t num_probing_received =
2285 connection_.GetStats().num_connectivity_probing_received;
2286 ProcessReceivedPacket(kSelfAddress, kPeerAddress, *received);
2287
2288 EXPECT_EQ(num_probing_received,
2289 connection_.GetStats().num_connectivity_probing_received);
2290 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2291 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2292}
2293
2294TEST_P(QuicConnectionTest, ReceiveConnectivityProbingAtClient) {
2295 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2296 set_perspective(Perspective::IS_CLIENT);
2297 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2298
2299 // Clear direct_peer_address.
2300 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2301 // Clear effective_peer_address, it is the same as direct_peer_address for
2302 // this test.
2303 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2304 QuicSocketAddress());
2305 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2306
nharper46833c32019-05-15 21:33:05 -07002307 QuicFrame frame;
2308 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2309 frame = QuicFrame(&crypto_frame_);
2310 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2311 } else {
2312 frame = QuicFrame(QuicStreamFrame(
2313 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
2314 0u, QuicStringPiece()));
2315 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2316 }
2317 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002318 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2319 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2320
2321 // Process a padded PING packet with a different self address on client side
2322 // is effectively receiving a connectivity probing.
2323 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyi83161e42019-08-19 09:06:25 -07002324 EXPECT_CALL(visitor_, OnPacketReceived(_, _, true)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002325
2326 const QuicSocketAddress kNewSelfAddress =
2327 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2328
2329 OwningSerializedPacketPointer probing_packet = ConstructProbingPacket();
2330 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2331 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2332 probing_packet->encrypted_length),
2333 clock_.Now()));
2334 uint64_t num_probing_received =
2335 connection_.GetStats().num_connectivity_probing_received;
2336 ProcessReceivedPacket(kNewSelfAddress, kPeerAddress, *received);
2337
2338 EXPECT_EQ(num_probing_received + 1,
2339 connection_.GetStats().num_connectivity_probing_received);
2340 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2341 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2342}
2343
2344TEST_P(QuicConnectionTest, PeerAddressChangeAtClient) {
2345 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2346 set_perspective(Perspective::IS_CLIENT);
2347 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2348
2349 // Clear direct_peer_address.
2350 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2351 // Clear effective_peer_address, it is the same as direct_peer_address for
2352 // this test.
2353 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2354 QuicSocketAddress());
2355 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2356
nharper46833c32019-05-15 21:33:05 -07002357 QuicFrame frame;
2358 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2359 frame = QuicFrame(&crypto_frame_);
2360 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2361 } else {
2362 frame = QuicFrame(QuicStreamFrame(
2363 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
2364 0u, QuicStringPiece()));
2365 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2366 }
2367 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002368 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2369 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2370
2371 // Process another packet with a different peer address on client side will
2372 // only update peer address.
2373 const QuicSocketAddress kNewPeerAddress =
2374 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2375 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
nharper46833c32019-05-15 21:33:05 -07002376 ProcessFramePacketWithAddresses(frame, kSelfAddress, kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002377 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2378 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2379}
2380
2381TEST_P(QuicConnectionTest, MaxPacketSize) {
2382 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2383 EXPECT_EQ(1350u, connection_.max_packet_length());
2384}
2385
2386TEST_P(QuicConnectionTest, SmallerServerMaxPacketSize) {
2387 TestConnection connection(TestConnectionId(), kPeerAddress, helper_.get(),
2388 alarm_factory_.get(), writer_.get(),
2389 Perspective::IS_SERVER, version());
2390 EXPECT_EQ(Perspective::IS_SERVER, connection.perspective());
2391 EXPECT_EQ(1000u, connection.max_packet_length());
2392}
2393
2394TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSize) {
2395 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2396
2397 set_perspective(Perspective::IS_SERVER);
2398 connection_.SetMaxPacketLength(1000);
2399
2400 QuicPacketHeader header;
2401 header.destination_connection_id = connection_id_;
2402 header.version_flag = true;
nharper21af28e2019-06-17 15:54:34 -07002403 header.packet_number = QuicPacketNumber(12);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002404
2405 if (QuicVersionHasLongHeaderLengths(
2406 peer_framer_.version().transport_version)) {
2407 header.long_packet_type = INITIAL;
2408 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
2409 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
2410 }
2411
2412 QuicFrames frames;
2413 QuicPaddingFrame padding;
nharper46833c32019-05-15 21:33:05 -07002414 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2415 frames.push_back(QuicFrame(&crypto_frame_));
2416 } else {
2417 frames.push_back(QuicFrame(frame1_));
2418 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002419 frames.push_back(QuicFrame(padding));
2420 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
dschinazi66dea072019-04-09 11:41:06 -07002421 char buffer[kMaxOutgoingPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07002422 size_t encrypted_length =
2423 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12),
dschinazi66dea072019-04-09 11:41:06 -07002424 *packet, buffer, kMaxOutgoingPacketSize);
2425 EXPECT_EQ(kMaxOutgoingPacketSize, encrypted_length);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002426
2427 framer_.set_version(version());
nharper46833c32019-05-15 21:33:05 -07002428 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2429 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
2430 } else {
2431 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2432 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002433 connection_.ProcessUdpPacket(
2434 kSelfAddress, kPeerAddress,
2435 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
2436
dschinazi66dea072019-04-09 11:41:06 -07002437 EXPECT_EQ(kMaxOutgoingPacketSize, connection_.max_packet_length());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002438}
2439
2440TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSizeWhileWriterLimited) {
2441 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2442
2443 const QuicByteCount lower_max_packet_size = 1240;
2444 writer_->set_max_packet_size(lower_max_packet_size);
2445 set_perspective(Perspective::IS_SERVER);
2446 connection_.SetMaxPacketLength(1000);
2447 EXPECT_EQ(1000u, connection_.max_packet_length());
2448
2449 QuicPacketHeader header;
2450 header.destination_connection_id = connection_id_;
2451 header.version_flag = true;
nharper21af28e2019-06-17 15:54:34 -07002452 header.packet_number = QuicPacketNumber(12);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002453
2454 if (QuicVersionHasLongHeaderLengths(
2455 peer_framer_.version().transport_version)) {
2456 header.long_packet_type = INITIAL;
2457 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
2458 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
2459 }
2460
2461 QuicFrames frames;
2462 QuicPaddingFrame padding;
nharper46833c32019-05-15 21:33:05 -07002463 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2464 frames.push_back(QuicFrame(&crypto_frame_));
2465 } else {
2466 frames.push_back(QuicFrame(frame1_));
2467 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002468 frames.push_back(QuicFrame(padding));
2469 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
dschinazi66dea072019-04-09 11:41:06 -07002470 char buffer[kMaxOutgoingPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07002471 size_t encrypted_length =
2472 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12),
dschinazi66dea072019-04-09 11:41:06 -07002473 *packet, buffer, kMaxOutgoingPacketSize);
2474 EXPECT_EQ(kMaxOutgoingPacketSize, encrypted_length);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002475
2476 framer_.set_version(version());
nharper46833c32019-05-15 21:33:05 -07002477 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2478 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
2479 } else {
2480 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2481 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002482 connection_.ProcessUdpPacket(
2483 kSelfAddress, kPeerAddress,
2484 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
2485
2486 // Here, the limit imposed by the writer is lower than the size of the packet
2487 // received, so the writer max packet size is used.
2488 EXPECT_EQ(lower_max_packet_size, connection_.max_packet_length());
2489}
2490
2491TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriter) {
2492 const QuicByteCount lower_max_packet_size = 1240;
2493 writer_->set_max_packet_size(lower_max_packet_size);
2494
2495 static_assert(lower_max_packet_size < kDefaultMaxPacketSize,
2496 "Default maximum packet size is too low");
2497 connection_.SetMaxPacketLength(kDefaultMaxPacketSize);
2498
2499 EXPECT_EQ(lower_max_packet_size, connection_.max_packet_length());
2500}
2501
2502TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriterForNewConnection) {
2503 const QuicConnectionId connection_id = TestConnectionId(17);
2504 const QuicByteCount lower_max_packet_size = 1240;
2505 writer_->set_max_packet_size(lower_max_packet_size);
2506 TestConnection connection(connection_id, kPeerAddress, helper_.get(),
2507 alarm_factory_.get(), writer_.get(),
2508 Perspective::IS_CLIENT, version());
2509 EXPECT_EQ(Perspective::IS_CLIENT, connection.perspective());
2510 EXPECT_EQ(lower_max_packet_size, connection.max_packet_length());
2511}
2512
2513TEST_P(QuicConnectionTest, PacketsInOrder) {
2514 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2515
2516 ProcessPacket(1);
fayangc31c9952019-06-05 13:54:48 -07002517 EXPECT_EQ(QuicPacketNumber(1u), LargestAcked(connection_.ack_frame()));
2518 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002519
2520 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07002521 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(connection_.ack_frame()));
2522 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002523
2524 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002525 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
2526 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002527}
2528
2529TEST_P(QuicConnectionTest, PacketsOutOfOrder) {
2530 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2531
2532 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002533 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002534 EXPECT_TRUE(IsMissing(2));
2535 EXPECT_TRUE(IsMissing(1));
2536
2537 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07002538 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002539 EXPECT_FALSE(IsMissing(2));
2540 EXPECT_TRUE(IsMissing(1));
2541
2542 ProcessPacket(1);
fayangc31c9952019-06-05 13:54:48 -07002543 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002544 EXPECT_FALSE(IsMissing(2));
2545 EXPECT_FALSE(IsMissing(1));
2546}
2547
2548TEST_P(QuicConnectionTest, DuplicatePacket) {
2549 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2550
2551 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002552 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002553 EXPECT_TRUE(IsMissing(2));
2554 EXPECT_TRUE(IsMissing(1));
2555
2556 // Send packet 3 again, but do not set the expectation that
2557 // the visitor OnStreamFrame() will be called.
2558 ProcessDataPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002559 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002560 EXPECT_TRUE(IsMissing(2));
2561 EXPECT_TRUE(IsMissing(1));
2562}
2563
2564TEST_P(QuicConnectionTest, PacketsOutOfOrderWithAdditionsAndLeastAwaiting) {
QUICHE teamcd098022019-03-22 18:49:55 -07002565 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2566 return;
2567 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002568 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2569
2570 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002571 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002572 EXPECT_TRUE(IsMissing(2));
2573 EXPECT_TRUE(IsMissing(1));
2574
2575 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07002576 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002577 EXPECT_TRUE(IsMissing(1));
2578
2579 ProcessPacket(5);
fayangc31c9952019-06-05 13:54:48 -07002580 EXPECT_EQ(QuicPacketNumber(5u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002581 EXPECT_TRUE(IsMissing(1));
2582 EXPECT_TRUE(IsMissing(4));
2583
2584 // Pretend at this point the client has gotten acks for 2 and 3 and 1 is a
2585 // packet the peer will not retransmit. It indicates this by sending 'least
2586 // awaiting' is 4. The connection should then realize 1 will not be
2587 // retransmitted, and will remove it from the missing list.
2588 QuicAckFrame frame = InitAckFrame(1);
2589 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
2590 ProcessAckPacket(6, &frame);
2591
2592 // Force an ack to be sent.
2593 SendAckPacketToPeer();
2594 EXPECT_TRUE(IsMissing(4));
2595}
2596
QUICHE teama6ef0a62019-03-07 20:34:33 -05002597TEST_P(QuicConnectionTest, RejectUnencryptedStreamData) {
2598 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
2599 if (!IsDefaultTestConfiguration()) {
2600 return;
2601 }
2602
2603 // Process an unencrypted packet from the non-crypto stream.
2604 frame1_.stream_id = 3;
2605 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fkastenholz5d880a92019-06-21 09:01:56 -07002606 EXPECT_CALL(visitor_,
2607 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
nharper2c9f02a2019-05-08 10:25:50 -07002608 EXPECT_QUIC_PEER_BUG(ProcessDataPacketAtLevel(1, false, ENCRYPTION_INITIAL),
2609 "");
fkastenholz5d880a92019-06-21 09:01:56 -07002610 TestConnectionCloseQuicErrorCode(QUIC_UNENCRYPTED_STREAM_DATA);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002611}
2612
2613TEST_P(QuicConnectionTest, OutOfOrderReceiptCausesAckSend) {
2614 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2615
2616 ProcessPacket(3);
fayang6dba4902019-06-17 10:04:23 -07002617 // Should not cause an ack.
2618 EXPECT_EQ(0u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002619
2620 ProcessPacket(2);
fayang6dba4902019-06-17 10:04:23 -07002621 // Should ack immediately, since this fills the last hole.
2622 EXPECT_EQ(1u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002623
2624 ProcessPacket(1);
2625 // Should ack immediately, since this fills the last hole.
fayang6dba4902019-06-17 10:04:23 -07002626 EXPECT_EQ(2u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002627
2628 ProcessPacket(4);
2629 // Should not cause an ack.
fayang6dba4902019-06-17 10:04:23 -07002630 EXPECT_EQ(2u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002631}
2632
2633TEST_P(QuicConnectionTest, OutOfOrderAckReceiptCausesNoAck) {
2634 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2635
2636 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
2637 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
2638 EXPECT_EQ(2u, writer_->packets_write_attempts());
2639
2640 QuicAckFrame ack1 = InitAckFrame(1);
2641 QuicAckFrame ack2 = InitAckFrame(2);
2642 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2643 ProcessAckPacket(2, &ack2);
2644 // Should ack immediately since we have missing packets.
2645 EXPECT_EQ(2u, writer_->packets_write_attempts());
2646
2647 ProcessAckPacket(1, &ack1);
2648 // Should not ack an ack filling a missing packet.
2649 EXPECT_EQ(2u, writer_->packets_write_attempts());
2650}
2651
2652TEST_P(QuicConnectionTest, AckReceiptCausesAckSend) {
2653 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2654 QuicPacketNumber original, second;
2655
2656 QuicByteCount packet_size =
2657 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &original); // 1st packet.
2658 SendStreamDataToPeer(3, "bar", 3, NO_FIN, &second); // 2nd packet.
2659
2660 QuicAckFrame frame = InitAckFrame({{second, second + 1}});
2661 // First nack triggers early retransmit.
2662 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07002663 lost_packets.push_back(LostPacket(original, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002664 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
2665 .WillOnce(SetArgPointee<5>(lost_packets));
2666 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2667 QuicPacketNumber retransmission;
2668 // Packet 1 is short header for IETF QUIC because the encryption level
2669 // switched to ENCRYPTION_FORWARD_SECURE in SendStreamDataToPeer.
fayangd4291e42019-05-30 10:31:21 -07002670 EXPECT_CALL(*send_algorithm_,
2671 OnPacketSent(_, _, _,
2672 VersionHasIetfInvariantHeader(
2673 GetParam().version.transport_version)
2674 ? packet_size
2675 : packet_size - kQuicVersionSize,
2676 _))
QUICHE teama6ef0a62019-03-07 20:34:33 -05002677 .WillOnce(SaveArg<2>(&retransmission));
2678
2679 ProcessAckPacket(&frame);
2680
2681 QuicAckFrame frame2 = ConstructAckFrame(retransmission, original);
2682 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2683 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
2684 ProcessAckPacket(&frame2);
2685
2686 // Now if the peer sends an ack which still reports the retransmitted packet
2687 // as missing, that will bundle an ack with data after two acks in a row
2688 // indicate the high water mark needs to be raised.
2689 EXPECT_CALL(*send_algorithm_,
2690 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA));
2691 connection_.SendStreamDataWithString(3, "foo", 6, NO_FIN);
2692 // No ack sent.
nharper55fa6132019-05-07 19:37:21 -07002693 size_t padding_frame_count = writer_->padding_frames().size();
2694 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002695 EXPECT_EQ(1u, writer_->stream_frames().size());
2696
2697 // No more packet loss for the rest of the test.
2698 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
2699 .Times(AnyNumber());
2700 ProcessAckPacket(&frame2);
2701 EXPECT_CALL(*send_algorithm_,
2702 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA));
fayang03916692019-05-22 17:57:18 -07002703 connection_.SendStreamDataWithString(3, "foofoofoo", 9, NO_FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002704 // Ack bundled.
2705 if (GetParam().no_stop_waiting) {
fayange8b0cab2019-07-17 14:23:07 -07002706 if (GetQuicReloadableFlag(quic_simplify_stop_waiting)) {
2707 // Do not ACK acks.
2708 EXPECT_EQ(1u, writer_->frame_count());
2709 } else {
2710 EXPECT_EQ(2u, writer_->frame_count());
2711 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002712 } else {
2713 EXPECT_EQ(3u, writer_->frame_count());
2714 }
2715 EXPECT_EQ(1u, writer_->stream_frames().size());
fayange8b0cab2019-07-17 14:23:07 -07002716 if (GetParam().no_stop_waiting &&
2717 GetQuicReloadableFlag(quic_simplify_stop_waiting)) {
fayang03916692019-05-22 17:57:18 -07002718 EXPECT_TRUE(writer_->ack_frames().empty());
2719 } else {
2720 EXPECT_FALSE(writer_->ack_frames().empty());
2721 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002722
2723 // But an ack with no missing packets will not send an ack.
2724 AckPacket(original, &frame2);
2725 ProcessAckPacket(&frame2);
2726 ProcessAckPacket(&frame2);
2727}
2728
2729TEST_P(QuicConnectionTest, AckSentEveryNthPacket) {
2730 connection_.set_ack_frequency_before_ack_decimation(3);
2731
2732 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2733 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(39);
2734
2735 // Expect 13 acks, every 3rd packet.
2736 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(13);
2737 // Receives packets 1 - 39.
2738 for (size_t i = 1; i <= 39; ++i) {
2739 ProcessDataPacket(i);
2740 }
2741}
2742
2743TEST_P(QuicConnectionTest, AckDecimationReducesAcks) {
2744 const size_t kMinRttMs = 40;
2745 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
2746 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
2747 QuicTime::Delta::Zero(), QuicTime::Zero());
2748 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
2749
2750 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
2751
2752 // Start ack decimation from 10th packet.
2753 connection_.set_min_received_before_ack_decimation(10);
2754
2755 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2756 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(30);
2757
2758 // Expect 6 acks: 5 acks between packets 1-10, and ack at 20.
2759 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(6);
2760 // Receives packets 1 - 29.
2761 for (size_t i = 1; i <= 29; ++i) {
2762 ProcessDataPacket(i);
2763 }
2764
2765 // We now receive the 30th packet, and so we send an ack.
2766 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2767 ProcessDataPacket(30);
2768}
2769
2770TEST_P(QuicConnectionTest, AckNeedsRetransmittableFrames) {
ianswett68cf0042019-05-09 08:37:58 -07002771 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002772 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2773 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(99);
2774
2775 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(19);
2776 // Receives packets 1 - 39.
2777 for (size_t i = 1; i <= 39; ++i) {
2778 ProcessDataPacket(i);
2779 }
2780 // Receiving Packet 40 causes 20th ack to send. Session is informed and adds
2781 // WINDOW_UPDATE.
2782 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
2783 .WillOnce(Invoke([this]() {
2784 connection_.SendControlFrame(
2785 QuicFrame(new QuicWindowUpdateFrame(1, 0, 0)));
2786 }));
2787 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2788 EXPECT_EQ(0u, writer_->window_update_frames().size());
2789 ProcessDataPacket(40);
2790 EXPECT_EQ(1u, writer_->window_update_frames().size());
2791
2792 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(9);
2793 // Receives packets 41 - 59.
2794 for (size_t i = 41; i <= 59; ++i) {
2795 ProcessDataPacket(i);
2796 }
2797 // Send a packet containing stream frame.
QUICHE team8c1daa22019-03-13 08:33:41 -07002798 SendStreamDataToPeer(
nharper46833c32019-05-15 21:33:05 -07002799 QuicUtils::GetFirstBidirectionalStreamId(
2800 connection_.version().transport_version, Perspective::IS_CLIENT),
QUICHE team8c1daa22019-03-13 08:33:41 -07002801 "bar", 0, NO_FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002802
2803 // Session will not be informed until receiving another 20 packets.
2804 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(19);
2805 for (size_t i = 60; i <= 98; ++i) {
2806 ProcessDataPacket(i);
2807 EXPECT_EQ(0u, writer_->window_update_frames().size());
2808 }
2809 // Session does not add a retransmittable frame.
2810 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
2811 .WillOnce(Invoke([this]() {
2812 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
2813 }));
2814 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2815 EXPECT_EQ(0u, writer_->ping_frames().size());
2816 ProcessDataPacket(99);
2817 EXPECT_EQ(0u, writer_->window_update_frames().size());
2818 // A ping frame will be added.
2819 EXPECT_EQ(1u, writer_->ping_frames().size());
2820}
2821
2822TEST_P(QuicConnectionTest, LeastUnackedLower) {
fayangc31c9952019-06-05 13:54:48 -07002823 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002824 return;
2825 }
2826 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2827
2828 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
2829 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
2830 SendStreamDataToPeer(1, "eep", 6, NO_FIN, nullptr);
2831
2832 // Start out saying the least unacked is 2.
2833 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
2834 ProcessStopWaitingPacket(InitStopWaitingFrame(2));
2835
2836 // Change it to 1, but lower the packet number to fake out-of-order packets.
2837 // This should be fine.
2838 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 1);
2839 // The scheduler will not process out of order acks, but all packet processing
2840 // causes the connection to try to write.
2841 if (!GetParam().no_stop_waiting) {
2842 EXPECT_CALL(visitor_, OnCanWrite());
2843 }
2844 ProcessStopWaitingPacket(InitStopWaitingFrame(1));
2845
2846 // Now claim it's one, but set the ordering so it was sent "after" the first
2847 // one. This should cause a connection error.
2848 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 7);
2849 if (!GetParam().no_stop_waiting) {
2850 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
fkastenholz5d880a92019-06-21 09:01:56 -07002851 EXPECT_CALL(visitor_,
2852 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002853 }
2854 ProcessStopWaitingPacket(InitStopWaitingFrame(1));
fkastenholz5d880a92019-06-21 09:01:56 -07002855 if (!GetParam().no_stop_waiting) {
2856 TestConnectionCloseQuicErrorCode(QUIC_INVALID_STOP_WAITING_DATA);
2857 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002858}
2859
2860TEST_P(QuicConnectionTest, TooManySentPackets) {
2861 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2862
2863 QuicPacketCount max_tracked_packets = 50;
2864 QuicConnectionPeer::SetMaxTrackedPackets(&connection_, max_tracked_packets);
2865
2866 const int num_packets = max_tracked_packets + 5;
2867
2868 for (int i = 0; i < num_packets; ++i) {
2869 SendStreamDataToPeer(1, "foo", 3 * i, NO_FIN, nullptr);
2870 }
2871
2872 // Ack packet 1, which leaves more than the limit outstanding.
2873 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2874 EXPECT_CALL(visitor_,
fkastenholz5d880a92019-06-21 09:01:56 -07002875 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002876
2877 // Nack the first packet and ack the rest, leaving a huge gap.
2878 QuicAckFrame frame1 = ConstructAckFrame(num_packets, 1);
2879 ProcessAckPacket(&frame1);
fkastenholz5d880a92019-06-21 09:01:56 -07002880 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002881}
2882
2883TEST_P(QuicConnectionTest, LargestObservedLower) {
2884 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2885
2886 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
2887 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
2888 SendStreamDataToPeer(1, "eep", 6, NO_FIN, nullptr);
2889 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2890
2891 // Start out saying the largest observed is 2.
2892 QuicAckFrame frame1 = InitAckFrame(1);
2893 QuicAckFrame frame2 = InitAckFrame(2);
2894 ProcessAckPacket(&frame2);
2895
fayang745c93a2019-06-21 13:43:04 -07002896 EXPECT_CALL(visitor_, OnCanWrite());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002897 ProcessAckPacket(&frame1);
2898}
2899
2900TEST_P(QuicConnectionTest, AckUnsentData) {
2901 // Ack a packet which has not been sent.
fkastenholz5d880a92019-06-21 09:01:56 -07002902 EXPECT_CALL(visitor_,
2903 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002904 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2905 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2906 QuicAckFrame frame = InitAckFrame(1);
2907 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
2908 ProcessAckPacket(&frame);
fkastenholz5d880a92019-06-21 09:01:56 -07002909 TestConnectionCloseQuicErrorCode(QUIC_INVALID_ACK_DATA);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002910}
2911
2912TEST_P(QuicConnectionTest, BasicSending) {
QUICHE teamcd098022019-03-22 18:49:55 -07002913 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2914 return;
2915 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002916 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2917 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2918 ProcessDataPacket(1);
2919 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
2920 QuicPacketNumber last_packet;
2921 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
2922 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
2923 SendAckPacketToPeer(); // Packet 2
2924
2925 if (GetParam().no_stop_waiting) {
2926 // Expect no stop waiting frame is sent.
2927 EXPECT_FALSE(least_unacked().IsInitialized());
2928 } else {
2929 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
2930 }
2931
2932 SendAckPacketToPeer(); // Packet 3
2933 if (GetParam().no_stop_waiting) {
2934 // Expect no stop waiting frame is sent.
2935 EXPECT_FALSE(least_unacked().IsInitialized());
2936 } else {
2937 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
2938 }
2939
2940 SendStreamDataToPeer(1, "bar", 3, NO_FIN, &last_packet); // Packet 4
2941 EXPECT_EQ(QuicPacketNumber(4u), last_packet);
2942 SendAckPacketToPeer(); // Packet 5
2943 if (GetParam().no_stop_waiting) {
2944 // Expect no stop waiting frame is sent.
2945 EXPECT_FALSE(least_unacked().IsInitialized());
2946 } else {
2947 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
2948 }
2949
2950 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2951
2952 // Peer acks up to packet 3.
2953 QuicAckFrame frame = InitAckFrame(3);
2954 ProcessAckPacket(&frame);
2955 SendAckPacketToPeer(); // Packet 6
2956
2957 // As soon as we've acked one, we skip ack packets 2 and 3 and note lack of
2958 // ack for 4.
2959 if (GetParam().no_stop_waiting) {
2960 // Expect no stop waiting frame is sent.
2961 EXPECT_FALSE(least_unacked().IsInitialized());
2962 } else {
2963 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
2964 }
2965
2966 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2967
2968 // Peer acks up to packet 4, the last packet.
2969 QuicAckFrame frame2 = InitAckFrame(6);
2970 ProcessAckPacket(&frame2); // Acks don't instigate acks.
2971
2972 // Verify that we did not send an ack.
2973 EXPECT_EQ(QuicPacketNumber(6u), writer_->header().packet_number);
2974
2975 // So the last ack has not changed.
2976 if (GetParam().no_stop_waiting) {
2977 // Expect no stop waiting frame is sent.
2978 EXPECT_FALSE(least_unacked().IsInitialized());
2979 } else {
2980 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
2981 }
2982
2983 // If we force an ack, we shouldn't change our retransmit state.
2984 SendAckPacketToPeer(); // Packet 7
2985 if (GetParam().no_stop_waiting) {
2986 // Expect no stop waiting frame is sent.
2987 EXPECT_FALSE(least_unacked().IsInitialized());
2988 } else {
2989 EXPECT_EQ(QuicPacketNumber(7u), least_unacked());
2990 }
2991
2992 // But if we send more data it should.
2993 SendStreamDataToPeer(1, "eep", 6, NO_FIN, &last_packet); // Packet 8
2994 EXPECT_EQ(QuicPacketNumber(8u), last_packet);
2995 SendAckPacketToPeer(); // Packet 9
2996 if (GetParam().no_stop_waiting) {
2997 // Expect no stop waiting frame is sent.
2998 EXPECT_FALSE(least_unacked().IsInitialized());
2999 } else {
3000 EXPECT_EQ(QuicPacketNumber(7u), least_unacked());
3001 }
3002}
3003
3004// QuicConnection should record the packet sent-time prior to sending the
3005// packet.
3006TEST_P(QuicConnectionTest, RecordSentTimeBeforePacketSent) {
3007 // We're using a MockClock for the tests, so we have complete control over the
3008 // time.
3009 // Our recorded timestamp for the last packet sent time will be passed in to
3010 // the send_algorithm. Make sure that it is set to the correct value.
3011 QuicTime actual_recorded_send_time = QuicTime::Zero();
3012 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3013 .WillOnce(SaveArg<0>(&actual_recorded_send_time));
3014
3015 // First send without any pause and check the result.
3016 QuicTime expected_recorded_send_time = clock_.Now();
3017 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3018 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
3019 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
3020 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
3021
3022 // Now pause during the write, and check the results.
3023 actual_recorded_send_time = QuicTime::Zero();
3024 const QuicTime::Delta write_pause_time_delta =
3025 QuicTime::Delta::FromMilliseconds(5000);
3026 SetWritePauseTimeDelta(write_pause_time_delta);
3027 expected_recorded_send_time = clock_.Now();
3028
3029 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3030 .WillOnce(SaveArg<0>(&actual_recorded_send_time));
3031 connection_.SendStreamDataWithString(2, "baz", 0, NO_FIN);
3032 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
3033 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
3034 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
3035}
3036
3037TEST_P(QuicConnectionTest, FramePacking) {
3038 // Send two stream frames in 1 packet by queueing them.
3039 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3040 {
fayanga4b37b22019-06-18 13:37:47 -07003041 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003042 connection_.SendStreamData3();
3043 connection_.SendStreamData5();
3044 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3045 }
3046 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3047 EXPECT_FALSE(connection_.HasQueuedData());
3048
3049 // Parse the last packet and ensure it's an ack and two stream frames from
3050 // two different streams.
3051 if (GetParam().no_stop_waiting) {
3052 EXPECT_EQ(2u, writer_->frame_count());
3053 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
3054 } else {
3055 EXPECT_EQ(2u, writer_->frame_count());
3056 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
3057 }
3058
3059 EXPECT_TRUE(writer_->ack_frames().empty());
3060
3061 ASSERT_EQ(2u, writer_->stream_frames().size());
3062 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3063 writer_->stream_frames()[0]->stream_id);
3064 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3065 writer_->stream_frames()[1]->stream_id);
3066}
3067
3068TEST_P(QuicConnectionTest, FramePackingNonCryptoThenCrypto) {
3069 // Send two stream frames (one non-crypto, then one crypto) in 2 packets by
3070 // queueing them.
3071 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3072 {
3073 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
fayanga4b37b22019-06-18 13:37:47 -07003074 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003075 connection_.SendStreamData3();
3076 connection_.SendCryptoStreamData();
3077 }
3078 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3079 EXPECT_FALSE(connection_.HasQueuedData());
3080
3081 // Parse the last packet and ensure it's the crypto stream frame.
3082 EXPECT_EQ(2u, writer_->frame_count());
3083 ASSERT_EQ(1u, writer_->padding_frames().size());
QUICHE teamea740082019-03-11 17:58:43 -07003084 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003085 ASSERT_EQ(1u, writer_->stream_frames().size());
3086 EXPECT_EQ(QuicUtils::GetCryptoStreamId(connection_.transport_version()),
3087 writer_->stream_frames()[0]->stream_id);
3088 } else {
3089 EXPECT_EQ(1u, writer_->crypto_frames().size());
3090 }
3091}
3092
3093TEST_P(QuicConnectionTest, FramePackingCryptoThenNonCrypto) {
3094 // Send two stream frames (one crypto, then one non-crypto) in 2 packets by
3095 // queueing them.
3096 {
3097 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3098 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
fayanga4b37b22019-06-18 13:37:47 -07003099 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003100 connection_.SendCryptoStreamData();
3101 connection_.SendStreamData3();
3102 }
3103 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3104 EXPECT_FALSE(connection_.HasQueuedData());
3105
3106 // Parse the last packet and ensure it's the stream frame from stream 3.
nharper55fa6132019-05-07 19:37:21 -07003107 size_t padding_frame_count = writer_->padding_frames().size();
3108 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003109 ASSERT_EQ(1u, writer_->stream_frames().size());
3110 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3111 writer_->stream_frames()[0]->stream_id);
3112}
3113
3114TEST_P(QuicConnectionTest, FramePackingAckResponse) {
3115 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3116 // Process a data packet to queue up a pending ack.
fayang3451f6e2019-06-11 08:18:12 -07003117 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3118 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
3119 } else {
3120 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3121 }
3122 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
3123
QUICHE teama6ef0a62019-03-07 20:34:33 -05003124 QuicPacketNumber last_packet;
nharper46833c32019-05-15 21:33:05 -07003125 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3126 connection_.SendCryptoDataWithString("foo", 0);
3127 } else {
3128 SendStreamDataToPeer(
3129 QuicUtils::GetCryptoStreamId(connection_.transport_version()), "foo", 0,
3130 NO_FIN, &last_packet);
3131 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003132 // Verify ack is bundled with outging packet.
3133 EXPECT_FALSE(writer_->ack_frames().empty());
3134
3135 EXPECT_CALL(visitor_, OnCanWrite())
3136 .WillOnce(DoAll(IgnoreResult(InvokeWithoutArgs(
3137 &connection_, &TestConnection::SendStreamData3)),
3138 IgnoreResult(InvokeWithoutArgs(
3139 &connection_, &TestConnection::SendStreamData5))));
3140
3141 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3142
3143 // Process a data packet to cause the visitor's OnCanWrite to be invoked.
3144 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
QUICHE team8c1daa22019-03-13 08:33:41 -07003145 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07003146 std::make_unique<TaggingEncrypter>(0x01));
zhongyi546cc452019-04-12 15:27:49 -07003147 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07003148 std::make_unique<StrictTaggingDecrypter>(0x01));
nharper2c9f02a2019-05-08 10:25:50 -07003149 ProcessDataPacket(2);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003150
3151 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3152 EXPECT_FALSE(connection_.HasQueuedData());
3153
3154 // Parse the last packet and ensure it's an ack and two stream frames from
3155 // two different streams.
3156 if (GetParam().no_stop_waiting) {
3157 EXPECT_EQ(3u, writer_->frame_count());
3158 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
3159 } else {
3160 EXPECT_EQ(4u, writer_->frame_count());
3161 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3162 }
3163 EXPECT_FALSE(writer_->ack_frames().empty());
3164 ASSERT_EQ(2u, writer_->stream_frames().size());
3165 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3166 writer_->stream_frames()[0]->stream_id);
3167 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3168 writer_->stream_frames()[1]->stream_id);
3169}
3170
3171TEST_P(QuicConnectionTest, FramePackingSendv) {
nharper46833c32019-05-15 21:33:05 -07003172 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003173 // Send data in 1 packet by writing multiple blocks in a single iovector
3174 // using writev.
3175 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3176
3177 char data[] = "ABCDEF";
3178 struct iovec iov[2];
3179 iov[0].iov_base = data;
3180 iov[0].iov_len = 4;
3181 iov[1].iov_base = data + 4;
3182 iov[1].iov_len = 2;
nharper46833c32019-05-15 21:33:05 -07003183 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
3184 connection_.transport_version(), Perspective::IS_CLIENT);
3185 connection_.SaveAndSendStreamData(stream_id, iov, 2, 6, 0, NO_FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003186
3187 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3188 EXPECT_FALSE(connection_.HasQueuedData());
3189
3190 // Parse the last packet and ensure multiple iovector blocks have
3191 // been packed into a single stream frame from one stream.
nharper46833c32019-05-15 21:33:05 -07003192 EXPECT_EQ(1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003193 EXPECT_EQ(1u, writer_->stream_frames().size());
nharper46833c32019-05-15 21:33:05 -07003194 EXPECT_EQ(0u, writer_->padding_frames().size());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003195 QuicStreamFrame* frame = writer_->stream_frames()[0].get();
nharper46833c32019-05-15 21:33:05 -07003196 EXPECT_EQ(stream_id, frame->stream_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003197 EXPECT_EQ("ABCDEF", QuicStringPiece(frame->data_buffer, frame->data_length));
3198}
3199
3200TEST_P(QuicConnectionTest, FramePackingSendvQueued) {
nharper46833c32019-05-15 21:33:05 -07003201 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003202 // Try to send two stream frames in 1 packet by using writev.
3203 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3204
3205 BlockOnNextWrite();
3206 char data[] = "ABCDEF";
3207 struct iovec iov[2];
3208 iov[0].iov_base = data;
3209 iov[0].iov_len = 4;
3210 iov[1].iov_base = data + 4;
3211 iov[1].iov_len = 2;
nharper46833c32019-05-15 21:33:05 -07003212 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
3213 connection_.transport_version(), Perspective::IS_CLIENT);
3214 connection_.SaveAndSendStreamData(stream_id, iov, 2, 6, 0, NO_FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003215
3216 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3217 EXPECT_TRUE(connection_.HasQueuedData());
3218
3219 // Unblock the writes and actually send.
3220 writer_->SetWritable();
3221 connection_.OnCanWrite();
3222 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3223
3224 // Parse the last packet and ensure it's one stream frame from one stream.
nharper46833c32019-05-15 21:33:05 -07003225 EXPECT_EQ(1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003226 EXPECT_EQ(1u, writer_->stream_frames().size());
nharper46833c32019-05-15 21:33:05 -07003227 EXPECT_EQ(0u, writer_->padding_frames().size());
3228 EXPECT_EQ(stream_id, writer_->stream_frames()[0]->stream_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003229}
3230
3231TEST_P(QuicConnectionTest, SendingZeroBytes) {
3232 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3233 // Send a zero byte write with a fin using writev.
3234 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
nharper46833c32019-05-15 21:33:05 -07003235 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
3236 connection_.transport_version(), Perspective::IS_CLIENT);
3237 connection_.SaveAndSendStreamData(stream_id, nullptr, 0, 0, 0, FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003238
3239 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3240 EXPECT_FALSE(connection_.HasQueuedData());
3241
nharper55fa6132019-05-07 19:37:21 -07003242 // Padding frames are added by v99 to ensure a minimum packet size.
3243 size_t extra_padding_frames = 0;
3244 if (GetParam().version.HasHeaderProtection()) {
3245 extra_padding_frames = 1;
3246 }
3247
QUICHE teama6ef0a62019-03-07 20:34:33 -05003248 // Parse the last packet and ensure it's one stream frame from one stream.
nharper55fa6132019-05-07 19:37:21 -07003249 EXPECT_EQ(1u + extra_padding_frames, writer_->frame_count());
3250 EXPECT_EQ(extra_padding_frames, writer_->padding_frames().size());
3251 ASSERT_EQ(1u, writer_->stream_frames().size());
nharper46833c32019-05-15 21:33:05 -07003252 EXPECT_EQ(stream_id, writer_->stream_frames()[0]->stream_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003253 EXPECT_TRUE(writer_->stream_frames()[0]->fin);
3254}
3255
3256TEST_P(QuicConnectionTest, LargeSendWithPendingAck) {
3257 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3258 // Set the ack alarm by processing a ping frame.
3259 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3260
3261 // Processs a PING frame.
3262 ProcessFramePacket(QuicFrame(QuicPingFrame()));
3263 // Ensure that this has caused the ACK alarm to be set.
3264 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
3265 EXPECT_TRUE(ack_alarm->IsSet());
3266
3267 // Send data and ensure the ack is bundled.
3268 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(8);
3269 size_t len = 10000;
3270 std::unique_ptr<char[]> data_array(new char[len]);
3271 memset(data_array.get(), '?', len);
3272 struct iovec iov;
3273 iov.iov_base = data_array.get();
3274 iov.iov_len = len;
3275 QuicConsumedData consumed = connection_.SaveAndSendStreamData(
dschinazi552accc2019-06-17 17:07:34 -07003276 GetNthClientInitiatedStreamId(0, connection_.transport_version()), &iov,
3277 1, len, 0, FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003278 EXPECT_EQ(len, consumed.bytes_consumed);
3279 EXPECT_TRUE(consumed.fin_consumed);
3280 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3281 EXPECT_FALSE(connection_.HasQueuedData());
3282
3283 // Parse the last packet and ensure it's one stream frame with a fin.
3284 EXPECT_EQ(1u, writer_->frame_count());
nharper55fa6132019-05-07 19:37:21 -07003285 ASSERT_EQ(1u, writer_->stream_frames().size());
dschinazi552accc2019-06-17 17:07:34 -07003286 EXPECT_EQ(GetNthClientInitiatedStreamId(0, connection_.transport_version()),
QUICHE teama6ef0a62019-03-07 20:34:33 -05003287 writer_->stream_frames()[0]->stream_id);
3288 EXPECT_TRUE(writer_->stream_frames()[0]->fin);
3289 // Ensure the ack alarm was cancelled when the ack was sent.
3290 EXPECT_FALSE(ack_alarm->IsSet());
3291}
3292
3293TEST_P(QuicConnectionTest, OnCanWrite) {
3294 // Visitor's OnCanWrite will send data, but will have more pending writes.
3295 EXPECT_CALL(visitor_, OnCanWrite())
3296 .WillOnce(DoAll(IgnoreResult(InvokeWithoutArgs(
3297 &connection_, &TestConnection::SendStreamData3)),
3298 IgnoreResult(InvokeWithoutArgs(
3299 &connection_, &TestConnection::SendStreamData5))));
3300 {
3301 InSequence seq;
3302 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillOnce(Return(true));
3303 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
3304 .WillRepeatedly(Return(false));
3305 }
3306
3307 EXPECT_CALL(*send_algorithm_, CanSend(_))
3308 .WillRepeatedly(testing::Return(true));
3309
3310 connection_.OnCanWrite();
3311
3312 // Parse the last packet and ensure it's the two stream frames from
3313 // two different streams.
3314 EXPECT_EQ(2u, writer_->frame_count());
3315 EXPECT_EQ(2u, writer_->stream_frames().size());
3316 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3317 writer_->stream_frames()[0]->stream_id);
3318 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3319 writer_->stream_frames()[1]->stream_id);
3320}
3321
3322TEST_P(QuicConnectionTest, RetransmitOnNack) {
3323 QuicPacketNumber last_packet;
3324 QuicByteCount second_packet_size;
3325 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet); // Packet 1
3326 second_packet_size =
3327 SendStreamDataToPeer(3, "foos", 3, NO_FIN, &last_packet); // Packet 2
3328 SendStreamDataToPeer(3, "fooos", 7, NO_FIN, &last_packet); // Packet 3
3329
3330 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3331
3332 // Don't lose a packet on an ack, and nothing is retransmitted.
3333 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3334 QuicAckFrame ack_one = InitAckFrame(1);
3335 ProcessAckPacket(&ack_one);
3336
3337 // Lose a packet and ensure it triggers retransmission.
3338 QuicAckFrame nack_two = ConstructAckFrame(3, 2);
3339 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003340 lost_packets.push_back(
3341 LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003342 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3343 .WillOnce(SetArgPointee<5>(lost_packets));
3344 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3345 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3346 EXPECT_FALSE(QuicPacketCreatorPeer::SendVersionInPacket(creator_));
3347 ProcessAckPacket(&nack_two);
3348}
3349
3350TEST_P(QuicConnectionTest, DoNotSendQueuedPacketForResetStream) {
3351 // Block the connection to queue the packet.
3352 BlockOnNextWrite();
3353
3354 QuicStreamId stream_id = 2;
3355 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
3356
3357 // Now that there is a queued packet, reset the stream.
3358 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
3359
3360 // Unblock the connection and verify that only the RST_STREAM is sent.
3361 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3362 writer_->SetWritable();
3363 connection_.OnCanWrite();
3364 if (!connection_.session_decides_what_to_write()) {
3365 // OnCanWrite will cause RST_STREAM be sent again.
3366 connection_.SendControlFrame(QuicFrame(new QuicRstStreamFrame(
3367 1, stream_id, QUIC_ERROR_PROCESSING_STREAM, 14)));
3368 }
nharper55fa6132019-05-07 19:37:21 -07003369 size_t padding_frame_count = writer_->padding_frames().size();
3370 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003371 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3372}
3373
3374TEST_P(QuicConnectionTest, SendQueuedPacketForQuicRstStreamNoError) {
3375 // Block the connection to queue the packet.
3376 BlockOnNextWrite();
3377
3378 QuicStreamId stream_id = 2;
fayang2ce66082019-10-02 06:29:04 -07003379 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
3380 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3381 } else {
3382 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3383 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003384 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
3385
3386 // Now that there is a queued packet, reset the stream.
3387 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 3);
3388
3389 // Unblock the connection and verify that the RST_STREAM is sent and the data
3390 // packet is sent.
fayang2ce66082019-10-02 06:29:04 -07003391 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
3392 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3393 .Times(AtLeast(1));
3394 } else {
3395 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3396 .Times(AtLeast(2));
3397 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003398 writer_->SetWritable();
3399 connection_.OnCanWrite();
3400 if (!connection_.session_decides_what_to_write()) {
3401 // OnCanWrite will cause RST_STREAM be sent again.
3402 connection_.SendControlFrame(QuicFrame(
3403 new QuicRstStreamFrame(1, stream_id, QUIC_STREAM_NO_ERROR, 14)));
3404 }
nharper55fa6132019-05-07 19:37:21 -07003405 size_t padding_frame_count = writer_->padding_frames().size();
3406 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003407 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3408}
3409
3410TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnNack) {
3411 QuicStreamId stream_id = 2;
3412 QuicPacketNumber last_packet;
3413 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3414 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3415 SendStreamDataToPeer(stream_id, "fooos", 7, NO_FIN, &last_packet);
3416
3417 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3418 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 12);
3419
3420 // Lose a packet and ensure it does not trigger retransmission.
3421 QuicAckFrame nack_two = ConstructAckFrame(last_packet, last_packet - 1);
3422 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3423 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3424 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3425 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3426 ProcessAckPacket(&nack_two);
3427}
3428
3429TEST_P(QuicConnectionTest, RetransmitForQuicRstStreamNoErrorOnNack) {
3430 QuicStreamId stream_id = 2;
3431 QuicPacketNumber last_packet;
3432 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3433 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3434 SendStreamDataToPeer(stream_id, "fooos", 7, NO_FIN, &last_packet);
3435
3436 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3437 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 12);
3438
3439 // Lose a packet, ensure it triggers retransmission.
3440 QuicAckFrame nack_two = ConstructAckFrame(last_packet, last_packet - 1);
3441 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3442 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003443 lost_packets.push_back(LostPacket(last_packet - 1, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003444 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3445 .WillOnce(SetArgPointee<5>(lost_packets));
3446 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3447 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
3448 ProcessAckPacket(&nack_two);
3449}
3450
3451TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnRTO) {
3452 QuicStreamId stream_id = 2;
3453 QuicPacketNumber last_packet;
3454 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3455
3456 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3457 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
3458
3459 // Fire the RTO and verify that the RST_STREAM is resent, not stream data.
3460 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3461 clock_.AdvanceTime(DefaultRetransmissionTime());
3462 connection_.GetRetransmissionAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07003463 size_t padding_frame_count = writer_->padding_frames().size();
3464 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003465 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3466 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
3467}
3468
3469// Ensure that if the only data in flight is non-retransmittable, the
3470// retransmission alarm is not set.
3471TEST_P(QuicConnectionTest, CancelRetransmissionAlarmAfterResetStream) {
3472 QuicStreamId stream_id = 2;
3473 QuicPacketNumber last_data_packet;
3474 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
3475
3476 // Cancel the stream.
3477 const QuicPacketNumber rst_packet = last_data_packet + 1;
3478 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, rst_packet, _, _)).Times(1);
3479 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
3480
3481 // Ack the RST_STREAM frame (since it's retransmittable), but not the data
3482 // packet, which is no longer retransmittable since the stream was cancelled.
3483 QuicAckFrame nack_stream_data =
3484 ConstructAckFrame(rst_packet, last_data_packet);
3485 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3486 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3487 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3488 ProcessAckPacket(&nack_stream_data);
3489
3490 // Ensure that the data is still in flight, but the retransmission alarm is no
3491 // longer set.
ianswett9f459cb2019-04-21 06:39:59 -07003492 EXPECT_GT(manager_->GetBytesInFlight(), 0u);
fayang67f82272019-08-14 16:08:45 -07003493 if (QuicConnectionPeer::GetSentPacketManager(&connection_)
3494 ->fix_rto_retransmission()) {
3495 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3496 } else {
3497 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3498 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003499}
3500
3501TEST_P(QuicConnectionTest, RetransmitForQuicRstStreamNoErrorOnRTO) {
3502 connection_.SetMaxTailLossProbes(0);
3503
3504 QuicStreamId stream_id = 2;
3505 QuicPacketNumber last_packet;
3506 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3507
3508 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3509 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 3);
3510
3511 // Fire the RTO and verify that the RST_STREAM is resent, the stream data
3512 // is sent.
3513 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(2));
3514 clock_.AdvanceTime(DefaultRetransmissionTime());
3515 connection_.GetRetransmissionAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07003516 size_t padding_frame_count = writer_->padding_frames().size();
3517 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003518 ASSERT_EQ(1u, writer_->rst_stream_frames().size());
3519 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
3520}
3521
3522TEST_P(QuicConnectionTest, DoNotSendPendingRetransmissionForResetStream) {
3523 QuicStreamId stream_id = 2;
3524 QuicPacketNumber last_packet;
3525 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3526 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3527 BlockOnNextWrite();
3528 connection_.SendStreamDataWithString(stream_id, "fooos", 7, NO_FIN);
3529
3530 // Lose a packet which will trigger a pending retransmission.
3531 QuicAckFrame ack = ConstructAckFrame(last_packet, last_packet - 1);
3532 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3533 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3534 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3535 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3536 ProcessAckPacket(&ack);
3537
3538 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 12);
3539
3540 // Unblock the connection and verify that the RST_STREAM is sent but not the
3541 // second data packet nor a retransmit.
3542 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3543 writer_->SetWritable();
3544 connection_.OnCanWrite();
3545 if (!connection_.session_decides_what_to_write()) {
3546 // OnCanWrite will cause this RST_STREAM_FRAME be sent again.
3547 connection_.SendControlFrame(QuicFrame(new QuicRstStreamFrame(
3548 1, stream_id, QUIC_ERROR_PROCESSING_STREAM, 14)));
3549 }
nharper55fa6132019-05-07 19:37:21 -07003550 size_t padding_frame_count = writer_->padding_frames().size();
3551 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
zhongyi546cc452019-04-12 15:27:49 -07003552 ASSERT_EQ(1u, writer_->rst_stream_frames().size());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003553 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
3554}
3555
3556TEST_P(QuicConnectionTest, SendPendingRetransmissionForQuicRstStreamNoError) {
3557 QuicStreamId stream_id = 2;
3558 QuicPacketNumber last_packet;
3559 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3560 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3561 BlockOnNextWrite();
3562 connection_.SendStreamDataWithString(stream_id, "fooos", 7, NO_FIN);
3563
3564 // Lose a packet which will trigger a pending retransmission.
3565 QuicAckFrame ack = ConstructAckFrame(last_packet, last_packet - 1);
3566 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3567 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003568 lost_packets.push_back(LostPacket(last_packet - 1, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003569 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3570 .WillOnce(SetArgPointee<5>(lost_packets));
3571 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3572 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3573 ProcessAckPacket(&ack);
3574
3575 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 12);
3576
3577 // Unblock the connection and verify that the RST_STREAM is sent and the
3578 // second data packet or a retransmit is sent.
3579 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(2));
3580 writer_->SetWritable();
3581 connection_.OnCanWrite();
3582 // The RST_STREAM_FRAME is sent after queued packets and pending
3583 // retransmission.
3584 connection_.SendControlFrame(QuicFrame(
3585 new QuicRstStreamFrame(1, stream_id, QUIC_STREAM_NO_ERROR, 14)));
nharper55fa6132019-05-07 19:37:21 -07003586 size_t padding_frame_count = writer_->padding_frames().size();
3587 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003588 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3589}
3590
3591TEST_P(QuicConnectionTest, RetransmitAckedPacket) {
3592 QuicPacketNumber last_packet;
3593 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
3594 SendStreamDataToPeer(1, "foos", 3, NO_FIN, &last_packet); // Packet 2
3595 SendStreamDataToPeer(1, "fooos", 7, NO_FIN, &last_packet); // Packet 3
3596
3597 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3598
3599 // Instigate a loss with an ack.
3600 QuicAckFrame nack_two = ConstructAckFrame(3, 2);
3601 // The first nack should trigger a fast retransmission, but we'll be
3602 // write blocked, so the packet will be queued.
3603 BlockOnNextWrite();
3604
3605 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003606 lost_packets.push_back(
3607 LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003608 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3609 .WillOnce(SetArgPointee<5>(lost_packets));
3610 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
fayang2ce66082019-10-02 06:29:04 -07003611 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
3612 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _))
3613 .Times(1);
3614 } else {
3615 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3616 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003617 ProcessAckPacket(&nack_two);
3618 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3619
3620 // Now, ack the previous transmission.
3621 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3622 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(false, _, _, _, _));
3623 QuicAckFrame ack_all = InitAckFrame(3);
3624 ProcessAckPacket(&ack_all);
3625
fayang2ce66082019-10-02 06:29:04 -07003626 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
3627 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _))
3628 .Times(0);
3629 } else {
3630 // Unblock the socket and attempt to send the queued packets. We will always
3631 // send the retransmission.
3632 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _))
3633 .Times(1);
3634 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003635
3636 writer_->SetWritable();
3637 connection_.OnCanWrite();
3638
3639 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3640 // We do not store retransmittable frames of this retransmission.
3641 EXPECT_FALSE(QuicConnectionPeer::HasRetransmittableFrames(&connection_, 4));
3642}
3643
3644TEST_P(QuicConnectionTest, RetransmitNackedLargestObserved) {
3645 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3646 QuicPacketNumber original, second;
3647
3648 QuicByteCount packet_size =
3649 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &original); // 1st packet.
3650 SendStreamDataToPeer(3, "bar", 3, NO_FIN, &second); // 2nd packet.
3651
3652 QuicAckFrame frame = InitAckFrame({{second, second + 1}});
3653 // The first nack should retransmit the largest observed packet.
3654 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003655 lost_packets.push_back(LostPacket(original, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003656 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3657 .WillOnce(SetArgPointee<5>(lost_packets));
3658 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3659 // Packet 1 is short header for IETF QUIC because the encryption level
3660 // switched to ENCRYPTION_FORWARD_SECURE in SendStreamDataToPeer.
fayangd4291e42019-05-30 10:31:21 -07003661 EXPECT_CALL(*send_algorithm_,
3662 OnPacketSent(_, _, _,
3663 VersionHasIetfInvariantHeader(
3664 GetParam().version.transport_version)
3665 ? packet_size
3666 : packet_size - kQuicVersionSize,
3667 _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003668 ProcessAckPacket(&frame);
3669}
3670
3671TEST_P(QuicConnectionTest, QueueAfterTwoRTOs) {
fayang5f135052019-08-22 17:59:40 -07003672 if (connection_.PtoEnabled()) {
3673 return;
3674 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003675 connection_.SetMaxTailLossProbes(0);
3676
3677 for (int i = 0; i < 10; ++i) {
3678 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3679 connection_.SendStreamDataWithString(3, "foo", i * 3, NO_FIN);
3680 }
3681
3682 // Block the writer and ensure they're queued.
3683 BlockOnNextWrite();
3684 clock_.AdvanceTime(DefaultRetransmissionTime());
3685 // Only one packet should be retransmitted.
fayang2ce66082019-10-02 06:29:04 -07003686 if (connection_.session_decides_what_to_write()) {
3687 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
3688 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3689 } else {
3690 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3691 }
3692 } else {
3693 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
3694 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3695 } else {
3696 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3697 }
3698 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003699 connection_.GetRetransmissionAlarm()->Fire();
3700 EXPECT_TRUE(connection_.HasQueuedData());
3701
3702 // Unblock the writer.
3703 writer_->SetWritable();
3704 clock_.AdvanceTime(QuicTime::Delta::FromMicroseconds(
3705 2 * DefaultRetransmissionTime().ToMicroseconds()));
3706 // Retransmit already retransmitted packets event though the packet number
3707 // greater than the largest observed.
3708 if (connection_.session_decides_what_to_write()) {
fayang2ce66082019-10-02 06:29:04 -07003709 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
3710 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3711 } else {
3712 // 2 RTOs + 1 TLP.
3713 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
3714 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003715 } else {
fayang2ce66082019-10-02 06:29:04 -07003716 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
3717 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3718 } else {
3719 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3720 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003721 }
3722 connection_.GetRetransmissionAlarm()->Fire();
3723 connection_.OnCanWrite();
3724}
3725
3726TEST_P(QuicConnectionTest, WriteBlockedBufferedThenSent) {
3727 BlockOnNextWrite();
3728 writer_->set_is_write_blocked_data_buffered(true);
3729 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3730 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3731 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3732
3733 writer_->SetWritable();
3734 connection_.OnCanWrite();
3735 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3736}
3737
3738TEST_P(QuicConnectionTest, WriteBlockedThenSent) {
3739 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3740 BlockOnNextWrite();
fayang2ce66082019-10-02 06:29:04 -07003741 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
3742 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3743 } else {
3744 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3745 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003746 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
fayang2ce66082019-10-02 06:29:04 -07003747 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
3748 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3749 } else {
3750 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3751 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003752 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3753
3754 // The second packet should also be queued, in order to ensure packets are
3755 // never sent out of order.
3756 writer_->SetWritable();
fayang2ce66082019-10-02 06:29:04 -07003757 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
3758 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3759 } else {
3760 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3761 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003762 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3763 EXPECT_EQ(2u, connection_.NumQueuedPackets());
3764
3765 // Now both are sent in order when we unblock.
fayang2ce66082019-10-02 06:29:04 -07003766 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
3767 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3768 } else {
3769 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3770 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003771 connection_.OnCanWrite();
3772 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
fayang2ce66082019-10-02 06:29:04 -07003773 EXPECT_EQ(0u, connection_.NumQueuedPackets());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003774}
3775
3776TEST_P(QuicConnectionTest, RetransmitWriteBlockedAckedOriginalThenSent) {
3777 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3778 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
3779 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3780
3781 BlockOnNextWrite();
3782 writer_->set_is_write_blocked_data_buffered(true);
3783 // Simulate the retransmission alarm firing.
3784 clock_.AdvanceTime(DefaultRetransmissionTime());
3785 connection_.GetRetransmissionAlarm()->Fire();
3786
3787 // Ack the sent packet before the callback returns, which happens in
3788 // rare circumstances with write blocked sockets.
3789 QuicAckFrame ack = InitAckFrame(1);
3790 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3791 ProcessAckPacket(&ack);
3792
3793 writer_->SetWritable();
3794 connection_.OnCanWrite();
fayang67f82272019-08-14 16:08:45 -07003795 if (QuicConnectionPeer::GetSentPacketManager(&connection_)
3796 ->fix_rto_retransmission()) {
3797 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3798 } else {
3799 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3800 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003801 EXPECT_FALSE(QuicConnectionPeer::HasRetransmittableFrames(&connection_, 2));
3802}
3803
3804TEST_P(QuicConnectionTest, AlarmsWhenWriteBlocked) {
3805 // Block the connection.
3806 BlockOnNextWrite();
3807 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
3808 EXPECT_EQ(1u, writer_->packets_write_attempts());
3809 EXPECT_TRUE(writer_->IsWriteBlocked());
3810
3811 // Set the send alarm. Fire the alarm and ensure it doesn't attempt to write.
3812 connection_.GetSendAlarm()->Set(clock_.ApproximateNow());
3813 connection_.GetSendAlarm()->Fire();
3814 EXPECT_TRUE(writer_->IsWriteBlocked());
3815 EXPECT_EQ(1u, writer_->packets_write_attempts());
3816}
3817
3818TEST_P(QuicConnectionTest, NoSendAlarmAfterProcessPacketWhenWriteBlocked) {
3819 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3820
3821 // Block the connection.
3822 BlockOnNextWrite();
3823 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
3824 EXPECT_TRUE(writer_->IsWriteBlocked());
3825 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3826 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
3827
3828 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3829 // Process packet number 1. Can not call ProcessPacket or ProcessDataPacket
3830 // here, because they will fire the alarm after QuicConnection::ProcessPacket
3831 // is returned.
3832 const uint64_t received_packet_num = 1;
3833 const bool has_stop_waiting = false;
nharperc6b99512019-09-19 11:13:48 -07003834 const EncryptionLevel level = ENCRYPTION_FORWARD_SECURE;
3835 std::unique_ptr<QuicPacket> packet(
3836 ConstructDataPacket(received_packet_num, has_stop_waiting, level));
dschinazi66dea072019-04-09 11:41:06 -07003837 char buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05003838 size_t encrypted_length =
3839 peer_framer_.EncryptPayload(level, QuicPacketNumber(received_packet_num),
dschinazi66dea072019-04-09 11:41:06 -07003840 *packet, buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003841 connection_.ProcessUdpPacket(
3842 kSelfAddress, kPeerAddress,
3843 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
3844
3845 EXPECT_TRUE(writer_->IsWriteBlocked());
3846 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
3847}
3848
3849TEST_P(QuicConnectionTest, AddToWriteBlockedListIfWriterBlockedWhenProcessing) {
3850 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3851 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
3852
3853 // Simulate the case where a shared writer gets blocked by another connection.
3854 writer_->SetWriteBlocked();
3855
3856 // Process an ACK, make sure the connection calls visitor_->OnWriteBlocked().
3857 QuicAckFrame ack1 = InitAckFrame(1);
3858 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
3859 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
3860 ProcessAckPacket(1, &ack1);
3861}
3862
3863TEST_P(QuicConnectionTest, DoNotAddToWriteBlockedListAfterDisconnect) {
3864 writer_->SetBatchMode(true);
3865 EXPECT_TRUE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07003866 // Have to explicitly grab the OnConnectionClosed frame and check
3867 // its parameters because this is a silent connection close and the
3868 // frame is not also transmitted to the peer.
3869 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
3870 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003871
3872 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
3873
3874 {
fayanga4b37b22019-06-18 13:37:47 -07003875 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003876 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
3877 ConnectionCloseBehavior::SILENT_CLOSE);
3878
3879 EXPECT_FALSE(connection_.connected());
3880 writer_->SetWriteBlocked();
3881 }
fkastenholz5d880a92019-06-21 09:01:56 -07003882 EXPECT_EQ(1, connection_close_frame_count_);
3883 EXPECT_EQ(QUIC_PEER_GOING_AWAY,
3884 saved_connection_close_frame_.quic_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003885}
3886
3887TEST_P(QuicConnectionTest, AddToWriteBlockedListIfBlockedOnFlushPackets) {
3888 writer_->SetBatchMode(true);
3889 writer_->BlockOnNextFlush();
3890
3891 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
3892 {
fayanga4b37b22019-06-18 13:37:47 -07003893 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003894 // flusher's destructor will call connection_.FlushPackets, which should add
3895 // the connection to the write blocked list.
3896 }
3897}
3898
3899TEST_P(QuicConnectionTest, NoLimitPacketsPerNack) {
3900 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3901 int offset = 0;
3902 // Send packets 1 to 15.
3903 for (int i = 0; i < 15; ++i) {
3904 SendStreamDataToPeer(1, "foo", offset, NO_FIN, nullptr);
3905 offset += 3;
3906 }
3907
3908 // Ack 15, nack 1-14.
3909
3910 QuicAckFrame nack =
3911 InitAckFrame({{QuicPacketNumber(15), QuicPacketNumber(16)}});
3912
3913 // 14 packets have been NACK'd and lost.
3914 LostPacketVector lost_packets;
3915 for (int i = 1; i < 15; ++i) {
dschinazi66dea072019-04-09 11:41:06 -07003916 lost_packets.push_back(
3917 LostPacket(QuicPacketNumber(i), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003918 }
3919 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3920 .WillOnce(SetArgPointee<5>(lost_packets));
3921 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3922 if (connection_.session_decides_what_to_write()) {
3923 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3924 } else {
3925 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(14);
3926 }
3927 ProcessAckPacket(&nack);
3928}
3929
3930// Test sending multiple acks from the connection to the session.
3931TEST_P(QuicConnectionTest, MultipleAcks) {
QUICHE teamcd098022019-03-22 18:49:55 -07003932 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3933 return;
3934 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003935 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3936 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3937 ProcessDataPacket(1);
3938 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
3939 QuicPacketNumber last_packet;
3940 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
3941 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
3942 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet); // Packet 2
3943 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
3944 SendAckPacketToPeer(); // Packet 3
3945 SendStreamDataToPeer(5, "foo", 0, NO_FIN, &last_packet); // Packet 4
3946 EXPECT_EQ(QuicPacketNumber(4u), last_packet);
3947 SendStreamDataToPeer(1, "foo", 3, NO_FIN, &last_packet); // Packet 5
3948 EXPECT_EQ(QuicPacketNumber(5u), last_packet);
3949 SendStreamDataToPeer(3, "foo", 3, NO_FIN, &last_packet); // Packet 6
3950 EXPECT_EQ(QuicPacketNumber(6u), last_packet);
3951
3952 // Client will ack packets 1, 2, [!3], 4, 5.
3953 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3954 QuicAckFrame frame1 = ConstructAckFrame(5, 3);
3955 ProcessAckPacket(&frame1);
3956
3957 // Now the client implicitly acks 3, and explicitly acks 6.
3958 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3959 QuicAckFrame frame2 = InitAckFrame(6);
3960 ProcessAckPacket(&frame2);
3961}
3962
3963TEST_P(QuicConnectionTest, DontLatchUnackedPacket) {
QUICHE teamcd098022019-03-22 18:49:55 -07003964 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3965 return;
3966 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003967 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3968 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3969 ProcessDataPacket(1);
3970 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
3971 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr); // Packet 1;
3972 // From now on, we send acks, so the send algorithm won't mark them pending.
3973 SendAckPacketToPeer(); // Packet 2
3974
3975 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3976 QuicAckFrame frame = InitAckFrame(1);
3977 ProcessAckPacket(&frame);
3978
3979 // Verify that our internal state has least-unacked as 2, because we're still
3980 // waiting for a potential ack for 2.
3981
3982 EXPECT_EQ(QuicPacketNumber(2u), stop_waiting()->least_unacked);
3983
3984 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3985 frame = InitAckFrame(2);
3986 ProcessAckPacket(&frame);
3987 EXPECT_EQ(QuicPacketNumber(3u), stop_waiting()->least_unacked);
3988
3989 // When we send an ack, we make sure our least-unacked makes sense. In this
3990 // case since we're not waiting on an ack for 2 and all packets are acked, we
3991 // set it to 3.
3992 SendAckPacketToPeer(); // Packet 3
3993 // Least_unacked remains at 3 until another ack is received.
3994 EXPECT_EQ(QuicPacketNumber(3u), stop_waiting()->least_unacked);
3995 if (GetParam().no_stop_waiting) {
3996 // Expect no stop waiting frame is sent.
3997 EXPECT_FALSE(least_unacked().IsInitialized());
3998 } else {
3999 // Check that the outgoing ack had its packet number as least_unacked.
4000 EXPECT_EQ(QuicPacketNumber(3u), least_unacked());
4001 }
4002
4003 // Ack the ack, which updates the rtt and raises the least unacked.
4004 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4005 frame = InitAckFrame(3);
4006 ProcessAckPacket(&frame);
4007
4008 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr); // Packet 4
4009 EXPECT_EQ(QuicPacketNumber(4u), stop_waiting()->least_unacked);
4010 SendAckPacketToPeer(); // Packet 5
4011 if (GetParam().no_stop_waiting) {
4012 // Expect no stop waiting frame is sent.
4013 EXPECT_FALSE(least_unacked().IsInitialized());
4014 } else {
4015 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
4016 }
4017
4018 // Send two data packets at the end, and ensure if the last one is acked,
4019 // the least unacked is raised above the ack packets.
4020 SendStreamDataToPeer(1, "bar", 6, NO_FIN, nullptr); // Packet 6
4021 SendStreamDataToPeer(1, "bar", 9, NO_FIN, nullptr); // Packet 7
4022
4023 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4024 frame = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(5)},
4025 {QuicPacketNumber(7), QuicPacketNumber(8)}});
4026 ProcessAckPacket(&frame);
4027
4028 EXPECT_EQ(QuicPacketNumber(6u), stop_waiting()->least_unacked);
4029}
4030
4031TEST_P(QuicConnectionTest, TLP) {
4032 connection_.SetMaxTailLossProbes(1);
4033
4034 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
4035 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4036 QuicTime retransmission_time =
4037 connection_.GetRetransmissionAlarm()->deadline();
4038 EXPECT_NE(QuicTime::Zero(), retransmission_time);
4039
4040 EXPECT_EQ(QuicPacketNumber(1u), writer_->header().packet_number);
4041 // Simulate the retransmission alarm firing and sending a tlp,
4042 // so send algorithm's OnRetransmissionTimeout is not called.
4043 clock_.AdvanceTime(retransmission_time - clock_.Now());
4044 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
4045 connection_.GetRetransmissionAlarm()->Fire();
4046 EXPECT_EQ(QuicPacketNumber(2u), writer_->header().packet_number);
4047 // We do not raise the high water mark yet.
4048 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4049}
4050
zhongyifbb25772019-04-10 16:54:08 -07004051TEST_P(QuicConnectionTest, TailLossProbeDelayForStreamDataInTLPR) {
fayang5f135052019-08-22 17:59:40 -07004052 if (!connection_.session_decides_what_to_write() ||
4053 connection_.PtoEnabled()) {
zhongyi1b2f7832019-06-14 13:31:34 -07004054 return;
4055 }
4056
zhongyifbb25772019-04-10 16:54:08 -07004057 // Set TLPR from QuicConfig.
4058 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4059 QuicConfig config;
4060 QuicTagVector options;
4061 options.push_back(kTLPR);
4062 config.SetConnectionOptionsToSend(options);
4063 connection_.SetFromConfig(config);
4064 connection_.SetMaxTailLossProbes(1);
4065
4066 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
4067 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4068
4069 QuicTime retransmission_time =
4070 connection_.GetRetransmissionAlarm()->deadline();
4071 EXPECT_NE(QuicTime::Zero(), retransmission_time);
4072 QuicTime::Delta expected_tlp_delay =
4073 0.5 * manager_->GetRttStats()->SmoothedOrInitialRtt();
4074 EXPECT_EQ(expected_tlp_delay, retransmission_time - clock_.Now());
4075
4076 EXPECT_EQ(QuicPacketNumber(1u), writer_->header().packet_number);
4077 // Simulate firing of the retransmission alarm and retransmit the packet.
4078 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
4079 clock_.AdvanceTime(retransmission_time - clock_.Now());
4080 connection_.GetRetransmissionAlarm()->Fire();
4081 EXPECT_EQ(QuicPacketNumber(2u), writer_->header().packet_number);
4082
4083 // We do not raise the high water mark yet.
4084 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4085}
4086
4087TEST_P(QuicConnectionTest, TailLossProbeDelayForNonStreamDataInTLPR) {
fayang5f135052019-08-22 17:59:40 -07004088 if (!connection_.session_decides_what_to_write() ||
4089 connection_.PtoEnabled()) {
zhongyi1b2f7832019-06-14 13:31:34 -07004090 return;
4091 }
4092
zhongyifbb25772019-04-10 16:54:08 -07004093 // Set TLPR from QuicConfig.
4094 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4095 QuicConfig config;
4096 QuicTagVector options;
4097 options.push_back(kTLPR);
4098 config.SetConnectionOptionsToSend(options);
4099 connection_.SetFromConfig(config);
4100 connection_.SetMaxTailLossProbes(1);
4101
4102 // Sets retransmittable on wire.
4103 const QuicTime::Delta retransmittable_on_wire_timeout =
4104 QuicTime::Delta::FromMilliseconds(50);
4105 connection_.set_retransmittable_on_wire_timeout(
4106 retransmittable_on_wire_timeout);
4107
4108 EXPECT_TRUE(connection_.connected());
4109 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4110 .WillRepeatedly(Return(true));
4111 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
4112 EXPECT_FALSE(connection_.IsPathDegrading());
4113 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4114
4115 const char data[] = "data";
4116 size_t data_size = strlen(data);
4117 QuicStreamOffset offset = 0;
4118
4119 // Send a data packet.
4120 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
4121 offset += data_size;
4122
4123 // Path degrading alarm should be set when there is a retransmittable packet
4124 // on the wire.
4125 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
4126
4127 // Verify the path degrading delay.
4128 // First TLP with stream data.
4129 QuicTime::Delta srtt = manager_->GetRttStats()->SmoothedOrInitialRtt();
4130 QuicTime::Delta expected_delay = 0.5 * srtt;
4131 // Add 1st RTO.
4132 QuicTime::Delta retransmission_delay =
4133 QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
4134 expected_delay = expected_delay + retransmission_delay;
4135 // Add 2nd RTO.
4136 expected_delay = expected_delay + retransmission_delay * 2;
4137 EXPECT_EQ(expected_delay,
4138 QuicConnectionPeer::GetSentPacketManager(&connection_)
4139 ->GetPathDegradingDelay());
4140 ASSERT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
4141
4142 // The ping alarm is set for the ping timeout, not the shorter
4143 // retransmittable_on_wire_timeout.
4144 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4145 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
4146 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
4147
4148 // Receive an ACK for the data packet.
4149 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4150 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4151 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4152 QuicAckFrame frame =
4153 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
4154 ProcessAckPacket(&frame);
4155
4156 // Path degrading alarm should be cancelled as there is no more
4157 // reretransmittable packets on the wire.
4158 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
4159 // The ping alarm should be set to the retransmittable_on_wire_timeout.
4160 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4161 EXPECT_EQ(retransmittable_on_wire_timeout,
4162 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
4163
4164 // Simulate firing of the retransmittable on wire and send a PING.
4165 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
4166 clock_.AdvanceTime(retransmittable_on_wire_timeout);
4167 connection_.GetPingAlarm()->Fire();
4168
4169 // The retransmission alarm and the path degrading alarm should be set as
4170 // there is a retransmittable packet (PING) on the wire,
4171 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4172 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
4173
4174 // Verify the retransmission delay.
4175 QuicTime::Delta min_rto_timeout =
4176 QuicTime::Delta::FromMilliseconds(kMinRetransmissionTimeMs);
4177 srtt = manager_->GetRttStats()->SmoothedOrInitialRtt();
zhongyi9fa2be32019-09-10 12:39:01 -07004178
4179 // First TLP without unacked stream data will no longer use TLPR.
4180 expected_delay = std::max(2 * srtt, 1.5 * srtt + 0.5 * min_rto_timeout);
zhongyifbb25772019-04-10 16:54:08 -07004181 EXPECT_EQ(expected_delay,
4182 connection_.GetRetransmissionAlarm()->deadline() - clock_.Now());
4183
zhongyi1b2f7832019-06-14 13:31:34 -07004184 // Verify the path degrading delay = TLP delay + 1st RTO + 2nd RTO.
zhongyifbb25772019-04-10 16:54:08 -07004185 // Add 1st RTO.
4186 retransmission_delay =
4187 std::max(manager_->GetRttStats()->smoothed_rtt() +
4188 4 * manager_->GetRttStats()->mean_deviation(),
4189 min_rto_timeout);
4190 expected_delay = expected_delay + retransmission_delay;
4191 // Add 2nd RTO.
4192 expected_delay = expected_delay + retransmission_delay * 2;
4193 EXPECT_EQ(expected_delay,
4194 QuicConnectionPeer::GetSentPacketManager(&connection_)
4195 ->GetPathDegradingDelay());
4196
4197 // The ping alarm is set for the ping timeout, not the shorter
4198 // retransmittable_on_wire_timeout.
4199 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4200 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
4201 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
zhongyi1b2f7832019-06-14 13:31:34 -07004202
4203 // Advance a small period of time: 5ms. And receive a retransmitted ACK.
4204 // This will update the retransmission alarm, verify the retransmission delay
4205 // is correct.
4206 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4207 QuicAckFrame ack = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
4208 ProcessAckPacket(&ack);
4209
4210 // Verify the retransmission delay.
zhongyi9fa2be32019-09-10 12:39:01 -07004211 // First TLP without unacked stream data will no longer use TLPR.
4212 expected_delay = std::max(2 * srtt, 1.5 * srtt + 0.5 * min_rto_timeout);
zhongyi1b2f7832019-06-14 13:31:34 -07004213 expected_delay = expected_delay - QuicTime::Delta::FromMilliseconds(5);
4214 EXPECT_EQ(expected_delay,
4215 connection_.GetRetransmissionAlarm()->deadline() - clock_.Now());
zhongyifbb25772019-04-10 16:54:08 -07004216}
4217
QUICHE teama6ef0a62019-03-07 20:34:33 -05004218TEST_P(QuicConnectionTest, RTO) {
fayang5f135052019-08-22 17:59:40 -07004219 if (connection_.PtoEnabled()) {
4220 return;
4221 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004222 connection_.SetMaxTailLossProbes(0);
4223
4224 QuicTime default_retransmission_time =
4225 clock_.ApproximateNow() + DefaultRetransmissionTime();
4226 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
4227 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4228
4229 EXPECT_EQ(QuicPacketNumber(1u), writer_->header().packet_number);
4230 EXPECT_EQ(default_retransmission_time,
4231 connection_.GetRetransmissionAlarm()->deadline());
4232 // Simulate the retransmission alarm firing.
4233 clock_.AdvanceTime(DefaultRetransmissionTime());
4234 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
4235 connection_.GetRetransmissionAlarm()->Fire();
4236 EXPECT_EQ(QuicPacketNumber(2u), writer_->header().packet_number);
4237 // We do not raise the high water mark yet.
4238 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4239}
4240
fayanga29eb242019-07-16 12:25:38 -07004241// Regression test of b/133771183.
4242TEST_P(QuicConnectionTest, RtoWithNoDataToRetransmit) {
fayang5f135052019-08-22 17:59:40 -07004243 if (!connection_.session_decides_what_to_write() ||
4244 connection_.PtoEnabled()) {
fayanga29eb242019-07-16 12:25:38 -07004245 return;
4246 }
4247 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4248 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4249 connection_.SetMaxTailLossProbes(0);
4250
4251 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
4252 // Connection is cwnd limited.
4253 CongestionBlockWrites();
4254 // Stream gets reset.
4255 SendRstStream(3, QUIC_ERROR_PROCESSING_STREAM, 3);
4256 // Simulate the retransmission alarm firing.
4257 clock_.AdvanceTime(DefaultRetransmissionTime());
4258 // RTO fires, but there is no packet to be RTOed.
fayang67f82272019-08-14 16:08:45 -07004259 if (GetQuicReloadableFlag(quic_fix_rto_retransmission3)) {
fayanga29eb242019-07-16 12:25:38 -07004260 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4261 } else {
4262 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4263 }
4264 connection_.GetRetransmissionAlarm()->Fire();
fayang67f82272019-08-14 16:08:45 -07004265 if (GetQuicReloadableFlag(quic_fix_rto_retransmission3)) {
fayanga29eb242019-07-16 12:25:38 -07004266 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
4267 }
4268
4269 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(40);
4270 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(20);
fayang67f82272019-08-14 16:08:45 -07004271 if (GetQuicReloadableFlag(quic_fix_rto_retransmission3)) {
fayanga29eb242019-07-16 12:25:38 -07004272 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
4273 .WillRepeatedly(Return(false));
4274 } else {
4275 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
4276 }
fayang67f82272019-08-14 16:08:45 -07004277 if (GetQuicReloadableFlag(quic_fix_rto_retransmission3)) {
fayanga29eb242019-07-16 12:25:38 -07004278 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(1);
4279 } else {
4280 // Since there is a buffered RST_STREAM, no retransmittable frame is bundled
4281 // with ACKs.
4282 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(0);
4283 }
4284 // Receives packets 1 - 40.
4285 for (size_t i = 1; i <= 40; ++i) {
4286 ProcessDataPacket(i);
4287 }
4288}
4289
QUICHE teama6ef0a62019-03-07 20:34:33 -05004290TEST_P(QuicConnectionTest, RetransmitWithSameEncryptionLevel) {
4291 use_tagging_decrypter();
4292
4293 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
4294 // the end of the packet. We can test this to check which encrypter was used.
QUICHE team6987b4a2019-03-15 16:23:04 -07004295 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07004296 std::make_unique<TaggingEncrypter>(0x01));
nharper46833c32019-05-15 21:33:05 -07004297 QuicByteCount packet_size;
4298 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4299 .WillOnce(SaveArg<3>(&packet_size));
4300 connection_.SendCryptoDataWithString("foo", 0);
4301 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004302 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
4303
4304 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004305 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004306 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4307 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
4308 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
4309
4310 {
4311 InSequence s;
4312 EXPECT_CALL(*send_algorithm_,
4313 OnPacketSent(_, _, QuicPacketNumber(3), _, _));
4314 EXPECT_CALL(*send_algorithm_,
4315 OnPacketSent(_, _, QuicPacketNumber(4), _, _));
4316 }
4317
4318 // Manually mark both packets for retransmission.
4319 connection_.RetransmitUnackedPackets(ALL_UNACKED_RETRANSMISSION);
4320
QUICHE team6987b4a2019-03-15 16:23:04 -07004321 // Packet should have been sent with ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05004322 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_previous_packet());
4323
4324 // Packet should have been sent with ENCRYPTION_ZERO_RTT.
4325 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
4326}
4327
4328TEST_P(QuicConnectionTest, SendHandshakeMessages) {
4329 use_tagging_decrypter();
4330 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
4331 // the end of the packet. We can test this to check which encrypter was used.
QUICHE team6987b4a2019-03-15 16:23:04 -07004332 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07004333 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004334
4335 // Attempt to send a handshake message and have the socket block.
4336 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
4337 BlockOnNextWrite();
nharper46833c32019-05-15 21:33:05 -07004338 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004339 // The packet should be serialized, but not queued.
4340 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4341
4342 // Switch to the new encrypter.
4343 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004344 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004345 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4346
4347 // Now become writeable and flush the packets.
4348 writer_->SetWritable();
4349 EXPECT_CALL(visitor_, OnCanWrite());
4350 connection_.OnCanWrite();
4351 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4352
4353 // Verify that the handshake packet went out at the null encryption.
4354 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
4355}
4356
4357TEST_P(QuicConnectionTest,
4358 DropRetransmitsForNullEncryptedPacketAfterForwardSecure) {
4359 use_tagging_decrypter();
QUICHE team6987b4a2019-03-15 16:23:04 -07004360 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07004361 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004362 QuicPacketNumber packet_number;
4363 connection_.SendCryptoStreamData();
4364
4365 // Simulate the retransmission alarm firing and the socket blocking.
4366 BlockOnNextWrite();
4367 clock_.AdvanceTime(DefaultRetransmissionTime());
fayang2ce66082019-10-02 06:29:04 -07004368 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
4369 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4370 } else {
4371 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4372 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004373 connection_.GetRetransmissionAlarm()->Fire();
fayang2ce66082019-10-02 06:29:04 -07004374 EXPECT_EQ(1u, connection_.NumQueuedPackets());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004375
4376 // Go forward secure.
4377 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07004378 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004379 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4380 notifier_.NeuterUnencryptedData();
4381 connection_.NeuterUnencryptedPackets();
fayang2ce66082019-10-02 06:29:04 -07004382 connection_.OnHandshakeComplete();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004383
4384 EXPECT_EQ(QuicTime::Zero(), connection_.GetRetransmissionAlarm()->deadline());
4385 // Unblock the socket and ensure that no packets are sent.
4386 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4387 writer_->SetWritable();
4388 connection_.OnCanWrite();
4389}
4390
4391TEST_P(QuicConnectionTest, RetransmitPacketsWithInitialEncryption) {
4392 use_tagging_decrypter();
QUICHE team6987b4a2019-03-15 16:23:04 -07004393 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07004394 std::make_unique<TaggingEncrypter>(0x01));
QUICHE team6987b4a2019-03-15 16:23:04 -07004395 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004396
nharper46833c32019-05-15 21:33:05 -07004397 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004398
4399 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004400 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004401 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4402
4403 SendStreamDataToPeer(2, "bar", 0, NO_FIN, nullptr);
4404 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4405
4406 connection_.RetransmitUnackedPackets(ALL_INITIAL_RETRANSMISSION);
4407}
4408
4409TEST_P(QuicConnectionTest, BufferNonDecryptablePackets) {
QUICHE teamcd098022019-03-22 18:49:55 -07004410 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4411 return;
4412 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004413 // SetFromConfig is always called after construction from InitializeSession.
4414 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4415 QuicConfig config;
4416 connection_.SetFromConfig(config);
4417 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4418 use_tagging_decrypter();
4419
4420 const uint8_t tag = 0x07;
4421 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004422 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004423
4424 // Process an encrypted packet which can not yet be decrypted which should
4425 // result in the packet being buffered.
4426 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4427
4428 // Transition to the new encryption state and process another encrypted packet
4429 // which should result in the original packet being processed.
zhongyi546cc452019-04-12 15:27:49 -07004430 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004431 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004432 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4433 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004434 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004435 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(2);
4436 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4437
4438 // Finally, process a third packet and note that we do not reprocess the
4439 // buffered packet.
4440 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4441 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4442}
4443
4444TEST_P(QuicConnectionTest, TestRetransmitOrder) {
fayang5f135052019-08-22 17:59:40 -07004445 if (connection_.PtoEnabled()) {
4446 return;
4447 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004448 connection_.SetMaxTailLossProbes(0);
4449
4450 QuicByteCount first_packet_size;
4451 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4452 .WillOnce(SaveArg<3>(&first_packet_size));
4453
4454 connection_.SendStreamDataWithString(3, "first_packet", 0, NO_FIN);
4455 QuicByteCount second_packet_size;
4456 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4457 .WillOnce(SaveArg<3>(&second_packet_size));
4458 connection_.SendStreamDataWithString(3, "second_packet", 12, NO_FIN);
4459 EXPECT_NE(first_packet_size, second_packet_size);
4460 // Advance the clock by huge time to make sure packets will be retransmitted.
4461 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
4462 {
4463 InSequence s;
4464 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, first_packet_size, _));
4465 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, second_packet_size, _));
4466 }
4467 connection_.GetRetransmissionAlarm()->Fire();
4468
4469 // Advance again and expect the packets to be sent again in the same order.
4470 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(20));
4471 {
4472 InSequence s;
4473 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, first_packet_size, _));
4474 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, second_packet_size, _));
4475 }
4476 connection_.GetRetransmissionAlarm()->Fire();
4477}
4478
4479TEST_P(QuicConnectionTest, Buffer100NonDecryptablePacketsThenKeyChange) {
QUICHE teamcd098022019-03-22 18:49:55 -07004480 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4481 return;
4482 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004483 // SetFromConfig is always called after construction from InitializeSession.
4484 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4485 QuicConfig config;
4486 config.set_max_undecryptable_packets(100);
4487 connection_.SetFromConfig(config);
4488 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4489 use_tagging_decrypter();
4490
4491 const uint8_t tag = 0x07;
4492 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004493 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004494
4495 // Process an encrypted packet which can not yet be decrypted which should
4496 // result in the packet being buffered.
4497 for (uint64_t i = 1; i <= 100; ++i) {
4498 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4499 }
4500
4501 // Transition to the new encryption state and process another encrypted packet
4502 // which should result in the original packets being processed.
4503 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
zhongyi546cc452019-04-12 15:27:49 -07004504 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004505 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004506 EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
4507 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4508 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004509 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004510
4511 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(100);
4512 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
4513
4514 // Finally, process a third packet and note that we do not reprocess the
4515 // buffered packet.
4516 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4517 ProcessDataPacketAtLevel(102, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4518}
4519
4520TEST_P(QuicConnectionTest, SetRTOAfterWritingToSocket) {
4521 BlockOnNextWrite();
fayang2ce66082019-10-02 06:29:04 -07004522 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
4523 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4524 } else {
4525 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4526 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004527 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
fayang2ce66082019-10-02 06:29:04 -07004528 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
4529 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4530 } else {
4531 // Make sure that RTO is not started when the packet is queued.
4532 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4533 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004534
4535 // Test that RTO is started once we write to the socket.
4536 writer_->SetWritable();
fayang2ce66082019-10-02 06:29:04 -07004537 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
4538 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4539 } else {
4540 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4541 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004542 connection_.OnCanWrite();
4543 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4544}
4545
4546TEST_P(QuicConnectionTest, DelayRTOWithAckReceipt) {
fayang5f135052019-08-22 17:59:40 -07004547 if (connection_.PtoEnabled()) {
4548 return;
4549 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004550 connection_.SetMaxTailLossProbes(0);
4551
4552 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4553 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
4554 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
4555 connection_.SendStreamDataWithString(3, "bar", 0, NO_FIN);
4556 QuicAlarm* retransmission_alarm = connection_.GetRetransmissionAlarm();
4557 EXPECT_TRUE(retransmission_alarm->IsSet());
4558 EXPECT_EQ(clock_.Now() + DefaultRetransmissionTime(),
4559 retransmission_alarm->deadline());
4560
4561 // Advance the time right before the RTO, then receive an ack for the first
4562 // packet to delay the RTO.
4563 clock_.AdvanceTime(DefaultRetransmissionTime());
4564 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4565 QuicAckFrame ack = InitAckFrame(1);
4566 ProcessAckPacket(&ack);
4567 // Now we have an RTT sample of DefaultRetransmissionTime(500ms),
4568 // so the RTO has increased to 2 * SRTT.
4569 EXPECT_TRUE(retransmission_alarm->IsSet());
4570 EXPECT_EQ(retransmission_alarm->deadline(),
4571 clock_.Now() + 2 * DefaultRetransmissionTime());
4572
4573 // Move forward past the original RTO and ensure the RTO is still pending.
4574 clock_.AdvanceTime(2 * DefaultRetransmissionTime());
4575
4576 // Ensure the second packet gets retransmitted when it finally fires.
4577 EXPECT_TRUE(retransmission_alarm->IsSet());
4578 EXPECT_EQ(retransmission_alarm->deadline(), clock_.ApproximateNow());
4579 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4580 // Manually cancel the alarm to simulate a real test.
4581 connection_.GetRetransmissionAlarm()->Fire();
4582
4583 // The new retransmitted packet number should set the RTO to a larger value
4584 // than previously.
4585 EXPECT_TRUE(retransmission_alarm->IsSet());
4586 QuicTime next_rto_time = retransmission_alarm->deadline();
4587 QuicTime expected_rto_time =
4588 connection_.sent_packet_manager().GetRetransmissionTime();
4589 EXPECT_EQ(next_rto_time, expected_rto_time);
4590}
4591
4592TEST_P(QuicConnectionTest, TestQueued) {
4593 connection_.SetMaxTailLossProbes(0);
4594
4595 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4596 BlockOnNextWrite();
4597 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4598 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4599
4600 // Unblock the writes and actually send.
4601 writer_->SetWritable();
4602 connection_.OnCanWrite();
4603 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4604}
4605
4606TEST_P(QuicConnectionTest, InitialTimeout) {
4607 EXPECT_TRUE(connection_.connected());
4608 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4609 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4610
4611 // SetFromConfig sets the initial timeouts before negotiation.
4612 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4613 QuicConfig config;
4614 connection_.SetFromConfig(config);
4615 // Subtract a second from the idle timeout on the client side.
4616 QuicTime default_timeout =
4617 clock_.ApproximateNow() +
4618 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4619 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
4620
fkastenholz5d880a92019-06-21 09:01:56 -07004621 EXPECT_CALL(visitor_,
4622 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004623 // Simulate the timeout alarm firing.
4624 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1));
4625 connection_.GetTimeoutAlarm()->Fire();
4626
4627 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4628 EXPECT_FALSE(connection_.connected());
4629
4630 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
4631 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4632 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4633 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4634 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
renjietang11e4a3d2019-05-03 11:27:26 -07004635 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07004636 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004637}
4638
4639TEST_P(QuicConnectionTest, IdleTimeoutAfterFirstSentPacket) {
4640 EXPECT_TRUE(connection_.connected());
4641 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4642 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4643
4644 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4645 QuicConfig config;
4646 connection_.SetFromConfig(config);
4647 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4648 QuicTime initial_ddl =
4649 clock_.ApproximateNow() +
4650 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4651 EXPECT_EQ(initial_ddl, connection_.GetTimeoutAlarm()->deadline());
4652 EXPECT_TRUE(connection_.connected());
4653
4654 // Advance the time and send the first packet to the peer.
4655 clock_.AdvanceTime(QuicTime::Delta::FromMicroseconds(20));
4656 QuicPacketNumber last_packet;
4657 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4658 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4659 // This will be the updated deadline for the connection to idle time out.
4660 QuicTime new_ddl = clock_.ApproximateNow() +
4661 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4662
4663 // Simulate the timeout alarm firing, the connection should not be closed as
4664 // a new packet has been sent.
fkastenholz5d880a92019-06-21 09:01:56 -07004665 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004666 QuicTime::Delta delay = initial_ddl - clock_.ApproximateNow();
4667 clock_.AdvanceTime(delay);
4668 connection_.GetTimeoutAlarm()->Fire();
4669 // Verify the timeout alarm deadline is updated.
4670 EXPECT_TRUE(connection_.connected());
4671 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4672 EXPECT_EQ(new_ddl, connection_.GetTimeoutAlarm()->deadline());
4673
4674 // Simulate the timeout alarm firing again, the connection now should be
4675 // closed.
fkastenholz5d880a92019-06-21 09:01:56 -07004676 EXPECT_CALL(visitor_,
4677 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004678 clock_.AdvanceTime(new_ddl - clock_.ApproximateNow());
4679 connection_.GetTimeoutAlarm()->Fire();
4680 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4681 EXPECT_FALSE(connection_.connected());
4682
4683 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
4684 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4685 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4686 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4687 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07004688 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004689}
4690
4691TEST_P(QuicConnectionTest, IdleTimeoutAfterSendTwoPackets) {
4692 EXPECT_TRUE(connection_.connected());
4693 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4694 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4695
4696 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4697 QuicConfig config;
4698 connection_.SetFromConfig(config);
4699 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4700 QuicTime initial_ddl =
4701 clock_.ApproximateNow() +
4702 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4703 EXPECT_EQ(initial_ddl, connection_.GetTimeoutAlarm()->deadline());
4704 EXPECT_TRUE(connection_.connected());
4705
4706 // Immediately send the first packet, this is a rare case but test code will
4707 // hit this issue often as MockClock used for tests doesn't move with code
4708 // execution until manually adjusted.
4709 QuicPacketNumber last_packet;
4710 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4711 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4712
4713 // Advance the time and send the second packet to the peer.
4714 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
4715 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4716 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
4717
zhongyic1cab062019-06-19 12:02:24 -07004718 // Simulate the timeout alarm firing, the connection will be closed.
fkastenholz5d880a92019-06-21 09:01:56 -07004719 EXPECT_CALL(visitor_,
4720 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
zhongyic1cab062019-06-19 12:02:24 -07004721 clock_.AdvanceTime(initial_ddl - clock_.ApproximateNow());
4722 connection_.GetTimeoutAlarm()->Fire();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004723
4724 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4725 EXPECT_FALSE(connection_.connected());
4726
4727 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
4728 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4729 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4730 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4731 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07004732 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004733}
4734
4735TEST_P(QuicConnectionTest, HandshakeTimeout) {
4736 // Use a shorter handshake timeout than idle timeout for this test.
4737 const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(5);
4738 connection_.SetNetworkTimeouts(timeout, timeout);
4739 EXPECT_TRUE(connection_.connected());
4740 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4741
4742 QuicTime handshake_timeout =
4743 clock_.ApproximateNow() + timeout - QuicTime::Delta::FromSeconds(1);
4744 EXPECT_EQ(handshake_timeout, connection_.GetTimeoutAlarm()->deadline());
4745 EXPECT_TRUE(connection_.connected());
4746
4747 // Send and ack new data 3 seconds later to lengthen the idle timeout.
4748 SendStreamDataToPeer(
dschinazi552accc2019-06-17 17:07:34 -07004749 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
4750 "GET /", 0, FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004751 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(3));
4752 QuicAckFrame frame = InitAckFrame(1);
4753 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4754 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4755 ProcessAckPacket(&frame);
4756
4757 // Fire early to verify it wouldn't timeout yet.
4758 connection_.GetTimeoutAlarm()->Fire();
4759 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4760 EXPECT_TRUE(connection_.connected());
4761
4762 clock_.AdvanceTime(timeout - QuicTime::Delta::FromSeconds(2));
4763
fkastenholz5d880a92019-06-21 09:01:56 -07004764 EXPECT_CALL(visitor_,
4765 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004766 // Simulate the timeout alarm firing.
4767 connection_.GetTimeoutAlarm()->Fire();
4768
4769 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4770 EXPECT_FALSE(connection_.connected());
4771
4772 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
4773 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4774 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4775 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07004776 TestConnectionCloseQuicErrorCode(QUIC_HANDSHAKE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004777}
4778
4779TEST_P(QuicConnectionTest, PingAfterSend) {
QUICHE teamcd098022019-03-22 18:49:55 -07004780 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4781 return;
4782 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004783 EXPECT_TRUE(connection_.connected());
4784 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4785 .WillRepeatedly(Return(true));
4786 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4787
4788 // Advance to 5ms, and send a packet to the peer, which will set
4789 // the ping alarm.
4790 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4791 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4792 SendStreamDataToPeer(
dschinazi552accc2019-06-17 17:07:34 -07004793 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
4794 "GET /", 0, FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004795 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4796 EXPECT_EQ(clock_.ApproximateNow() + QuicTime::Delta::FromSeconds(15),
4797 connection_.GetPingAlarm()->deadline());
4798
4799 // Now recevie an ACK of the previous packet, which will move the
4800 // ping alarm forward.
4801 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4802 QuicAckFrame frame = InitAckFrame(1);
4803 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4804 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4805 ProcessAckPacket(&frame);
4806 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4807 // The ping timer is set slightly less than 15 seconds in the future, because
4808 // of the 1s ping timer alarm granularity.
4809 EXPECT_EQ(clock_.ApproximateNow() + QuicTime::Delta::FromSeconds(15) -
4810 QuicTime::Delta::FromMilliseconds(5),
4811 connection_.GetPingAlarm()->deadline());
4812
4813 writer_->Reset();
4814 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15));
zhongyifbb25772019-04-10 16:54:08 -07004815 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004816 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07004817 size_t padding_frame_count = writer_->padding_frames().size();
4818 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004819 ASSERT_EQ(1u, writer_->ping_frames().size());
4820 writer_->Reset();
4821
4822 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4823 .WillRepeatedly(Return(false));
4824 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4825 SendAckPacketToPeer();
4826
4827 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4828}
4829
4830TEST_P(QuicConnectionTest, ReducedPingTimeout) {
QUICHE teamcd098022019-03-22 18:49:55 -07004831 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4832 return;
4833 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004834 EXPECT_TRUE(connection_.connected());
4835 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4836 .WillRepeatedly(Return(true));
4837 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4838
4839 // Use a reduced ping timeout for this connection.
4840 connection_.set_ping_timeout(QuicTime::Delta::FromSeconds(10));
4841
4842 // Advance to 5ms, and send a packet to the peer, which will set
4843 // the ping alarm.
4844 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4845 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4846 SendStreamDataToPeer(
dschinazi552accc2019-06-17 17:07:34 -07004847 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
4848 "GET /", 0, FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004849 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4850 EXPECT_EQ(clock_.ApproximateNow() + QuicTime::Delta::FromSeconds(10),
4851 connection_.GetPingAlarm()->deadline());
4852
4853 // Now recevie an ACK of the previous packet, which will move the
4854 // ping alarm forward.
4855 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4856 QuicAckFrame frame = InitAckFrame(1);
4857 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4858 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4859 ProcessAckPacket(&frame);
4860 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4861 // The ping timer is set slightly less than 10 seconds in the future, because
4862 // of the 1s ping timer alarm granularity.
4863 EXPECT_EQ(clock_.ApproximateNow() + QuicTime::Delta::FromSeconds(10) -
4864 QuicTime::Delta::FromMilliseconds(5),
4865 connection_.GetPingAlarm()->deadline());
4866
4867 writer_->Reset();
4868 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
4869 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
4870 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
4871 }));
4872 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07004873 size_t padding_frame_count = writer_->padding_frames().size();
4874 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004875 ASSERT_EQ(1u, writer_->ping_frames().size());
4876 writer_->Reset();
4877
4878 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4879 .WillRepeatedly(Return(false));
4880 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4881 SendAckPacketToPeer();
4882
4883 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4884}
4885
4886// Tests whether sending an MTU discovery packet to peer successfully causes the
4887// maximum packet size to increase.
4888TEST_P(QuicConnectionTest, SendMtuDiscoveryPacket) {
QUICHE teamcd098022019-03-22 18:49:55 -07004889 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4890 return;
4891 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004892 EXPECT_TRUE(connection_.connected());
4893
4894 // Send an MTU probe.
4895 const size_t new_mtu = kDefaultMaxPacketSize + 100;
4896 QuicByteCount mtu_probe_size;
4897 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4898 .WillOnce(SaveArg<3>(&mtu_probe_size));
4899 connection_.SendMtuDiscoveryPacket(new_mtu);
4900 EXPECT_EQ(new_mtu, mtu_probe_size);
4901 EXPECT_EQ(QuicPacketNumber(1u), creator_->packet_number());
4902
nharperc1bbfe62019-09-27 16:48:40 -07004903 // QuicFramer::GetMaxPlaintextSize uses the smallest max plaintext size across
4904 // all encrypters. The initial encrypter used with IETF QUIC has a 16-byte
4905 // overhead, while the NullEncrypter used throughout this test has a 12-byte
4906 // overhead. This test tests behavior that relies on computing the packet size
4907 // correctly, so by unsetting the initial encrypter, we avoid having a
4908 // mismatch between the overheads for the encrypters used. In non-test
4909 // scenarios all encrypters used for a given connection have the same
4910 // overhead, either 12 bytes for ones using Google QUIC crypto, or 16 bytes
4911 // for ones using TLS.
4912 connection_.SetEncrypter(ENCRYPTION_INITIAL, nullptr);
4913
QUICHE teama6ef0a62019-03-07 20:34:33 -05004914 // Send more than MTU worth of data. No acknowledgement was received so far,
4915 // so the MTU should be at its old value.
vasilvvc48c8712019-03-11 13:38:16 -07004916 const std::string data(kDefaultMaxPacketSize + 1, '.');
QUICHE teama6ef0a62019-03-07 20:34:33 -05004917 QuicByteCount size_before_mtu_change;
4918 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4919 .Times(2)
4920 .WillOnce(SaveArg<3>(&size_before_mtu_change))
4921 .WillOnce(Return());
4922 connection_.SendStreamDataWithString(3, data, 0, FIN);
4923 EXPECT_EQ(QuicPacketNumber(3u), creator_->packet_number());
4924 EXPECT_EQ(kDefaultMaxPacketSize, size_before_mtu_change);
4925
4926 // Acknowledge all packets so far.
4927 QuicAckFrame probe_ack = InitAckFrame(3);
4928 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4929 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4930 ProcessAckPacket(&probe_ack);
4931 EXPECT_EQ(new_mtu, connection_.max_packet_length());
4932
4933 // Send the same data again. Check that it fits into a single packet now.
4934 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4935 connection_.SendStreamDataWithString(3, data, 0, FIN);
4936 EXPECT_EQ(QuicPacketNumber(4u), creator_->packet_number());
4937}
4938
4939// Tests whether MTU discovery does not happen when it is not explicitly enabled
4940// by the connection options.
4941TEST_P(QuicConnectionTest, MtuDiscoveryDisabled) {
4942 EXPECT_TRUE(connection_.connected());
4943
4944 const QuicPacketCount packets_between_probes_base = 10;
4945 set_packets_between_probes_base(packets_between_probes_base);
4946
4947 const QuicPacketCount number_of_packets = packets_between_probes_base * 2;
4948 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
4949 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
4950 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4951 EXPECT_EQ(0u, connection_.mtu_probe_count());
4952 }
4953}
4954
4955// Tests whether MTU discovery works when the probe gets acknowledged on the
4956// first try.
4957TEST_P(QuicConnectionTest, MtuDiscoveryEnabled) {
4958 EXPECT_TRUE(connection_.connected());
4959
nharperc6b99512019-09-19 11:13:48 -07004960 // QuicFramer::GetMaxPlaintextSize uses the smallest max plaintext size across
4961 // all encrypters. The initial encrypter used with IETF QUIC has a 16-byte
4962 // overhead, while the NullEncrypter used throughout this test has a 12-byte
4963 // overhead. This test tests behavior that relies on computing the packet size
4964 // correctly, so by unsetting the initial encrypter, we avoid having a
4965 // mismatch between the overheads for the encrypters used. In non-test
4966 // scenarios all encrypters used for a given connection have the same
4967 // overhead, either 12 bytes for ones using Google QUIC crypto, or 16 bytes
4968 // for ones using TLS.
nharperc1bbfe62019-09-27 16:48:40 -07004969 connection_.SetEncrypter(ENCRYPTION_INITIAL, nullptr);
nharperc6b99512019-09-19 11:13:48 -07004970
QUICHE teama6ef0a62019-03-07 20:34:33 -05004971 connection_.EnablePathMtuDiscovery(send_algorithm_);
4972
4973 const QuicPacketCount packets_between_probes_base = 5;
4974 set_packets_between_probes_base(packets_between_probes_base);
4975
4976 // Send enough packets so that the next one triggers path MTU discovery.
4977 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
4978 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
4979 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4980 }
4981
4982 // Trigger the probe.
4983 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
4984 nullptr);
4985 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4986 QuicByteCount probe_size;
4987 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4988 .WillOnce(SaveArg<3>(&probe_size));
4989 connection_.GetMtuDiscoveryAlarm()->Fire();
4990 EXPECT_EQ(kMtuDiscoveryTargetPacketSizeHigh, probe_size);
4991
4992 const QuicPacketNumber probe_packet_number =
4993 FirstSendingPacketNumber() + packets_between_probes_base;
4994 ASSERT_EQ(probe_packet_number, creator_->packet_number());
4995
4996 // Acknowledge all packets sent so far.
4997 QuicAckFrame probe_ack = InitAckFrame(probe_packet_number);
4998 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4999 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5000 ProcessAckPacket(&probe_ack);
5001 EXPECT_EQ(kMtuDiscoveryTargetPacketSizeHigh, connection_.max_packet_length());
5002 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5003
5004 // Send more packets, and ensure that none of them sets the alarm.
5005 for (QuicPacketCount i = 0; i < 4 * packets_between_probes_base; i++) {
5006 SendStreamDataToPeer(3, ".", packets_between_probes_base + i, NO_FIN,
5007 nullptr);
5008 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5009 }
5010
5011 EXPECT_EQ(1u, connection_.mtu_probe_count());
5012}
5013
5014// Tests whether MTU discovery works correctly when the probes never get
5015// acknowledged.
5016TEST_P(QuicConnectionTest, MtuDiscoveryFailed) {
5017 EXPECT_TRUE(connection_.connected());
5018
5019 connection_.EnablePathMtuDiscovery(send_algorithm_);
5020
5021 const QuicTime::Delta rtt = QuicTime::Delta::FromMilliseconds(100);
5022
5023 EXPECT_EQ(kPacketsBetweenMtuProbesBase,
5024 QuicConnectionPeer::GetPacketsBetweenMtuProbes(&connection_));
5025 // Lower the number of probes between packets in order to make the test go
5026 // much faster.
5027 const QuicPacketCount packets_between_probes_base = 5;
5028 set_packets_between_probes_base(packets_between_probes_base);
5029
5030 // This tests sends more packets than strictly necessary to make sure that if
5031 // the connection was to send more discovery packets than needed, those would
5032 // get caught as well.
5033 const QuicPacketCount number_of_packets =
5034 packets_between_probes_base * (1 << (kMtuDiscoveryAttempts + 1));
5035 std::vector<QuicPacketNumber> mtu_discovery_packets;
5036 // Called by the first ack.
5037 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5038 // Called on many acks.
5039 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5040 .Times(AnyNumber());
5041 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
5042 SendStreamDataToPeer(3, "!", i, NO_FIN, nullptr);
5043 clock_.AdvanceTime(rtt);
5044
5045 // Receive an ACK, which marks all data packets as received, and all MTU
5046 // discovery packets as missing.
5047
5048 QuicAckFrame ack;
5049
5050 if (!mtu_discovery_packets.empty()) {
5051 QuicPacketNumber min_packet = *min_element(mtu_discovery_packets.begin(),
5052 mtu_discovery_packets.end());
5053 QuicPacketNumber max_packet = *max_element(mtu_discovery_packets.begin(),
5054 mtu_discovery_packets.end());
5055 ack.packets.AddRange(QuicPacketNumber(1), min_packet);
5056 ack.packets.AddRange(QuicPacketNumber(max_packet + 1),
5057 creator_->packet_number() + 1);
5058 ack.largest_acked = creator_->packet_number();
5059
5060 } else {
5061 ack.packets.AddRange(QuicPacketNumber(1), creator_->packet_number() + 1);
5062 ack.largest_acked = creator_->packet_number();
5063 }
5064
5065 ProcessAckPacket(&ack);
5066
5067 // Trigger MTU probe if it would be scheduled now.
5068 if (!connection_.GetMtuDiscoveryAlarm()->IsSet()) {
5069 continue;
5070 }
5071
5072 // Fire the alarm. The alarm should cause a packet to be sent.
5073 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5074 connection_.GetMtuDiscoveryAlarm()->Fire();
5075 // Record the packet number of the MTU discovery packet in order to
5076 // mark it as NACK'd.
5077 mtu_discovery_packets.push_back(creator_->packet_number());
5078 }
5079
5080 // Ensure the number of packets between probes grows exponentially by checking
5081 // it against the closed-form expression for the packet number.
5082 ASSERT_EQ(kMtuDiscoveryAttempts, mtu_discovery_packets.size());
5083 for (uint64_t i = 0; i < kMtuDiscoveryAttempts; i++) {
5084 // 2^0 + 2^1 + 2^2 + ... + 2^n = 2^(n + 1) - 1
5085 const QuicPacketCount packets_between_probes =
5086 packets_between_probes_base * ((1 << (i + 1)) - 1);
5087 EXPECT_EQ(QuicPacketNumber(packets_between_probes + (i + 1)),
5088 mtu_discovery_packets[i]);
5089 }
5090
5091 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5092 EXPECT_EQ(kDefaultMaxPacketSize, connection_.max_packet_length());
5093 EXPECT_EQ(kMtuDiscoveryAttempts, connection_.mtu_probe_count());
5094}
5095
5096// Tests whether MTU discovery works when the writer has a limit on how large a
5097// packet can be.
5098TEST_P(QuicConnectionTest, MtuDiscoveryWriterLimited) {
5099 EXPECT_TRUE(connection_.connected());
5100
nharperc6b99512019-09-19 11:13:48 -07005101 // QuicFramer::GetMaxPlaintextSize uses the smallest max plaintext size across
5102 // all encrypters. The initial encrypter used with IETF QUIC has a 16-byte
5103 // overhead, while the NullEncrypter used throughout this test has a 12-byte
5104 // overhead. This test tests behavior that relies on computing the packet size
5105 // correctly, so by unsetting the initial encrypter, we avoid having a
5106 // mismatch between the overheads for the encrypters used. In non-test
5107 // scenarios all encrypters used for a given connection have the same
5108 // overhead, either 12 bytes for ones using Google QUIC crypto, or 16 bytes
5109 // for ones using TLS.
nharperc1bbfe62019-09-27 16:48:40 -07005110 connection_.SetEncrypter(ENCRYPTION_INITIAL, nullptr);
nharperc6b99512019-09-19 11:13:48 -07005111
QUICHE teama6ef0a62019-03-07 20:34:33 -05005112 const QuicByteCount mtu_limit = kMtuDiscoveryTargetPacketSizeHigh - 1;
5113 writer_->set_max_packet_size(mtu_limit);
5114 connection_.EnablePathMtuDiscovery(send_algorithm_);
5115
5116 const QuicPacketCount packets_between_probes_base = 5;
5117 set_packets_between_probes_base(packets_between_probes_base);
5118
5119 // Send enough packets so that the next one triggers path MTU discovery.
5120 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5121 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5122 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5123 }
5124
5125 // Trigger the probe.
5126 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5127 nullptr);
5128 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5129 QuicByteCount probe_size;
5130 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5131 .WillOnce(SaveArg<3>(&probe_size));
5132 connection_.GetMtuDiscoveryAlarm()->Fire();
5133 EXPECT_EQ(mtu_limit, probe_size);
5134
5135 const QuicPacketNumber probe_sequence_number =
5136 FirstSendingPacketNumber() + packets_between_probes_base;
5137 ASSERT_EQ(probe_sequence_number, creator_->packet_number());
5138
5139 // Acknowledge all packets sent so far.
5140 QuicAckFrame probe_ack = InitAckFrame(probe_sequence_number);
5141 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5142 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5143 ProcessAckPacket(&probe_ack);
5144 EXPECT_EQ(mtu_limit, connection_.max_packet_length());
5145 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5146
5147 // Send more packets, and ensure that none of them sets the alarm.
5148 for (QuicPacketCount i = 0; i < 4 * packets_between_probes_base; i++) {
5149 SendStreamDataToPeer(3, ".", packets_between_probes_base + i, NO_FIN,
5150 nullptr);
5151 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5152 }
5153
5154 EXPECT_EQ(1u, connection_.mtu_probe_count());
5155}
5156
5157// Tests whether MTU discovery works when the writer returns an error despite
5158// advertising higher packet length.
5159TEST_P(QuicConnectionTest, MtuDiscoveryWriterFailed) {
5160 EXPECT_TRUE(connection_.connected());
5161
5162 const QuicByteCount mtu_limit = kMtuDiscoveryTargetPacketSizeHigh - 1;
5163 const QuicByteCount initial_mtu = connection_.max_packet_length();
5164 EXPECT_LT(initial_mtu, mtu_limit);
5165 writer_->set_max_packet_size(mtu_limit);
5166 connection_.EnablePathMtuDiscovery(send_algorithm_);
5167
5168 const QuicPacketCount packets_between_probes_base = 5;
5169 set_packets_between_probes_base(packets_between_probes_base);
5170
5171 // Send enough packets so that the next one triggers path MTU discovery.
5172 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5173 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5174 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5175 }
5176
5177 // Trigger the probe.
5178 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5179 nullptr);
5180 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5181 writer_->SimulateNextPacketTooLarge();
5182 connection_.GetMtuDiscoveryAlarm()->Fire();
5183 ASSERT_TRUE(connection_.connected());
5184
5185 // Send more data.
5186 QuicPacketNumber probe_number = creator_->packet_number();
5187 QuicPacketCount extra_packets = packets_between_probes_base * 3;
5188 for (QuicPacketCount i = 0; i < extra_packets; i++) {
5189 connection_.EnsureWritableAndSendStreamData5();
5190 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5191 }
5192
5193 // Acknowledge all packets sent so far, except for the lost probe.
5194 QuicAckFrame probe_ack =
5195 ConstructAckFrame(creator_->packet_number(), probe_number);
5196 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5197 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5198 ProcessAckPacket(&probe_ack);
5199 EXPECT_EQ(initial_mtu, connection_.max_packet_length());
5200
5201 // Send more packets, and ensure that none of them sets the alarm.
5202 for (QuicPacketCount i = 0; i < 4 * packets_between_probes_base; i++) {
5203 connection_.EnsureWritableAndSendStreamData5();
5204 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5205 }
5206
5207 EXPECT_EQ(initial_mtu, connection_.max_packet_length());
5208 EXPECT_EQ(1u, connection_.mtu_probe_count());
5209}
5210
5211TEST_P(QuicConnectionTest, NoMtuDiscoveryAfterConnectionClosed) {
5212 EXPECT_TRUE(connection_.connected());
5213
5214 connection_.EnablePathMtuDiscovery(send_algorithm_);
5215
5216 const QuicPacketCount packets_between_probes_base = 10;
5217 set_packets_between_probes_base(packets_between_probes_base);
5218
5219 // Send enough packets so that the next one triggers path MTU discovery.
5220 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5221 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5222 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5223 }
5224
5225 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5226 nullptr);
5227 EXPECT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5228
fkastenholz5d880a92019-06-21 09:01:56 -07005229 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005230 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
5231 ConnectionCloseBehavior::SILENT_CLOSE);
5232 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5233}
5234
5235TEST_P(QuicConnectionTest, TimeoutAfterSend) {
5236 EXPECT_TRUE(connection_.connected());
5237 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5238 QuicConfig config;
5239 connection_.SetFromConfig(config);
5240 EXPECT_FALSE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
5241
5242 const QuicTime::Delta initial_idle_timeout =
5243 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5244 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5245 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
5246
5247 // When we send a packet, the timeout will change to 5ms +
5248 // kInitialIdleTimeoutSecs.
5249 clock_.AdvanceTime(five_ms);
5250 SendStreamDataToPeer(
5251 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5252 0, FIN, nullptr);
5253 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5254
5255 // Now send more data. This will not move the timeout because
5256 // no data has been received since the previous write.
5257 clock_.AdvanceTime(five_ms);
5258 SendStreamDataToPeer(
5259 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5260 3, FIN, nullptr);
5261 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5262
5263 // The original alarm will fire. We should not time out because we had a
5264 // network event at t=5ms. The alarm will reregister.
5265 clock_.AdvanceTime(initial_idle_timeout - five_ms - five_ms);
5266 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
5267 connection_.GetTimeoutAlarm()->Fire();
5268 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5269 EXPECT_TRUE(connection_.connected());
5270 EXPECT_EQ(default_timeout + five_ms,
5271 connection_.GetTimeoutAlarm()->deadline());
5272
5273 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07005274 EXPECT_CALL(visitor_,
5275 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005276 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5277 clock_.AdvanceTime(five_ms);
5278 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5279 connection_.GetTimeoutAlarm()->Fire();
5280 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5281 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005282 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005283}
5284
5285TEST_P(QuicConnectionTest, TimeoutAfterRetransmission) {
fayang5f135052019-08-22 17:59:40 -07005286 if (connection_.PtoEnabled()) {
5287 return;
5288 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005289 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5290 EXPECT_TRUE(connection_.connected());
5291 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5292 QuicConfig config;
5293 connection_.SetFromConfig(config);
5294 EXPECT_FALSE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
5295
5296 const QuicTime start_time = clock_.Now();
5297 const QuicTime::Delta initial_idle_timeout =
5298 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5299 QuicTime default_timeout = clock_.Now() + initial_idle_timeout;
5300
5301 connection_.SetMaxTailLossProbes(0);
5302 const QuicTime default_retransmission_time =
5303 start_time + DefaultRetransmissionTime();
5304
5305 ASSERT_LT(default_retransmission_time, default_timeout);
5306
5307 // When we send a packet, the timeout will change to 5 ms +
5308 // kInitialIdleTimeoutSecs (but it will not reschedule the alarm).
5309 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5310 const QuicTime send_time = start_time + five_ms;
5311 clock_.AdvanceTime(five_ms);
5312 ASSERT_EQ(send_time, clock_.Now());
5313 SendStreamDataToPeer(
5314 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5315 0, FIN, nullptr);
5316 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5317
5318 // Move forward 5 ms and receive a packet, which will move the timeout
5319 // forward 5 ms more (but will not reschedule the alarm).
5320 const QuicTime receive_time = send_time + five_ms;
5321 clock_.AdvanceTime(receive_time - clock_.Now());
5322 ASSERT_EQ(receive_time, clock_.Now());
5323 ProcessPacket(1);
5324
5325 // Now move forward to the retransmission time and retransmit the
5326 // packet, which should move the timeout forward again (but will not
5327 // reschedule the alarm).
5328 EXPECT_EQ(default_retransmission_time + five_ms,
5329 connection_.GetRetransmissionAlarm()->deadline());
5330 // Simulate the retransmission alarm firing.
5331 const QuicTime rto_time = send_time + DefaultRetransmissionTime();
5332 const QuicTime final_timeout = rto_time + initial_idle_timeout;
5333 clock_.AdvanceTime(rto_time - clock_.Now());
5334 ASSERT_EQ(rto_time, clock_.Now());
5335 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _));
5336 connection_.GetRetransmissionAlarm()->Fire();
5337
5338 // Advance to the original timeout and fire the alarm. The connection should
5339 // timeout, and the alarm should be registered based on the time of the
5340 // retransmission.
5341 clock_.AdvanceTime(default_timeout - clock_.Now());
5342 ASSERT_EQ(default_timeout.ToDebuggingValue(),
5343 clock_.Now().ToDebuggingValue());
5344 EXPECT_EQ(default_timeout, clock_.Now());
5345 connection_.GetTimeoutAlarm()->Fire();
5346 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5347 EXPECT_TRUE(connection_.connected());
5348 ASSERT_EQ(final_timeout.ToDebuggingValue(),
5349 connection_.GetTimeoutAlarm()->deadline().ToDebuggingValue());
5350
5351 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07005352 EXPECT_CALL(visitor_,
5353 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005354 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5355 clock_.AdvanceTime(final_timeout - clock_.Now());
5356 EXPECT_EQ(connection_.GetTimeoutAlarm()->deadline(), clock_.Now());
5357 EXPECT_EQ(final_timeout, clock_.Now());
5358 connection_.GetTimeoutAlarm()->Fire();
5359 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5360 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005361 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005362}
5363
5364TEST_P(QuicConnectionTest, NewTimeoutAfterSendSilentClose) {
5365 // Same test as above, but complete a handshake which enables silent close,
5366 // causing no connection close packet to be sent.
5367 EXPECT_TRUE(connection_.connected());
5368 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5369 QuicConfig config;
5370
5371 // Create a handshake message that also enables silent close.
5372 CryptoHandshakeMessage msg;
vasilvvc48c8712019-03-11 13:38:16 -07005373 std::string error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005374 QuicConfig client_config;
5375 client_config.SetInitialStreamFlowControlWindowToSend(
5376 kInitialStreamFlowControlWindowForTest);
5377 client_config.SetInitialSessionFlowControlWindowToSend(
5378 kInitialSessionFlowControlWindowForTest);
5379 client_config.SetIdleNetworkTimeout(
5380 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs),
5381 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs));
fkastenholzd3a1de92019-05-15 07:00:07 -07005382 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005383 const QuicErrorCode error =
5384 config.ProcessPeerHello(msg, CLIENT, &error_details);
5385 EXPECT_EQ(QUIC_NO_ERROR, error);
5386
5387 connection_.SetFromConfig(config);
5388 EXPECT_TRUE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
5389
5390 const QuicTime::Delta default_idle_timeout =
5391 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs - 1);
5392 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5393 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5394
5395 // When we send a packet, the timeout will change to 5ms +
5396 // kInitialIdleTimeoutSecs.
5397 clock_.AdvanceTime(five_ms);
5398 SendStreamDataToPeer(
5399 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5400 0, FIN, nullptr);
5401 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5402
5403 // Now send more data. This will not move the timeout because
5404 // no data has been received since the previous write.
5405 clock_.AdvanceTime(five_ms);
5406 SendStreamDataToPeer(
5407 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5408 3, FIN, nullptr);
5409 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5410
5411 // The original alarm will fire. We should not time out because we had a
5412 // network event at t=5ms. The alarm will reregister.
5413 clock_.AdvanceTime(default_idle_timeout - five_ms - five_ms);
5414 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
5415 connection_.GetTimeoutAlarm()->Fire();
5416 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5417 EXPECT_TRUE(connection_.connected());
5418 EXPECT_EQ(default_timeout + five_ms,
5419 connection_.GetTimeoutAlarm()->deadline());
5420
5421 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07005422 // This results in a SILENT_CLOSE, so the writer will not be invoked
5423 // and will not save the frame. Grab the frame from OnConnectionClosed
5424 // directly.
5425 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
5426 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
5427
QUICHE teama6ef0a62019-03-07 20:34:33 -05005428 clock_.AdvanceTime(five_ms);
5429 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5430 connection_.GetTimeoutAlarm()->Fire();
5431 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5432 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005433 EXPECT_EQ(1, connection_close_frame_count_);
5434 EXPECT_EQ(QUIC_NETWORK_IDLE_TIMEOUT,
5435 saved_connection_close_frame_.quic_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005436}
5437
5438TEST_P(QuicConnectionTest, TimeoutAfterSendSilentCloseAndTLP) {
fayang5f135052019-08-22 17:59:40 -07005439 if (connection_.PtoEnabled()) {
5440 return;
5441 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005442 // Same test as above, but complete a handshake which enables silent close,
5443 // but sending TLPs causes the connection close to be sent.
5444 EXPECT_TRUE(connection_.connected());
5445 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5446 QuicConfig config;
5447
5448 // Create a handshake message that also enables silent close.
5449 CryptoHandshakeMessage msg;
vasilvvc48c8712019-03-11 13:38:16 -07005450 std::string error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005451 QuicConfig client_config;
5452 client_config.SetInitialStreamFlowControlWindowToSend(
5453 kInitialStreamFlowControlWindowForTest);
5454 client_config.SetInitialSessionFlowControlWindowToSend(
5455 kInitialSessionFlowControlWindowForTest);
5456 client_config.SetIdleNetworkTimeout(
5457 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs),
5458 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs));
fkastenholzd3a1de92019-05-15 07:00:07 -07005459 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005460 const QuicErrorCode error =
5461 config.ProcessPeerHello(msg, CLIENT, &error_details);
5462 EXPECT_EQ(QUIC_NO_ERROR, error);
5463
5464 connection_.SetFromConfig(config);
5465 EXPECT_TRUE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
5466
5467 const QuicTime::Delta default_idle_timeout =
5468 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs - 1);
5469 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5470 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5471
5472 // When we send a packet, the timeout will change to 5ms +
5473 // kInitialIdleTimeoutSecs.
5474 clock_.AdvanceTime(five_ms);
5475 SendStreamDataToPeer(
5476 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5477 0, FIN, nullptr);
5478 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5479
5480 // Retransmit the packet via tail loss probe.
5481 clock_.AdvanceTime(connection_.GetRetransmissionAlarm()->deadline() -
5482 clock_.Now());
5483 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _));
5484 connection_.GetRetransmissionAlarm()->Fire();
5485
5486 // This time, we should time out and send a connection close due to the TLP.
fkastenholz5d880a92019-06-21 09:01:56 -07005487 EXPECT_CALL(visitor_,
5488 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005489 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5490 clock_.AdvanceTime(connection_.GetTimeoutAlarm()->deadline() -
5491 clock_.ApproximateNow() + five_ms);
5492 connection_.GetTimeoutAlarm()->Fire();
5493 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5494 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005495 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005496}
5497
5498TEST_P(QuicConnectionTest, TimeoutAfterSendSilentCloseWithOpenStreams) {
5499 // Same test as above, but complete a handshake which enables silent close,
5500 // but having open streams causes the connection close to be sent.
5501 EXPECT_TRUE(connection_.connected());
5502 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5503 QuicConfig config;
5504
5505 // Create a handshake message that also enables silent close.
5506 CryptoHandshakeMessage msg;
vasilvvc48c8712019-03-11 13:38:16 -07005507 std::string error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005508 QuicConfig client_config;
5509 client_config.SetInitialStreamFlowControlWindowToSend(
5510 kInitialStreamFlowControlWindowForTest);
5511 client_config.SetInitialSessionFlowControlWindowToSend(
5512 kInitialSessionFlowControlWindowForTest);
5513 client_config.SetIdleNetworkTimeout(
5514 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs),
5515 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs));
fkastenholzd3a1de92019-05-15 07:00:07 -07005516 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005517 const QuicErrorCode error =
5518 config.ProcessPeerHello(msg, CLIENT, &error_details);
5519 EXPECT_EQ(QUIC_NO_ERROR, error);
5520
5521 connection_.SetFromConfig(config);
5522 EXPECT_TRUE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
5523
5524 const QuicTime::Delta default_idle_timeout =
5525 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs - 1);
5526 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5527 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5528
5529 // When we send a packet, the timeout will change to 5ms +
5530 // kInitialIdleTimeoutSecs.
5531 clock_.AdvanceTime(five_ms);
5532 SendStreamDataToPeer(
5533 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5534 0, FIN, nullptr);
5535 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5536
5537 // Indicate streams are still open.
5538 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
5539 .WillRepeatedly(Return(true));
5540
5541 // This time, we should time out and send a connection close due to the TLP.
fkastenholz5d880a92019-06-21 09:01:56 -07005542 EXPECT_CALL(visitor_,
5543 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005544 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5545 clock_.AdvanceTime(connection_.GetTimeoutAlarm()->deadline() -
5546 clock_.ApproximateNow() + five_ms);
5547 connection_.GetTimeoutAlarm()->Fire();
5548 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5549 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005550 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005551}
5552
5553TEST_P(QuicConnectionTest, TimeoutAfterReceive) {
5554 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5555 EXPECT_TRUE(connection_.connected());
5556 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5557 QuicConfig config;
5558 connection_.SetFromConfig(config);
5559 EXPECT_FALSE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
5560
5561 const QuicTime::Delta initial_idle_timeout =
5562 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5563 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5564 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
5565
5566 connection_.SendStreamDataWithString(
5567 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5568 0, NO_FIN);
5569 connection_.SendStreamDataWithString(
5570 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5571 3, NO_FIN);
5572
5573 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5574 clock_.AdvanceTime(five_ms);
5575
5576 // When we receive a packet, the timeout will change to 5ms +
5577 // kInitialIdleTimeoutSecs.
5578 QuicAckFrame ack = InitAckFrame(2);
5579 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5580 ProcessAckPacket(&ack);
5581
5582 // The original alarm will fire. We should not time out because we had a
5583 // network event at t=5ms. The alarm will reregister.
5584 clock_.AdvanceTime(initial_idle_timeout - five_ms);
5585 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
5586 connection_.GetTimeoutAlarm()->Fire();
5587 EXPECT_TRUE(connection_.connected());
5588 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5589 EXPECT_EQ(default_timeout + five_ms,
5590 connection_.GetTimeoutAlarm()->deadline());
5591
5592 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07005593 EXPECT_CALL(visitor_,
5594 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005595 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5596 clock_.AdvanceTime(five_ms);
5597 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5598 connection_.GetTimeoutAlarm()->Fire();
5599 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5600 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005601 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005602}
5603
5604TEST_P(QuicConnectionTest, TimeoutAfterReceiveNotSendWhenUnacked) {
5605 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5606 EXPECT_TRUE(connection_.connected());
5607 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5608 QuicConfig config;
5609 connection_.SetFromConfig(config);
5610 EXPECT_FALSE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
5611
5612 const QuicTime::Delta initial_idle_timeout =
5613 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5614 connection_.SetNetworkTimeouts(
5615 QuicTime::Delta::Infinite(),
5616 initial_idle_timeout + QuicTime::Delta::FromSeconds(1));
5617 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5618 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
5619
5620 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5621 connection_.SendStreamDataWithString(
5622 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5623 0, NO_FIN);
5624 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5625 connection_.SendStreamDataWithString(
5626 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5627 3, NO_FIN);
5628
5629 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5630
5631 clock_.AdvanceTime(five_ms);
5632
5633 // When we receive a packet, the timeout will change to 5ms +
5634 // kInitialIdleTimeoutSecs.
5635 QuicAckFrame ack = InitAckFrame(2);
5636 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5637 ProcessAckPacket(&ack);
5638
5639 // The original alarm will fire. We should not time out because we had a
5640 // network event at t=5ms. The alarm will reregister.
5641 clock_.AdvanceTime(initial_idle_timeout - five_ms);
5642 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
5643 connection_.GetTimeoutAlarm()->Fire();
5644 EXPECT_TRUE(connection_.connected());
5645 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5646 EXPECT_EQ(default_timeout + five_ms,
5647 connection_.GetTimeoutAlarm()->deadline());
5648
5649 // Now, send packets while advancing the time and verify that the connection
5650 // eventually times out.
fkastenholz5d880a92019-06-21 09:01:56 -07005651 EXPECT_CALL(visitor_,
5652 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005653 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
5654 for (int i = 0; i < 100 && connection_.connected(); ++i) {
5655 QUIC_LOG(INFO) << "sending data packet";
5656 connection_.SendStreamDataWithString(
5657 GetNthClientInitiatedStreamId(1, connection_.transport_version()),
5658 "foo", 0, NO_FIN);
5659 connection_.GetTimeoutAlarm()->Fire();
5660 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
5661 }
5662 EXPECT_FALSE(connection_.connected());
5663 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07005664 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005665}
5666
5667TEST_P(QuicConnectionTest, TimeoutAfter5ClientRTOs) {
fayang5f135052019-08-22 17:59:40 -07005668 if (connection_.PtoEnabled()) {
5669 return;
5670 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005671 connection_.SetMaxTailLossProbes(2);
5672 EXPECT_TRUE(connection_.connected());
5673 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5674 QuicConfig config;
5675 QuicTagVector connection_options;
5676 connection_options.push_back(k5RTO);
5677 config.SetConnectionOptionsToSend(connection_options);
5678 connection_.SetFromConfig(config);
5679
5680 // Send stream data.
5681 SendStreamDataToPeer(
5682 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5683 0, FIN, nullptr);
5684
5685 // Fire the retransmission alarm 6 times, twice for TLP and 4 times for RTO.
5686 for (int i = 0; i < 6; ++i) {
5687 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5688 connection_.GetRetransmissionAlarm()->Fire();
5689 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5690 EXPECT_TRUE(connection_.connected());
5691 }
5692
5693 EXPECT_EQ(2u, connection_.sent_packet_manager().GetConsecutiveTlpCount());
5694 EXPECT_EQ(4u, connection_.sent_packet_manager().GetConsecutiveRtoCount());
5695 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07005696 EXPECT_CALL(visitor_,
5697 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005698 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5699 connection_.GetRetransmissionAlarm()->Fire();
5700 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5701 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005702 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005703}
5704
5705TEST_P(QuicConnectionTest, SendScheduler) {
5706 // Test that if we send a packet without delay, it is not queued.
5707 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
QUICHE team8c1daa22019-03-13 08:33:41 -07005708 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07005709 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005710 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
5711 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
QUICHE team6987b4a2019-03-15 16:23:04 -07005712 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05005713 HAS_RETRANSMITTABLE_DATA, false, false);
5714 EXPECT_EQ(0u, connection_.NumQueuedPackets());
5715}
5716
5717TEST_P(QuicConnectionTest, FailToSendFirstPacket) {
5718 // Test that the connection does not crash when it fails to send the first
5719 // packet at which point self_address_ might be uninitialized.
5720 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
fkastenholz5d880a92019-06-21 09:01:56 -07005721 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
QUICHE team8c1daa22019-03-13 08:33:41 -07005722 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07005723 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005724 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
5725 writer_->SetShouldWriteFail();
QUICHE team6987b4a2019-03-15 16:23:04 -07005726 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05005727 HAS_RETRANSMITTABLE_DATA, false, false);
5728}
5729
5730TEST_P(QuicConnectionTest, SendSchedulerEAGAIN) {
5731 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
QUICHE team8c1daa22019-03-13 08:33:41 -07005732 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07005733 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005734 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
5735 BlockOnNextWrite();
5736 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _))
5737 .Times(0);
QUICHE team6987b4a2019-03-15 16:23:04 -07005738 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05005739 HAS_RETRANSMITTABLE_DATA, false, false);
5740 EXPECT_EQ(1u, connection_.NumQueuedPackets());
5741}
5742
5743TEST_P(QuicConnectionTest, TestQueueLimitsOnSendStreamData) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005744 // Queue the first packet.
ianswett3085da82019-04-04 07:24:24 -07005745 size_t payload_length = connection_.max_packet_length();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005746 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(testing::Return(false));
vasilvvc48c8712019-03-11 13:38:16 -07005747 const std::string payload(payload_length, 'a');
ianswett3085da82019-04-04 07:24:24 -07005748 QuicStreamId first_bidi_stream_id(QuicUtils::GetFirstBidirectionalStreamId(
5749 connection_.version().transport_version, Perspective::IS_CLIENT));
5750 EXPECT_EQ(0u, connection_
5751 .SendStreamDataWithString(first_bidi_stream_id, payload, 0,
5752 NO_FIN)
QUICHE teama6ef0a62019-03-07 20:34:33 -05005753 .bytes_consumed);
5754 EXPECT_EQ(0u, connection_.NumQueuedPackets());
5755}
5756
ianswett3085da82019-04-04 07:24:24 -07005757TEST_P(QuicConnectionTest, SendingThreePackets) {
ianswett3085da82019-04-04 07:24:24 -07005758 // Make the payload twice the size of the packet, so 3 packets are written.
5759 size_t total_payload_length = 2 * connection_.max_packet_length();
vasilvvc48c8712019-03-11 13:38:16 -07005760 const std::string payload(total_payload_length, 'a');
ianswett3085da82019-04-04 07:24:24 -07005761 QuicStreamId first_bidi_stream_id(QuicUtils::GetFirstBidirectionalStreamId(
5762 connection_.version().transport_version, Perspective::IS_CLIENT));
5763 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
5764 EXPECT_EQ(payload.size(), connection_
5765 .SendStreamDataWithString(first_bidi_stream_id,
5766 payload, 0, NO_FIN)
5767 .bytes_consumed);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005768}
5769
5770TEST_P(QuicConnectionTest, LoopThroughSendingPacketsWithTruncation) {
5771 set_perspective(Perspective::IS_SERVER);
fayangd4291e42019-05-30 10:31:21 -07005772 if (!VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005773 // For IETF QUIC, encryption level will be switched to FORWARD_SECURE in
5774 // SendStreamDataWithString.
5775 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
5776 }
5777 // Set up a larger payload than will fit in one packet.
vasilvvc48c8712019-03-11 13:38:16 -07005778 const std::string payload(connection_.max_packet_length(), 'a');
QUICHE teama6ef0a62019-03-07 20:34:33 -05005779 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
5780
5781 // Now send some packets with no truncation.
5782 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
5783 EXPECT_EQ(payload.size(),
5784 connection_.SendStreamDataWithString(3, payload, 0, NO_FIN)
5785 .bytes_consumed);
5786 // Track the size of the second packet here. The overhead will be the largest
5787 // we see in this test, due to the non-truncated connection id.
5788 size_t non_truncated_packet_size = writer_->last_packet_size();
5789
5790 // Change to a 0 byte connection id.
5791 QuicConfig config;
5792 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
5793 connection_.SetFromConfig(config);
5794 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
5795 EXPECT_EQ(payload.size(),
5796 connection_.SendStreamDataWithString(3, payload, 1350, NO_FIN)
5797 .bytes_consumed);
fayangd4291e42019-05-30 10:31:21 -07005798 if (VersionHasIetfInvariantHeader(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005799 // Short header packets sent from server omit connection ID already, and
5800 // stream offset size increases from 0 to 2.
5801 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() - 2);
5802 } else {
5803 // Just like above, we save 8 bytes on payload, and 8 on truncation. -2
5804 // because stream offset size is 2 instead of 0.
5805 EXPECT_EQ(non_truncated_packet_size,
5806 writer_->last_packet_size() + 8 * 2 - 2);
5807 }
5808}
5809
5810TEST_P(QuicConnectionTest, SendDelayedAck) {
5811 QuicTime ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
5812 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5813 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5814 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07005815 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07005816 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005817 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07005818 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005819 // Process a packet from the non-crypto stream.
5820 frame1_.stream_id = 3;
5821
5822 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07005823 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005824 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5825 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5826
5827 // Check if delayed ack timer is running for the expected interval.
5828 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5829 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5830 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07005831 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005832 connection_.GetAckAlarm()->Fire();
5833 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07005834 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005835 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07005836 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005837 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
5838 } else {
nharper55fa6132019-05-07 19:37:21 -07005839 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005840 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
5841 }
5842 EXPECT_FALSE(writer_->ack_frames().empty());
5843 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5844}
5845
5846TEST_P(QuicConnectionTest, SendDelayedAfterQuiescence) {
5847 QuicConnectionPeer::SetFastAckAfterQuiescence(&connection_, true);
5848
5849 // The beginning of the connection counts as quiescence.
5850 QuicTime ack_time =
5851 clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
5852 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5853 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5854 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07005855 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07005856 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005857 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07005858 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005859 // Process a packet from the non-crypto stream.
5860 frame1_.stream_id = 3;
5861
5862 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07005863 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005864 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5865 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5866
5867 // Check if delayed ack timer is running for the expected interval.
5868 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5869 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5870 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07005871 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005872 connection_.GetAckAlarm()->Fire();
5873 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07005874 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005875 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07005876 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005877 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
5878 } else {
nharper55fa6132019-05-07 19:37:21 -07005879 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005880 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
5881 }
5882 EXPECT_FALSE(writer_->ack_frames().empty());
5883 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5884
5885 // Process another packet immedately after sending the ack and expect the
5886 // ack alarm to be set delayed ack time in the future.
5887 ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
5888 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5889 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5890
5891 // Check if delayed ack timer is running for the expected interval.
5892 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5893 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5894 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07005895 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005896 connection_.GetAckAlarm()->Fire();
5897 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07005898 padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005899 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07005900 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005901 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
5902 } else {
nharper55fa6132019-05-07 19:37:21 -07005903 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005904 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
5905 }
5906 EXPECT_FALSE(writer_->ack_frames().empty());
5907 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5908
5909 // Wait 1 second and enesure the ack alarm is set to 1ms in the future.
5910 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
5911 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
5912 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5913 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5914
5915 // Check if delayed ack timer is running for the expected interval.
5916 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5917 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5918}
5919
5920TEST_P(QuicConnectionTest, SendDelayedAckDecimation) {
5921 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
5922 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION);
5923
5924 const size_t kMinRttMs = 40;
5925 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
5926 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
5927 QuicTime::Delta::Zero(), QuicTime::Zero());
5928 // The ack time should be based on min_rtt/4, since it's less than the
5929 // default delayed ack time.
5930 QuicTime ack_time = clock_.ApproximateNow() +
5931 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
5932 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5933 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5934 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07005935 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07005936 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005937 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07005938 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005939 // Process a packet from the non-crypto stream.
5940 frame1_.stream_id = 3;
5941
5942 // Process all the initial packets in order so there aren't missing packets.
5943 uint64_t kFirstDecimatedPacket = 101;
5944 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
5945 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5946 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5947 }
5948 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5949 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07005950 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005951 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5952 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
5953 ENCRYPTION_ZERO_RTT);
5954
5955 // Check if delayed ack timer is running for the expected interval.
5956 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5957 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5958
5959 // The 10th received packet causes an ack to be sent.
5960 for (int i = 0; i < 9; ++i) {
5961 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5962 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5963 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
5964 ENCRYPTION_ZERO_RTT);
5965 }
5966 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07005967 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005968 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07005969 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005970 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
5971 } else {
nharperc32d8ab2019-10-09 11:09:06 -07005972 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005973 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
5974 }
5975 EXPECT_FALSE(writer_->ack_frames().empty());
5976 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5977}
5978
5979TEST_P(QuicConnectionTest, SendDelayedAckAckDecimationAfterQuiescence) {
5980 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
5981 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION);
5982 QuicConnectionPeer::SetFastAckAfterQuiescence(&connection_, true);
5983
5984 const size_t kMinRttMs = 40;
5985 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
5986 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
5987 QuicTime::Delta::Zero(), QuicTime::Zero());
5988
5989 // The beginning of the connection counts as quiescence.
5990 QuicTime ack_time =
5991 clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
5992 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5993 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5994 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07005995 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07005996 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005997 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07005998 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005999 // Process a packet from the non-crypto stream.
6000 frame1_.stream_id = 3;
6001
6002 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006003 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006004 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6005 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6006
6007 // Check if delayed ack timer is running for the expected interval.
6008 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6009 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6010 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07006011 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006012 connection_.GetAckAlarm()->Fire();
6013 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006014 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006015 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006016 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006017 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6018 } else {
nharper55fa6132019-05-07 19:37:21 -07006019 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006020 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6021 }
6022 EXPECT_FALSE(writer_->ack_frames().empty());
6023 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6024
6025 // Process another packet immedately after sending the ack and expect the
6026 // ack alarm to be set delayed ack time in the future.
6027 ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6028 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6029 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6030
6031 // Check if delayed ack timer is running for the expected interval.
6032 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6033 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6034 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07006035 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006036 connection_.GetAckAlarm()->Fire();
6037 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006038 padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006039 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006040 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006041 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6042 } else {
nharper55fa6132019-05-07 19:37:21 -07006043 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006044 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6045 }
6046 EXPECT_FALSE(writer_->ack_frames().empty());
6047 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6048
6049 // Wait 1 second and enesure the ack alarm is set to 1ms in the future.
6050 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
6051 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
6052 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6053 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6054
6055 // Check if delayed ack timer is running for the expected interval.
6056 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6057 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6058
6059 // Process enough packets to get into ack decimation behavior.
6060 // The ack time should be based on min_rtt/4, since it's less than the
6061 // default delayed ack time.
6062 ack_time = clock_.ApproximateNow() +
6063 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6064 uint64_t kFirstDecimatedPacket = 101;
6065 for (unsigned int i = 0; i < kFirstDecimatedPacket - 4; ++i) {
6066 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6067 ProcessDataPacketAtLevel(4 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6068 }
6069 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6070 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006071 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006072 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6073 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6074 ENCRYPTION_ZERO_RTT);
6075
6076 // Check if delayed ack timer is running for the expected interval.
6077 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6078 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6079
6080 // The 10th received packet causes an ack to be sent.
6081 for (int i = 0; i < 9; ++i) {
6082 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6083 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6084 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6085 ENCRYPTION_ZERO_RTT);
6086 }
6087 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07006088 padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006089 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07006090 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006091 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6092 } else {
nharperc32d8ab2019-10-09 11:09:06 -07006093 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006094 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6095 }
6096 EXPECT_FALSE(writer_->ack_frames().empty());
6097 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6098
6099 // Wait 1 second and enesure the ack alarm is set to 1ms in the future.
6100 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
6101 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
6102 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6103 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 10, !kHasStopWaiting,
6104 ENCRYPTION_ZERO_RTT);
6105
6106 // Check if delayed ack timer is running for the expected interval.
6107 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6108 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6109}
6110
6111TEST_P(QuicConnectionTest, SendDelayedAckDecimationUnlimitedAggregation) {
6112 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6113 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6114 QuicConfig config;
6115 QuicTagVector connection_options;
6116 connection_options.push_back(kACKD);
6117 // No limit on the number of packets received before sending an ack.
6118 connection_options.push_back(kAKDU);
6119 config.SetConnectionOptionsToSend(connection_options);
6120 connection_.SetFromConfig(config);
6121
6122 const size_t kMinRttMs = 40;
6123 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6124 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6125 QuicTime::Delta::Zero(), QuicTime::Zero());
6126 // The ack time should be based on min_rtt/4, since it's less than the
6127 // default delayed ack time.
6128 QuicTime ack_time = clock_.ApproximateNow() +
6129 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6130 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6131 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6132 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006133 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006134 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006135 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006136 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006137 // Process a packet from the non-crypto stream.
6138 frame1_.stream_id = 3;
6139
6140 // Process all the initial packets in order so there aren't missing packets.
6141 uint64_t kFirstDecimatedPacket = 101;
6142 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6143 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6144 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6145 }
6146 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6147 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006148 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006149 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6150 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6151 ENCRYPTION_ZERO_RTT);
6152
6153 // Check if delayed ack timer is running for the expected interval.
6154 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6155 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6156
6157 // 18 packets will not cause an ack to be sent. 19 will because when
6158 // stop waiting frames are in use, we ack every 20 packets no matter what.
6159 for (int i = 0; i < 18; ++i) {
6160 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6161 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6162 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6163 ENCRYPTION_ZERO_RTT);
6164 }
6165 // The delayed ack timer should still be set to the expected deadline.
6166 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6167 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6168}
6169
6170TEST_P(QuicConnectionTest, SendDelayedAckDecimationEighthRtt) {
6171 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6172 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION);
6173 QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
6174
6175 const size_t kMinRttMs = 40;
6176 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6177 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6178 QuicTime::Delta::Zero(), QuicTime::Zero());
6179 // The ack time should be based on min_rtt/8, since it's less than the
6180 // default delayed ack time.
6181 QuicTime ack_time = clock_.ApproximateNow() +
6182 QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
6183 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6184 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6185 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006186 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006187 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006188 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006189 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006190 // Process a packet from the non-crypto stream.
6191 frame1_.stream_id = 3;
6192
6193 // Process all the initial packets in order so there aren't missing packets.
6194 uint64_t kFirstDecimatedPacket = 101;
6195 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6196 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6197 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6198 }
6199 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6200 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006201 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006202 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6203 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6204 ENCRYPTION_ZERO_RTT);
6205
6206 // Check if delayed ack timer is running for the expected interval.
6207 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6208 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6209
6210 // The 10th received packet causes an ack to be sent.
6211 for (int i = 0; i < 9; ++i) {
6212 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6213 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6214 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6215 ENCRYPTION_ZERO_RTT);
6216 }
6217 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07006218 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006219 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07006220 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006221 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6222 } else {
nharperc32d8ab2019-10-09 11:09:06 -07006223 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006224 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6225 }
6226 EXPECT_FALSE(writer_->ack_frames().empty());
6227 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6228}
6229
6230TEST_P(QuicConnectionTest, SendDelayedAckDecimationWithReordering) {
6231 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6232 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6233
6234 const size_t kMinRttMs = 40;
6235 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6236 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6237 QuicTime::Delta::Zero(), QuicTime::Zero());
6238 // The ack time should be based on min_rtt/4, since it's less than the
6239 // default delayed ack time.
6240 QuicTime ack_time = clock_.ApproximateNow() +
6241 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6242 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6243 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6244 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006245 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006246 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006247 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006248 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006249 // Process a packet from the non-crypto stream.
6250 frame1_.stream_id = 3;
6251
6252 // Process all the initial packets in order so there aren't missing packets.
6253 uint64_t kFirstDecimatedPacket = 101;
6254 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6255 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6256 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6257 }
6258 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6259
6260 // Receive one packet out of order and then the rest in order.
6261 // The loop leaves a one packet gap between acks sent to simulate some loss.
6262 for (int j = 0; j < 3; ++j) {
6263 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6264 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6265 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 9 + (j * 11),
6266 !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6267 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
6268 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6269 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6270
6271 // The 10th received packet causes an ack to be sent.
6272 writer_->Reset();
6273 for (int i = 0; i < 9; ++i) {
6274 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6275 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6276 // The ACK shouldn't be sent until the 10th packet is processed.
6277 EXPECT_TRUE(writer_->ack_frames().empty());
6278 ProcessDataPacketAtLevel(kFirstDecimatedPacket + i + (j * 11),
6279 !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6280 }
6281 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07006282 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006283 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07006284 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006285 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6286 } else {
nharperc32d8ab2019-10-09 11:09:06 -07006287 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006288 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6289 }
6290 EXPECT_FALSE(writer_->ack_frames().empty());
6291 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6292 }
6293}
6294
6295TEST_P(QuicConnectionTest, SendDelayedAckDecimationWithLargeReordering) {
6296 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6297 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6298
6299 const size_t kMinRttMs = 40;
6300 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6301 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6302 QuicTime::Delta::Zero(), QuicTime::Zero());
6303 // The ack time should be based on min_rtt/4, since it's less than the
6304 // default delayed ack time.
6305 QuicTime ack_time = clock_.ApproximateNow() +
6306 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6307 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6308 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6309 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006310 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006311 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006312 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006313 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006314 // Process a packet from the non-crypto stream.
6315 frame1_.stream_id = 3;
6316
6317 // Process all the initial packets in order so there aren't missing packets.
6318 uint64_t kFirstDecimatedPacket = 101;
6319 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6320 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6321 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6322 }
6323 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6324 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006325 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006326 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6327 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6328 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
6334 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6335 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6336 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 19, !kHasStopWaiting,
6337 ENCRYPTION_ZERO_RTT);
6338 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
6339 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6340 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6341
6342 // The 10th received packet causes an ack to be sent.
6343 for (int i = 0; i < 8; ++i) {
6344 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6345 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6346 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6347 ENCRYPTION_ZERO_RTT);
6348 }
6349 // Check that ack is sent and that delayed ack alarm is reset.
6350 if (GetParam().no_stop_waiting) {
6351 EXPECT_EQ(1u, writer_->frame_count());
6352 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6353 } else {
6354 EXPECT_EQ(2u, writer_->frame_count());
6355 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6356 }
6357 EXPECT_FALSE(writer_->ack_frames().empty());
6358 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6359
6360 // The next packet received in order will cause an immediate ack,
6361 // because it fills a hole.
6362 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6363 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6364 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 10, !kHasStopWaiting,
6365 ENCRYPTION_ZERO_RTT);
6366 // Check that ack is sent and that delayed ack alarm is reset.
6367 if (GetParam().no_stop_waiting) {
6368 EXPECT_EQ(1u, writer_->frame_count());
6369 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6370 } else {
6371 EXPECT_EQ(2u, writer_->frame_count());
6372 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6373 }
6374 EXPECT_FALSE(writer_->ack_frames().empty());
6375 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6376}
6377
6378TEST_P(QuicConnectionTest, SendDelayedAckDecimationWithReorderingEighthRtt) {
6379 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6380 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6381 QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
6382
6383 const size_t kMinRttMs = 40;
6384 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6385 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6386 QuicTime::Delta::Zero(), QuicTime::Zero());
6387 // The ack time should be based on min_rtt/8, since it's less than the
6388 // default delayed ack time.
6389 QuicTime ack_time = clock_.ApproximateNow() +
6390 QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
6391 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6392 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6393 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006394 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006395 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006396 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006397 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006398 // Process a packet from the non-crypto stream.
6399 frame1_.stream_id = 3;
6400
6401 // Process all the initial packets in order so there aren't missing packets.
6402 uint64_t kFirstDecimatedPacket = 101;
6403 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6404 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6405 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6406 }
6407 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6408 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006409 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006410 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6411 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6412 ENCRYPTION_ZERO_RTT);
6413
6414 // Check if delayed ack timer is running for the expected interval.
6415 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6416 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6417
6418 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6419 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6420 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 9, !kHasStopWaiting,
6421 ENCRYPTION_ZERO_RTT);
6422 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
6423 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6424 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6425
6426 // The 10th received packet causes an ack to be sent.
6427 for (int i = 0; i < 8; ++i) {
6428 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6429 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6430 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6431 ENCRYPTION_ZERO_RTT);
6432 }
6433 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07006434 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006435 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07006436 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006437 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6438 } else {
nharperc32d8ab2019-10-09 11:09:06 -07006439 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006440 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6441 }
6442 EXPECT_FALSE(writer_->ack_frames().empty());
6443 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6444}
6445
6446TEST_P(QuicConnectionTest,
6447 SendDelayedAckDecimationWithLargeReorderingEighthRtt) {
6448 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6449 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6450 QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
6451
6452 const size_t kMinRttMs = 40;
6453 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6454 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6455 QuicTime::Delta::Zero(), QuicTime::Zero());
6456 // The ack time should be based on min_rtt/8, since it's less than the
6457 // default delayed ack time.
6458 QuicTime ack_time = clock_.ApproximateNow() +
6459 QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
6460 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6461 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6462 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006463 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006464 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006465 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006466 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006467 // Process a packet from the non-crypto stream.
6468 frame1_.stream_id = 3;
6469
6470 // Process all the initial packets in order so there aren't missing packets.
6471 uint64_t kFirstDecimatedPacket = 101;
6472 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6473 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6474 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6475 }
6476 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6477 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006478 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006479 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6480 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6481 ENCRYPTION_ZERO_RTT);
6482
6483 // Check if delayed ack timer is running for the expected interval.
6484 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6485 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6486
6487 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6488 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6489 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 19, !kHasStopWaiting,
6490 ENCRYPTION_ZERO_RTT);
6491 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
6492 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6493 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6494
6495 // The 10th received packet causes an ack to be sent.
6496 for (int i = 0; i < 8; ++i) {
6497 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6498 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6499 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6500 ENCRYPTION_ZERO_RTT);
6501 }
6502 // Check that ack is sent and that delayed ack alarm is reset.
6503 if (GetParam().no_stop_waiting) {
6504 EXPECT_EQ(1u, writer_->frame_count());
6505 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6506 } else {
6507 EXPECT_EQ(2u, writer_->frame_count());
6508 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6509 }
6510 EXPECT_FALSE(writer_->ack_frames().empty());
6511 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6512
6513 // The next packet received in order will cause an immediate ack,
6514 // because it fills a hole.
6515 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6516 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6517 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 10, !kHasStopWaiting,
6518 ENCRYPTION_ZERO_RTT);
6519 // Check that ack is sent and that delayed ack alarm is reset.
6520 if (GetParam().no_stop_waiting) {
6521 EXPECT_EQ(1u, writer_->frame_count());
6522 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6523 } else {
6524 EXPECT_EQ(2u, writer_->frame_count());
6525 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6526 }
6527 EXPECT_FALSE(writer_->ack_frames().empty());
6528 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6529}
6530
6531TEST_P(QuicConnectionTest, SendDelayedAckOnHandshakeConfirmed) {
6532 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6533 ProcessPacket(1);
6534 // Check that ack is sent and that delayed ack alarm is set.
6535 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6536 QuicTime ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6537 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6538
6539 // Completing the handshake as the server does nothing.
6540 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_SERVER);
6541 connection_.OnHandshakeComplete();
6542 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6543 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6544
6545 // Complete the handshake as the client decreases the delayed ack time to 0ms.
6546 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_CLIENT);
6547 connection_.OnHandshakeComplete();
6548 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6549 EXPECT_EQ(clock_.ApproximateNow(), connection_.GetAckAlarm()->deadline());
6550}
6551
6552TEST_P(QuicConnectionTest, SendDelayedAckOnSecondPacket) {
6553 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6554 ProcessPacket(1);
6555 ProcessPacket(2);
6556 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006557 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006558 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006559 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006560 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6561 } else {
nharper55fa6132019-05-07 19:37:21 -07006562 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006563 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6564 }
6565 EXPECT_FALSE(writer_->ack_frames().empty());
6566 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6567}
6568
6569TEST_P(QuicConnectionTest, NoAckOnOldNacks) {
6570 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang6dba4902019-06-17 10:04:23 -07006571 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006572 ProcessPacket(2);
6573 size_t frames_per_ack = GetParam().no_stop_waiting ? 1 : 2;
QUICHE teama6ef0a62019-03-07 20:34:33 -05006574
6575 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
6576 ProcessPacket(3);
nharper55fa6132019-05-07 19:37:21 -07006577 size_t padding_frame_count = writer_->padding_frames().size();
6578 EXPECT_EQ(padding_frame_count + frames_per_ack, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006579 EXPECT_FALSE(writer_->ack_frames().empty());
6580 writer_->Reset();
6581
fayang6dba4902019-06-17 10:04:23 -07006582 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006583 ProcessPacket(4);
fayang6dba4902019-06-17 10:04:23 -07006584 EXPECT_EQ(0u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006585
6586 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
6587 ProcessPacket(5);
nharper55fa6132019-05-07 19:37:21 -07006588 padding_frame_count = writer_->padding_frames().size();
6589 EXPECT_EQ(padding_frame_count + frames_per_ack, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006590 EXPECT_FALSE(writer_->ack_frames().empty());
6591 writer_->Reset();
6592
6593 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6594 // Now only set the timer on the 6th packet, instead of sending another ack.
6595 ProcessPacket(6);
nharper55fa6132019-05-07 19:37:21 -07006596 padding_frame_count = writer_->padding_frames().size();
6597 EXPECT_EQ(padding_frame_count, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006598 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6599}
6600
6601TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingPacket) {
6602 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
QUICHE team8c1daa22019-03-13 08:33:41 -07006603 EXPECT_CALL(visitor_, OnStreamFrame(_));
6604 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07006605 std::make_unique<TaggingEncrypter>(0x01));
zhongyi546cc452019-04-12 15:27:49 -07006606 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07006607 std::make_unique<StrictTaggingDecrypter>(0x01));
nharper2c9f02a2019-05-08 10:25:50 -07006608 ProcessDataPacket(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006609 connection_.SendStreamDataWithString(
6610 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6611 0, NO_FIN);
6612 // Check that ack is bundled with outgoing data and that delayed ack
6613 // alarm is reset.
6614 if (GetParam().no_stop_waiting) {
6615 EXPECT_EQ(2u, writer_->frame_count());
6616 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6617 } else {
6618 EXPECT_EQ(3u, writer_->frame_count());
6619 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6620 }
6621 EXPECT_FALSE(writer_->ack_frames().empty());
6622 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6623}
6624
6625TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingCryptoPacket) {
6626 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayangc31c9952019-06-05 13:54:48 -07006627 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6628 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
6629 } else {
6630 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6631 }
6632 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
nharper46833c32019-05-15 21:33:05 -07006633 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006634 // Check that ack is bundled with outgoing crypto data.
6635 if (GetParam().no_stop_waiting) {
6636 EXPECT_EQ(3u, writer_->frame_count());
6637 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6638 } else {
6639 EXPECT_EQ(4u, writer_->frame_count());
6640 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6641 }
6642 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6643}
6644
6645TEST_P(QuicConnectionTest, BlockAndBufferOnFirstCHLOPacketOfTwo) {
6646 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6647 ProcessPacket(1);
6648 BlockOnNextWrite();
6649 writer_->set_is_write_blocked_data_buffered(true);
nharper46833c32019-05-15 21:33:05 -07006650 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006651 EXPECT_TRUE(writer_->IsWriteBlocked());
6652 EXPECT_FALSE(connection_.HasQueuedData());
nharper46833c32019-05-15 21:33:05 -07006653 connection_.SendCryptoDataWithString("bar", 3);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006654 EXPECT_TRUE(writer_->IsWriteBlocked());
6655 EXPECT_TRUE(connection_.HasQueuedData());
6656}
6657
6658TEST_P(QuicConnectionTest, BundleAckForSecondCHLO) {
6659 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6660 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6661 EXPECT_CALL(visitor_, OnCanWrite())
6662 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6663 &connection_, &TestConnection::SendCryptoStreamData)));
6664 // Process a packet from the crypto stream, which is frame1_'s default.
6665 // Receiving the CHLO as packet 2 first will cause the connection to
6666 // immediately send an ack, due to the packet gap.
fayangc31c9952019-06-05 13:54:48 -07006667 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6668 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
6669 } else {
6670 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6671 }
6672 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006673 // Check that ack is sent and that delayed ack alarm is reset.
6674 if (GetParam().no_stop_waiting) {
6675 EXPECT_EQ(3u, writer_->frame_count());
6676 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6677 } else {
6678 EXPECT_EQ(4u, writer_->frame_count());
6679 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6680 }
QUICHE teamea740082019-03-11 17:58:43 -07006681 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006682 EXPECT_EQ(1u, writer_->stream_frames().size());
6683 } else {
6684 EXPECT_EQ(1u, writer_->crypto_frames().size());
6685 }
6686 EXPECT_EQ(1u, writer_->padding_frames().size());
6687 ASSERT_FALSE(writer_->ack_frames().empty());
6688 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(writer_->ack_frames().front()));
6689 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6690}
6691
6692TEST_P(QuicConnectionTest, BundleAckForSecondCHLOTwoPacketReject) {
6693 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6694 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6695
6696 // Process two packets from the crypto stream, which is frame1_'s default,
6697 // simulating a 2 packet reject.
6698 {
fayangc31c9952019-06-05 13:54:48 -07006699 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6700 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
6701 } else {
6702 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6703 }
6704 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006705 // Send the new CHLO when the REJ is processed.
fayangc31c9952019-06-05 13:54:48 -07006706 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6707 EXPECT_CALL(visitor_, OnCryptoFrame(_))
6708 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6709 &connection_, &TestConnection::SendCryptoStreamData)));
6710 } else {
6711 EXPECT_CALL(visitor_, OnStreamFrame(_))
6712 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6713 &connection_, &TestConnection::SendCryptoStreamData)));
6714 }
6715 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006716 }
6717 // Check that ack is sent and that delayed ack alarm is reset.
6718 if (GetParam().no_stop_waiting) {
6719 EXPECT_EQ(3u, writer_->frame_count());
6720 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6721 } else {
6722 EXPECT_EQ(4u, writer_->frame_count());
6723 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6724 }
QUICHE teamea740082019-03-11 17:58:43 -07006725 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006726 EXPECT_EQ(1u, writer_->stream_frames().size());
6727 } else {
6728 EXPECT_EQ(1u, writer_->crypto_frames().size());
6729 }
6730 EXPECT_EQ(1u, writer_->padding_frames().size());
6731 ASSERT_FALSE(writer_->ack_frames().empty());
6732 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(writer_->ack_frames().front()));
6733 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6734}
6735
6736TEST_P(QuicConnectionTest, BundleAckWithDataOnIncomingAck) {
6737 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6738 connection_.SendStreamDataWithString(
6739 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6740 0, NO_FIN);
6741 connection_.SendStreamDataWithString(
6742 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6743 3, NO_FIN);
6744 // Ack the second packet, which will retransmit the first packet.
6745 QuicAckFrame ack = ConstructAckFrame(2, 1);
6746 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07006747 lost_packets.push_back(
6748 LostPacket(QuicPacketNumber(1), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006749 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
6750 .WillOnce(SetArgPointee<5>(lost_packets));
6751 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
6752 ProcessAckPacket(&ack);
nharper55fa6132019-05-07 19:37:21 -07006753 size_t padding_frame_count = writer_->padding_frames().size();
6754 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006755 EXPECT_EQ(1u, writer_->stream_frames().size());
6756 writer_->Reset();
6757
6758 // Now ack the retransmission, which will both raise the high water mark
6759 // and see if there is more data to send.
6760 ack = ConstructAckFrame(3, 1);
6761 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
6762 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
6763 ProcessAckPacket(&ack);
6764
6765 // Check that no packet is sent and the ack alarm isn't set.
6766 EXPECT_EQ(0u, writer_->frame_count());
6767 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6768 writer_->Reset();
6769
6770 // Send the same ack, but send both data and an ack together.
6771 ack = ConstructAckFrame(3, 1);
6772 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
6773 EXPECT_CALL(visitor_, OnCanWrite())
6774 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6775 &connection_, &TestConnection::EnsureWritableAndSendStreamData5)));
6776 ProcessAckPacket(&ack);
6777
6778 // Check that ack is bundled with outgoing data and the delayed ack
6779 // alarm is reset.
6780 if (GetParam().no_stop_waiting) {
fayange8b0cab2019-07-17 14:23:07 -07006781 if (GetQuicReloadableFlag(quic_simplify_stop_waiting)) {
6782 // Do not ACK acks.
6783 EXPECT_EQ(1u, writer_->frame_count());
6784 } else {
6785 EXPECT_EQ(2u, writer_->frame_count());
6786 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6787 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006788 } else {
6789 EXPECT_EQ(3u, writer_->frame_count());
6790 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6791 }
fayange8b0cab2019-07-17 14:23:07 -07006792 if (GetParam().no_stop_waiting &&
6793 GetQuicReloadableFlag(quic_simplify_stop_waiting)) {
fayang03916692019-05-22 17:57:18 -07006794 EXPECT_TRUE(writer_->ack_frames().empty());
6795 } else {
6796 EXPECT_FALSE(writer_->ack_frames().empty());
6797 EXPECT_EQ(QuicPacketNumber(3u),
6798 LargestAcked(writer_->ack_frames().front()));
6799 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006800 EXPECT_EQ(1u, writer_->stream_frames().size());
6801 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6802}
6803
6804TEST_P(QuicConnectionTest, NoAckSentForClose) {
6805 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6806 ProcessPacket(1);
fkastenholz5d880a92019-06-21 09:01:56 -07006807 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
6808 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006809 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6810 ProcessClosePacket(2);
fkastenholz5d880a92019-06-21 09:01:56 -07006811 EXPECT_EQ(1, connection_close_frame_count_);
6812 EXPECT_EQ(QUIC_PEER_GOING_AWAY,
6813 saved_connection_close_frame_.quic_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006814}
6815
6816TEST_P(QuicConnectionTest, SendWhenDisconnected) {
6817 EXPECT_TRUE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07006818 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
6819 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006820 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
6821 ConnectionCloseBehavior::SILENT_CLOSE);
6822 EXPECT_FALSE(connection_.connected());
6823 EXPECT_FALSE(connection_.CanWriteStreamData());
QUICHE team8c1daa22019-03-13 08:33:41 -07006824 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07006825 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006826 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6827 .Times(0);
QUICHE team6987b4a2019-03-15 16:23:04 -07006828 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05006829 HAS_RETRANSMITTABLE_DATA, false, false);
fkastenholz5d880a92019-06-21 09:01:56 -07006830 EXPECT_EQ(1, connection_close_frame_count_);
6831 EXPECT_EQ(QUIC_PEER_GOING_AWAY,
6832 saved_connection_close_frame_.quic_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006833}
6834
6835TEST_P(QuicConnectionTest, SendConnectivityProbingWhenDisconnected) {
6836 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
fayangc31c9952019-06-05 13:54:48 -07006837 if (!IsDefaultTestConfiguration()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006838 return;
6839 }
6840
6841 EXPECT_TRUE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07006842 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
6843 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006844 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
6845 ConnectionCloseBehavior::SILENT_CLOSE);
6846 EXPECT_FALSE(connection_.connected());
6847 EXPECT_FALSE(connection_.CanWriteStreamData());
6848
6849 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6850 .Times(0);
6851
6852 EXPECT_QUIC_BUG(connection_.SendConnectivityProbingPacket(
6853 writer_.get(), connection_.peer_address()),
6854 "Not sending connectivity probing packet as connection is "
6855 "disconnected.");
fkastenholz5d880a92019-06-21 09:01:56 -07006856 EXPECT_EQ(1, connection_close_frame_count_);
6857 EXPECT_EQ(QUIC_PEER_GOING_AWAY,
6858 saved_connection_close_frame_.quic_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006859}
6860
6861TEST_P(QuicConnectionTest, WriteBlockedAfterClientSendsConnectivityProbe) {
6862 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
6863 TestPacketWriter probing_writer(version(), &clock_);
6864 // Block next write so that sending connectivity probe will encounter a
6865 // blocked write when send a connectivity probe to the peer.
6866 probing_writer.BlockOnNextWrite();
6867 // Connection will not be marked as write blocked as connectivity probe only
6868 // affects the probing_writer which is not the default.
6869 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
6870
6871 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6872 .Times(1);
6873 connection_.SendConnectivityProbingPacket(&probing_writer,
6874 connection_.peer_address());
6875}
6876
6877TEST_P(QuicConnectionTest, WriterBlockedAfterServerSendsConnectivityProbe) {
6878 set_perspective(Perspective::IS_SERVER);
6879 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
6880
6881 // Block next write so that sending connectivity probe will encounter a
6882 // blocked write when send a connectivity probe to the peer.
6883 writer_->BlockOnNextWrite();
6884 // Connection will be marked as write blocked as server uses the default
6885 // writer to send connectivity probes.
6886 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
6887
6888 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6889 .Times(1);
6890 connection_.SendConnectivityProbingPacket(writer_.get(),
6891 connection_.peer_address());
6892}
6893
6894TEST_P(QuicConnectionTest, WriterErrorWhenClientSendsConnectivityProbe) {
6895 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
6896 TestPacketWriter probing_writer(version(), &clock_);
6897 probing_writer.SetShouldWriteFail();
6898
6899 // Connection should not be closed if a connectivity probe is failed to be
6900 // sent.
fkastenholz5d880a92019-06-21 09:01:56 -07006901 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006902
6903 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6904 .Times(0);
6905 connection_.SendConnectivityProbingPacket(&probing_writer,
6906 connection_.peer_address());
6907}
6908
6909TEST_P(QuicConnectionTest, WriterErrorWhenServerSendsConnectivityProbe) {
6910 set_perspective(Perspective::IS_SERVER);
6911 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
6912
6913 writer_->SetShouldWriteFail();
6914 // Connection should not be closed if a connectivity probe is failed to be
6915 // sent.
fkastenholz5d880a92019-06-21 09:01:56 -07006916 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006917
6918 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6919 .Times(0);
6920 connection_.SendConnectivityProbingPacket(writer_.get(),
6921 connection_.peer_address());
6922}
6923
6924TEST_P(QuicConnectionTest, PublicReset) {
fayangc31c9952019-06-05 13:54:48 -07006925 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006926 return;
6927 }
6928 QuicPublicResetPacket header;
6929 // Public reset packet in only built by server.
6930 header.connection_id = connection_id_;
6931 std::unique_ptr<QuicEncryptedPacket> packet(
6932 framer_.BuildPublicResetPacket(header));
6933 std::unique_ptr<QuicReceivedPacket> received(
6934 ConstructReceivedPacket(*packet, QuicTime::Zero()));
fkastenholz5d880a92019-06-21 09:01:56 -07006935 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
6936 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006937 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
fkastenholz5d880a92019-06-21 09:01:56 -07006938 EXPECT_EQ(1, connection_close_frame_count_);
6939 EXPECT_EQ(QUIC_PUBLIC_RESET, saved_connection_close_frame_.quic_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006940}
6941
6942TEST_P(QuicConnectionTest, IetfStatelessReset) {
fayangc31c9952019-06-05 13:54:48 -07006943 if (!VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006944 return;
6945 }
6946 const QuicUint128 kTestStatelessResetToken = 1010101;
6947 QuicConfig config;
6948 QuicConfigPeer::SetReceivedStatelessResetToken(&config,
6949 kTestStatelessResetToken);
6950 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6951 connection_.SetFromConfig(config);
6952 std::unique_ptr<QuicEncryptedPacket> packet(
6953 QuicFramer::BuildIetfStatelessResetPacket(connection_id_,
6954 kTestStatelessResetToken));
6955 std::unique_ptr<QuicReceivedPacket> received(
6956 ConstructReceivedPacket(*packet, QuicTime::Zero()));
fkastenholz5d880a92019-06-21 09:01:56 -07006957 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
6958 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006959 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
fkastenholz5d880a92019-06-21 09:01:56 -07006960 EXPECT_EQ(1, connection_close_frame_count_);
6961 EXPECT_EQ(QUIC_PUBLIC_RESET, saved_connection_close_frame_.quic_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006962}
6963
6964TEST_P(QuicConnectionTest, GoAway) {
fkastenholz305e1732019-06-18 05:01:22 -07006965 if (VersionHasIetfQuicFrames(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006966 // GoAway is not available in version 99.
6967 return;
6968 }
6969
6970 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6971
6972 QuicGoAwayFrame goaway;
6973 goaway.last_good_stream_id = 1;
6974 goaway.error_code = QUIC_PEER_GOING_AWAY;
6975 goaway.reason_phrase = "Going away.";
6976 EXPECT_CALL(visitor_, OnGoAway(_));
6977 ProcessGoAwayPacket(&goaway);
6978}
6979
6980TEST_P(QuicConnectionTest, WindowUpdate) {
6981 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6982
6983 QuicWindowUpdateFrame window_update;
6984 window_update.stream_id = 3;
6985 window_update.byte_offset = 1234;
6986 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
6987 ProcessFramePacket(QuicFrame(&window_update));
6988}
6989
6990TEST_P(QuicConnectionTest, Blocked) {
6991 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6992
6993 QuicBlockedFrame blocked;
6994 blocked.stream_id = 3;
6995 EXPECT_CALL(visitor_, OnBlockedFrame(_));
6996 ProcessFramePacket(QuicFrame(&blocked));
6997 EXPECT_EQ(1u, connection_.GetStats().blocked_frames_received);
6998 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
6999}
7000
7001TEST_P(QuicConnectionTest, ZeroBytePacket) {
7002 // Don't close the connection for zero byte packets.
fkastenholz5d880a92019-06-21 09:01:56 -07007003 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007004 QuicReceivedPacket encrypted(nullptr, 0, QuicTime::Zero());
7005 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, encrypted);
7006}
7007
7008TEST_P(QuicConnectionTest, MissingPacketsBeforeLeastUnacked) {
fayangd4291e42019-05-30 10:31:21 -07007009 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007010 return;
7011 }
7012 // Set the packet number of the ack packet to be least unacked (4).
7013 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 3);
7014 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7015 ProcessStopWaitingPacket(InitStopWaitingFrame(4));
fayangc31c9952019-06-05 13:54:48 -07007016 EXPECT_FALSE(connection_.ack_frame().packets.Empty());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007017}
7018
QUICHE teama6ef0a62019-03-07 20:34:33 -05007019TEST_P(QuicConnectionTest, ClientHandlesVersionNegotiation) {
dschinazi48ac9192019-07-31 00:07:26 -07007020 // All supported versions except the one the connection supports.
7021 ParsedQuicVersionVector versions;
7022 for (auto version : AllSupportedVersions()) {
7023 if (version != connection_.version()) {
7024 versions.push_back(version);
7025 }
7026 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007027
7028 // Send a version negotiation packet.
7029 std::unique_ptr<QuicEncryptedPacket> encrypted(
dschinazib417d602019-05-29 13:08:45 -07007030 QuicFramer::BuildVersionNegotiationPacket(
7031 connection_id_, EmptyQuicConnectionId(),
fayangd4291e42019-05-30 10:31:21 -07007032 VersionHasIetfInvariantHeader(connection_.transport_version()),
dschinazi48ac9192019-07-31 00:07:26 -07007033 connection_.version().HasLengthPrefixedConnectionIds(), versions));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007034 std::unique_ptr<QuicReceivedPacket> received(
7035 ConstructReceivedPacket(*encrypted, QuicTime::Zero()));
fkastenholz5d880a92019-06-21 09:01:56 -07007036 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7037 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007038 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
fayang9ed391a2019-06-20 11:16:59 -07007039 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07007040 EXPECT_EQ(1, connection_close_frame_count_);
7041 EXPECT_EQ(QUIC_INVALID_VERSION,
7042 saved_connection_close_frame_.quic_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007043}
7044
7045TEST_P(QuicConnectionTest, BadVersionNegotiation) {
7046 // Send a version negotiation packet with the version the client started with.
7047 // It should be rejected.
fkastenholz5d880a92019-06-21 09:01:56 -07007048 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7049 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007050 std::unique_ptr<QuicEncryptedPacket> encrypted(
dschinazib417d602019-05-29 13:08:45 -07007051 QuicFramer::BuildVersionNegotiationPacket(
7052 connection_id_, EmptyQuicConnectionId(),
fayangd4291e42019-05-30 10:31:21 -07007053 VersionHasIetfInvariantHeader(connection_.transport_version()),
dschinazi48ac9192019-07-31 00:07:26 -07007054 connection_.version().HasLengthPrefixedConnectionIds(),
QUICHE teama6ef0a62019-03-07 20:34:33 -05007055 AllSupportedVersions()));
7056 std::unique_ptr<QuicReceivedPacket> received(
7057 ConstructReceivedPacket(*encrypted, QuicTime::Zero()));
7058 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
fkastenholz5d880a92019-06-21 09:01:56 -07007059 EXPECT_EQ(1, connection_close_frame_count_);
7060 EXPECT_EQ(QUIC_INVALID_VERSION_NEGOTIATION_PACKET,
7061 saved_connection_close_frame_.quic_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007062}
7063
7064TEST_P(QuicConnectionTest, CheckSendStats) {
fayang5f135052019-08-22 17:59:40 -07007065 if (connection_.PtoEnabled()) {
7066 return;
7067 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007068 connection_.SetMaxTailLossProbes(0);
7069
7070 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7071 connection_.SendStreamDataWithString(3, "first", 0, NO_FIN);
7072 size_t first_packet_size = writer_->last_packet_size();
7073
7074 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7075 connection_.SendStreamDataWithString(5, "second", 0, NO_FIN);
7076 size_t second_packet_size = writer_->last_packet_size();
7077
7078 // 2 retransmissions due to rto, 1 due to explicit nack.
7079 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
7080 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
7081
7082 // Retransmit due to RTO.
7083 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
7084 connection_.GetRetransmissionAlarm()->Fire();
7085
7086 // Retransmit due to explicit nacks.
7087 QuicAckFrame nack_three =
7088 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)},
7089 {QuicPacketNumber(4), QuicPacketNumber(5)}});
7090
7091 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07007092 lost_packets.push_back(
7093 LostPacket(QuicPacketNumber(1), kMaxOutgoingPacketSize));
7094 lost_packets.push_back(
7095 LostPacket(QuicPacketNumber(3), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007096 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
7097 .WillOnce(SetArgPointee<5>(lost_packets));
7098 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7099 if (!connection_.session_decides_what_to_write()) {
7100 EXPECT_CALL(visitor_, OnCanWrite());
7101 }
7102 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7103 ProcessAckPacket(&nack_three);
7104
7105 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
7106 .WillOnce(Return(QuicBandwidth::Zero()));
7107
7108 const QuicConnectionStats& stats = connection_.GetStats();
7109 // For IETF QUIC, version is not included as the encryption level switches to
7110 // FORWARD_SECURE in SendStreamDataWithString.
7111 size_t save_on_version =
fayangd4291e42019-05-30 10:31:21 -07007112 VersionHasIetfInvariantHeader(GetParam().version.transport_version)
7113 ? 0
7114 : kQuicVersionSize;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007115 EXPECT_EQ(3 * first_packet_size + 2 * second_packet_size - save_on_version,
7116 stats.bytes_sent);
7117 EXPECT_EQ(5u, stats.packets_sent);
7118 EXPECT_EQ(2 * first_packet_size + second_packet_size - save_on_version,
7119 stats.bytes_retransmitted);
7120 EXPECT_EQ(3u, stats.packets_retransmitted);
7121 EXPECT_EQ(1u, stats.rto_count);
7122 EXPECT_EQ(kDefaultMaxPacketSize, stats.max_packet_size);
7123}
7124
7125TEST_P(QuicConnectionTest, ProcessFramesIfPacketClosedConnection) {
7126 // Construct a packet with stream frame and connection close frame.
7127 QuicPacketHeader header;
dschinazi5e1a7b22019-07-31 12:23:21 -07007128 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
QUICHE team2252b702019-05-14 23:55:14 -04007129 header.source_connection_id = connection_id_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007130 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
fayangd4291e42019-05-30 10:31:21 -07007131 if (!VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04007132 header.source_connection_id_included = CONNECTION_ID_PRESENT;
7133 }
7134 } else {
7135 header.destination_connection_id = connection_id_;
fayangd4291e42019-05-30 10:31:21 -07007136 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04007137 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
7138 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007139 }
7140 header.packet_number = QuicPacketNumber(1);
7141 header.version_flag = false;
7142
fkastenholz488a4622019-08-26 06:24:46 -07007143 QuicErrorCode kQuicErrorCode = QUIC_PEER_GOING_AWAY;
7144 // This QuicConnectionCloseFrame will default to being for a Google QUIC
7145 // close. If doing IETF QUIC then set fields appropriately for CC/T or CC/A,
7146 // depending on the mapping.
fkastenholz591814c2019-09-06 12:11:46 -07007147 QuicConnectionCloseFrame qccf(peer_framer_.transport_version(),
7148 kQuicErrorCode, "",
7149 /*transport_close_frame_type=*/0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007150 QuicFrames frames;
7151 frames.push_back(QuicFrame(frame1_));
7152 frames.push_back(QuicFrame(&qccf));
7153 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
7154 EXPECT_TRUE(nullptr != packet);
dschinazi66dea072019-04-09 11:41:06 -07007155 char buffer[kMaxOutgoingPacketSize];
nharperc6b99512019-09-19 11:13:48 -07007156 size_t encrypted_length = peer_framer_.EncryptPayload(
7157 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
7158 kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007159
fkastenholz5d880a92019-06-21 09:01:56 -07007160 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
7161 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007162 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7163 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7164
7165 connection_.ProcessUdpPacket(
7166 kSelfAddress, kPeerAddress,
7167 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
fkastenholz5d880a92019-06-21 09:01:56 -07007168 EXPECT_EQ(1, connection_close_frame_count_);
7169 EXPECT_EQ(QUIC_PEER_GOING_AWAY,
fkastenholz488a4622019-08-26 06:24:46 -07007170 saved_connection_close_frame_.extracted_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007171}
7172
7173TEST_P(QuicConnectionTest, SelectMutualVersion) {
7174 connection_.SetSupportedVersions(AllSupportedVersions());
7175 // Set the connection to speak the lowest quic version.
7176 connection_.set_version(QuicVersionMin());
7177 EXPECT_EQ(QuicVersionMin(), connection_.version());
7178
7179 // Pass in available versions which includes a higher mutually supported
7180 // version. The higher mutually supported version should be selected.
7181 ParsedQuicVersionVector supported_versions = AllSupportedVersions();
7182 EXPECT_TRUE(connection_.SelectMutualVersion(supported_versions));
7183 EXPECT_EQ(QuicVersionMax(), connection_.version());
7184
7185 // Expect that the lowest version is selected.
7186 // Ensure the lowest supported version is less than the max, unless they're
7187 // the same.
7188 ParsedQuicVersionVector lowest_version_vector;
7189 lowest_version_vector.push_back(QuicVersionMin());
7190 EXPECT_TRUE(connection_.SelectMutualVersion(lowest_version_vector));
7191 EXPECT_EQ(QuicVersionMin(), connection_.version());
7192
7193 // Shouldn't be able to find a mutually supported version.
7194 ParsedQuicVersionVector unsupported_version;
7195 unsupported_version.push_back(UnsupportedQuicVersion());
7196 EXPECT_FALSE(connection_.SelectMutualVersion(unsupported_version));
7197}
7198
7199TEST_P(QuicConnectionTest, ConnectionCloseWhenWritable) {
7200 EXPECT_FALSE(writer_->IsWriteBlocked());
7201
7202 // Send a packet.
7203 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7204 EXPECT_EQ(0u, connection_.NumQueuedPackets());
7205 EXPECT_EQ(1u, writer_->packets_write_attempts());
7206
7207 TriggerConnectionClose();
7208 EXPECT_EQ(2u, writer_->packets_write_attempts());
7209}
7210
7211TEST_P(QuicConnectionTest, ConnectionCloseGettingWriteBlocked) {
7212 BlockOnNextWrite();
7213 TriggerConnectionClose();
7214 EXPECT_EQ(1u, writer_->packets_write_attempts());
7215 EXPECT_TRUE(writer_->IsWriteBlocked());
7216}
7217
7218TEST_P(QuicConnectionTest, ConnectionCloseWhenWriteBlocked) {
7219 BlockOnNextWrite();
7220 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7221 EXPECT_EQ(1u, connection_.NumQueuedPackets());
7222 EXPECT_EQ(1u, writer_->packets_write_attempts());
7223 EXPECT_TRUE(writer_->IsWriteBlocked());
7224 TriggerConnectionClose();
7225 EXPECT_EQ(1u, writer_->packets_write_attempts());
7226}
7227
7228TEST_P(QuicConnectionTest, OnPacketSentDebugVisitor) {
7229 MockQuicConnectionDebugVisitor debug_visitor;
7230 connection_.set_debug_visitor(&debug_visitor);
7231
7232 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _)).Times(1);
7233 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7234
7235 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _)).Times(1);
7236 connection_.SendConnectivityProbingPacket(writer_.get(),
7237 connection_.peer_address());
7238}
7239
7240TEST_P(QuicConnectionTest, OnPacketHeaderDebugVisitor) {
7241 QuicPacketHeader header;
7242 header.packet_number = QuicPacketNumber(1);
fayangd4291e42019-05-30 10:31:21 -07007243 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007244 header.form = IETF_QUIC_LONG_HEADER_PACKET;
7245 }
7246
7247 MockQuicConnectionDebugVisitor debug_visitor;
7248 connection_.set_debug_visitor(&debug_visitor);
7249 EXPECT_CALL(debug_visitor, OnPacketHeader(Ref(header))).Times(1);
7250 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(1);
7251 EXPECT_CALL(debug_visitor, OnSuccessfulVersionNegotiation(_)).Times(1);
7252 connection_.OnPacketHeader(header);
7253}
7254
7255TEST_P(QuicConnectionTest, Pacing) {
7256 TestConnection server(connection_id_, kSelfAddress, helper_.get(),
7257 alarm_factory_.get(), writer_.get(),
7258 Perspective::IS_SERVER, version());
7259 TestConnection client(connection_id_, kPeerAddress, helper_.get(),
7260 alarm_factory_.get(), writer_.get(),
7261 Perspective::IS_CLIENT, version());
7262 EXPECT_FALSE(QuicSentPacketManagerPeer::UsingPacing(
7263 static_cast<const QuicSentPacketManager*>(
7264 &client.sent_packet_manager())));
7265 EXPECT_FALSE(QuicSentPacketManagerPeer::UsingPacing(
7266 static_cast<const QuicSentPacketManager*>(
7267 &server.sent_packet_manager())));
7268}
7269
7270TEST_P(QuicConnectionTest, WindowUpdateInstigateAcks) {
7271 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7272
7273 // Send a WINDOW_UPDATE frame.
7274 QuicWindowUpdateFrame window_update;
7275 window_update.stream_id = 3;
7276 window_update.byte_offset = 1234;
7277 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
7278 ProcessFramePacket(QuicFrame(&window_update));
7279
7280 // Ensure that this has caused the ACK alarm to be set.
7281 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
7282 EXPECT_TRUE(ack_alarm->IsSet());
7283}
7284
7285TEST_P(QuicConnectionTest, BlockedFrameInstigateAcks) {
7286 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7287
7288 // Send a BLOCKED frame.
7289 QuicBlockedFrame blocked;
7290 blocked.stream_id = 3;
7291 EXPECT_CALL(visitor_, OnBlockedFrame(_));
7292 ProcessFramePacket(QuicFrame(&blocked));
7293
7294 // Ensure that this has caused the ACK alarm to be set.
7295 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
7296 EXPECT_TRUE(ack_alarm->IsSet());
7297}
7298
7299TEST_P(QuicConnectionTest, ReevaluateTimeUntilSendOnAck) {
7300 // Enable pacing.
7301 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7302 QuicConfig config;
7303 connection_.SetFromConfig(config);
7304
7305 // Send two packets. One packet is not sufficient because if it gets acked,
7306 // there will be no packets in flight after that and the pacer will always
7307 // allow the next packet in that situation.
7308 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7309 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
7310 connection_.SendStreamDataWithString(
7311 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
7312 0, NO_FIN);
7313 connection_.SendStreamDataWithString(
7314 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "bar",
7315 3, NO_FIN);
7316 connection_.OnCanWrite();
7317
7318 // Schedule the next packet for a few milliseconds in future.
7319 QuicSentPacketManagerPeer::DisablePacerBursts(manager_);
7320 QuicTime scheduled_pacing_time =
7321 clock_.Now() + QuicTime::Delta::FromMilliseconds(5);
7322 QuicSentPacketManagerPeer::SetNextPacedPacketTime(manager_,
7323 scheduled_pacing_time);
7324
7325 // Send a packet and have it be blocked by congestion control.
7326 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(false));
7327 connection_.SendStreamDataWithString(
7328 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "baz",
7329 6, NO_FIN);
7330 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
7331
7332 // Process an ack and the send alarm will be set to the new 5ms delay.
7333 QuicAckFrame ack = InitAckFrame(1);
7334 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
7335 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7336 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
7337 ProcessAckPacket(&ack);
nharper55fa6132019-05-07 19:37:21 -07007338 size_t padding_frame_count = writer_->padding_frames().size();
7339 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007340 EXPECT_EQ(1u, writer_->stream_frames().size());
7341 EXPECT_TRUE(connection_.GetSendAlarm()->IsSet());
7342 EXPECT_EQ(scheduled_pacing_time, connection_.GetSendAlarm()->deadline());
7343 writer_->Reset();
7344}
7345
7346TEST_P(QuicConnectionTest, SendAcksImmediately) {
QUICHE teamcd098022019-03-22 18:49:55 -07007347 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7348 return;
7349 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007350 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7351 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7352 ProcessDataPacket(1);
7353 CongestionBlockWrites();
7354 SendAckPacketToPeer();
7355}
7356
7357TEST_P(QuicConnectionTest, SendPingImmediately) {
7358 MockQuicConnectionDebugVisitor debug_visitor;
7359 connection_.set_debug_visitor(&debug_visitor);
7360
7361 CongestionBlockWrites();
fayang93cc53a2019-08-22 12:47:30 -07007362 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007363 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7364 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _)).Times(1);
7365 EXPECT_CALL(debug_visitor, OnPingSent()).Times(1);
7366 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
7367 EXPECT_FALSE(connection_.HasQueuedData());
7368}
7369
7370TEST_P(QuicConnectionTest, SendBlockedImmediately) {
7371 MockQuicConnectionDebugVisitor debug_visitor;
7372 connection_.set_debug_visitor(&debug_visitor);
7373
fayang93cc53a2019-08-22 12:47:30 -07007374 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007375 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7376 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _)).Times(1);
7377 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7378 connection_.SendControlFrame(QuicFrame(new QuicBlockedFrame(1, 3)));
7379 EXPECT_EQ(1u, connection_.GetStats().blocked_frames_sent);
7380 EXPECT_FALSE(connection_.HasQueuedData());
7381}
7382
fayang93cc53a2019-08-22 12:47:30 -07007383TEST_P(QuicConnectionTest, FailedToSendBlockedFrames) {
7384 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
7385 return;
7386 }
7387 MockQuicConnectionDebugVisitor debug_visitor;
7388 connection_.set_debug_visitor(&debug_visitor);
7389 QuicBlockedFrame blocked(1, 3);
7390
7391 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
7392 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _)).Times(0);
7393 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7394 connection_.SendControlFrame(QuicFrame(&blocked));
7395 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7396 EXPECT_FALSE(connection_.HasQueuedData());
7397}
7398
QUICHE teama6ef0a62019-03-07 20:34:33 -05007399TEST_P(QuicConnectionTest, SendingUnencryptedStreamDataFails) {
7400 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
7401 if (!IsDefaultTestConfiguration()) {
7402 return;
7403 }
7404
fkastenholz5d880a92019-06-21 09:01:56 -07007405 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7406 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007407 struct iovec iov;
7408 MakeIOVector("", &iov);
7409 EXPECT_QUIC_BUG(connection_.SaveAndSendStreamData(3, &iov, 1, 0, 0, FIN),
fayang49523232019-05-03 06:28:22 -07007410 "Cannot send stream data with level: ENCRYPTION_INITIAL");
QUICHE teama6ef0a62019-03-07 20:34:33 -05007411 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07007412 EXPECT_EQ(1, connection_close_frame_count_);
7413 EXPECT_EQ(QUIC_ATTEMPT_TO_SEND_UNENCRYPTED_STREAM_DATA,
7414 saved_connection_close_frame_.quic_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007415}
7416
7417TEST_P(QuicConnectionTest, SetRetransmissionAlarmForCryptoPacket) {
7418 EXPECT_TRUE(connection_.connected());
7419 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
7420
7421 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7422 connection_.SendCryptoStreamData();
7423
7424 // Verify retransmission timer is correctly set after crypto packet has been
7425 // sent.
7426 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
7427 QuicTime retransmission_time =
7428 QuicConnectionPeer::GetSentPacketManager(&connection_)
7429 ->GetRetransmissionTime();
7430 EXPECT_NE(retransmission_time, clock_.ApproximateNow());
7431 EXPECT_EQ(retransmission_time,
7432 connection_.GetRetransmissionAlarm()->deadline());
7433
7434 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7435 connection_.GetRetransmissionAlarm()->Fire();
7436}
7437
7438TEST_P(QuicConnectionTest, PathDegradingAlarmForCryptoPacket) {
7439 EXPECT_TRUE(connection_.connected());
7440 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7441 EXPECT_FALSE(connection_.IsPathDegrading());
7442
7443 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7444 connection_.SendCryptoStreamData();
7445
7446 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7447 EXPECT_FALSE(connection_.IsPathDegrading());
7448 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7449 ->GetPathDegradingDelay();
7450 EXPECT_EQ(clock_.ApproximateNow() + delay,
7451 connection_.GetPathDegradingAlarm()->deadline());
7452
7453 // Fire the path degrading alarm, path degrading signal should be sent to
7454 // the visitor.
7455 EXPECT_CALL(visitor_, OnPathDegrading());
7456 clock_.AdvanceTime(delay);
7457 connection_.GetPathDegradingAlarm()->Fire();
7458 EXPECT_TRUE(connection_.IsPathDegrading());
7459 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7460}
7461
vasilvv693d5b02019-04-09 21:58:56 -07007462// Includes regression test for b/69979024.
QUICHE teama6ef0a62019-03-07 20:34:33 -05007463TEST_P(QuicConnectionTest, PathDegradingAlarmForNonCryptoPackets) {
7464 EXPECT_TRUE(connection_.connected());
7465 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7466 EXPECT_FALSE(connection_.IsPathDegrading());
7467
7468 const char data[] = "data";
7469 size_t data_size = strlen(data);
7470 QuicStreamOffset offset = 0;
7471
7472 for (int i = 0; i < 2; ++i) {
7473 // Send a packet. Now there's a retransmittable packet on the wire, so the
7474 // path degrading alarm should be set.
7475 connection_.SendStreamDataWithString(
7476 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
7477 offset, NO_FIN);
7478 offset += data_size;
7479 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7480 // Check the deadline of the path degrading alarm.
7481 QuicTime::Delta delay =
7482 QuicConnectionPeer::GetSentPacketManager(&connection_)
7483 ->GetPathDegradingDelay();
7484 EXPECT_EQ(clock_.ApproximateNow() + delay,
7485 connection_.GetPathDegradingAlarm()->deadline());
7486
7487 // Send a second packet. The path degrading alarm's deadline should remain
7488 // the same.
vasilvv693d5b02019-04-09 21:58:56 -07007489 // Regression test for b/69979024.
QUICHE teama6ef0a62019-03-07 20:34:33 -05007490 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7491 QuicTime prev_deadline = connection_.GetPathDegradingAlarm()->deadline();
7492 connection_.SendStreamDataWithString(
7493 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
7494 offset, NO_FIN);
7495 offset += data_size;
7496 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7497 EXPECT_EQ(prev_deadline, connection_.GetPathDegradingAlarm()->deadline());
7498
7499 // Now receive an ACK of the first packet. This should advance the path
7500 // degrading alarm's deadline since forward progress has been made.
7501 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7502 if (i == 0) {
7503 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7504 }
7505 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7506 QuicAckFrame frame = InitAckFrame(
7507 {{QuicPacketNumber(1u + 2u * i), QuicPacketNumber(2u + 2u * i)}});
7508 ProcessAckPacket(&frame);
7509 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7510 // Check the deadline of the path degrading alarm.
7511 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7512 ->GetPathDegradingDelay();
7513 EXPECT_EQ(clock_.ApproximateNow() + delay,
7514 connection_.GetPathDegradingAlarm()->deadline());
7515
7516 if (i == 0) {
7517 // Now receive an ACK of the second packet. Since there are no more
7518 // retransmittable packets on the wire, this should cancel the path
7519 // degrading alarm.
7520 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7521 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7522 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
7523 ProcessAckPacket(&frame);
7524 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7525 } else {
7526 // Advance time to the path degrading alarm's deadline and simulate
7527 // firing the alarm.
7528 clock_.AdvanceTime(delay);
7529 EXPECT_CALL(visitor_, OnPathDegrading());
7530 connection_.GetPathDegradingAlarm()->Fire();
7531 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7532 }
7533 }
7534 EXPECT_TRUE(connection_.IsPathDegrading());
7535}
7536
7537TEST_P(QuicConnectionTest, RetransmittableOnWireSetsPingAlarm) {
7538 const QuicTime::Delta retransmittable_on_wire_timeout =
7539 QuicTime::Delta::FromMilliseconds(50);
7540 connection_.set_retransmittable_on_wire_timeout(
7541 retransmittable_on_wire_timeout);
7542
7543 EXPECT_TRUE(connection_.connected());
7544 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7545 .WillRepeatedly(Return(true));
7546
7547 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7548 EXPECT_FALSE(connection_.IsPathDegrading());
7549 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
7550
7551 const char data[] = "data";
7552 size_t data_size = strlen(data);
7553 QuicStreamOffset offset = 0;
7554
7555 // Send a packet.
7556 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7557 offset += data_size;
7558 // Now there's a retransmittable packet on the wire, so the path degrading
7559 // alarm should be set.
7560 // The retransmittable-on-wire alarm should not be set.
7561 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7562 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7563 ->GetPathDegradingDelay();
7564 EXPECT_EQ(clock_.ApproximateNow() + delay,
7565 connection_.GetPathDegradingAlarm()->deadline());
7566 ASSERT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
7567 // The ping alarm is set for the ping timeout, not the shorter
7568 // retransmittable_on_wire_timeout.
7569 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7570 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
7571 EXPECT_EQ((clock_.ApproximateNow() + ping_delay),
7572 connection_.GetPingAlarm()->deadline());
7573
7574 // Now receive an ACK of the packet.
7575 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7576 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7577 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7578 QuicAckFrame frame =
7579 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7580 ProcessAckPacket(&frame);
7581 // No more retransmittable packets on the wire, so the path degrading alarm
7582 // should be cancelled, and the ping alarm should be set to the
7583 // retransmittable_on_wire_timeout.
7584 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7585 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7586 EXPECT_EQ(clock_.ApproximateNow() + retransmittable_on_wire_timeout,
7587 connection_.GetPingAlarm()->deadline());
7588
7589 // Simulate firing the ping alarm and sending a PING.
7590 clock_.AdvanceTime(retransmittable_on_wire_timeout);
7591 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
7592 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
7593 }));
7594 connection_.GetPingAlarm()->Fire();
7595
7596 // Now there's a retransmittable packet (PING) on the wire, so the path
7597 // degrading alarm should be set.
7598 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7599 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7600 ->GetPathDegradingDelay();
7601 EXPECT_EQ(clock_.ApproximateNow() + delay,
7602 connection_.GetPathDegradingAlarm()->deadline());
7603}
7604
7605// This test verifies that the connection marks path as degrading and does not
7606// spin timer to detect path degrading when a new packet is sent on the
7607// degraded path.
7608TEST_P(QuicConnectionTest, NoPathDegradingAlarmIfPathIsDegrading) {
7609 EXPECT_TRUE(connection_.connected());
7610 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7611 EXPECT_FALSE(connection_.IsPathDegrading());
7612
7613 const char data[] = "data";
7614 size_t data_size = strlen(data);
7615 QuicStreamOffset offset = 0;
7616
7617 // Send the first packet. Now there's a retransmittable packet on the wire, so
7618 // the path degrading alarm should be set.
7619 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7620 offset += data_size;
7621 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7622 // Check the deadline of the path degrading alarm.
7623 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7624 ->GetPathDegradingDelay();
7625 EXPECT_EQ(clock_.ApproximateNow() + delay,
7626 connection_.GetPathDegradingAlarm()->deadline());
7627
7628 // Send a second packet. The path degrading alarm's deadline should remain
7629 // the same.
7630 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7631 QuicTime prev_deadline = connection_.GetPathDegradingAlarm()->deadline();
7632 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7633 offset += data_size;
7634 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7635 EXPECT_EQ(prev_deadline, connection_.GetPathDegradingAlarm()->deadline());
7636
7637 // Now receive an ACK of the first packet. This should advance the path
7638 // degrading alarm's deadline since forward progress has been made.
7639 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7640 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7641 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7642 QuicAckFrame frame =
7643 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
7644 ProcessAckPacket(&frame);
7645 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7646 // Check the deadline of the path degrading alarm.
7647 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7648 ->GetPathDegradingDelay();
7649 EXPECT_EQ(clock_.ApproximateNow() + delay,
7650 connection_.GetPathDegradingAlarm()->deadline());
7651
7652 // Advance time to the path degrading alarm's deadline and simulate
7653 // firing the path degrading alarm. This path will be considered as
7654 // degrading.
7655 clock_.AdvanceTime(delay);
7656 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
7657 connection_.GetPathDegradingAlarm()->Fire();
7658 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7659 EXPECT_TRUE(connection_.IsPathDegrading());
7660
7661 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7662 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7663 // Send a third packet. The path degrading alarm is no longer set but path
7664 // should still be marked as degrading.
7665 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7666 offset += data_size;
7667 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7668 EXPECT_TRUE(connection_.IsPathDegrading());
7669}
7670
7671// This test verifies that the connection unmarks path as degrarding and spins
7672// the timer to detect future path degrading when forward progress is made
7673// after path has been marked degrading.
7674TEST_P(QuicConnectionTest, UnmarkPathDegradingOnForwardProgress) {
7675 EXPECT_TRUE(connection_.connected());
7676 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7677 EXPECT_FALSE(connection_.IsPathDegrading());
7678
7679 const char data[] = "data";
7680 size_t data_size = strlen(data);
7681 QuicStreamOffset offset = 0;
7682
7683 // Send the first packet. Now there's a retransmittable packet on the wire, so
7684 // the path degrading alarm should be set.
7685 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7686 offset += data_size;
7687 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7688 // Check the deadline of the path degrading alarm.
7689 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7690 ->GetPathDegradingDelay();
7691 EXPECT_EQ(clock_.ApproximateNow() + delay,
7692 connection_.GetPathDegradingAlarm()->deadline());
7693
7694 // Send a second packet. The path degrading alarm's deadline should remain
7695 // the same.
7696 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7697 QuicTime prev_deadline = connection_.GetPathDegradingAlarm()->deadline();
7698 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7699 offset += data_size;
7700 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7701 EXPECT_EQ(prev_deadline, connection_.GetPathDegradingAlarm()->deadline());
7702
7703 // Now receive an ACK of the first packet. This should advance the path
7704 // degrading alarm's deadline since forward progress has been made.
7705 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7706 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7707 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7708 QuicAckFrame frame =
7709 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
7710 ProcessAckPacket(&frame);
7711 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7712 // Check the deadline of the path degrading alarm.
7713 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7714 ->GetPathDegradingDelay();
7715 EXPECT_EQ(clock_.ApproximateNow() + delay,
7716 connection_.GetPathDegradingAlarm()->deadline());
7717
7718 // Advance time to the path degrading alarm's deadline and simulate
7719 // firing the alarm.
7720 clock_.AdvanceTime(delay);
7721 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
7722 connection_.GetPathDegradingAlarm()->Fire();
7723 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7724 EXPECT_TRUE(connection_.IsPathDegrading());
7725
7726 // Send a third packet. The path degrading alarm is no longer set but path
7727 // should still be marked as degrading.
7728 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7729 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7730 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7731 offset += data_size;
7732 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7733 EXPECT_TRUE(connection_.IsPathDegrading());
7734
7735 // Now receive an ACK of the second packet. This should unmark the path as
7736 // degrading. And will set a timer to detect new path degrading.
7737 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7738 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7739 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
7740 ProcessAckPacket(&frame);
7741 EXPECT_FALSE(connection_.IsPathDegrading());
7742 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7743}
7744
7745TEST_P(QuicConnectionTest, NoPathDegradingOnServer) {
QUICHE teamcd098022019-03-22 18:49:55 -07007746 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7747 return;
7748 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007749 set_perspective(Perspective::IS_SERVER);
7750 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
7751
7752 EXPECT_FALSE(connection_.IsPathDegrading());
7753 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7754
7755 // Send data.
7756 const char data[] = "data";
7757 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
7758 EXPECT_FALSE(connection_.IsPathDegrading());
7759 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7760
7761 // Ack data.
7762 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7763 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7764 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7765 QuicAckFrame frame =
7766 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
7767 ProcessAckPacket(&frame);
7768 EXPECT_FALSE(connection_.IsPathDegrading());
7769 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7770}
7771
7772TEST_P(QuicConnectionTest, NoPathDegradingAfterSendingAck) {
QUICHE teamcd098022019-03-22 18:49:55 -07007773 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7774 return;
7775 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007776 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7777 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7778 ProcessDataPacket(1);
7779 SendAckPacketToPeer();
7780 EXPECT_FALSE(connection_.sent_packet_manager().unacked_packets().empty());
7781 EXPECT_FALSE(connection_.sent_packet_manager().HasInFlightPackets());
7782 EXPECT_FALSE(connection_.IsPathDegrading());
7783 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7784}
7785
7786TEST_P(QuicConnectionTest, MultipleCallsToCloseConnection) {
7787 // Verifies that multiple calls to CloseConnection do not
7788 // result in multiple attempts to close the connection - it will be marked as
7789 // disconnected after the first call.
fkastenholz5d880a92019-06-21 09:01:56 -07007790 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007791 connection_.CloseConnection(QUIC_NO_ERROR, "no reason",
7792 ConnectionCloseBehavior::SILENT_CLOSE);
7793 connection_.CloseConnection(QUIC_NO_ERROR, "no reason",
7794 ConnectionCloseBehavior::SILENT_CLOSE);
7795}
7796
7797TEST_P(QuicConnectionTest, ServerReceivesChloOnNonCryptoStream) {
7798 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7799
7800 set_perspective(Perspective::IS_SERVER);
7801 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
7802
7803 CryptoHandshakeMessage message;
7804 CryptoFramer framer;
7805 message.set_tag(kCHLO);
QUICHE team3fe6a8b2019-03-14 09:10:38 -07007806 std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007807 frame1_.stream_id = 10;
7808 frame1_.data_buffer = data->data();
7809 frame1_.data_length = data->length();
7810
fkastenholz5d880a92019-06-21 09:01:56 -07007811 EXPECT_CALL(visitor_,
7812 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007813 ForceProcessFramePacket(QuicFrame(frame1_));
fkastenholz5d880a92019-06-21 09:01:56 -07007814 TestConnectionCloseQuicErrorCode(QUIC_MAYBE_CORRUPTED_MEMORY);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007815}
7816
7817TEST_P(QuicConnectionTest, ClientReceivesRejOnNonCryptoStream) {
7818 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7819
7820 CryptoHandshakeMessage message;
7821 CryptoFramer framer;
7822 message.set_tag(kREJ);
QUICHE team3fe6a8b2019-03-14 09:10:38 -07007823 std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007824 frame1_.stream_id = 10;
7825 frame1_.data_buffer = data->data();
7826 frame1_.data_length = data->length();
7827
fkastenholz5d880a92019-06-21 09:01:56 -07007828 EXPECT_CALL(visitor_,
7829 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007830 ForceProcessFramePacket(QuicFrame(frame1_));
fkastenholz5d880a92019-06-21 09:01:56 -07007831 TestConnectionCloseQuicErrorCode(QUIC_MAYBE_CORRUPTED_MEMORY);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007832}
7833
7834TEST_P(QuicConnectionTest, CloseConnectionOnPacketTooLarge) {
7835 SimulateNextPacketTooLarge();
7836 // A connection close packet is sent
fkastenholz5d880a92019-06-21 09:01:56 -07007837 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
QUICHE teama6ef0a62019-03-07 20:34:33 -05007838 .Times(1);
7839 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
fkastenholz5d880a92019-06-21 09:01:56 -07007840 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007841}
7842
7843TEST_P(QuicConnectionTest, AlwaysGetPacketTooLarge) {
7844 // Test even we always get packet too large, we do not infinitely try to send
7845 // close packet.
7846 AlwaysGetPacketTooLarge();
fkastenholz5d880a92019-06-21 09:01:56 -07007847 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
QUICHE teama6ef0a62019-03-07 20:34:33 -05007848 .Times(1);
7849 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
fkastenholz5d880a92019-06-21 09:01:56 -07007850 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007851}
7852
nharperef468962019-07-02 14:15:38 -07007853TEST_P(QuicConnectionTest, CloseConnectionOnQueuedWriteError) {
nharperef468962019-07-02 14:15:38 -07007854 // Regression test for crbug.com/979507.
7855 //
7856 // If we get a write error when writing queued packets, we should attempt to
7857 // send a connection close packet, but if sending that fails, it shouldn't get
7858 // queued.
7859
7860 // Queue a packet to write.
7861 BlockOnNextWrite();
7862 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7863 EXPECT_EQ(1u, connection_.NumQueuedPackets());
7864
7865 // Configure writer to always fail.
7866 AlwaysGetPacketTooLarge();
7867
7868 // Expect that we attempt to close the connection exactly once.
7869 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7870 .Times(1);
7871
7872 // Unblock the writes and actually send.
7873 writer_->SetWritable();
7874 connection_.OnCanWrite();
7875 EXPECT_EQ(0u, connection_.NumQueuedPackets());
7876
7877 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
7878}
7879
QUICHE teama6ef0a62019-03-07 20:34:33 -05007880// Verify that if connection has no outstanding data, it notifies the send
7881// algorithm after the write.
7882TEST_P(QuicConnectionTest, SendDataAndBecomeApplicationLimited) {
7883 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
7884 {
7885 InSequence seq;
7886 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7887 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7888 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
7889 .WillRepeatedly(Return(false));
7890 }
7891
7892 connection_.SendStreamData3();
7893}
7894
7895// Verify that the connection does not become app-limited if there is
7896// outstanding data to send after the write.
7897TEST_P(QuicConnectionTest, NotBecomeApplicationLimitedIfMoreDataAvailable) {
7898 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
7899 {
7900 InSequence seq;
7901 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7902 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7903 }
7904
7905 connection_.SendStreamData3();
7906}
7907
7908// Verify that the connection does not become app-limited after blocked write
7909// even if there is outstanding data to send after the write.
7910TEST_P(QuicConnectionTest, NotBecomeApplicationLimitedDueToWriteBlock) {
7911 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
7912 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7913 BlockOnNextWrite();
7914
fayang2ce66082019-10-02 06:29:04 -07007915 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
7916 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7917 } else {
7918 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
7919 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007920 connection_.SendStreamData3();
7921
7922 // Now unblock the writer, become congestion control blocked,
7923 // and ensure we become app-limited after writing.
7924 writer_->SetWritable();
7925 CongestionBlockWrites();
7926 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(false));
fayang2ce66082019-10-02 06:29:04 -07007927 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
7928 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
7929 } else {
7930 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007931 }
fayang2ce66082019-10-02 06:29:04 -07007932 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007933 connection_.OnCanWrite();
7934}
7935
7936// Test the mode in which the link is filled up with probing retransmissions if
7937// the connection becomes application-limited.
7938TEST_P(QuicConnectionTest, SendDataWhenApplicationLimited) {
7939 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7940 EXPECT_CALL(*send_algorithm_, ShouldSendProbingPacket())
7941 .WillRepeatedly(Return(true));
7942 {
7943 InSequence seq;
7944 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7945 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7946 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
7947 .WillRepeatedly(Return(false));
7948 }
QUICHE teamb8343252019-04-29 13:58:01 -07007949 EXPECT_CALL(visitor_, SendProbingData()).WillRepeatedly([this] {
7950 return connection_.sent_packet_manager().MaybeRetransmitOldestPacket(
7951 PROBING_RETRANSMISSION);
7952 });
QUICHE teama6ef0a62019-03-07 20:34:33 -05007953 // Fix congestion window to be 20,000 bytes.
7954 EXPECT_CALL(*send_algorithm_, CanSend(Ge(20000u)))
7955 .WillRepeatedly(Return(false));
7956 EXPECT_CALL(*send_algorithm_, CanSend(Lt(20000u)))
7957 .WillRepeatedly(Return(true));
7958
7959 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
7960 ASSERT_EQ(0u, connection_.GetStats().packets_sent);
7961 connection_.set_fill_up_link_during_probing(true);
7962 connection_.OnHandshakeComplete();
7963 connection_.SendStreamData3();
7964
7965 // We expect a lot of packets from a 20 kbyte window.
7966 EXPECT_GT(connection_.GetStats().packets_sent, 10u);
7967 // Ensure that the packets are padded.
7968 QuicByteCount average_packet_size =
7969 connection_.GetStats().bytes_sent / connection_.GetStats().packets_sent;
7970 EXPECT_GT(average_packet_size, 1000u);
7971
7972 // Acknowledge all packets sent, except for the last one.
7973 QuicAckFrame ack = InitAckFrame(
7974 connection_.sent_packet_manager().GetLargestSentPacket() - 1);
7975 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
7976 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7977
7978 // Ensure that since we no longer have retransmittable bytes in flight, this
7979 // will not cause any responses to be sent.
7980 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
7981 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
7982 ProcessAckPacket(&ack);
7983}
7984
7985TEST_P(QuicConnectionTest, DonotForceSendingAckOnPacketTooLarge) {
7986 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7987 // Send an ack by simulating delayed ack alarm firing.
7988 ProcessPacket(1);
7989 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
7990 EXPECT_TRUE(ack_alarm->IsSet());
7991 connection_.GetAckAlarm()->Fire();
7992 // Simulate data packet causes write error.
fkastenholz5d880a92019-06-21 09:01:56 -07007993 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007994 SimulateNextPacketTooLarge();
7995 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7996 EXPECT_EQ(1u, writer_->frame_count());
7997 EXPECT_FALSE(writer_->connection_close_frames().empty());
7998 // Ack frame is not bundled in connection close packet.
7999 EXPECT_TRUE(writer_->ack_frames().empty());
fkastenholz5d880a92019-06-21 09:01:56 -07008000 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008001}
8002
QUICHE teama6ef0a62019-03-07 20:34:33 -05008003// Regression test for b/63620844.
8004TEST_P(QuicConnectionTest, FailedToWriteHandshakePacket) {
8005 SimulateNextPacketTooLarge();
fkastenholz5d880a92019-06-21 09:01:56 -07008006 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
QUICHE teama6ef0a62019-03-07 20:34:33 -05008007 .Times(1);
fkastenholz5d880a92019-06-21 09:01:56 -07008008
QUICHE teama6ef0a62019-03-07 20:34:33 -05008009 connection_.SendCryptoStreamData();
fkastenholz5d880a92019-06-21 09:01:56 -07008010 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008011}
8012
8013TEST_P(QuicConnectionTest, MaxPacingRate) {
8014 EXPECT_EQ(0, connection_.MaxPacingRate().ToBytesPerSecond());
8015 connection_.SetMaxPacingRate(QuicBandwidth::FromBytesPerSecond(100));
8016 EXPECT_EQ(100, connection_.MaxPacingRate().ToBytesPerSecond());
8017}
8018
8019TEST_P(QuicConnectionTest, ClientAlwaysSendConnectionId) {
8020 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
8021 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8022 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
8023 EXPECT_EQ(CONNECTION_ID_PRESENT,
8024 writer_->last_packet_header().destination_connection_id_included);
8025
8026 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8027 QuicConfig config;
8028 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
8029 connection_.SetFromConfig(config);
8030
8031 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8032 connection_.SendStreamDataWithString(3, "bar", 3, NO_FIN);
8033 // Verify connection id is still sent in the packet.
8034 EXPECT_EQ(CONNECTION_ID_PRESENT,
8035 writer_->last_packet_header().destination_connection_id_included);
8036}
8037
8038TEST_P(QuicConnectionTest, SendProbingRetransmissions) {
8039 MockQuicConnectionDebugVisitor debug_visitor;
8040 connection_.set_debug_visitor(&debug_visitor);
8041
8042 const QuicStreamId stream_id = 2;
8043 QuicPacketNumber last_packet;
8044 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
8045 SendStreamDataToPeer(stream_id, "bar", 3, NO_FIN, &last_packet);
8046 SendStreamDataToPeer(stream_id, "test", 6, NO_FIN, &last_packet);
8047
8048 const QuicByteCount old_bytes_in_flight =
8049 connection_.sent_packet_manager().GetBytesInFlight();
8050
8051 // Allow 9 probing retransmissions to be sent.
8052 {
8053 InSequence seq;
8054 EXPECT_CALL(*send_algorithm_, CanSend(_))
8055 .Times(9 * 2)
8056 .WillRepeatedly(Return(true));
8057 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(Return(false));
8058 }
8059 // Expect them retransmitted in cyclic order (foo, bar, test, foo, bar...).
8060 QuicPacketCount sent_count = 0;
8061 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _))
8062 .WillRepeatedly(Invoke([this, &sent_count](const SerializedPacket&,
8063 QuicPacketNumber,
8064 TransmissionType, QuicTime) {
8065 ASSERT_EQ(1u, writer_->stream_frames().size());
8066 // Identify the frames by stream offset (0, 3, 6, 0, 3...).
8067 EXPECT_EQ(3 * (sent_count % 3), writer_->stream_frames()[0]->offset);
8068 sent_count++;
8069 }));
8070 EXPECT_CALL(*send_algorithm_, ShouldSendProbingPacket())
8071 .WillRepeatedly(Return(true));
QUICHE teamb8343252019-04-29 13:58:01 -07008072 EXPECT_CALL(visitor_, SendProbingData()).WillRepeatedly([this] {
8073 return connection_.sent_packet_manager().MaybeRetransmitOldestPacket(
8074 PROBING_RETRANSMISSION);
8075 });
QUICHE teama6ef0a62019-03-07 20:34:33 -05008076
8077 connection_.SendProbingRetransmissions();
8078
8079 // Ensure that the in-flight has increased.
8080 const QuicByteCount new_bytes_in_flight =
8081 connection_.sent_packet_manager().GetBytesInFlight();
8082 EXPECT_GT(new_bytes_in_flight, old_bytes_in_flight);
8083}
8084
8085// Ensure that SendProbingRetransmissions() does not retransmit anything when
8086// there are no outstanding packets.
8087TEST_P(QuicConnectionTest,
8088 SendProbingRetransmissionsFailsWhenNothingToRetransmit) {
8089 ASSERT_TRUE(connection_.sent_packet_manager().unacked_packets().empty());
8090
8091 MockQuicConnectionDebugVisitor debug_visitor;
8092 connection_.set_debug_visitor(&debug_visitor);
8093 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _)).Times(0);
8094 EXPECT_CALL(*send_algorithm_, ShouldSendProbingPacket())
8095 .WillRepeatedly(Return(true));
QUICHE teamb8343252019-04-29 13:58:01 -07008096 EXPECT_CALL(visitor_, SendProbingData()).WillRepeatedly([this] {
8097 return connection_.sent_packet_manager().MaybeRetransmitOldestPacket(
8098 PROBING_RETRANSMISSION);
8099 });
QUICHE teama6ef0a62019-03-07 20:34:33 -05008100
8101 connection_.SendProbingRetransmissions();
8102}
8103
8104TEST_P(QuicConnectionTest, PingAfterLastRetransmittablePacketAcked) {
8105 const QuicTime::Delta retransmittable_on_wire_timeout =
8106 QuicTime::Delta::FromMilliseconds(50);
8107 connection_.set_retransmittable_on_wire_timeout(
8108 retransmittable_on_wire_timeout);
8109
8110 EXPECT_TRUE(connection_.connected());
8111 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8112 .WillRepeatedly(Return(true));
8113
8114 const char data[] = "data";
8115 size_t data_size = strlen(data);
8116 QuicStreamOffset offset = 0;
8117
8118 // Advance 5ms, send a retransmittable packet to the peer.
8119 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8120 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8121 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8122 offset += data_size;
8123 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8124 // The ping alarm is set for the ping timeout, not the shorter
8125 // retransmittable_on_wire_timeout.
8126 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8127 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
8128 EXPECT_EQ((clock_.ApproximateNow() + ping_delay),
8129 connection_.GetPingAlarm()->deadline());
8130
8131 // Advance 5ms, send a second retransmittable packet to the peer.
8132 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8133 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8134 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8135 offset += data_size;
8136 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8137
8138 // Now receive an ACK of the first packet. This should not set the
8139 // retransmittable-on-wire alarm since packet 2 is still on the wire.
8140 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8141 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8142 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8143 QuicAckFrame frame =
8144 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8145 ProcessAckPacket(&frame);
8146 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8147 // The ping alarm is set for the ping timeout, not the shorter
8148 // retransmittable_on_wire_timeout.
8149 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8150 // The ping alarm has a 1 second granularity, and the clock has been advanced
8151 // 10ms since it was originally set.
8152 EXPECT_EQ((clock_.ApproximateNow() + ping_delay -
8153 QuicTime::Delta::FromMilliseconds(10)),
8154 connection_.GetPingAlarm()->deadline());
8155
8156 // Now receive an ACK of the second packet. This should set the
8157 // retransmittable-on-wire alarm now that no retransmittable packets are on
8158 // the wire.
8159 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8160 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8161 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8162 ProcessAckPacket(&frame);
8163 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8164 EXPECT_EQ(clock_.ApproximateNow() + retransmittable_on_wire_timeout,
8165 connection_.GetPingAlarm()->deadline());
8166
8167 // Now receive a duplicate ACK of the second packet. This should not update
8168 // the ping alarm.
8169 QuicTime prev_deadline = connection_.GetPingAlarm()->deadline();
8170 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8171 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8172 ProcessAckPacket(&frame);
8173 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8174 EXPECT_EQ(prev_deadline, connection_.GetPingAlarm()->deadline());
8175
8176 // Now receive a non-ACK packet. This should not update the ping alarm.
8177 prev_deadline = connection_.GetPingAlarm()->deadline();
8178 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8179 ProcessPacket(4);
8180 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8181 EXPECT_EQ(prev_deadline, connection_.GetPingAlarm()->deadline());
8182
8183 // Simulate the alarm firing and check that a PING is sent.
8184 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8185 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
8186 }));
8187 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07008188 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05008189 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07008190 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008191 } else {
nharper55fa6132019-05-07 19:37:21 -07008192 EXPECT_EQ(padding_frame_count + 3u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008193 }
8194 ASSERT_EQ(1u, writer_->ping_frames().size());
8195}
8196
8197TEST_P(QuicConnectionTest, NoPingIfRetransmittablePacketSent) {
8198 const QuicTime::Delta retransmittable_on_wire_timeout =
8199 QuicTime::Delta::FromMilliseconds(50);
8200 connection_.set_retransmittable_on_wire_timeout(
8201 retransmittable_on_wire_timeout);
8202
8203 EXPECT_TRUE(connection_.connected());
8204 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8205 .WillRepeatedly(Return(true));
8206
8207 const char data[] = "data";
8208 size_t data_size = strlen(data);
8209 QuicStreamOffset offset = 0;
8210
8211 // Advance 5ms, send a retransmittable packet to the peer.
8212 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8213 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8214 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8215 offset += data_size;
8216 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8217 // The ping alarm is set for the ping timeout, not the shorter
8218 // retransmittable_on_wire_timeout.
8219 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8220 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
8221 EXPECT_EQ((clock_.ApproximateNow() + ping_delay),
8222 connection_.GetPingAlarm()->deadline());
8223
8224 // Now receive an ACK of the first packet. This should set the
8225 // retransmittable-on-wire alarm now that no retransmittable packets are on
8226 // the wire.
8227 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8228 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8229 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8230 QuicAckFrame frame =
8231 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8232 ProcessAckPacket(&frame);
8233 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8234 EXPECT_EQ(clock_.ApproximateNow() + retransmittable_on_wire_timeout,
8235 connection_.GetPingAlarm()->deadline());
8236
8237 // Before the alarm fires, send another retransmittable packet. This should
8238 // cancel the retransmittable-on-wire alarm since now there's a
8239 // retransmittable packet on the wire.
8240 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8241 offset += data_size;
8242 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8243
8244 // Now receive an ACK of the second packet. This should set the
8245 // retransmittable-on-wire alarm now that no retransmittable packets are on
8246 // the wire.
8247 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8248 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8249 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8250 ProcessAckPacket(&frame);
8251 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8252 EXPECT_EQ(clock_.ApproximateNow() + retransmittable_on_wire_timeout,
8253 connection_.GetPingAlarm()->deadline());
8254
8255 // Simulate the alarm firing and check that a PING is sent.
8256 writer_->Reset();
8257 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8258 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
8259 }));
8260 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07008261 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05008262 if (GetParam().no_stop_waiting) {
fayange8b0cab2019-07-17 14:23:07 -07008263 if (GetQuicReloadableFlag(quic_simplify_stop_waiting)) {
8264 // Do not ACK acks.
8265 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
8266 } else {
8267 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
8268 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008269 } else {
nharper55fa6132019-05-07 19:37:21 -07008270 EXPECT_EQ(padding_frame_count + 3u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008271 }
8272 ASSERT_EQ(1u, writer_->ping_frames().size());
8273}
8274
8275TEST_P(QuicConnectionTest, OnForwardProgressConfirmed) {
8276 EXPECT_CALL(visitor_, OnForwardProgressConfirmed()).Times(Exactly(0));
8277 EXPECT_TRUE(connection_.connected());
8278
8279 const char data[] = "data";
8280 size_t data_size = strlen(data);
8281 QuicStreamOffset offset = 0;
8282
8283 // Send two packets.
8284 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8285 offset += data_size;
8286 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8287 offset += data_size;
8288
8289 // Ack packet 1. This increases the largest_acked to 1, so
8290 // OnForwardProgressConfirmed() should be called
8291 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8292 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8293 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8294 EXPECT_CALL(visitor_, OnForwardProgressConfirmed());
8295 QuicAckFrame frame =
8296 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8297 ProcessAckPacket(&frame);
8298
8299 // Ack packet 1 again. largest_acked remains at 1, so
8300 // OnForwardProgressConfirmed() should not be called.
8301 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8302 frame = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8303 ProcessAckPacket(&frame);
8304
8305 // Ack packet 2. This increases the largest_acked to 2, so
8306 // OnForwardProgressConfirmed() should be called.
8307 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8308 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8309 EXPECT_CALL(visitor_, OnForwardProgressConfirmed());
8310 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8311 ProcessAckPacket(&frame);
8312}
8313
8314TEST_P(QuicConnectionTest, ValidStatelessResetToken) {
8315 const QuicUint128 kTestToken = 1010101;
8316 const QuicUint128 kWrongTestToken = 1010100;
8317 QuicConfig config;
8318 // No token has been received.
8319 EXPECT_FALSE(connection_.IsValidStatelessResetToken(kTestToken));
8320
8321 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(2);
8322 // Token is different from received token.
8323 QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestToken);
8324 connection_.SetFromConfig(config);
8325 EXPECT_FALSE(connection_.IsValidStatelessResetToken(kWrongTestToken));
8326
8327 QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestToken);
8328 connection_.SetFromConfig(config);
8329 EXPECT_TRUE(connection_.IsValidStatelessResetToken(kTestToken));
8330}
8331
8332TEST_P(QuicConnectionTest, WriteBlockedWithInvalidAck) {
8333 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang2ce66082019-10-02 06:29:04 -07008334 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
8335 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
8336 } else {
8337 EXPECT_CALL(visitor_, OnConnectionClosed(_, _))
8338 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
8339 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008340 BlockOnNextWrite();
fayang2ce66082019-10-02 06:29:04 -07008341 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
8342 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8343 } else {
8344 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8345 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008346 connection_.SendStreamDataWithString(5, "foo", 0, FIN);
8347 // This causes connection to be closed because packet 1 has not been sent yet.
8348 QuicAckFrame frame = InitAckFrame(1);
fayang2ce66082019-10-02 06:29:04 -07008349 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
8350 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
8351 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008352 ProcessAckPacket(1, &frame);
fayang2ce66082019-10-02 06:29:04 -07008353 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
8354 EXPECT_EQ(0, connection_close_frame_count_);
8355 } else {
8356 EXPECT_EQ(1, connection_close_frame_count_);
8357 EXPECT_EQ(QUIC_INVALID_ACK_DATA,
8358 saved_connection_close_frame_.quic_error_code);
8359 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008360}
8361
8362TEST_P(QuicConnectionTest, SendMessage) {
fayangc31c9952019-06-05 13:54:48 -07008363 if (!VersionSupportsMessageFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008364 return;
8365 }
ianswettb239f862019-04-05 09:15:06 -07008366 std::string message(connection_.GetCurrentLargestMessagePayload() * 2, 'a');
QUICHE teama6ef0a62019-03-07 20:34:33 -05008367 QuicStringPiece message_data(message);
8368 QuicMemSliceStorage storage(nullptr, 0, nullptr, 0);
8369 {
fayanga4b37b22019-06-18 13:37:47 -07008370 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008371 connection_.SendStreamData3();
8372 // Send a message which cannot fit into current open packet, and 2 packets
8373 // get sent, one contains stream frame, and the other only contains the
8374 // message frame.
8375 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
8376 EXPECT_EQ(
8377 MESSAGE_STATUS_SUCCESS,
8378 connection_.SendMessage(
8379 1, MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(),
ianswettb239f862019-04-05 09:15:06 -07008380 QuicStringPiece(
8381 message_data.data(),
8382 connection_.GetCurrentLargestMessagePayload()),
QUICHE teama6ef0a62019-03-07 20:34:33 -05008383 &storage)));
8384 }
8385 // Fail to send a message if connection is congestion control blocked.
8386 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(Return(false));
8387 EXPECT_EQ(
8388 MESSAGE_STATUS_BLOCKED,
8389 connection_.SendMessage(
8390 2, MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(),
8391 "message", &storage)));
8392
8393 // Always fail to send a message which cannot fit into one packet.
8394 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8395 EXPECT_EQ(
8396 MESSAGE_STATUS_TOO_LARGE,
8397 connection_.SendMessage(
ianswettb239f862019-04-05 09:15:06 -07008398 3, MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(),
8399 QuicStringPiece(
8400 message_data.data(),
8401 connection_.GetCurrentLargestMessagePayload() + 1),
8402 &storage)));
QUICHE teama6ef0a62019-03-07 20:34:33 -05008403}
8404
8405// Test to check that the path challenge/path response logic works
8406// correctly. This test is only for version-99
8407TEST_P(QuicConnectionTest, PathChallengeResponse) {
fkastenholz305e1732019-06-18 05:01:22 -07008408 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008409 return;
8410 }
8411 // First check if we can probe from server to client and back
8412 set_perspective(Perspective::IS_SERVER);
8413 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
8414
8415 // Create and send the probe request (PATH_CHALLENGE frame).
8416 // SendConnectivityProbingPacket ends up calling
8417 // TestPacketWriter::WritePacket() which in turns receives and parses the
8418 // packet by calling framer_.ProcessPacket() -- which in turn calls
8419 // SimpleQuicFramer::OnPathChallengeFrame(). SimpleQuicFramer saves
8420 // the packet in writer_->path_challenge_frames()
8421 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8422 connection_.SendConnectivityProbingPacket(writer_.get(),
8423 connection_.peer_address());
8424 // Save the random contents of the challenge for later comparison to the
8425 // response.
nharper55fa6132019-05-07 19:37:21 -07008426 ASSERT_GE(writer_->path_challenge_frames().size(), 1u);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008427 QuicPathFrameBuffer challenge_data =
8428 writer_->path_challenge_frames().front().data_buffer;
8429
8430 // Normally, QuicConnection::OnPathChallengeFrame and OnPaddingFrame would be
8431 // called and it will perform actions to ensure that the rest of the protocol
8432 // is performed (specifically, call UpdatePacketContent to say that this is a
8433 // path challenge so that when QuicConnection::OnPacketComplete is called
8434 // (again, out of the framer), the response is generated). Simulate those
8435 // calls so that the right internal state is set up for generating
8436 // the response.
8437 EXPECT_TRUE(connection_.OnPathChallengeFrame(
8438 writer_->path_challenge_frames().front()));
8439 EXPECT_TRUE(connection_.OnPaddingFrame(writer_->padding_frames().front()));
8440 // Cause the response to be created and sent. Result is that the response
8441 // should be stashed in writer's path_response_frames.
8442 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8443 connection_.SendConnectivityProbingResponsePacket(connection_.peer_address());
8444
8445 // The final check is to ensure that the random data in the response matches
8446 // the random data from the challenge.
8447 EXPECT_EQ(0, memcmp(&challenge_data,
8448 &(writer_->path_response_frames().front().data_buffer),
8449 sizeof(challenge_data)));
8450}
8451
8452// Regression test for b/110259444
8453TEST_P(QuicConnectionTest, DoNotScheduleSpuriousAckAlarm) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008454 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8455 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
8456 writer_->SetWriteBlocked();
8457
8458 ProcessPacket(1);
8459 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
8460 // Verify ack alarm is set.
8461 EXPECT_TRUE(ack_alarm->IsSet());
8462 // Fire the ack alarm, verify no packet is sent because the writer is blocked.
8463 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8464 connection_.GetAckAlarm()->Fire();
8465
8466 writer_->SetWritable();
8467 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8468 ProcessPacket(2);
8469 // Verify ack alarm is not set.
8470 EXPECT_FALSE(ack_alarm->IsSet());
8471}
8472
8473TEST_P(QuicConnectionTest, DisablePacingOffloadConnectionOptions) {
8474 EXPECT_FALSE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
8475 writer_->set_supports_release_time(true);
8476 QuicConfig config;
8477 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8478 connection_.SetFromConfig(config);
8479 EXPECT_TRUE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
8480
8481 QuicTagVector connection_options;
8482 connection_options.push_back(kNPCO);
8483 config.SetConnectionOptionsToSend(connection_options);
8484 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8485 connection_.SetFromConfig(config);
8486 // Verify pacing offload is disabled.
8487 EXPECT_FALSE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
8488}
8489
8490// Regression test for b/110259444
8491// Get a path response without having issued a path challenge...
8492TEST_P(QuicConnectionTest, OrphanPathResponse) {
8493 QuicPathFrameBuffer data = {{0, 1, 2, 3, 4, 5, 6, 7}};
8494
8495 QuicPathResponseFrame frame(99, data);
8496 EXPECT_TRUE(connection_.OnPathResponseFrame(frame));
8497 // If PATH_RESPONSE was accepted (payload matches the payload saved
8498 // in QuicConnection::transmitted_connectivity_probe_payload_) then
8499 // current_packet_content_ would be set to FIRST_FRAME_IS_PING.
8500 // Since this PATH_RESPONSE does not match, current_packet_content_
8501 // must not be FIRST_FRAME_IS_PING.
8502 EXPECT_NE(QuicConnection::FIRST_FRAME_IS_PING,
8503 QuicConnectionPeer::GetCurrentPacketContent(&connection_));
8504}
8505
8506// Regression test for b/120791670
8507TEST_P(QuicConnectionTest, StopProcessingGQuicPacketInIetfQuicConnection) {
8508 // This test mimics a problematic scenario where an IETF QUIC connection
8509 // receives a Google QUIC packet and continue processing it using Google QUIC
8510 // wire format.
fayangd4291e42019-05-30 10:31:21 -07008511 if (!VersionHasIetfInvariantHeader(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008512 return;
8513 }
8514 set_perspective(Perspective::IS_SERVER);
nharper46833c32019-05-15 21:33:05 -07008515 QuicFrame frame;
8516 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
8517 frame = QuicFrame(&crypto_frame_);
8518 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
8519 } else {
8520 frame = QuicFrame(QuicStreamFrame(
8521 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
8522 0u, QuicStringPiece()));
8523 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
8524 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008525 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
nharper46833c32019-05-15 21:33:05 -07008526 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008527
8528 // Let connection process a Google QUIC packet.
8529 peer_framer_.set_version_for_tests(
8530 ParsedQuicVersion(PROTOCOL_QUIC_CRYPTO, QUIC_VERSION_43));
QUICHE team8c1daa22019-03-13 08:33:41 -07008531 std::unique_ptr<QuicPacket> packet(
QUICHE team6987b4a2019-03-15 16:23:04 -07008532 ConstructDataPacket(2, !kHasStopWaiting, ENCRYPTION_INITIAL));
dschinazi66dea072019-04-09 11:41:06 -07008533 char buffer[kMaxOutgoingPacketSize];
8534 size_t encrypted_length =
8535 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(2),
8536 *packet, buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008537 // Make sure no stream frame is processed.
8538 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(0);
8539 connection_.ProcessUdpPacket(
8540 kSelfAddress, kPeerAddress,
8541 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
8542
8543 EXPECT_EQ(2u, connection_.GetStats().packets_received);
8544 EXPECT_EQ(1u, connection_.GetStats().packets_processed);
8545}
8546
8547TEST_P(QuicConnectionTest, AcceptPacketNumberZero) {
fkastenholz305e1732019-06-18 05:01:22 -07008548 if (!VersionHasIetfQuicFrames(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008549 return;
8550 }
8551 // Set first_sending_packet_number to be 0 to allow successfully processing
8552 // acks which ack packet number 0.
8553 QuicFramerPeer::SetFirstSendingPacketNumber(writer_->framer()->framer(), 0);
8554 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8555
8556 ProcessPacket(0);
fayangc31c9952019-06-05 13:54:48 -07008557 EXPECT_EQ(QuicPacketNumber(0), LargestAcked(connection_.ack_frame()));
8558 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008559
8560 ProcessPacket(1);
fayangc31c9952019-06-05 13:54:48 -07008561 EXPECT_EQ(QuicPacketNumber(1), LargestAcked(connection_.ack_frame()));
8562 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008563
8564 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07008565 EXPECT_EQ(QuicPacketNumber(2), LargestAcked(connection_.ack_frame()));
8566 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008567}
8568
QUICHE teamcd098022019-03-22 18:49:55 -07008569TEST_P(QuicConnectionTest, MultiplePacketNumberSpacesBasicSending) {
8570 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8571 return;
8572 }
8573 use_tagging_decrypter();
8574 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07008575 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teamcd098022019-03-22 18:49:55 -07008576
8577 connection_.SendCryptoStreamData();
8578 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8579 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
8580 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8581 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8582 QuicAckFrame frame1 = InitAckFrame(1);
8583 // Received ACK for packet 1.
8584 ProcessFramePacketAtLevel(30, QuicFrame(&frame1), ENCRYPTION_INITIAL);
8585
8586 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(4);
8587 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
8588 NO_FIN);
8589 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 4,
8590 NO_FIN);
8591 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
8592 8, NO_FIN);
8593 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
8594 12, FIN);
8595 // Received ACK for packets 2, 4, 5.
8596 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
8597 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8598 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8599 QuicAckFrame frame2 =
8600 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)},
8601 {QuicPacketNumber(4), QuicPacketNumber(6)}});
8602 // Make sure although the same packet number is used, but they are in
8603 // different packet number spaces.
8604 ProcessFramePacketAtLevel(30, QuicFrame(&frame2), ENCRYPTION_FORWARD_SECURE);
8605}
8606
8607TEST_P(QuicConnectionTest, PeerAcksPacketsInWrongPacketNumberSpace) {
8608 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8609 return;
8610 }
8611 use_tagging_decrypter();
8612 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07008613 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teamcd098022019-03-22 18:49:55 -07008614
8615 connection_.SendCryptoStreamData();
8616 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8617 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
8618 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8619 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8620 QuicAckFrame frame1 = InitAckFrame(1);
8621 // Received ACK for packet 1.
8622 ProcessFramePacketAtLevel(30, QuicFrame(&frame1), ENCRYPTION_INITIAL);
8623
8624 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
8625 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
8626 NO_FIN);
8627 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 4,
8628 NO_FIN);
8629
8630 // Received ACK for packets 2 and 3 in wrong packet number space.
8631 QuicAckFrame invalid_ack =
8632 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(4)}});
fkastenholz5d880a92019-06-21 09:01:56 -07008633 EXPECT_CALL(visitor_,
8634 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teamcd098022019-03-22 18:49:55 -07008635 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8636 ProcessFramePacketAtLevel(300, QuicFrame(&invalid_ack), ENCRYPTION_INITIAL);
fkastenholz5d880a92019-06-21 09:01:56 -07008637 TestConnectionCloseQuicErrorCode(QUIC_INVALID_ACK_DATA);
QUICHE teamcd098022019-03-22 18:49:55 -07008638}
8639
8640TEST_P(QuicConnectionTest, MultiplePacketNumberSpacesBasicReceiving) {
8641 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8642 return;
8643 }
8644 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
nharper46833c32019-05-15 21:33:05 -07008645 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
8646 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
8647 }
QUICHE teamcd098022019-03-22 18:49:55 -07008648 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
8649 use_tagging_decrypter();
8650 // Receives packet 1000 in initial data.
nharper46833c32019-05-15 21:33:05 -07008651 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
QUICHE teamcd098022019-03-22 18:49:55 -07008652 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
8653 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07008654 std::make_unique<TaggingEncrypter>(0x02));
zhongyi546cc452019-04-12 15:27:49 -07008655 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07008656 std::make_unique<StrictTaggingDecrypter>(0x02));
QUICHE teamcd098022019-03-22 18:49:55 -07008657 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07008658 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teamcd098022019-03-22 18:49:55 -07008659 // Receives packet 1000 in application data.
8660 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
8661 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
8662 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
8663 NO_FIN);
8664 // Verify application data ACK gets bundled with outgoing data.
8665 EXPECT_EQ(2u, writer_->frame_count());
8666 // Make sure ACK alarm is still set because initial data is not ACKed.
8667 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
8668 // Receive packet 1001 in application data.
8669 ProcessDataPacketAtLevel(1001, false, ENCRYPTION_ZERO_RTT);
8670 clock_.AdvanceTime(DefaultRetransmissionTime());
8671 // Simulates ACK alarm fires and verify two ACKs are flushed.
8672 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
8673 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07008674 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teamcd098022019-03-22 18:49:55 -07008675 connection_.GetAckAlarm()->Fire();
8676 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
8677 // Receives more packets in application data.
8678 ProcessDataPacketAtLevel(1002, false, ENCRYPTION_ZERO_RTT);
8679 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
8680
8681 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07008682 std::make_unique<TaggingEncrypter>(0x02));
zhongyi546cc452019-04-12 15:27:49 -07008683 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07008684 std::make_unique<StrictTaggingDecrypter>(0x02));
QUICHE teamcd098022019-03-22 18:49:55 -07008685 // Verify zero rtt and forward secure packets get acked in the same packet.
8686 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
nharper2c9f02a2019-05-08 10:25:50 -07008687 ProcessDataPacket(1003);
QUICHE teamcd098022019-03-22 18:49:55 -07008688 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
8689}
8690
QUICHE team552f71f2019-03-23 15:37:59 -07008691TEST_P(QuicConnectionTest, CancelAckAlarmOnWriteBlocked) {
8692 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8693 return;
8694 }
8695 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
nharper46833c32019-05-15 21:33:05 -07008696 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
8697 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
8698 }
QUICHE team552f71f2019-03-23 15:37:59 -07008699 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
8700 use_tagging_decrypter();
8701 // Receives packet 1000 in initial data.
nharper46833c32019-05-15 21:33:05 -07008702 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
QUICHE team552f71f2019-03-23 15:37:59 -07008703 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
8704 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07008705 std::make_unique<TaggingEncrypter>(0x02));
zhongyi546cc452019-04-12 15:27:49 -07008706 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07008707 std::make_unique<StrictTaggingDecrypter>(0x02));
QUICHE team552f71f2019-03-23 15:37:59 -07008708 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07008709 std::make_unique<TaggingEncrypter>(0x02));
QUICHE team552f71f2019-03-23 15:37:59 -07008710 // Receives packet 1000 in application data.
8711 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
8712 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
8713
8714 writer_->SetWriteBlocked();
8715 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AnyNumber());
8716 // Simulates ACK alarm fires and verify no ACK is flushed because of write
8717 // blocked.
8718 clock_.AdvanceTime(DefaultDelayedAckTime());
8719 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8720 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07008721 std::make_unique<TaggingEncrypter>(0x02));
QUICHE team552f71f2019-03-23 15:37:59 -07008722 connection_.GetAckAlarm()->Fire();
8723 // Verify ACK alarm is not set.
8724 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
8725
8726 writer_->SetWritable();
8727 // Verify 2 ACKs are sent when connection gets unblocked.
8728 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
8729 connection_.OnCanWrite();
8730 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
8731}
8732
dschinazi346b7ce2019-06-05 01:38:18 -07008733// Make sure a packet received with the right client connection ID is processed.
8734TEST_P(QuicConnectionTest, ValidClientConnectionId) {
dschinazi346b7ce2019-06-05 01:38:18 -07008735 if (!framer_.version().SupportsClientConnectionIds()) {
8736 return;
8737 }
8738 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8739 connection_.set_client_connection_id(TestConnectionId(0x33));
8740 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_FORWARD_SECURE);
8741 header.destination_connection_id = TestConnectionId(0x33);
8742 header.destination_connection_id_included = CONNECTION_ID_PRESENT;
8743 header.source_connection_id_included = CONNECTION_ID_ABSENT;
8744 QuicFrames frames;
8745 QuicPingFrame ping_frame;
8746 QuicPaddingFrame padding_frame;
8747 frames.push_back(QuicFrame(ping_frame));
8748 frames.push_back(QuicFrame(padding_frame));
8749 std::unique_ptr<QuicPacket> packet =
8750 BuildUnsizedDataPacket(&framer_, header, frames);
8751 char buffer[kMaxOutgoingPacketSize];
8752 size_t encrypted_length = peer_framer_.EncryptPayload(
8753 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
8754 kMaxOutgoingPacketSize);
8755 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
8756 false);
8757 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
8758 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
8759 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
8760}
8761
8762// Make sure a packet received with a different client connection ID is dropped.
8763TEST_P(QuicConnectionTest, InvalidClientConnectionId) {
dschinazi346b7ce2019-06-05 01:38:18 -07008764 if (!framer_.version().SupportsClientConnectionIds()) {
8765 return;
8766 }
8767 connection_.set_client_connection_id(TestConnectionId(0x33));
8768 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_FORWARD_SECURE);
8769 header.destination_connection_id = TestConnectionId(0xbad);
8770 header.destination_connection_id_included = CONNECTION_ID_PRESENT;
8771 header.source_connection_id_included = CONNECTION_ID_ABSENT;
8772 QuicFrames frames;
8773 QuicPingFrame ping_frame;
8774 QuicPaddingFrame padding_frame;
8775 frames.push_back(QuicFrame(ping_frame));
8776 frames.push_back(QuicFrame(padding_frame));
8777 std::unique_ptr<QuicPacket> packet =
8778 BuildUnsizedDataPacket(&framer_, header, frames);
8779 char buffer[kMaxOutgoingPacketSize];
8780 size_t encrypted_length = peer_framer_.EncryptPayload(
8781 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
8782 kMaxOutgoingPacketSize);
8783 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
8784 false);
8785 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
8786 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
8787 EXPECT_EQ(1u, connection_.GetStats().packets_dropped);
8788}
8789
8790// Make sure the first packet received with a different client connection ID on
8791// the server is processed and it changes the client connection ID.
8792TEST_P(QuicConnectionTest, UpdateClientConnectionIdFromFirstPacket) {
dschinazi346b7ce2019-06-05 01:38:18 -07008793 if (!framer_.version().SupportsClientConnectionIds()) {
8794 return;
8795 }
8796 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8797 set_perspective(Perspective::IS_SERVER);
8798 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_INITIAL);
8799 header.source_connection_id = TestConnectionId(0x33);
8800 header.source_connection_id_included = CONNECTION_ID_PRESENT;
8801 QuicFrames frames;
8802 QuicPingFrame ping_frame;
8803 QuicPaddingFrame padding_frame;
8804 frames.push_back(QuicFrame(ping_frame));
8805 frames.push_back(QuicFrame(padding_frame));
8806 std::unique_ptr<QuicPacket> packet =
8807 BuildUnsizedDataPacket(&framer_, header, frames);
8808 char buffer[kMaxOutgoingPacketSize];
nharperc6b99512019-09-19 11:13:48 -07008809 size_t encrypted_length =
8810 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(1),
8811 *packet, buffer, kMaxOutgoingPacketSize);
dschinazi346b7ce2019-06-05 01:38:18 -07008812 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
8813 false);
8814 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
8815 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
8816 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
8817 EXPECT_EQ(TestConnectionId(0x33), connection_.client_connection_id());
8818}
8819
fayang40ec3ac2019-06-05 09:07:54 -07008820// Regression test for b/134416344.
8821TEST_P(QuicConnectionTest, CheckConnectedBeforeFlush) {
8822 // This test mimics a scenario where a connection processes 2 packets and the
8823 // 2nd packet contains connection close frame. When the 2nd flusher goes out
8824 // of scope, a delayed ACK is pending, and ACK alarm should not be scheduled
8825 // because connection is disconnected.
8826 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fkastenholz5d880a92019-06-21 09:01:56 -07008827 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
fayang40ec3ac2019-06-05 09:07:54 -07008828 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
fkastenholz88d08f42019-09-06 07:38:04 -07008829 const QuicErrorCode kErrorCode = QUIC_INTERNAL_ERROR;
fayang40ec3ac2019-06-05 09:07:54 -07008830 std::unique_ptr<QuicConnectionCloseFrame> connection_close_frame(
fkastenholz591814c2019-09-06 12:11:46 -07008831 new QuicConnectionCloseFrame(connection_.transport_version(), kErrorCode,
8832 "",
8833 /*transport_close_frame_type=*/0));
8834
fayang40ec3ac2019-06-05 09:07:54 -07008835 // Received 2 packets.
8836 QuicFrame frame;
8837 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
8838 frame = QuicFrame(&crypto_frame_);
8839 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
8840 } else {
8841 frame = QuicFrame(QuicStreamFrame(
8842 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
8843 0u, QuicStringPiece()));
8844 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
8845 }
8846 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
8847 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
8848 EXPECT_TRUE(ack_alarm->IsSet());
8849 ProcessFramePacketWithAddresses(QuicFrame(connection_close_frame.get()),
8850 kSelfAddress, kPeerAddress);
fayang0f0c4e62019-07-16 08:55:54 -07008851 // Verify ack alarm is not set.
8852 EXPECT_FALSE(ack_alarm->IsSet());
fayang40ec3ac2019-06-05 09:07:54 -07008853}
8854
dschinazi8d551132019-08-02 19:17:16 -07008855// Verify that a packet containing three coalesced packets is parsed correctly.
8856TEST_P(QuicConnectionTest, CoalescedPacket) {
8857 if (!QuicVersionHasLongHeaderLengths(connection_.transport_version())) {
8858 // Coalesced packets can only be encoded using long header lengths.
8859 return;
8860 }
8861 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8862 EXPECT_TRUE(connection_.connected());
8863 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
8864 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(3);
8865 } else {
8866 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(3);
8867 }
8868
8869 uint64_t packet_numbers[3] = {1, 2, 3};
8870 EncryptionLevel encryption_levels[3] = {
8871 ENCRYPTION_INITIAL, ENCRYPTION_INITIAL, ENCRYPTION_FORWARD_SECURE};
8872 char buffer[kMaxOutgoingPacketSize] = {};
8873 size_t total_encrypted_length = 0;
8874 for (int i = 0; i < 3; i++) {
8875 QuicPacketHeader header =
8876 ConstructPacketHeader(packet_numbers[i], encryption_levels[i]);
8877 QuicFrames frames;
8878 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
8879 frames.push_back(QuicFrame(&crypto_frame_));
8880 } else {
8881 frames.push_back(QuicFrame(frame1_));
8882 }
8883 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
8884 peer_creator_.set_encryption_level(encryption_levels[i]);
8885 size_t encrypted_length = peer_framer_.EncryptPayload(
8886 encryption_levels[i], QuicPacketNumber(packet_numbers[i]), *packet,
8887 buffer + total_encrypted_length,
8888 sizeof(buffer) - total_encrypted_length);
8889 EXPECT_GT(encrypted_length, 0u);
8890 total_encrypted_length += encrypted_length;
8891 }
8892 connection_.ProcessUdpPacket(
8893 kSelfAddress, kPeerAddress,
8894 QuicReceivedPacket(buffer, total_encrypted_length, clock_.Now(), false));
8895 if (connection_.GetSendAlarm()->IsSet()) {
8896 connection_.GetSendAlarm()->Fire();
8897 }
8898
8899 EXPECT_TRUE(connection_.connected());
8900}
8901
dschinazi66fc0242019-08-16 10:00:25 -07008902// Regression test for crbug.com/992831.
8903TEST_P(QuicConnectionTest, CoalescedPacketThatSavesFrames) {
8904 if (!QuicVersionHasLongHeaderLengths(connection_.transport_version())) {
8905 // Coalesced packets can only be encoded using long header lengths.
8906 return;
8907 }
8908 if (connection_.SupportsMultiplePacketNumberSpaces()) {
8909 // TODO(b/129151114) Enable this test with multiple packet number spaces.
8910 return;
8911 }
8912 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8913 EXPECT_TRUE(connection_.connected());
8914 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
8915 EXPECT_CALL(visitor_, OnCryptoFrame(_))
8916 .Times(3)
8917 .WillRepeatedly([this](const QuicCryptoFrame& /*frame*/) {
8918 // QuicFrame takes ownership of the QuicBlockedFrame.
8919 connection_.SendControlFrame(QuicFrame(new QuicBlockedFrame(1, 3)));
8920 });
8921 } else {
8922 EXPECT_CALL(visitor_, OnStreamFrame(_))
8923 .Times(3)
8924 .WillRepeatedly([this](const QuicStreamFrame& /*frame*/) {
8925 // QuicFrame takes ownership of the QuicBlockedFrame.
8926 connection_.SendControlFrame(QuicFrame(new QuicBlockedFrame(1, 3)));
8927 });
8928 }
8929
8930 uint64_t packet_numbers[3] = {1, 2, 3};
8931 EncryptionLevel encryption_levels[3] = {
8932 ENCRYPTION_INITIAL, ENCRYPTION_INITIAL, ENCRYPTION_FORWARD_SECURE};
8933 char buffer[kMaxOutgoingPacketSize] = {};
8934 size_t total_encrypted_length = 0;
8935 for (int i = 0; i < 3; i++) {
8936 QuicPacketHeader header =
8937 ConstructPacketHeader(packet_numbers[i], encryption_levels[i]);
8938 QuicFrames frames;
8939 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
8940 frames.push_back(QuicFrame(&crypto_frame_));
8941 } else {
8942 frames.push_back(QuicFrame(frame1_));
8943 }
8944 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
8945 peer_creator_.set_encryption_level(encryption_levels[i]);
8946 size_t encrypted_length = peer_framer_.EncryptPayload(
8947 encryption_levels[i], QuicPacketNumber(packet_numbers[i]), *packet,
8948 buffer + total_encrypted_length,
8949 sizeof(buffer) - total_encrypted_length);
8950 EXPECT_GT(encrypted_length, 0u);
8951 total_encrypted_length += encrypted_length;
8952 }
8953 connection_.ProcessUdpPacket(
8954 kSelfAddress, kPeerAddress,
8955 QuicReceivedPacket(buffer, total_encrypted_length, clock_.Now(), false));
8956 if (connection_.GetSendAlarm()->IsSet()) {
8957 connection_.GetSendAlarm()->Fire();
8958 }
8959
8960 EXPECT_TRUE(connection_.connected());
8961
8962 SendAckPacketToPeer();
8963}
8964
fayangd3016832019-08-08 07:24:45 -07008965// Regresstion test for b/138962304.
8966TEST_P(QuicConnectionTest, RtoAndWriteBlocked) {
8967 if (!QuicConnectionPeer::GetSentPacketManager(&connection_)
8968 ->fix_rto_retransmission()) {
8969 return;
8970 }
8971 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
8972
8973 QuicStreamId stream_id = 2;
8974 QuicPacketNumber last_data_packet;
8975 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
8976 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
8977
8978 // Writer gets blocked.
8979 writer_->SetWriteBlocked();
8980
8981 // Cancel the stream.
8982 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8983 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
fayang67f82272019-08-14 16:08:45 -07008984 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
8985 .WillRepeatedly(
8986 Invoke(&notifier_, &SimpleSessionNotifier::WillingToWrite));
fayangd3016832019-08-08 07:24:45 -07008987 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
8988
8989 // Retransmission timer fires in RTO mode.
8990 connection_.GetRetransmissionAlarm()->Fire();
8991 // Verify no packets get flushed when writer is blocked.
8992 EXPECT_EQ(0u, connection_.NumQueuedPackets());
8993}
8994
8995// Regresstion test for b/138962304.
8996TEST_P(QuicConnectionTest, TlpAndWriteBlocked) {
8997 if (!QuicConnectionPeer::GetSentPacketManager(&connection_)
8998 ->fix_rto_retransmission()) {
8999 return;
9000 }
9001 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9002 connection_.SetMaxTailLossProbes(1);
9003
9004 QuicStreamId stream_id = 2;
9005 QuicPacketNumber last_data_packet;
9006 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
9007 SendStreamDataToPeer(4, "foo", 0, NO_FIN, &last_data_packet);
9008 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9009
9010 // Writer gets blocked.
9011 writer_->SetWriteBlocked();
9012
9013 // Cancel stream 2.
9014 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9015 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
9016 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9017
fayang2ce66082019-10-02 06:29:04 -07009018 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
9019 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9020 } else {
9021 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9022 }
fayangd3016832019-08-08 07:24:45 -07009023 // Retransmission timer fires in TLP mode.
9024 connection_.GetRetransmissionAlarm()->Fire();
9025 // Verify one packets is forced flushed when writer is blocked.
9026 EXPECT_EQ(1u, connection_.NumQueuedPackets());
9027}
9028
fayang67f82272019-08-14 16:08:45 -07009029// Regresstion test for b/139375344.
9030TEST_P(QuicConnectionTest, RtoForcesSendingPing) {
9031 if (!QuicConnectionPeer::GetSentPacketManager(&connection_)
fayang5f135052019-08-22 17:59:40 -07009032 ->fix_rto_retransmission() ||
9033 connection_.PtoEnabled()) {
fayang67f82272019-08-14 16:08:45 -07009034 return;
9035 }
9036 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9037 connection_.SetMaxTailLossProbes(2);
9038 EXPECT_EQ(0u, connection_.GetStats().tlp_count);
9039 EXPECT_EQ(0u, connection_.GetStats().rto_count);
9040
9041 SendStreamDataToPeer(2, "foo", 0, NO_FIN, nullptr);
9042 QuicTime retransmission_time =
9043 connection_.GetRetransmissionAlarm()->deadline();
9044 EXPECT_NE(QuicTime::Zero(), retransmission_time);
9045 // TLP fires.
9046 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
9047 clock_.AdvanceTime(retransmission_time - clock_.Now());
9048 connection_.GetRetransmissionAlarm()->Fire();
9049 EXPECT_EQ(1u, connection_.GetStats().tlp_count);
9050 EXPECT_EQ(0u, connection_.GetStats().rto_count);
9051 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9052
9053 // Packet 1 gets acked.
9054 QuicAckFrame frame = InitAckFrame(1);
9055 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
9056 ProcessAckPacket(1, &frame);
9057 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9058 retransmission_time = connection_.GetRetransmissionAlarm()->deadline();
9059
9060 // RTO fires, verify a PING packet gets sent because there is no data to send.
9061 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(3), _, _));
9062 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
9063 clock_.AdvanceTime(retransmission_time - clock_.Now());
9064 connection_.GetRetransmissionAlarm()->Fire();
9065 EXPECT_EQ(1u, connection_.GetStats().tlp_count);
9066 EXPECT_EQ(1u, connection_.GetStats().rto_count);
9067 EXPECT_EQ(1u, writer_->ping_frames().size());
9068}
9069
fayangce0a3162019-08-15 09:05:36 -07009070TEST_P(QuicConnectionTest, ProbeTimeout) {
9071 if (!connection_.session_decides_what_to_write() ||
9072 !GetQuicReloadableFlag(quic_fix_rto_retransmission3)) {
9073 return;
9074 }
9075 SetQuicReloadableFlag(quic_enable_pto, true);
9076 SetQuicReloadableFlag(quic_fix_rto_retransmission3, true);
9077 QuicConfig config;
9078 QuicTagVector connection_options;
9079 connection_options.push_back(k2PTO);
9080 config.SetConnectionOptionsToSend(connection_options);
9081 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9082 connection_.SetFromConfig(config);
9083 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9084
9085 QuicStreamId stream_id = 2;
9086 QuicPacketNumber last_packet;
9087 SendStreamDataToPeer(stream_id, "foooooo", 0, NO_FIN, &last_packet);
9088 SendStreamDataToPeer(stream_id, "foooooo", 7, NO_FIN, &last_packet);
9089 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9090
9091 // Reset stream.
9092 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9093 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9094
9095 // Fire the PTO and verify only the RST_STREAM is resent, not stream data.
9096 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9097 connection_.GetRetransmissionAlarm()->Fire();
9098 EXPECT_EQ(0u, writer_->stream_frames().size());
9099 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
9100 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9101}
9102
fayang97ce41e2019-10-07 08:37:29 -07009103TEST_P(QuicConnectionTest, CloseConnectionAfter6ClientPTOs) {
9104 if (!connection_.session_decides_what_to_write() ||
9105 !GetQuicReloadableFlag(quic_fix_rto_retransmission3)) {
9106 return;
9107 }
9108 SetQuicReloadableFlag(quic_enable_pto, true);
9109 QuicConfig config;
9110 QuicTagVector connection_options;
9111 connection_options.push_back(k1PTO);
9112 connection_options.push_back(k6PTO);
9113 config.SetConnectionOptionsToSend(connection_options);
9114 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9115 connection_.SetFromConfig(config);
9116 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9117
9118 // Send stream data.
9119 SendStreamDataToPeer(
9120 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
9121 0, FIN, nullptr);
9122
9123 // 5PTO + 1 connection close.
9124 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(6);
9125
9126 // Fire the retransmission alarm 5 times.
9127 for (int i = 0; i < 5; ++i) {
9128 connection_.GetRetransmissionAlarm()->Fire();
9129 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
9130 EXPECT_TRUE(connection_.connected());
9131 }
9132
9133 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveTlpCount());
9134 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveRtoCount());
9135 EXPECT_EQ(5u, connection_.sent_packet_manager().GetConsecutivePtoCount());
9136 // Closes connection on 6th PTO.
9137 EXPECT_CALL(visitor_,
9138 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
9139 connection_.GetRetransmissionAlarm()->Fire();
9140 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
9141 EXPECT_FALSE(connection_.connected());
9142 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
9143}
9144
fayangce0a3162019-08-15 09:05:36 -07009145TEST_P(QuicConnectionTest, CloseConnectionAfter7ClientPTOs) {
9146 if (!connection_.session_decides_what_to_write() ||
9147 !GetQuicReloadableFlag(quic_fix_rto_retransmission3)) {
9148 return;
9149 }
9150 SetQuicReloadableFlag(quic_enable_pto, true);
9151 QuicConfig config;
9152 QuicTagVector connection_options;
9153 connection_options.push_back(k2PTO);
9154 connection_options.push_back(k7PTO);
9155 config.SetConnectionOptionsToSend(connection_options);
9156 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9157 connection_.SetFromConfig(config);
9158 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9159
9160 // Send stream data.
9161 SendStreamDataToPeer(
9162 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
9163 0, FIN, nullptr);
9164
9165 // Fire the retransmission alarm 6 times.
9166 for (int i = 0; i < 6; ++i) {
9167 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
9168 connection_.GetRetransmissionAlarm()->Fire();
9169 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
9170 EXPECT_TRUE(connection_.connected());
9171 }
9172
9173 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveTlpCount());
9174 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveRtoCount());
9175 EXPECT_EQ(6u, connection_.sent_packet_manager().GetConsecutivePtoCount());
9176 // Closes connection on 7th PTO.
9177 EXPECT_CALL(visitor_,
9178 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
9179 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
9180 connection_.GetRetransmissionAlarm()->Fire();
9181 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
9182 EXPECT_FALSE(connection_.connected());
9183 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
9184}
9185
9186TEST_P(QuicConnectionTest, CloseConnectionAfter8ClientPTOs) {
9187 if (!connection_.session_decides_what_to_write() ||
9188 !GetQuicReloadableFlag(quic_fix_rto_retransmission3)) {
9189 return;
9190 }
9191 SetQuicReloadableFlag(quic_enable_pto, true);
9192 QuicConfig config;
9193 QuicTagVector connection_options;
9194 connection_options.push_back(k2PTO);
9195 connection_options.push_back(k8PTO);
9196 config.SetConnectionOptionsToSend(connection_options);
9197 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9198 connection_.SetFromConfig(config);
9199 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9200
9201 // Send stream data.
9202 SendStreamDataToPeer(
9203 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
9204 0, FIN, nullptr);
9205
9206 // Fire the retransmission alarm 7 times.
9207 for (int i = 0; i < 7; ++i) {
9208 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
9209 connection_.GetRetransmissionAlarm()->Fire();
9210 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
9211 EXPECT_TRUE(connection_.connected());
9212 }
9213
9214 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveTlpCount());
9215 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveRtoCount());
9216 EXPECT_EQ(7u, connection_.sent_packet_manager().GetConsecutivePtoCount());
9217 // Closes connection on 8th PTO.
9218 EXPECT_CALL(visitor_,
9219 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
9220 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
9221 connection_.GetRetransmissionAlarm()->Fire();
9222 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
9223 EXPECT_FALSE(connection_.connected());
9224 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
9225}
9226
fayang5f135052019-08-22 17:59:40 -07009227TEST_P(QuicConnectionTest, DeprecateHandshakeMode) {
9228 if (!connection_.version().SupportsAntiAmplificationLimit()) {
9229 return;
9230 }
9231 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9232 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9233
9234 // Send CHLO.
9235 connection_.SendCryptoStreamData();
9236 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9237
9238 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
9239 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
9240 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9241 QuicAckFrame frame1 = InitAckFrame(1);
9242 // Received ACK for packet 1.
9243 ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL);
9244
9245 // Verify retransmission alarm is still set because handshake is not
9246 // confirmed although there is nothing in flight.
9247 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9248 EXPECT_EQ(0u, connection_.GetStats().pto_count);
9249 EXPECT_EQ(0u, connection_.GetStats().crypto_retransmit_count);
9250
9251 // PTO fires, verify a PING packet gets sent because there is no data to send.
9252 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
9253 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
9254 connection_.GetRetransmissionAlarm()->Fire();
9255 EXPECT_EQ(1u, connection_.GetStats().pto_count);
9256 EXPECT_EQ(0u, connection_.GetStats().crypto_retransmit_count);
9257 EXPECT_EQ(1u, writer_->ping_frames().size());
9258}
9259
9260TEST_P(QuicConnectionTest, AntiAmplificationLimit) {
9261 if (!connection_.version().SupportsAntiAmplificationLimit()) {
9262 return;
9263 }
9264 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9265 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9266
9267 set_perspective(Perspective::IS_SERVER);
9268 // Verify no data can be sent at the beginning because bytes received is 0.
9269 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9270 connection_.SendCryptoDataWithString("foo", 0);
9271 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9272
9273 // Receives packet 1.
9274 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
9275
9276 const size_t anti_amplification_factor =
9277 GetQuicFlag(FLAGS_quic_anti_amplification_factor);
9278 // Verify now packets can be sent.
9279 for (size_t i = 0; i < anti_amplification_factor; ++i) {
9280 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9281 connection_.SendCryptoDataWithString("foo", i * 3);
9282 // Verify retransmission alarm is not set if throttled by anti-amplification
9283 // limit.
9284 EXPECT_EQ(i != anti_amplification_factor - 1,
9285 connection_.GetRetransmissionAlarm()->IsSet());
9286 }
9287 // Verify server is throttled by anti-amplification limit.
9288 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9289 connection_.SendCryptoDataWithString("foo", anti_amplification_factor * 3);
9290
9291 // Receives packet 2.
9292 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
9293 // Verify more packets can be sent.
9294 for (size_t i = anti_amplification_factor; i < anti_amplification_factor * 2;
9295 ++i) {
9296 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9297 connection_.SendCryptoDataWithString("foo", i * 3);
9298 }
9299 // Verify server is throttled by anti-amplification limit.
9300 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9301 connection_.SendCryptoDataWithString("foo",
9302 2 * anti_amplification_factor * 3);
9303
9304 ProcessPacket(3);
9305 // Verify anti-amplification limit is gone after address validation.
9306 for (size_t i = 0; i < 100; ++i) {
9307 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9308 connection_.SendStreamDataWithString(3, "first", i * 0, NO_FIN);
9309 }
9310}
9311
fkastenholza3660102019-08-28 05:19:24 -07009312TEST_P(QuicConnectionTest, ConnectionCloseFrameType) {
9313 if (!VersionHasIetfQuicFrames(version().transport_version)) {
9314 // Test relevent only for IETF QUIC.
9315 return;
9316 }
9317 const QuicErrorCode kQuicErrorCode = IETF_QUIC_PROTOCOL_VIOLATION;
9318 // Use the (unknown) frame type of 9999 to avoid triggering any logic
9319 // which might be associated with the processing of a known frame type.
9320 const uint64_t kTransportCloseFrameType = 9999u;
9321 QuicFramerPeer::set_current_received_frame_type(
9322 QuicConnectionPeer::GetFramer(&connection_), kTransportCloseFrameType);
9323 // Do a transport connection close
9324 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
9325 connection_.CloseConnection(
9326 kQuicErrorCode, "Some random error message",
9327 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
9328 const std::vector<QuicConnectionCloseFrame>& connection_close_frames =
9329 writer_->connection_close_frames();
9330 ASSERT_EQ(1u, connection_close_frames.size());
9331 EXPECT_EQ(IETF_QUIC_TRANSPORT_CONNECTION_CLOSE,
9332 connection_close_frames[0].close_type);
9333 EXPECT_EQ(kQuicErrorCode, connection_close_frames[0].extracted_error_code);
9334 EXPECT_EQ(kTransportCloseFrameType,
9335 connection_close_frames[0].transport_close_frame_type);
9336}
9337
fayang0fcbf352019-08-30 11:15:58 -07009338// Regression test for b/137401387 and b/138962304.
9339TEST_P(QuicConnectionTest, RtoPacketAsTwo) {
9340 if (!QuicConnectionPeer::GetSentPacketManager(&connection_)
9341 ->fix_rto_retransmission() ||
fayangd6b31432019-09-18 06:26:59 -07009342 connection_.PtoEnabled() ||
9343 GetQuicReloadableFlag(quic_grant_enough_credits)) {
fayang0fcbf352019-08-30 11:15:58 -07009344 return;
9345 }
9346 connection_.SetMaxTailLossProbes(1);
9347 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
9348 std::string stream_data(3000, 's');
9349 // Send packets 1 - 66 and exhaust cwnd.
9350 for (size_t i = 0; i < 22; ++i) {
9351 // 3 packets for each stream, the first 2 are guaranteed to be full packets.
9352 SendStreamDataToPeer(i + 2, stream_data, 0, FIN, nullptr);
9353 }
9354 CongestionBlockWrites();
9355
9356 // Fires TLP. Please note, this tail loss probe has 1 byte less stream data
9357 // compared to packet 1 because packet number length increases.
9358 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(67), _, _));
9359 connection_.GetRetransmissionAlarm()->Fire();
9360 // Fires RTO. Please note, although packets 2 and 3 *should* be RTOed, but
9361 // packet 2 gets RTOed to two packets because packet number length increases.
9362 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(68), _, _));
9363 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(69), _, _));
9364 connection_.GetRetransmissionAlarm()->Fire();
9365
9366 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9367 // Resets all streams except 2 and ack packets 1 and 2. Now, packet 3 is the
9368 // only one containing retransmittable frames.
9369 for (size_t i = 1; i < 22; ++i) {
9370 notifier_.OnStreamReset(i + 2, QUIC_STREAM_CANCELLED);
9371 }
9372 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
9373 QuicAckFrame frame =
9374 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(3)}});
9375 ProcessAckPacket(1, &frame);
9376 CongestionUnblockWrites();
9377
9378 // Fires TLP, verify a PING gets sent because packet 3 is marked
9379 // RTO_RETRANSMITTED.
9380 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(70), _, _));
9381 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
9382 connection_.GetRetransmissionAlarm()->Fire();
9383}
9384
fayang4c1c2362019-09-13 07:20:01 -07009385TEST_P(QuicConnectionTest, PtoSkipsPacketNumber) {
9386 if (!connection_.session_decides_what_to_write() ||
9387 !GetQuicReloadableFlag(quic_fix_rto_retransmission3)) {
9388 return;
9389 }
9390 SetQuicReloadableFlag(quic_enable_pto, true);
9391 SetQuicReloadableFlag(quic_skip_packet_number_for_pto, true);
9392 QuicConfig config;
9393 QuicTagVector connection_options;
9394 connection_options.push_back(k1PTO);
9395 connection_options.push_back(kPTOS);
9396 config.SetConnectionOptionsToSend(connection_options);
9397 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9398 connection_.SetFromConfig(config);
9399 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9400
9401 QuicStreamId stream_id = 2;
9402 QuicPacketNumber last_packet;
9403 SendStreamDataToPeer(stream_id, "foooooo", 0, NO_FIN, &last_packet);
9404 SendStreamDataToPeer(stream_id, "foooooo", 7, NO_FIN, &last_packet);
9405 EXPECT_EQ(QuicPacketNumber(2), last_packet);
9406 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9407
9408 // Fire PTO and verify the PTO retransmission skips one packet number.
9409 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9410 connection_.GetRetransmissionAlarm()->Fire();
9411 EXPECT_EQ(1u, writer_->stream_frames().size());
9412 EXPECT_EQ(QuicPacketNumber(4), writer_->last_packet_header().packet_number);
9413 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9414}
9415
fayangd6b31432019-09-18 06:26:59 -07009416TEST_P(QuicConnectionTest, RetransmitPacketAsTwo) {
9417 if (!connection_.session_decides_what_to_write() ||
9418 !GetQuicReloadableFlag(quic_grant_enough_credits)) {
9419 return;
9420 }
9421 connection_.SetMaxTailLossProbes(1);
9422 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
9423 std::string stream_data(3000, 's');
9424 // Send packets 1 - 66 and exhaust cwnd.
9425 for (size_t i = 0; i < 22; ++i) {
9426 // 3 packets for each stream, the first 2 are guaranteed to be full packets.
9427 SendStreamDataToPeer(i + 2, stream_data, 0, FIN, nullptr);
9428 }
9429 CongestionBlockWrites();
9430
9431 if (connection_.PtoEnabled()) {
9432 // Fires PTO, packets 1 and 2 are retransmitted as 4 packets.
9433 EXPECT_CALL(*send_algorithm_,
9434 OnPacketSent(_, _, QuicPacketNumber(67), _, _));
9435 EXPECT_CALL(*send_algorithm_,
9436 OnPacketSent(_, _, QuicPacketNumber(68), _, _));
9437 EXPECT_CALL(*send_algorithm_,
9438 OnPacketSent(_, _, QuicPacketNumber(69), _, _));
9439 EXPECT_CALL(*send_algorithm_,
9440 OnPacketSent(_, _, QuicPacketNumber(70), _, _));
9441 } else {
9442 // Fires TLP. Verify 2 packets gets sent.
9443 EXPECT_CALL(*send_algorithm_,
9444 OnPacketSent(_, _, QuicPacketNumber(67), _, _));
9445 EXPECT_CALL(*send_algorithm_,
9446 OnPacketSent(_, _, QuicPacketNumber(68), _, _));
9447 }
9448 connection_.GetRetransmissionAlarm()->Fire();
9449
9450 if (connection_.PtoEnabled()) {
9451 // Fires PTO, packets 3 and 4 are retransmitted as 3 packets.
9452 EXPECT_CALL(*send_algorithm_,
9453 OnPacketSent(_, _, QuicPacketNumber(71), _, _));
9454 EXPECT_CALL(*send_algorithm_,
9455 OnPacketSent(_, _, QuicPacketNumber(72), _, _));
9456 EXPECT_CALL(*send_algorithm_,
9457 OnPacketSent(_, _, QuicPacketNumber(73), _, _));
9458 } else {
9459 // Fires RTO. Verify packets 2 and 3 are retransmitted as 3 packets.
9460 EXPECT_CALL(*send_algorithm_,
9461 OnPacketSent(_, _, QuicPacketNumber(69), _, _));
9462 EXPECT_CALL(*send_algorithm_,
9463 OnPacketSent(_, _, QuicPacketNumber(70), _, _));
9464 EXPECT_CALL(*send_algorithm_,
9465 OnPacketSent(_, _, QuicPacketNumber(71), _, _));
9466 }
9467 connection_.GetRetransmissionAlarm()->Fire();
9468 EXPECT_EQ(
9469 0u, connection_.sent_packet_manager().pending_timer_transmission_count());
9470}
9471
QUICHE teama6ef0a62019-03-07 20:34:33 -05009472} // namespace
9473} // namespace test
9474} // namespace quic