blob: e2ef8385c43a2e0fbbfd266835e83261a14687d2 [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"
QUICHE teama6ef0a62019-03-07 20:34:33 -050029#include "net/third_party/quiche/src/quic/platform/api/quic_reference_counted.h"
30#include "net/third_party/quiche/src/quic/platform/api/quic_str_cat.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050031#include "net/third_party/quiche/src/quic/platform/api/quic_string_piece.h"
32#include "net/third_party/quiche/src/quic/platform/api/quic_test.h"
33#include "net/third_party/quiche/src/quic/test_tools/mock_clock.h"
34#include "net/third_party/quiche/src/quic/test_tools/mock_random.h"
35#include "net/third_party/quiche/src/quic/test_tools/quic_config_peer.h"
36#include "net/third_party/quiche/src/quic/test_tools/quic_connection_peer.h"
37#include "net/third_party/quiche/src/quic/test_tools/quic_framer_peer.h"
38#include "net/third_party/quiche/src/quic/test_tools/quic_packet_creator_peer.h"
39#include "net/third_party/quiche/src/quic/test_tools/quic_packet_generator_peer.h"
40#include "net/third_party/quiche/src/quic/test_tools/quic_sent_packet_manager_peer.h"
41#include "net/third_party/quiche/src/quic/test_tools/quic_test_utils.h"
42#include "net/third_party/quiche/src/quic/test_tools/simple_data_producer.h"
43#include "net/third_party/quiche/src/quic/test_tools/simple_quic_framer.h"
44#include "net/third_party/quiche/src/quic/test_tools/simple_session_notifier.h"
45
46using testing::_;
47using testing::AnyNumber;
48using testing::AtLeast;
49using testing::DoAll;
50using testing::Exactly;
51using testing::Ge;
52using testing::IgnoreResult;
53using testing::InSequence;
54using testing::Invoke;
55using testing::InvokeWithoutArgs;
56using testing::Lt;
57using testing::Ref;
58using testing::Return;
59using testing::SaveArg;
60using testing::SetArgPointee;
61using testing::StrictMock;
62
63namespace quic {
64namespace test {
65namespace {
66
nharper55fa6132019-05-07 19:37:21 -070067const char data1[] = "foo data";
68const char data2[] = "bar data";
QUICHE teama6ef0a62019-03-07 20:34:33 -050069
70const bool kHasStopWaiting = true;
71
72const int kDefaultRetransmissionTimeMs = 500;
73
QUICHE team548d51b2019-03-14 10:06:54 -070074DiversificationNonce kTestDiversificationNonce = {
75 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a',
76 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b',
77 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b',
78};
79
QUICHE teama6ef0a62019-03-07 20:34:33 -050080const QuicSocketAddress kPeerAddress =
81 QuicSocketAddress(QuicIpAddress::Loopback6(),
82 /*port=*/12345);
83const QuicSocketAddress kSelfAddress =
84 QuicSocketAddress(QuicIpAddress::Loopback6(),
85 /*port=*/443);
86
QUICHE teama6ef0a62019-03-07 20:34:33 -050087QuicStreamId GetNthClientInitiatedStreamId(int n,
88 QuicTransportVersion version) {
dschinazi552accc2019-06-17 17:07:34 -070089 return QuicUtils::GetFirstBidirectionalStreamId(version,
90 Perspective::IS_CLIENT) +
91 n * 2;
QUICHE teama6ef0a62019-03-07 20:34:33 -050092}
93
QUICHE team8c1daa22019-03-13 08:33:41 -070094QuicLongHeaderType EncryptionlevelToLongHeaderType(EncryptionLevel level) {
95 switch (level) {
QUICHE team6987b4a2019-03-15 16:23:04 -070096 case ENCRYPTION_INITIAL:
QUICHE team8c1daa22019-03-13 08:33:41 -070097 return INITIAL;
QUICHE team88ea0082019-03-15 10:05:26 -070098 case ENCRYPTION_HANDSHAKE:
99 return HANDSHAKE;
QUICHE team8c1daa22019-03-13 08:33:41 -0700100 case ENCRYPTION_ZERO_RTT:
101 return ZERO_RTT_PROTECTED;
102 case ENCRYPTION_FORWARD_SECURE:
103 DCHECK(false);
104 return INVALID_PACKET_TYPE;
105 default:
106 DCHECK(false);
107 return INVALID_PACKET_TYPE;
108 }
109}
110
QUICHE teama6ef0a62019-03-07 20:34:33 -0500111// TaggingEncrypter appends kTagSize bytes of |tag| to the end of each message.
112class TaggingEncrypter : public QuicEncrypter {
113 public:
114 explicit TaggingEncrypter(uint8_t tag) : tag_(tag) {}
115 TaggingEncrypter(const TaggingEncrypter&) = delete;
116 TaggingEncrypter& operator=(const TaggingEncrypter&) = delete;
117
118 ~TaggingEncrypter() override {}
119
120 // QuicEncrypter interface.
dschinazi17d42422019-06-18 16:35:07 -0700121 bool SetKey(QuicStringPiece /*key*/) override { return true; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500122
dschinazi17d42422019-06-18 16:35:07 -0700123 bool SetNoncePrefix(QuicStringPiece /*nonce_prefix*/) override {
124 return true;
125 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500126
dschinazi17d42422019-06-18 16:35:07 -0700127 bool SetIV(QuicStringPiece /*iv*/) override { return true; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500128
dschinazi17d42422019-06-18 16:35:07 -0700129 bool SetHeaderProtectionKey(QuicStringPiece /*key*/) override { return true; }
QUICHE team2d187972019-03-19 16:23:47 -0700130
dschinazi17d42422019-06-18 16:35:07 -0700131 bool EncryptPacket(uint64_t /*packet_number*/,
132 QuicStringPiece /*associated_data*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500133 QuicStringPiece plaintext,
134 char* output,
135 size_t* output_length,
136 size_t max_output_length) override {
137 const size_t len = plaintext.size() + kTagSize;
138 if (max_output_length < len) {
139 return false;
140 }
141 // Memmove is safe for inplace encryption.
142 memmove(output, plaintext.data(), plaintext.size());
143 output += plaintext.size();
144 memset(output, tag_, kTagSize);
145 *output_length = len;
146 return true;
147 }
148
dschinazi17d42422019-06-18 16:35:07 -0700149 std::string GenerateHeaderProtectionMask(
150 QuicStringPiece /*sample*/) override {
QUICHE team2d187972019-03-19 16:23:47 -0700151 return std::string(5, 0);
152 }
153
QUICHE teama6ef0a62019-03-07 20:34:33 -0500154 size_t GetKeySize() const override { return 0; }
155 size_t GetNoncePrefixSize() const override { return 0; }
156 size_t GetIVSize() const override { return 0; }
157
158 size_t GetMaxPlaintextSize(size_t ciphertext_size) const override {
159 return ciphertext_size - kTagSize;
160 }
161
162 size_t GetCiphertextSize(size_t plaintext_size) const override {
163 return plaintext_size + kTagSize;
164 }
165
166 QuicStringPiece GetKey() const override { return QuicStringPiece(); }
167
168 QuicStringPiece GetNoncePrefix() const override { return QuicStringPiece(); }
169
170 private:
171 enum {
172 kTagSize = 12,
173 };
174
175 const uint8_t tag_;
176};
177
178// TaggingDecrypter ensures that the final kTagSize bytes of the message all
179// have the same value and then removes them.
180class TaggingDecrypter : public QuicDecrypter {
181 public:
182 ~TaggingDecrypter() override {}
183
184 // QuicDecrypter interface
dschinazi17d42422019-06-18 16:35:07 -0700185 bool SetKey(QuicStringPiece /*key*/) override { return true; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500186
dschinazi17d42422019-06-18 16:35:07 -0700187 bool SetNoncePrefix(QuicStringPiece /*nonce_prefix*/) override {
188 return true;
189 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500190
dschinazi17d42422019-06-18 16:35:07 -0700191 bool SetIV(QuicStringPiece /*iv*/) override { return true; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500192
dschinazi17d42422019-06-18 16:35:07 -0700193 bool SetHeaderProtectionKey(QuicStringPiece /*key*/) override { return true; }
QUICHE team2d187972019-03-19 16:23:47 -0700194
dschinazi17d42422019-06-18 16:35:07 -0700195 bool SetPreliminaryKey(QuicStringPiece /*key*/) override {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500196 QUIC_BUG << "should not be called";
197 return false;
198 }
199
dschinazi17d42422019-06-18 16:35:07 -0700200 bool SetDiversificationNonce(const DiversificationNonce& /*key*/) override {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500201 return true;
202 }
203
dschinazi17d42422019-06-18 16:35:07 -0700204 bool DecryptPacket(uint64_t /*packet_number*/,
205 QuicStringPiece /*associated_data*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500206 QuicStringPiece ciphertext,
207 char* output,
208 size_t* output_length,
dschinazi17d42422019-06-18 16:35:07 -0700209 size_t /*max_output_length*/) override {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500210 if (ciphertext.size() < kTagSize) {
211 return false;
212 }
213 if (!CheckTag(ciphertext, GetTag(ciphertext))) {
214 return false;
215 }
216 *output_length = ciphertext.size() - kTagSize;
217 memcpy(output, ciphertext.data(), *output_length);
218 return true;
219 }
220
QUICHE team2d187972019-03-19 16:23:47 -0700221 std::string GenerateHeaderProtectionMask(
dschinazi17d42422019-06-18 16:35:07 -0700222 QuicDataReader* /*sample_reader*/) override {
QUICHE team2d187972019-03-19 16:23:47 -0700223 return std::string(5, 0);
224 }
225
QUICHE teama6ef0a62019-03-07 20:34:33 -0500226 size_t GetKeySize() const override { return 0; }
nharper965e5922019-09-23 22:33:54 -0700227 size_t GetNoncePrefixSize() const override { return 0; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500228 size_t GetIVSize() const override { return 0; }
229 QuicStringPiece GetKey() const override { return QuicStringPiece(); }
230 QuicStringPiece GetNoncePrefix() const override { return QuicStringPiece(); }
231 // Use a distinct value starting with 0xFFFFFF, which is never used by TLS.
232 uint32_t cipher_id() const override { return 0xFFFFFFF0; }
233
234 protected:
235 virtual uint8_t GetTag(QuicStringPiece ciphertext) {
236 return ciphertext.data()[ciphertext.size() - 1];
237 }
238
239 private:
240 enum {
241 kTagSize = 12,
242 };
243
244 bool CheckTag(QuicStringPiece ciphertext, uint8_t tag) {
245 for (size_t i = ciphertext.size() - kTagSize; i < ciphertext.size(); i++) {
246 if (ciphertext.data()[i] != tag) {
247 return false;
248 }
249 }
250
251 return true;
252 }
253};
254
255// StringTaggingDecrypter ensures that the final kTagSize bytes of the message
256// match the expected value.
257class StrictTaggingDecrypter : public TaggingDecrypter {
258 public:
259 explicit StrictTaggingDecrypter(uint8_t tag) : tag_(tag) {}
260 ~StrictTaggingDecrypter() override {}
261
262 // TaggingQuicDecrypter
dschinazi17d42422019-06-18 16:35:07 -0700263 uint8_t GetTag(QuicStringPiece /*ciphertext*/) override { return tag_; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500264
265 // Use a distinct value starting with 0xFFFFFF, which is never used by TLS.
266 uint32_t cipher_id() const override { return 0xFFFFFFF1; }
267
268 private:
269 const uint8_t tag_;
270};
271
272class TestConnectionHelper : public QuicConnectionHelperInterface {
273 public:
274 TestConnectionHelper(MockClock* clock, MockRandom* random_generator)
275 : clock_(clock), random_generator_(random_generator) {
276 clock_->AdvanceTime(QuicTime::Delta::FromSeconds(1));
277 }
278 TestConnectionHelper(const TestConnectionHelper&) = delete;
279 TestConnectionHelper& operator=(const TestConnectionHelper&) = delete;
280
281 // QuicConnectionHelperInterface
282 const QuicClock* GetClock() const override { return clock_; }
283
284 QuicRandom* GetRandomGenerator() override { return random_generator_; }
285
286 QuicBufferAllocator* GetStreamSendBufferAllocator() override {
287 return &buffer_allocator_;
288 }
289
290 private:
291 MockClock* clock_;
292 MockRandom* random_generator_;
293 SimpleBufferAllocator buffer_allocator_;
294};
295
296class TestAlarmFactory : public QuicAlarmFactory {
297 public:
298 class TestAlarm : public QuicAlarm {
299 public:
300 explicit TestAlarm(QuicArenaScopedPtr<QuicAlarm::Delegate> delegate)
301 : QuicAlarm(std::move(delegate)) {}
302
303 void SetImpl() override {}
304 void CancelImpl() override {}
305 using QuicAlarm::Fire;
306 };
307
308 TestAlarmFactory() {}
309 TestAlarmFactory(const TestAlarmFactory&) = delete;
310 TestAlarmFactory& operator=(const TestAlarmFactory&) = delete;
311
312 QuicAlarm* CreateAlarm(QuicAlarm::Delegate* delegate) override {
313 return new TestAlarm(QuicArenaScopedPtr<QuicAlarm::Delegate>(delegate));
314 }
315
316 QuicArenaScopedPtr<QuicAlarm> CreateAlarm(
317 QuicArenaScopedPtr<QuicAlarm::Delegate> delegate,
318 QuicConnectionArena* arena) override {
319 return arena->New<TestAlarm>(std::move(delegate));
320 }
321};
322
323class TestPacketWriter : public QuicPacketWriter {
324 public:
325 TestPacketWriter(ParsedQuicVersion version, MockClock* clock)
326 : version_(version),
327 framer_(SupportedVersions(version_), Perspective::IS_SERVER),
328 last_packet_size_(0),
329 write_blocked_(false),
330 write_should_fail_(false),
331 block_on_next_flush_(false),
332 block_on_next_write_(false),
333 next_packet_too_large_(false),
334 always_get_packet_too_large_(false),
335 is_write_blocked_data_buffered_(false),
336 is_batch_mode_(false),
337 final_bytes_of_last_packet_(0),
338 final_bytes_of_previous_packet_(0),
339 use_tagging_decrypter_(false),
340 packets_write_attempts_(0),
341 clock_(clock),
342 write_pause_time_delta_(QuicTime::Delta::Zero()),
dschinazi66dea072019-04-09 11:41:06 -0700343 max_packet_size_(kMaxOutgoingPacketSize),
dschinazib953d022019-08-01 18:05:58 -0700344 supports_release_time_(false) {
345 QuicFramerPeer::SetLastSerializedServerConnectionId(framer_.framer(),
346 TestConnectionId());
nharperc6b99512019-09-19 11:13:48 -0700347 framer_.framer()->SetInitialObfuscators(TestConnectionId());
dschinazib953d022019-08-01 18:05:58 -0700348 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500349 TestPacketWriter(const TestPacketWriter&) = delete;
350 TestPacketWriter& operator=(const TestPacketWriter&) = delete;
351
352 // QuicPacketWriter interface
353 WriteResult WritePacket(const char* buffer,
354 size_t buf_len,
dschinazi17d42422019-06-18 16:35:07 -0700355 const QuicIpAddress& /*self_address*/,
356 const QuicSocketAddress& /*peer_address*/,
357 PerPacketOptions* /*options*/) override {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500358 QuicEncryptedPacket packet(buffer, buf_len);
359 ++packets_write_attempts_;
360
361 if (packet.length() >= sizeof(final_bytes_of_last_packet_)) {
362 final_bytes_of_previous_packet_ = final_bytes_of_last_packet_;
363 memcpy(&final_bytes_of_last_packet_, packet.data() + packet.length() - 4,
364 sizeof(final_bytes_of_last_packet_));
365 }
366
367 if (use_tagging_decrypter_) {
zhongyi546cc452019-04-12 15:27:49 -0700368 if (framer_.framer()->version().KnowsWhichDecrypterToUse()) {
vasilvv0fc587f2019-09-06 13:33:08 -0700369 framer_.framer()->InstallDecrypter(
370 ENCRYPTION_INITIAL, std::make_unique<TaggingDecrypter>());
371 framer_.framer()->InstallDecrypter(
372 ENCRYPTION_ZERO_RTT, std::make_unique<TaggingDecrypter>());
373 framer_.framer()->InstallDecrypter(
374 ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingDecrypter>());
zhongyi546cc452019-04-12 15:27:49 -0700375 } else {
376 framer_.framer()->SetDecrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -0700377 std::make_unique<TaggingDecrypter>());
zhongyi546cc452019-04-12 15:27:49 -0700378 }
379 } else if (framer_.framer()->version().KnowsWhichDecrypterToUse()) {
380 framer_.framer()->InstallDecrypter(
381 ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -0700382 std::make_unique<NullDecrypter>(Perspective::IS_SERVER));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500383 }
384 EXPECT_TRUE(framer_.ProcessPacket(packet));
385 if (block_on_next_write_) {
386 write_blocked_ = true;
387 block_on_next_write_ = false;
388 }
389 if (next_packet_too_large_) {
390 next_packet_too_large_ = false;
391 return WriteResult(WRITE_STATUS_ERROR, QUIC_EMSGSIZE);
392 }
393 if (always_get_packet_too_large_) {
394 return WriteResult(WRITE_STATUS_ERROR, QUIC_EMSGSIZE);
395 }
396 if (IsWriteBlocked()) {
397 return WriteResult(is_write_blocked_data_buffered_
398 ? WRITE_STATUS_BLOCKED_DATA_BUFFERED
399 : WRITE_STATUS_BLOCKED,
400 0);
401 }
402
403 if (ShouldWriteFail()) {
404 return WriteResult(WRITE_STATUS_ERROR, 0);
405 }
406
407 last_packet_size_ = packet.length();
408 last_packet_header_ = framer_.header();
409
410 if (!write_pause_time_delta_.IsZero()) {
411 clock_->AdvanceTime(write_pause_time_delta_);
412 }
413 return WriteResult(WRITE_STATUS_OK, last_packet_size_);
414 }
415
416 bool ShouldWriteFail() { return write_should_fail_; }
417
418 bool IsWriteBlocked() const override { return write_blocked_; }
419
420 void SetWriteBlocked() { write_blocked_ = true; }
421
422 void SetWritable() override { write_blocked_ = false; }
423
424 void SetShouldWriteFail() { write_should_fail_ = true; }
425
426 QuicByteCount GetMaxPacketSize(
427 const QuicSocketAddress& /*peer_address*/) const override {
428 return max_packet_size_;
429 }
430
dschinazi61eb6432019-06-14 16:27:16 -0700431 bool SupportsReleaseTime() const override { return supports_release_time_; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500432
433 bool IsBatchMode() const override { return is_batch_mode_; }
434
dschinazi17d42422019-06-18 16:35:07 -0700435 char* GetNextWriteLocation(
436 const QuicIpAddress& /*self_address*/,
437 const QuicSocketAddress& /*peer_address*/) override {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500438 return nullptr;
439 }
440
441 WriteResult Flush() override {
442 if (block_on_next_flush_) {
443 block_on_next_flush_ = false;
444 SetWriteBlocked();
445 return WriteResult(WRITE_STATUS_BLOCKED, /*errno*/ -1);
446 }
447 return WriteResult(WRITE_STATUS_OK, 0);
448 }
449
450 void BlockOnNextFlush() { block_on_next_flush_ = true; }
451
452 void BlockOnNextWrite() { block_on_next_write_ = true; }
453
454 void SimulateNextPacketTooLarge() { next_packet_too_large_ = true; }
455
456 void AlwaysGetPacketTooLarge() { always_get_packet_too_large_ = true; }
457
458 // Sets the amount of time that the writer should before the actual write.
459 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
460 write_pause_time_delta_ = delta;
461 }
462
463 void SetBatchMode(bool new_value) { is_batch_mode_ = new_value; }
464
465 const QuicPacketHeader& header() { return framer_.header(); }
466
467 size_t frame_count() const { return framer_.num_frames(); }
468
469 const std::vector<QuicAckFrame>& ack_frames() const {
470 return framer_.ack_frames();
471 }
472
473 const std::vector<QuicStopWaitingFrame>& stop_waiting_frames() const {
474 return framer_.stop_waiting_frames();
475 }
476
477 const std::vector<QuicConnectionCloseFrame>& connection_close_frames() const {
478 return framer_.connection_close_frames();
479 }
480
481 const std::vector<QuicRstStreamFrame>& rst_stream_frames() const {
482 return framer_.rst_stream_frames();
483 }
484
485 const std::vector<std::unique_ptr<QuicStreamFrame>>& stream_frames() const {
486 return framer_.stream_frames();
487 }
488
489 const std::vector<std::unique_ptr<QuicCryptoFrame>>& crypto_frames() const {
490 return framer_.crypto_frames();
491 }
492
493 const std::vector<QuicPingFrame>& ping_frames() const {
494 return framer_.ping_frames();
495 }
496
497 const std::vector<QuicMessageFrame>& message_frames() const {
498 return framer_.message_frames();
499 }
500
501 const std::vector<QuicWindowUpdateFrame>& window_update_frames() const {
502 return framer_.window_update_frames();
503 }
504
505 const std::vector<QuicPaddingFrame>& padding_frames() const {
506 return framer_.padding_frames();
507 }
508
509 const std::vector<QuicPathChallengeFrame>& path_challenge_frames() const {
510 return framer_.path_challenge_frames();
511 }
512
513 const std::vector<QuicPathResponseFrame>& path_response_frames() const {
514 return framer_.path_response_frames();
515 }
516
517 size_t last_packet_size() { return last_packet_size_; }
518
519 const QuicPacketHeader& last_packet_header() const {
520 return last_packet_header_;
521 }
522
523 const QuicVersionNegotiationPacket* version_negotiation_packet() {
524 return framer_.version_negotiation_packet();
525 }
526
527 void set_is_write_blocked_data_buffered(bool buffered) {
528 is_write_blocked_data_buffered_ = buffered;
529 }
530
531 void set_perspective(Perspective perspective) {
532 // We invert perspective here, because the framer needs to parse packets
533 // we send.
534 QuicFramerPeer::SetPerspective(framer_.framer(),
nharper4eba09b2019-06-26 20:17:25 -0700535 QuicUtils::InvertPerspective(perspective));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500536 }
537
538 // final_bytes_of_last_packet_ returns the last four bytes of the previous
539 // packet as a little-endian, uint32_t. This is intended to be used with a
540 // TaggingEncrypter so that tests can determine which encrypter was used for
541 // a given packet.
542 uint32_t final_bytes_of_last_packet() { return final_bytes_of_last_packet_; }
543
544 // Returns the final bytes of the second to last packet.
545 uint32_t final_bytes_of_previous_packet() {
546 return final_bytes_of_previous_packet_;
547 }
548
549 void use_tagging_decrypter() { use_tagging_decrypter_ = true; }
550
551 uint32_t packets_write_attempts() { return packets_write_attempts_; }
552
553 void Reset() { framer_.Reset(); }
554
555 void SetSupportedVersions(const ParsedQuicVersionVector& versions) {
556 framer_.SetSupportedVersions(versions);
557 }
558
559 void set_max_packet_size(QuicByteCount max_packet_size) {
560 max_packet_size_ = max_packet_size;
561 }
562
563 void set_supports_release_time(bool supports_release_time) {
564 supports_release_time_ = supports_release_time;
565 }
566
567 SimpleQuicFramer* framer() { return &framer_; }
568
569 private:
570 ParsedQuicVersion version_;
571 SimpleQuicFramer framer_;
572 size_t last_packet_size_;
573 QuicPacketHeader last_packet_header_;
574 bool write_blocked_;
575 bool write_should_fail_;
576 bool block_on_next_flush_;
577 bool block_on_next_write_;
578 bool next_packet_too_large_;
579 bool always_get_packet_too_large_;
580 bool is_write_blocked_data_buffered_;
581 bool is_batch_mode_;
582 uint32_t final_bytes_of_last_packet_;
583 uint32_t final_bytes_of_previous_packet_;
584 bool use_tagging_decrypter_;
585 uint32_t packets_write_attempts_;
586 MockClock* clock_;
587 // If non-zero, the clock will pause during WritePacket for this amount of
588 // time.
589 QuicTime::Delta write_pause_time_delta_;
590 QuicByteCount max_packet_size_;
591 bool supports_release_time_;
592};
593
594class TestConnection : public QuicConnection {
595 public:
596 TestConnection(QuicConnectionId connection_id,
597 QuicSocketAddress address,
598 TestConnectionHelper* helper,
599 TestAlarmFactory* alarm_factory,
600 TestPacketWriter* writer,
601 Perspective perspective,
602 ParsedQuicVersion version)
603 : QuicConnection(connection_id,
604 address,
605 helper,
606 alarm_factory,
607 writer,
608 /* owns_writer= */ false,
609 perspective,
610 SupportedVersions(version)),
611 notifier_(nullptr) {
612 writer->set_perspective(perspective);
613 SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -0700614 std::make_unique<NullEncrypter>(perspective));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500615 SetDataProducer(&producer_);
616 }
617 TestConnection(const TestConnection&) = delete;
618 TestConnection& operator=(const TestConnection&) = delete;
619
QUICHE teama6ef0a62019-03-07 20:34:33 -0500620 void SetSendAlgorithm(SendAlgorithmInterface* send_algorithm) {
621 QuicConnectionPeer::SetSendAlgorithm(this, send_algorithm);
622 }
623
624 void SetLossAlgorithm(LossDetectionInterface* loss_algorithm) {
625 QuicConnectionPeer::SetLossAlgorithm(this, loss_algorithm);
626 }
627
dschinazi17d42422019-06-18 16:35:07 -0700628 void SendPacket(EncryptionLevel /*level*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500629 uint64_t packet_number,
630 std::unique_ptr<QuicPacket> packet,
631 HasRetransmittableData retransmittable,
632 bool has_ack,
633 bool has_pending_frames) {
dschinazi66dea072019-04-09 11:41:06 -0700634 char buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -0500635 size_t encrypted_length =
636 QuicConnectionPeer::GetFramer(this)->EncryptPayload(
QUICHE team6987b4a2019-03-15 16:23:04 -0700637 ENCRYPTION_INITIAL, QuicPacketNumber(packet_number), *packet,
dschinazi66dea072019-04-09 11:41:06 -0700638 buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500639 SerializedPacket serialized_packet(
640 QuicPacketNumber(packet_number), PACKET_4BYTE_PACKET_NUMBER, buffer,
641 encrypted_length, has_ack, has_pending_frames);
642 if (retransmittable == HAS_RETRANSMITTABLE_DATA) {
643 serialized_packet.retransmittable_frames.push_back(
644 QuicFrame(QuicStreamFrame()));
645 }
646 OnSerializedPacket(&serialized_packet);
647 }
648
649 QuicConsumedData SaveAndSendStreamData(QuicStreamId id,
650 const struct iovec* iov,
651 int iov_count,
652 size_t total_length,
653 QuicStreamOffset offset,
654 StreamSendingState state) {
fayanga4b37b22019-06-18 13:37:47 -0700655 ScopedPacketFlusher flusher(this);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500656 producer_.SaveStreamData(id, iov, iov_count, 0u, total_length);
657 if (notifier_ != nullptr) {
658 return notifier_->WriteOrBufferData(id, total_length, state);
659 }
660 return QuicConnection::SendStreamData(id, total_length, offset, state);
661 }
662
663 QuicConsumedData SendStreamDataWithString(QuicStreamId id,
664 QuicStringPiece data,
665 QuicStreamOffset offset,
666 StreamSendingState state) {
fayanga4b37b22019-06-18 13:37:47 -0700667 ScopedPacketFlusher flusher(this);
nharper46833c32019-05-15 21:33:05 -0700668 if (!QuicUtils::IsCryptoStreamId(transport_version(), id) &&
QUICHE team6987b4a2019-03-15 16:23:04 -0700669 this->encryption_level() == ENCRYPTION_INITIAL) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500670 this->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
fayang5f135052019-08-22 17:59:40 -0700671 if (perspective() == Perspective::IS_CLIENT && !IsHandshakeConfirmed()) {
672 OnHandshakeComplete();
673 }
674 if (version().SupportsAntiAmplificationLimit()) {
675 QuicConnectionPeer::SetAddressValidated(this);
676 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500677 }
678 struct iovec iov;
679 MakeIOVector(data, &iov);
680 return SaveAndSendStreamData(id, &iov, 1, data.length(), offset, state);
681 }
682
QUICHE teamcd098022019-03-22 18:49:55 -0700683 QuicConsumedData SendApplicationDataAtLevel(EncryptionLevel encryption_level,
684 QuicStreamId id,
685 QuicStringPiece data,
686 QuicStreamOffset offset,
687 StreamSendingState state) {
fayanga4b37b22019-06-18 13:37:47 -0700688 ScopedPacketFlusher flusher(this);
QUICHE teamcd098022019-03-22 18:49:55 -0700689 DCHECK(encryption_level >= ENCRYPTION_ZERO_RTT);
vasilvv0fc587f2019-09-06 13:33:08 -0700690 SetEncrypter(encryption_level, std::make_unique<TaggingEncrypter>(0x01));
QUICHE teamcd098022019-03-22 18:49:55 -0700691 SetDefaultEncryptionLevel(encryption_level);
692 struct iovec iov;
693 MakeIOVector(data, &iov);
694 return SaveAndSendStreamData(id, &iov, 1, data.length(), offset, state);
695 }
696
QUICHE teama6ef0a62019-03-07 20:34:33 -0500697 QuicConsumedData SendStreamData3() {
698 return SendStreamDataWithString(
699 GetNthClientInitiatedStreamId(1, transport_version()), "food", 0,
700 NO_FIN);
701 }
702
703 QuicConsumedData SendStreamData5() {
704 return SendStreamDataWithString(
705 GetNthClientInitiatedStreamId(2, transport_version()), "food2", 0,
706 NO_FIN);
707 }
708
709 // Ensures the connection can write stream data before writing.
710 QuicConsumedData EnsureWritableAndSendStreamData5() {
711 EXPECT_TRUE(CanWriteStreamData());
712 return SendStreamData5();
713 }
714
715 // The crypto stream has special semantics so that it is not blocked by a
716 // congestion window limitation, and also so that it gets put into a separate
717 // packet (so that it is easier to reason about a crypto frame not being
718 // split needlessly across packet boundaries). As a result, we have separate
719 // tests for some cases for this stream.
720 QuicConsumedData SendCryptoStreamData() {
721 QuicStreamOffset offset = 0;
722 QuicStringPiece data("chlo");
fayang2ce66082019-10-02 06:29:04 -0700723 if (!QuicVersionUsesCryptoFrames(transport_version())) {
724 return SendCryptoDataWithString(data, offset);
725 }
726 producer_.SaveCryptoData(ENCRYPTION_INITIAL, offset, data);
727 size_t bytes_written;
728 if (notifier_) {
729 bytes_written =
730 notifier_->WriteCryptoData(ENCRYPTION_INITIAL, data.length(), offset);
731 } else {
732 bytes_written = QuicConnection::SendCryptoData(ENCRYPTION_INITIAL,
733 data.length(), offset);
734 }
735 return QuicConsumedData(bytes_written, /*fin_consumed*/ false);
nharper46833c32019-05-15 21:33:05 -0700736 }
737
738 QuicConsumedData SendCryptoDataWithString(QuicStringPiece data,
739 QuicStreamOffset offset) {
QUICHE teamea740082019-03-11 17:58:43 -0700740 if (!QuicVersionUsesCryptoFrames(transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500741 return SendStreamDataWithString(
742 QuicUtils::GetCryptoStreamId(transport_version()), data, offset,
743 NO_FIN);
744 }
QUICHE team6987b4a2019-03-15 16:23:04 -0700745 producer_.SaveCryptoData(ENCRYPTION_INITIAL, offset, data);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500746 size_t bytes_written;
747 if (notifier_) {
748 bytes_written =
QUICHE team6987b4a2019-03-15 16:23:04 -0700749 notifier_->WriteCryptoData(ENCRYPTION_INITIAL, data.length(), offset);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500750 } else {
QUICHE team6987b4a2019-03-15 16:23:04 -0700751 bytes_written = QuicConnection::SendCryptoData(ENCRYPTION_INITIAL,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500752 data.length(), offset);
753 }
754 return QuicConsumedData(bytes_written, /*fin_consumed*/ false);
755 }
756
757 void set_version(ParsedQuicVersion version) {
758 QuicConnectionPeer::GetFramer(this)->set_version(version);
759 }
760
761 void SetSupportedVersions(const ParsedQuicVersionVector& versions) {
762 QuicConnectionPeer::GetFramer(this)->SetSupportedVersions(versions);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500763 writer()->SetSupportedVersions(versions);
764 }
765
766 void set_perspective(Perspective perspective) {
767 writer()->set_perspective(perspective);
768 QuicConnectionPeer::SetPerspective(this, perspective);
769 }
770
771 // Enable path MTU discovery. Assumes that the test is performed from the
772 // client perspective and the higher value of MTU target is used.
773 void EnablePathMtuDiscovery(MockSendAlgorithm* send_algorithm) {
774 ASSERT_EQ(Perspective::IS_CLIENT, perspective());
775
776 QuicConfig config;
777 QuicTagVector connection_options;
778 connection_options.push_back(kMTUH);
779 config.SetConnectionOptionsToSend(connection_options);
780 EXPECT_CALL(*send_algorithm, SetFromConfig(_, _));
781 SetFromConfig(config);
782
783 // Normally, the pacing would be disabled in the test, but calling
784 // SetFromConfig enables it. Set nearly-infinite bandwidth to make the
785 // pacing algorithm work.
786 EXPECT_CALL(*send_algorithm, PacingRate(_))
787 .WillRepeatedly(Return(QuicBandwidth::Infinite()));
788 }
789
790 TestAlarmFactory::TestAlarm* GetAckAlarm() {
791 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
792 QuicConnectionPeer::GetAckAlarm(this));
793 }
794
795 TestAlarmFactory::TestAlarm* GetPingAlarm() {
796 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
797 QuicConnectionPeer::GetPingAlarm(this));
798 }
799
800 TestAlarmFactory::TestAlarm* GetRetransmissionAlarm() {
801 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
802 QuicConnectionPeer::GetRetransmissionAlarm(this));
803 }
804
805 TestAlarmFactory::TestAlarm* GetSendAlarm() {
806 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
807 QuicConnectionPeer::GetSendAlarm(this));
808 }
809
810 TestAlarmFactory::TestAlarm* GetTimeoutAlarm() {
811 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
812 QuicConnectionPeer::GetTimeoutAlarm(this));
813 }
814
815 TestAlarmFactory::TestAlarm* GetMtuDiscoveryAlarm() {
816 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
817 QuicConnectionPeer::GetMtuDiscoveryAlarm(this));
818 }
819
820 TestAlarmFactory::TestAlarm* GetPathDegradingAlarm() {
821 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
822 QuicConnectionPeer::GetPathDegradingAlarm(this));
823 }
824
825 TestAlarmFactory::TestAlarm* GetProcessUndecryptablePacketsAlarm() {
826 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
827 QuicConnectionPeer::GetProcessUndecryptablePacketsAlarm(this));
828 }
829
830 void SetMaxTailLossProbes(size_t max_tail_loss_probes) {
831 QuicSentPacketManagerPeer::SetMaxTailLossProbes(
832 QuicConnectionPeer::GetSentPacketManager(this), max_tail_loss_probes);
833 }
834
835 QuicByteCount GetBytesInFlight() {
ianswett9f459cb2019-04-21 06:39:59 -0700836 return QuicConnectionPeer::GetSentPacketManager(this)->GetBytesInFlight();
QUICHE teama6ef0a62019-03-07 20:34:33 -0500837 }
838
839 void set_notifier(SimpleSessionNotifier* notifier) { notifier_ = notifier; }
840
841 void ReturnEffectivePeerAddressForNextPacket(const QuicSocketAddress& addr) {
vasilvv0fc587f2019-09-06 13:33:08 -0700842 next_effective_peer_addr_ = std::make_unique<QuicSocketAddress>(addr);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500843 }
844
fayang5f135052019-08-22 17:59:40 -0700845 bool PtoEnabled() {
846 if (QuicConnectionPeer::GetSentPacketManager(this)->pto_enabled()) {
847 // PTO mode is default enabled for T099. And TLP/RTO related tests are
848 // stale.
849 DCHECK_EQ(ParsedQuicVersion(PROTOCOL_TLS1_3, QUIC_VERSION_99), version());
850 return true;
851 }
852 return false;
853 }
854
nharper46833c32019-05-15 21:33:05 -0700855 SimpleDataProducer* producer() { return &producer_; }
856
QUICHE teama6ef0a62019-03-07 20:34:33 -0500857 using QuicConnection::active_effective_peer_migration_type;
858 using QuicConnection::IsCurrentPacketConnectivityProbing;
859 using QuicConnection::SelectMutualVersion;
860 using QuicConnection::SendProbingRetransmissions;
861 using QuicConnection::set_defer_send_in_response_to_packets;
862
863 protected:
864 QuicSocketAddress GetEffectivePeerAddressFromCurrentPacket() const override {
865 if (next_effective_peer_addr_) {
866 return *std::move(next_effective_peer_addr_);
867 }
868 return QuicConnection::GetEffectivePeerAddressFromCurrentPacket();
869 }
870
871 private:
872 TestPacketWriter* writer() {
873 return static_cast<TestPacketWriter*>(QuicConnection::writer());
874 }
875
876 SimpleDataProducer producer_;
877
878 SimpleSessionNotifier* notifier_;
879
880 std::unique_ptr<QuicSocketAddress> next_effective_peer_addr_;
881};
882
883enum class AckResponse { kDefer, kImmediate };
884
885// Run tests with combinations of {ParsedQuicVersion, AckResponse}.
886struct TestParams {
887 TestParams(ParsedQuicVersion version,
888 AckResponse ack_response,
889 bool no_stop_waiting)
890 : version(version),
891 ack_response(ack_response),
892 no_stop_waiting(no_stop_waiting) {}
893
QUICHE teama6ef0a62019-03-07 20:34:33 -0500894 ParsedQuicVersion version;
895 AckResponse ack_response;
896 bool no_stop_waiting;
897};
898
dschinazi142051a2019-09-18 18:17:29 -0700899// Used by ::testing::PrintToStringParamName().
900std::string PrintToString(const TestParams& p) {
901 return QuicStrCat(
902 ParsedQuicVersionToString(p.version), "_",
903 (p.ack_response == AckResponse::kDefer ? "defer" : "immediate"), "_",
904 (p.no_stop_waiting ? "No" : ""), "StopWaiting");
905}
906
QUICHE teama6ef0a62019-03-07 20:34:33 -0500907// Constructs various test permutations.
908std::vector<TestParams> GetTestParams() {
909 QuicFlagSaver flags;
rch16df2a52019-09-10 10:50:09 -0700910 SetQuicReloadableFlag(quic_supports_tls_handshake, true);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500911 std::vector<TestParams> params;
912 ParsedQuicVersionVector all_supported_versions = AllSupportedVersions();
913 for (size_t i = 0; i < all_supported_versions.size(); ++i) {
914 for (AckResponse ack_response :
915 {AckResponse::kDefer, AckResponse::kImmediate}) {
dschinazi142051a2019-09-18 18:17:29 -0700916 params.push_back(
917 TestParams(all_supported_versions[i], ack_response, true));
918 if (!VersionHasIetfInvariantHeader(
919 all_supported_versions[i].transport_version)) {
fayangd4291e42019-05-30 10:31:21 -0700920 params.push_back(
dschinazi142051a2019-09-18 18:17:29 -0700921 TestParams(all_supported_versions[i], ack_response, false));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500922 }
923 }
924 }
925 return params;
926}
927
928class QuicConnectionTest : public QuicTestWithParam<TestParams> {
fkastenholz5d880a92019-06-21 09:01:56 -0700929 public:
930 // For tests that do silent connection closes, no such packet is generated. In
931 // order to verify the contents of the OnConnectionClosed upcall, EXPECTs
932 // should invoke this method, saving the frame, and then the test can verify
933 // the contents.
934 void SaveConnectionCloseFrame(const QuicConnectionCloseFrame& frame,
935 ConnectionCloseSource /*source*/) {
936 saved_connection_close_frame_ = frame;
937 connection_close_frame_count_++;
938 }
939
QUICHE teama6ef0a62019-03-07 20:34:33 -0500940 protected:
941 QuicConnectionTest()
942 : connection_id_(TestConnectionId()),
943 framer_(SupportedVersions(version()),
944 QuicTime::Zero(),
945 Perspective::IS_CLIENT,
946 connection_id_.length()),
947 send_algorithm_(new StrictMock<MockSendAlgorithm>),
948 loss_algorithm_(new MockLossAlgorithm()),
949 helper_(new TestConnectionHelper(&clock_, &random_generator_)),
950 alarm_factory_(new TestAlarmFactory()),
951 peer_framer_(SupportedVersions(version()),
952 QuicTime::Zero(),
953 Perspective::IS_SERVER,
954 connection_id_.length()),
955 peer_creator_(connection_id_,
956 &peer_framer_,
957 /*delegate=*/nullptr),
958 writer_(new TestPacketWriter(version(), &clock_)),
959 connection_(connection_id_,
960 kPeerAddress,
961 helper_.get(),
962 alarm_factory_.get(),
963 writer_.get(),
964 Perspective::IS_CLIENT,
965 version()),
966 creator_(QuicConnectionPeer::GetPacketCreator(&connection_)),
967 generator_(QuicConnectionPeer::GetPacketGenerator(&connection_)),
968 manager_(QuicConnectionPeer::GetSentPacketManager(&connection_)),
nharper46833c32019-05-15 21:33:05 -0700969 frame1_(0, false, 0, QuicStringPiece(data1)),
970 frame2_(0, false, 3, QuicStringPiece(data2)),
971 crypto_frame_(ENCRYPTION_INITIAL, 0, QuicStringPiece(data1)),
QUICHE teama6ef0a62019-03-07 20:34:33 -0500972 packet_number_length_(PACKET_4BYTE_PACKET_NUMBER),
973 connection_id_included_(CONNECTION_ID_PRESENT),
fkastenholz5d880a92019-06-21 09:01:56 -0700974 notifier_(&connection_),
975 connection_close_frame_count_(0) {
dschinazi142051a2019-09-18 18:17:29 -0700976 QUIC_DVLOG(2) << "QuicConnectionTest(" << PrintToString(GetParam()) << ")";
rch16df2a52019-09-10 10:50:09 -0700977 SetQuicReloadableFlag(quic_supports_tls_handshake, true);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500978 connection_.set_defer_send_in_response_to_packets(GetParam().ack_response ==
979 AckResponse::kDefer);
nharperc6b99512019-09-19 11:13:48 -0700980 framer_.SetInitialObfuscators(TestConnectionId());
981 connection_.InstallInitialCrypters(TestConnectionId());
982 CrypterPair crypters;
983 CryptoUtils::CreateInitialObfuscators(Perspective::IS_SERVER, version(),
984 TestConnectionId(), &crypters);
985 peer_creator_.SetEncrypter(ENCRYPTION_INITIAL,
986 std::move(crypters.encrypter));
987 if (version().KnowsWhichDecrypterToUse()) {
988 peer_framer_.InstallDecrypter(ENCRYPTION_INITIAL,
989 std::move(crypters.decrypter));
990 } else {
991 peer_framer_.SetDecrypter(ENCRYPTION_INITIAL,
992 std::move(crypters.decrypter));
993 }
nharper2c9f02a2019-05-08 10:25:50 -0700994 for (EncryptionLevel level :
995 {ENCRYPTION_ZERO_RTT, ENCRYPTION_FORWARD_SECURE}) {
996 peer_creator_.SetEncrypter(
vasilvv0fc587f2019-09-06 13:33:08 -0700997 level, std::make_unique<NullEncrypter>(peer_framer_.perspective()));
nharper2c9f02a2019-05-08 10:25:50 -0700998 }
dschinazi7b9278c2019-05-20 07:36:21 -0700999 QuicFramerPeer::SetLastSerializedServerConnectionId(
QUICHE teama6ef0a62019-03-07 20:34:33 -05001000 QuicConnectionPeer::GetFramer(&connection_), connection_id_);
nharperc6b99512019-09-19 11:13:48 -07001001 QuicFramerPeer::SetLastWrittenPacketNumberLength(
1002 QuicConnectionPeer::GetFramer(&connection_), packet_number_length_);
fayangd4291e42019-05-30 10:31:21 -07001003 if (VersionHasIetfInvariantHeader(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001004 EXPECT_TRUE(QuicConnectionPeer::GetNoStopWaitingFrames(&connection_));
1005 } else {
1006 QuicConnectionPeer::SetNoStopWaitingFrames(&connection_,
1007 GetParam().no_stop_waiting);
1008 }
nharper46833c32019-05-15 21:33:05 -07001009 QuicStreamId stream_id;
1010 if (QuicVersionUsesCryptoFrames(version().transport_version)) {
1011 stream_id = QuicUtils::GetFirstBidirectionalStreamId(
1012 version().transport_version, Perspective::IS_CLIENT);
1013 } else {
1014 stream_id = QuicUtils::GetCryptoStreamId(version().transport_version);
1015 }
1016 frame1_.stream_id = stream_id;
1017 frame2_.stream_id = stream_id;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001018 connection_.set_visitor(&visitor_);
1019 if (connection_.session_decides_what_to_write()) {
1020 connection_.SetSessionNotifier(&notifier_);
1021 connection_.set_notifier(&notifier_);
1022 }
1023 connection_.SetSendAlgorithm(send_algorithm_);
1024 connection_.SetLossAlgorithm(loss_algorithm_.get());
1025 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
1026 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1027 .Times(AnyNumber());
1028 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
1029 .WillRepeatedly(Return(kDefaultTCPMSS));
1030 EXPECT_CALL(*send_algorithm_, PacingRate(_))
1031 .WillRepeatedly(Return(QuicBandwidth::Zero()));
1032 EXPECT_CALL(*send_algorithm_, HasReliableBandwidthEstimate())
1033 .Times(AnyNumber());
1034 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
1035 .Times(AnyNumber())
1036 .WillRepeatedly(Return(QuicBandwidth::Zero()));
1037 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
1038 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
1039 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
1040 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).Times(AnyNumber());
1041 EXPECT_CALL(visitor_, HasPendingHandshake()).Times(AnyNumber());
1042 if (connection_.session_decides_what_to_write()) {
1043 EXPECT_CALL(visitor_, OnCanWrite())
1044 .WillRepeatedly(
1045 Invoke(&notifier_, &SimpleSessionNotifier::OnCanWrite));
1046 } else {
1047 EXPECT_CALL(visitor_, OnCanWrite()).Times(AnyNumber());
1048 }
1049 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
1050 .WillRepeatedly(Return(false));
1051 EXPECT_CALL(visitor_, OnCongestionWindowChange(_)).Times(AnyNumber());
zhongyi83161e42019-08-19 09:06:25 -07001052 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -05001053 EXPECT_CALL(visitor_, OnForwardProgressConfirmed()).Times(AnyNumber());
1054
1055 EXPECT_CALL(*loss_algorithm_, GetLossTimeout())
1056 .WillRepeatedly(Return(QuicTime::Zero()));
1057 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
1058 .Times(AnyNumber());
zhongyi546cc452019-04-12 15:27:49 -07001059
1060 if (connection_.version().KnowsWhichDecrypterToUse()) {
1061 connection_.InstallDecrypter(
1062 ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07001063 std::make_unique<NullDecrypter>(Perspective::IS_CLIENT));
zhongyi546cc452019-04-12 15:27:49 -07001064 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001065 }
1066
1067 QuicConnectionTest(const QuicConnectionTest&) = delete;
1068 QuicConnectionTest& operator=(const QuicConnectionTest&) = delete;
1069
1070 ParsedQuicVersion version() { return GetParam().version; }
1071
QUICHE teama6ef0a62019-03-07 20:34:33 -05001072 QuicStopWaitingFrame* stop_waiting() {
1073 QuicConnectionPeer::PopulateStopWaitingFrame(&connection_, &stop_waiting_);
1074 return &stop_waiting_;
1075 }
1076
1077 QuicPacketNumber least_unacked() {
1078 if (writer_->stop_waiting_frames().empty()) {
1079 return QuicPacketNumber();
1080 }
1081 return writer_->stop_waiting_frames()[0].least_unacked;
1082 }
1083
1084 void use_tagging_decrypter() { writer_->use_tagging_decrypter(); }
1085
zhongyi546cc452019-04-12 15:27:49 -07001086 void SetDecrypter(EncryptionLevel level,
1087 std::unique_ptr<QuicDecrypter> decrypter) {
1088 if (connection_.version().KnowsWhichDecrypterToUse()) {
1089 connection_.InstallDecrypter(level, std::move(decrypter));
1090 connection_.RemoveDecrypter(ENCRYPTION_INITIAL);
1091 } else {
1092 connection_.SetDecrypter(level, std::move(decrypter));
1093 }
1094 }
1095
QUICHE teama6ef0a62019-03-07 20:34:33 -05001096 void ProcessPacket(uint64_t number) {
1097 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
1098 ProcessDataPacket(number);
1099 if (connection_.GetSendAlarm()->IsSet()) {
1100 connection_.GetSendAlarm()->Fire();
1101 }
1102 }
1103
1104 void ProcessReceivedPacket(const QuicSocketAddress& self_address,
1105 const QuicSocketAddress& peer_address,
1106 const QuicReceivedPacket& packet) {
1107 connection_.ProcessUdpPacket(self_address, peer_address, packet);
1108 if (connection_.GetSendAlarm()->IsSet()) {
1109 connection_.GetSendAlarm()->Fire();
1110 }
1111 }
1112
1113 void ProcessFramePacket(QuicFrame frame) {
1114 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
1115 }
1116
1117 void ProcessFramePacketWithAddresses(QuicFrame frame,
1118 QuicSocketAddress self_address,
1119 QuicSocketAddress peer_address) {
1120 QuicFrames frames;
1121 frames.push_back(QuicFrame(frame));
1122 QuicPacketCreatorPeer::SetSendVersionInPacket(
1123 &peer_creator_, connection_.perspective() == Perspective::IS_SERVER);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001124
dschinazi66dea072019-04-09 11:41:06 -07001125 char buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05001126 SerializedPacket serialized_packet =
dschinazi66dea072019-04-09 11:41:06 -07001127 QuicPacketCreatorPeer::SerializeAllFrames(
1128 &peer_creator_, frames, buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001129 connection_.ProcessUdpPacket(
1130 self_address, peer_address,
1131 QuicReceivedPacket(serialized_packet.encrypted_buffer,
1132 serialized_packet.encrypted_length, clock_.Now()));
1133 if (connection_.GetSendAlarm()->IsSet()) {
1134 connection_.GetSendAlarm()->Fire();
1135 }
1136 }
1137
1138 // Bypassing the packet creator is unrealistic, but allows us to process
1139 // packets the QuicPacketCreator won't allow us to create.
1140 void ForceProcessFramePacket(QuicFrame frame) {
1141 QuicFrames frames;
1142 frames.push_back(QuicFrame(frame));
zhongyi546cc452019-04-12 15:27:49 -07001143 bool send_version = connection_.perspective() == Perspective::IS_SERVER;
1144 if (connection_.version().KnowsWhichDecrypterToUse()) {
1145 send_version = true;
1146 }
1147 QuicPacketCreatorPeer::SetSendVersionInPacket(&peer_creator_, send_version);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001148 QuicPacketHeader header;
1149 QuicPacketCreatorPeer::FillPacketHeader(&peer_creator_, &header);
dschinazi66dea072019-04-09 11:41:06 -07001150 char encrypted_buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05001151 size_t length = peer_framer_.BuildDataPacket(
dschinazi66dea072019-04-09 11:41:06 -07001152 header, frames, encrypted_buffer, kMaxOutgoingPacketSize,
1153 ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001154 DCHECK_GT(length, 0u);
1155
1156 const size_t encrypted_length = peer_framer_.EncryptInPlace(
QUICHE team6987b4a2019-03-15 16:23:04 -07001157 ENCRYPTION_INITIAL, header.packet_number,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001158 GetStartOfEncryptedData(peer_framer_.version().transport_version,
1159 header),
dschinazi66dea072019-04-09 11:41:06 -07001160 length, kMaxOutgoingPacketSize, encrypted_buffer);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001161 DCHECK_GT(encrypted_length, 0u);
1162
1163 connection_.ProcessUdpPacket(
1164 kSelfAddress, kPeerAddress,
1165 QuicReceivedPacket(encrypted_buffer, encrypted_length, clock_.Now()));
1166 }
1167
1168 size_t ProcessFramePacketAtLevel(uint64_t number,
1169 QuicFrame frame,
1170 EncryptionLevel level) {
1171 QuicPacketHeader header;
1172 header.destination_connection_id = connection_id_;
1173 header.packet_number_length = packet_number_length_;
1174 header.destination_connection_id_included = connection_id_included_;
dschinazi5e1a7b22019-07-31 12:23:21 -07001175 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001176 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1177 }
zhongyi546cc452019-04-12 15:27:49 -07001178 if (level == ENCRYPTION_INITIAL &&
1179 peer_framer_.version().KnowsWhichDecrypterToUse()) {
1180 header.version_flag = true;
nharperd43f1d62019-07-01 15:18:20 -07001181 if (QuicVersionHasLongHeaderLengths(peer_framer_.transport_version())) {
1182 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
1183 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
1184 }
QUICHE team2252b702019-05-14 23:55:14 -04001185 }
dschinazi5e1a7b22019-07-31 12:23:21 -07001186 if (header.version_flag &&
QUICHE team2252b702019-05-14 23:55:14 -04001187 peer_framer_.perspective() == Perspective::IS_SERVER) {
1188 header.source_connection_id = connection_id_;
1189 header.source_connection_id_included = CONNECTION_ID_PRESENT;
zhongyi546cc452019-04-12 15:27:49 -07001190 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001191 header.packet_number = QuicPacketNumber(number);
1192 QuicFrames frames;
1193 frames.push_back(frame);
1194 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
QUICHE teamcd098022019-03-22 18:49:55 -07001195 // Set the correct encryption level and encrypter on peer_creator and
1196 // peer_framer, respectively.
1197 peer_creator_.set_encryption_level(level);
1198 if (QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_) >
1199 ENCRYPTION_INITIAL) {
1200 peer_framer_.SetEncrypter(
1201 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
vasilvv0fc587f2019-09-06 13:33:08 -07001202 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teamcd098022019-03-22 18:49:55 -07001203 // Set the corresponding decrypter.
zhongyi546cc452019-04-12 15:27:49 -07001204 if (connection_.version().KnowsWhichDecrypterToUse()) {
1205 connection_.InstallDecrypter(
1206 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
vasilvv0fc587f2019-09-06 13:33:08 -07001207 std::make_unique<StrictTaggingDecrypter>(0x01));
zhongyi546cc452019-04-12 15:27:49 -07001208 connection_.RemoveDecrypter(ENCRYPTION_INITIAL);
1209 } else {
1210 connection_.SetDecrypter(
1211 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
vasilvv0fc587f2019-09-06 13:33:08 -07001212 std::make_unique<StrictTaggingDecrypter>(0x01));
zhongyi546cc452019-04-12 15:27:49 -07001213 }
QUICHE teamcd098022019-03-22 18:49:55 -07001214 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001215
dschinazi66dea072019-04-09 11:41:06 -07001216 char buffer[kMaxOutgoingPacketSize];
1217 size_t encrypted_length =
1218 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
1219 buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001220 connection_.ProcessUdpPacket(
1221 kSelfAddress, kPeerAddress,
QUICHE teamcd098022019-03-22 18:49:55 -07001222 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1223 if (connection_.GetSendAlarm()->IsSet()) {
1224 connection_.GetSendAlarm()->Fire();
1225 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001226 return encrypted_length;
1227 }
1228
1229 size_t ProcessDataPacket(uint64_t number) {
nharper2c9f02a2019-05-08 10:25:50 -07001230 return ProcessDataPacketAtLevel(number, false, ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001231 }
1232
1233 size_t ProcessDataPacket(QuicPacketNumber packet_number) {
nharper2c9f02a2019-05-08 10:25:50 -07001234 return ProcessDataPacketAtLevel(packet_number, false,
1235 ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001236 }
1237
1238 size_t ProcessDataPacketAtLevel(QuicPacketNumber packet_number,
1239 bool has_stop_waiting,
1240 EncryptionLevel level) {
1241 return ProcessDataPacketAtLevel(packet_number.ToUint64(), has_stop_waiting,
1242 level);
1243 }
1244
dschinazi17d42422019-06-18 16:35:07 -07001245 size_t ProcessCryptoPacketAtLevel(uint64_t number,
1246 EncryptionLevel /*level*/) {
fayangc31c9952019-06-05 13:54:48 -07001247 QuicPacketHeader header = ConstructPacketHeader(number, ENCRYPTION_INITIAL);
nharper46833c32019-05-15 21:33:05 -07001248 QuicFrames frames;
1249 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1250 frames.push_back(QuicFrame(&crypto_frame_));
1251 } else {
1252 frames.push_back(QuicFrame(frame1_));
1253 }
fayang5f135052019-08-22 17:59:40 -07001254 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
nharper46833c32019-05-15 21:33:05 -07001255 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
1256 char buffer[kMaxOutgoingPacketSize];
1257 peer_creator_.set_encryption_level(ENCRYPTION_INITIAL);
fayangc31c9952019-06-05 13:54:48 -07001258 size_t encrypted_length = peer_framer_.EncryptPayload(
1259 ENCRYPTION_INITIAL, QuicPacketNumber(number), *packet, buffer,
1260 kMaxOutgoingPacketSize);
nharper46833c32019-05-15 21:33:05 -07001261 connection_.ProcessUdpPacket(
1262 kSelfAddress, kPeerAddress,
1263 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1264 if (connection_.GetSendAlarm()->IsSet()) {
1265 connection_.GetSendAlarm()->Fire();
1266 }
1267 return encrypted_length;
1268 }
1269
QUICHE teama6ef0a62019-03-07 20:34:33 -05001270 size_t ProcessDataPacketAtLevel(uint64_t number,
1271 bool has_stop_waiting,
1272 EncryptionLevel level) {
1273 std::unique_ptr<QuicPacket> packet(
QUICHE team8c1daa22019-03-13 08:33:41 -07001274 ConstructDataPacket(number, has_stop_waiting, level));
dschinazi66dea072019-04-09 11:41:06 -07001275 char buffer[kMaxOutgoingPacketSize];
QUICHE teamcd098022019-03-22 18:49:55 -07001276 peer_creator_.set_encryption_level(level);
dschinazi66dea072019-04-09 11:41:06 -07001277 size_t encrypted_length =
1278 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
1279 buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001280 connection_.ProcessUdpPacket(
1281 kSelfAddress, kPeerAddress,
1282 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1283 if (connection_.GetSendAlarm()->IsSet()) {
1284 connection_.GetSendAlarm()->Fire();
1285 }
1286 return encrypted_length;
1287 }
1288
1289 void ProcessClosePacket(uint64_t number) {
1290 std::unique_ptr<QuicPacket> packet(ConstructClosePacket(number));
dschinazi66dea072019-04-09 11:41:06 -07001291 char buffer[kMaxOutgoingPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07001292 size_t encrypted_length = peer_framer_.EncryptPayload(
nharperc6b99512019-09-19 11:13:48 -07001293 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(number), *packet, buffer,
dschinazi66dea072019-04-09 11:41:06 -07001294 kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001295 connection_.ProcessUdpPacket(
1296 kSelfAddress, kPeerAddress,
1297 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
1298 }
1299
1300 QuicByteCount SendStreamDataToPeer(QuicStreamId id,
1301 QuicStringPiece data,
1302 QuicStreamOffset offset,
1303 StreamSendingState state,
1304 QuicPacketNumber* last_packet) {
1305 QuicByteCount packet_size;
fayang0fcbf352019-08-30 11:15:58 -07001306 // Save the last packet's size.
QUICHE teama6ef0a62019-03-07 20:34:33 -05001307 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
fayang0fcbf352019-08-30 11:15:58 -07001308 .Times(AnyNumber())
1309 .WillRepeatedly(SaveArg<3>(&packet_size));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001310 connection_.SendStreamDataWithString(id, data, offset, state);
1311 if (last_packet != nullptr) {
1312 *last_packet = creator_->packet_number();
1313 }
1314 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1315 .Times(AnyNumber());
1316 return packet_size;
1317 }
1318
1319 void SendAckPacketToPeer() {
1320 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1321 {
fayanga4b37b22019-06-18 13:37:47 -07001322 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001323 connection_.SendAck();
1324 }
1325 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1326 .Times(AnyNumber());
1327 }
1328
1329 void SendRstStream(QuicStreamId id,
1330 QuicRstStreamErrorCode error,
1331 QuicStreamOffset bytes_written) {
1332 if (connection_.session_decides_what_to_write()) {
1333 notifier_.WriteOrBufferRstStream(id, error, bytes_written);
1334 connection_.OnStreamReset(id, error);
1335 return;
1336 }
1337 std::unique_ptr<QuicRstStreamFrame> rst_stream =
vasilvv0fc587f2019-09-06 13:33:08 -07001338 std::make_unique<QuicRstStreamFrame>(1, id, error, bytes_written);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001339 if (connection_.SendControlFrame(QuicFrame(rst_stream.get()))) {
1340 rst_stream.release();
1341 }
1342 connection_.OnStreamReset(id, error);
1343 }
1344
zhongyifbb25772019-04-10 16:54:08 -07001345 void SendPing() {
1346 if (connection_.session_decides_what_to_write()) {
1347 notifier_.WriteOrBufferPing();
1348 } else {
1349 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
1350 }
1351 }
1352
QUICHE teama6ef0a62019-03-07 20:34:33 -05001353 void ProcessAckPacket(uint64_t packet_number, QuicAckFrame* frame) {
1354 if (packet_number > 1) {
1355 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, packet_number - 1);
1356 } else {
1357 QuicPacketCreatorPeer::ClearPacketNumber(&peer_creator_);
1358 }
1359 ProcessFramePacket(QuicFrame(frame));
1360 }
1361
1362 void ProcessAckPacket(QuicAckFrame* frame) {
1363 ProcessFramePacket(QuicFrame(frame));
1364 }
1365
1366 void ProcessStopWaitingPacket(QuicStopWaitingFrame frame) {
1367 ProcessFramePacket(QuicFrame(frame));
1368 }
1369
1370 size_t ProcessStopWaitingPacketAtLevel(uint64_t number,
1371 QuicStopWaitingFrame frame,
dschinazi17d42422019-06-18 16:35:07 -07001372 EncryptionLevel /*level*/) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001373 return ProcessFramePacketAtLevel(number, QuicFrame(frame),
1374 ENCRYPTION_ZERO_RTT);
1375 }
1376
1377 void ProcessGoAwayPacket(QuicGoAwayFrame* frame) {
1378 ProcessFramePacket(QuicFrame(frame));
1379 }
1380
1381 bool IsMissing(uint64_t number) {
fayangc31c9952019-06-05 13:54:48 -07001382 return IsAwaitingPacket(connection_.ack_frame(), QuicPacketNumber(number),
QUICHE teama6ef0a62019-03-07 20:34:33 -05001383 QuicPacketNumber());
1384 }
1385
1386 std::unique_ptr<QuicPacket> ConstructPacket(const QuicPacketHeader& header,
1387 const QuicFrames& frames) {
1388 auto packet = BuildUnsizedDataPacket(&peer_framer_, header, frames);
1389 EXPECT_NE(nullptr, packet.get());
1390 return packet;
1391 }
1392
nharper46833c32019-05-15 21:33:05 -07001393 QuicPacketHeader ConstructPacketHeader(uint64_t number,
1394 EncryptionLevel level) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001395 QuicPacketHeader header;
fayangd4291e42019-05-30 10:31:21 -07001396 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version()) &&
QUICHE team8c1daa22019-03-13 08:33:41 -07001397 level < ENCRYPTION_FORWARD_SECURE) {
1398 // Set long header type accordingly.
1399 header.version_flag = true;
nharperc6b99512019-09-19 11:13:48 -07001400 header.form = IETF_QUIC_LONG_HEADER_PACKET;
QUICHE team8c1daa22019-03-13 08:33:41 -07001401 header.long_packet_type = EncryptionlevelToLongHeaderType(level);
1402 if (QuicVersionHasLongHeaderLengths(
1403 peer_framer_.version().transport_version)) {
1404 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
1405 if (header.long_packet_type == INITIAL) {
1406 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
1407 }
1408 }
1409 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001410 // Set connection_id to peer's in memory representation as this data packet
1411 // is created by peer_framer.
dschinazi5e1a7b22019-07-31 12:23:21 -07001412 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
QUICHE team2252b702019-05-14 23:55:14 -04001413 header.source_connection_id = connection_id_;
1414 header.source_connection_id_included = connection_id_included_;
1415 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1416 } else {
1417 header.destination_connection_id = connection_id_;
1418 header.destination_connection_id_included = connection_id_included_;
1419 }
fayangd4291e42019-05-30 10:31:21 -07001420 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version()) &&
QUICHE teama6ef0a62019-03-07 20:34:33 -05001421 peer_framer_.perspective() == Perspective::IS_SERVER) {
1422 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
QUICHE team8c1daa22019-03-13 08:33:41 -07001423 if (header.version_flag) {
1424 header.source_connection_id = connection_id_;
1425 header.source_connection_id_included = CONNECTION_ID_PRESENT;
1426 if (GetParam().version.handshake_protocol == PROTOCOL_QUIC_CRYPTO &&
1427 header.long_packet_type == ZERO_RTT_PROTECTED) {
QUICHE team548d51b2019-03-14 10:06:54 -07001428 header.nonce = &kTestDiversificationNonce;
QUICHE team8c1daa22019-03-13 08:33:41 -07001429 }
1430 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001431 }
QUICHE team2252b702019-05-14 23:55:14 -04001432 header.packet_number_length = packet_number_length_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001433 header.packet_number = QuicPacketNumber(number);
nharper46833c32019-05-15 21:33:05 -07001434 return header;
1435 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001436
nharper46833c32019-05-15 21:33:05 -07001437 std::unique_ptr<QuicPacket> ConstructDataPacket(uint64_t number,
1438 bool has_stop_waiting,
1439 EncryptionLevel level) {
1440 QuicPacketHeader header = ConstructPacketHeader(number, level);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001441 QuicFrames frames;
1442 frames.push_back(QuicFrame(frame1_));
1443 if (has_stop_waiting) {
1444 frames.push_back(QuicFrame(stop_waiting_));
1445 }
1446 return ConstructPacket(header, frames);
1447 }
1448
1449 OwningSerializedPacketPointer ConstructProbingPacket() {
fkastenholz305e1732019-06-18 05:01:22 -07001450 if (VersionHasIetfQuicFrames(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001451 QuicPathFrameBuffer payload = {
1452 {0xde, 0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xfe}};
1453 return QuicPacketCreatorPeer::
1454 SerializePathChallengeConnectivityProbingPacket(&peer_creator_,
1455 &payload);
1456 }
1457 return QuicPacketCreatorPeer::SerializeConnectivityProbingPacket(
1458 &peer_creator_);
1459 }
1460
1461 std::unique_ptr<QuicPacket> ConstructClosePacket(uint64_t number) {
1462 QuicPacketHeader header;
1463 // Set connection_id to peer's in memory representation as this connection
1464 // close packet is created by peer_framer.
dschinazi5e1a7b22019-07-31 12:23:21 -07001465 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
QUICHE team2252b702019-05-14 23:55:14 -04001466 header.source_connection_id = connection_id_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001467 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
fayangd4291e42019-05-30 10:31:21 -07001468 if (!VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04001469 header.source_connection_id_included = CONNECTION_ID_PRESENT;
1470 }
1471 } else {
1472 header.destination_connection_id = connection_id_;
fayangd4291e42019-05-30 10:31:21 -07001473 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04001474 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1475 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001476 }
1477
QUICHE team2252b702019-05-14 23:55:14 -04001478 header.packet_number = QuicPacketNumber(number);
1479
fkastenholz0d6554a2019-08-05 12:20:35 -07001480 QuicErrorCode kQuicErrorCode = QUIC_PEER_GOING_AWAY;
fkastenholz591814c2019-09-06 12:11:46 -07001481 QuicConnectionCloseFrame qccf(peer_framer_.transport_version(),
1482 kQuicErrorCode, "",
1483 /*transport_close_frame_type=*/0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001484 QuicFrames frames;
1485 frames.push_back(QuicFrame(&qccf));
1486 return ConstructPacket(header, frames);
1487 }
1488
1489 QuicTime::Delta DefaultRetransmissionTime() {
1490 return QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
1491 }
1492
1493 QuicTime::Delta DefaultDelayedAckTime() {
1494 return QuicTime::Delta::FromMilliseconds(kDefaultDelayedAckTimeMs);
1495 }
1496
1497 const QuicStopWaitingFrame InitStopWaitingFrame(uint64_t least_unacked) {
1498 QuicStopWaitingFrame frame;
1499 frame.least_unacked = QuicPacketNumber(least_unacked);
1500 return frame;
1501 }
1502
1503 // Construct a ack_frame that acks all packet numbers between 1 and
1504 // |largest_acked|, except |missing|.
1505 // REQUIRES: 1 <= |missing| < |largest_acked|
1506 QuicAckFrame ConstructAckFrame(uint64_t largest_acked, uint64_t missing) {
1507 return ConstructAckFrame(QuicPacketNumber(largest_acked),
1508 QuicPacketNumber(missing));
1509 }
1510
1511 QuicAckFrame ConstructAckFrame(QuicPacketNumber largest_acked,
1512 QuicPacketNumber missing) {
1513 if (missing == QuicPacketNumber(1)) {
1514 return InitAckFrame({{missing + 1, largest_acked + 1}});
1515 }
1516 return InitAckFrame(
1517 {{QuicPacketNumber(1), missing}, {missing + 1, largest_acked + 1}});
1518 }
1519
1520 // Undo nacking a packet within the frame.
1521 void AckPacket(QuicPacketNumber arrived, QuicAckFrame* frame) {
1522 EXPECT_FALSE(frame->packets.Contains(arrived));
1523 frame->packets.Add(arrived);
1524 }
1525
1526 void TriggerConnectionClose() {
1527 // Send an erroneous packet to close the connection.
fkastenholz5d880a92019-06-21 09:01:56 -07001528 EXPECT_CALL(visitor_,
1529 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
1530 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
1531
QUICHE teamcd098022019-03-22 18:49:55 -07001532 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1533 // Triggers a connection by receiving ACK of unsent packet.
1534 QuicAckFrame frame = InitAckFrame(10000);
1535 ProcessAckPacket(1, &frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001536 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1537 nullptr);
fkastenholz5d880a92019-06-21 09:01:56 -07001538 EXPECT_EQ(1, connection_close_frame_count_);
1539 EXPECT_EQ(QUIC_INVALID_ACK_DATA,
1540 saved_connection_close_frame_.quic_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001541 }
1542
1543 void BlockOnNextWrite() {
1544 writer_->BlockOnNextWrite();
1545 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
1546 }
1547
1548 void SimulateNextPacketTooLarge() { writer_->SimulateNextPacketTooLarge(); }
1549
1550 void AlwaysGetPacketTooLarge() { writer_->AlwaysGetPacketTooLarge(); }
1551
1552 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
1553 writer_->SetWritePauseTimeDelta(delta);
1554 }
1555
1556 void CongestionBlockWrites() {
1557 EXPECT_CALL(*send_algorithm_, CanSend(_))
1558 .WillRepeatedly(testing::Return(false));
1559 }
1560
1561 void CongestionUnblockWrites() {
1562 EXPECT_CALL(*send_algorithm_, CanSend(_))
1563 .WillRepeatedly(testing::Return(true));
1564 }
1565
1566 void set_perspective(Perspective perspective) {
1567 connection_.set_perspective(perspective);
1568 if (perspective == Perspective::IS_SERVER) {
1569 connection_.set_can_truncate_connection_ids(true);
1570 }
1571 QuicFramerPeer::SetPerspective(&peer_framer_,
nharper4eba09b2019-06-26 20:17:25 -07001572 QuicUtils::InvertPerspective(perspective));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001573 }
1574
1575 void set_packets_between_probes_base(
1576 const QuicPacketCount packets_between_probes_base) {
wubf76cf2a2019-10-11 18:49:07 -07001577 if (GetQuicReloadableFlag(quic_mtu_discovery_v2)) {
1578 QuicConnectionPeer::ReInitializeMtuDiscoverer(
1579 &connection_, packets_between_probes_base,
1580 QuicPacketNumber(packets_between_probes_base));
1581 } else {
1582 QuicConnectionPeer::SetPacketsBetweenMtuProbes(
1583 &connection_, packets_between_probes_base);
1584 QuicConnectionPeer::SetNextMtuProbeAt(
1585 &connection_, QuicPacketNumber(packets_between_probes_base));
1586 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001587 }
1588
1589 bool IsDefaultTestConfiguration() {
1590 TestParams p = GetParam();
1591 return p.ack_response == AckResponse::kImmediate &&
1592 p.version == AllSupportedVersions()[0] && p.no_stop_waiting;
1593 }
1594
fkastenholz5d880a92019-06-21 09:01:56 -07001595 void TestConnectionCloseQuicErrorCode(QuicErrorCode expected_code) {
1596 // Not strictly needed for this test, but is commonly done.
1597 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1598 nullptr);
1599 const std::vector<QuicConnectionCloseFrame>& connection_close_frames =
1600 writer_->connection_close_frames();
1601 ASSERT_EQ(1u, connection_close_frames.size());
fkastenholz0d6554a2019-08-05 12:20:35 -07001602 if (!VersionHasIetfQuicFrames(version().transport_version)) {
1603 EXPECT_EQ(expected_code, connection_close_frames[0].quic_error_code);
1604 EXPECT_EQ(GOOGLE_QUIC_CONNECTION_CLOSE,
1605 connection_close_frames[0].close_type);
1606 return;
1607 }
1608
1609 QuicErrorCodeToIetfMapping mapping =
1610 QuicErrorCodeToTransportErrorCode(expected_code);
1611
1612 if (mapping.is_transport_close_) {
1613 // This Google QUIC Error Code maps to a transport close,
1614 EXPECT_EQ(IETF_QUIC_TRANSPORT_CONNECTION_CLOSE,
1615 connection_close_frames[0].close_type);
1616 EXPECT_EQ(mapping.transport_error_code_,
1617 connection_close_frames[0].transport_error_code);
1618 // TODO(fkastenholz): when the extracted error code CL lands,
1619 // need to test that extracted==expected.
1620 } else {
1621 // This maps to an application close.
1622 EXPECT_EQ(expected_code, connection_close_frames[0].quic_error_code);
1623 EXPECT_EQ(IETF_QUIC_APPLICATION_CONNECTION_CLOSE,
1624 connection_close_frames[0].close_type);
1625 // TODO(fkastenholz): when the extracted error code CL lands,
1626 // need to test that extracted==expected.
1627 }
fkastenholz5d880a92019-06-21 09:01:56 -07001628 }
1629
QUICHE teama6ef0a62019-03-07 20:34:33 -05001630 QuicConnectionId connection_id_;
1631 QuicFramer framer_;
1632
1633 MockSendAlgorithm* send_algorithm_;
1634 std::unique_ptr<MockLossAlgorithm> loss_algorithm_;
1635 MockClock clock_;
1636 MockRandom random_generator_;
1637 SimpleBufferAllocator buffer_allocator_;
1638 std::unique_ptr<TestConnectionHelper> helper_;
1639 std::unique_ptr<TestAlarmFactory> alarm_factory_;
1640 QuicFramer peer_framer_;
1641 QuicPacketCreator peer_creator_;
1642 std::unique_ptr<TestPacketWriter> writer_;
1643 TestConnection connection_;
1644 QuicPacketCreator* creator_;
1645 QuicPacketGenerator* generator_;
1646 QuicSentPacketManager* manager_;
1647 StrictMock<MockQuicConnectionVisitor> visitor_;
1648
1649 QuicStreamFrame frame1_;
1650 QuicStreamFrame frame2_;
nharper46833c32019-05-15 21:33:05 -07001651 QuicCryptoFrame crypto_frame_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001652 QuicAckFrame ack_;
1653 QuicStopWaitingFrame stop_waiting_;
1654 QuicPacketNumberLength packet_number_length_;
1655 QuicConnectionIdIncluded connection_id_included_;
1656
1657 SimpleSessionNotifier notifier_;
fkastenholz5d880a92019-06-21 09:01:56 -07001658
1659 QuicConnectionCloseFrame saved_connection_close_frame_;
1660 int connection_close_frame_count_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001661};
1662
1663// Run all end to end tests with all supported versions.
1664INSTANTIATE_TEST_SUITE_P(SupportedVersion,
1665 QuicConnectionTest,
dschinazi142051a2019-09-18 18:17:29 -07001666 ::testing::ValuesIn(GetTestParams()),
1667 ::testing::PrintToStringParamName());
QUICHE teama6ef0a62019-03-07 20:34:33 -05001668
fkastenholz0d6554a2019-08-05 12:20:35 -07001669// These two tests ensure that the QuicErrorCode mapping works correctly.
1670// Both tests expect to see a Google QUIC close if not running IETF QUIC.
1671// If running IETF QUIC, the first will generate a transport connection
1672// close, the second an application connection close.
1673// The connection close codes for the two tests are manually chosen;
1674// they are expected to always map to transport- and application-
1675// closes, respectively. If that changes, mew codes should be chosen.
1676TEST_P(QuicConnectionTest, CloseErrorCodeTestTransport) {
1677 EXPECT_TRUE(connection_.connected());
1678 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
1679 connection_.CloseConnection(
1680 IETF_QUIC_PROTOCOL_VIOLATION, "Should be transport close",
1681 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1682 EXPECT_FALSE(connection_.connected());
1683 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
1684}
1685
1686// Test that the IETF QUIC Error code mapping function works
1687// properly for application connection close codes.
1688TEST_P(QuicConnectionTest, CloseErrorCodeTestApplication) {
1689 EXPECT_TRUE(connection_.connected());
1690 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
1691 connection_.CloseConnection(
1692 QUIC_HEADERS_STREAM_DATA_DECOMPRESS_FAILURE,
1693 "Should be application close",
1694 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1695 EXPECT_FALSE(connection_.connected());
1696 TestConnectionCloseQuicErrorCode(QUIC_HEADERS_STREAM_DATA_DECOMPRESS_FAILURE);
1697}
1698
QUICHE teama6ef0a62019-03-07 20:34:33 -05001699TEST_P(QuicConnectionTest, SelfAddressChangeAtClient) {
1700 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1701
1702 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
1703 EXPECT_TRUE(connection_.connected());
1704
nharper46833c32019-05-15 21:33:05 -07001705 QuicFrame frame;
1706 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1707 frame = QuicFrame(&crypto_frame_);
1708 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1709 } else {
1710 frame = QuicFrame(QuicStreamFrame(
1711 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
1712 0u, QuicStringPiece()));
1713 EXPECT_CALL(visitor_, OnStreamFrame(_));
1714 }
1715 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001716 // Cause change in self_address.
1717 QuicIpAddress host;
1718 host.FromString("1.1.1.1");
1719 QuicSocketAddress self_address(host, 123);
nharper46833c32019-05-15 21:33:05 -07001720 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1721 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1722 } else {
1723 EXPECT_CALL(visitor_, OnStreamFrame(_));
1724 }
1725 ProcessFramePacketWithAddresses(frame, self_address, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001726 EXPECT_TRUE(connection_.connected());
1727}
1728
1729TEST_P(QuicConnectionTest, SelfAddressChangeAtServer) {
1730 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1731
1732 set_perspective(Perspective::IS_SERVER);
1733 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1734
1735 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1736 EXPECT_TRUE(connection_.connected());
1737
nharper46833c32019-05-15 21:33:05 -07001738 QuicFrame frame;
1739 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1740 frame = QuicFrame(&crypto_frame_);
1741 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1742 } else {
1743 frame = QuicFrame(QuicStreamFrame(
1744 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
1745 0u, QuicStringPiece()));
1746 EXPECT_CALL(visitor_, OnStreamFrame(_));
1747 }
1748 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001749 // Cause change in self_address.
1750 QuicIpAddress host;
1751 host.FromString("1.1.1.1");
1752 QuicSocketAddress self_address(host, 123);
1753 EXPECT_CALL(visitor_, AllowSelfAddressChange()).WillOnce(Return(false));
fkastenholz5d880a92019-06-21 09:01:56 -07001754 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
nharper46833c32019-05-15 21:33:05 -07001755 ProcessFramePacketWithAddresses(frame, self_address, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001756 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07001757 TestConnectionCloseQuicErrorCode(QUIC_ERROR_MIGRATING_ADDRESS);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001758}
1759
1760TEST_P(QuicConnectionTest, AllowSelfAddressChangeToMappedIpv4AddressAtServer) {
1761 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1762
1763 set_perspective(Perspective::IS_SERVER);
1764 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1765
1766 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1767 EXPECT_TRUE(connection_.connected());
1768
nharper46833c32019-05-15 21:33:05 -07001769 QuicFrame frame;
1770 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1771 frame = QuicFrame(&crypto_frame_);
1772 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(3);
1773 } else {
1774 frame = QuicFrame(QuicStreamFrame(
1775 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
1776 0u, QuicStringPiece()));
1777 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(3);
1778 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001779 QuicIpAddress host;
1780 host.FromString("1.1.1.1");
1781 QuicSocketAddress self_address1(host, 443);
nharper46833c32019-05-15 21:33:05 -07001782 ProcessFramePacketWithAddresses(frame, self_address1, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001783 // Cause self_address change to mapped Ipv4 address.
1784 QuicIpAddress host2;
1785 host2.FromString(
1786 QuicStrCat("::ffff:", connection_.self_address().host().ToString()));
1787 QuicSocketAddress self_address2(host2, connection_.self_address().port());
nharper46833c32019-05-15 21:33:05 -07001788 ProcessFramePacketWithAddresses(frame, self_address2, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001789 EXPECT_TRUE(connection_.connected());
1790 // self_address change back to Ipv4 address.
nharper46833c32019-05-15 21:33:05 -07001791 ProcessFramePacketWithAddresses(frame, self_address1, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001792 EXPECT_TRUE(connection_.connected());
1793}
1794
1795TEST_P(QuicConnectionTest, ClientAddressChangeAndPacketReordered) {
1796 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1797 set_perspective(Perspective::IS_SERVER);
1798 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1799
1800 // Clear direct_peer_address.
1801 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1802 // Clear effective_peer_address, it is the same as direct_peer_address for
1803 // this test.
1804 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1805 QuicSocketAddress());
1806
nharper46833c32019-05-15 21:33:05 -07001807 QuicFrame frame;
1808 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1809 frame = QuicFrame(&crypto_frame_);
1810 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1811 } else {
1812 frame = QuicFrame(QuicStreamFrame(
1813 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
1814 0u, QuicStringPiece()));
1815 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1816 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001817 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001818 const QuicSocketAddress kNewPeerAddress =
1819 QuicSocketAddress(QuicIpAddress::Loopback6(),
1820 /*port=*/23456);
nharper46833c32019-05-15 21:33:05 -07001821 ProcessFramePacketWithAddresses(frame, kSelfAddress, kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001822 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1823 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1824
1825 // Decrease packet number to simulate out-of-order packets.
1826 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 4);
1827 // This is an old packet, do not migrate.
1828 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
nharper46833c32019-05-15 21:33:05 -07001829 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001830 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1831 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1832}
1833
1834TEST_P(QuicConnectionTest, PeerAddressChangeAtServer) {
1835 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1836 set_perspective(Perspective::IS_SERVER);
1837 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1838 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1839
1840 // Clear direct_peer_address.
1841 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1842 // Clear effective_peer_address, it is the same as direct_peer_address for
1843 // this test.
1844 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1845 QuicSocketAddress());
1846 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1847
nharper46833c32019-05-15 21:33:05 -07001848 QuicFrame frame;
1849 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1850 frame = QuicFrame(&crypto_frame_);
1851 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1852 } else {
1853 frame = QuicFrame(QuicStreamFrame(
1854 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
1855 0u, QuicStringPiece()));
1856 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1857 }
1858 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001859 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1860 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1861
1862 // Process another packet with a different peer address on server side will
1863 // start connection migration.
1864 const QuicSocketAddress kNewPeerAddress =
1865 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
1866 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
nharper46833c32019-05-15 21:33:05 -07001867 ProcessFramePacketWithAddresses(frame, kSelfAddress, kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001868 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1869 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1870}
1871
1872TEST_P(QuicConnectionTest, EffectivePeerAddressChangeAtServer) {
1873 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1874 set_perspective(Perspective::IS_SERVER);
1875 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1876 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1877
1878 // Clear direct_peer_address.
1879 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1880 // Clear effective_peer_address, it is different from direct_peer_address for
1881 // this test.
1882 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1883 QuicSocketAddress());
1884 const QuicSocketAddress kEffectivePeerAddress =
1885 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/43210);
1886 connection_.ReturnEffectivePeerAddressForNextPacket(kEffectivePeerAddress);
1887
nharper46833c32019-05-15 21:33:05 -07001888 QuicFrame frame;
1889 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1890 frame = QuicFrame(&crypto_frame_);
1891 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1892 } else {
1893 frame = QuicFrame(QuicStreamFrame(
1894 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
1895 0u, QuicStringPiece()));
1896 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1897 }
1898 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001899 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1900 EXPECT_EQ(kEffectivePeerAddress, connection_.effective_peer_address());
1901
1902 // Process another packet with the same direct peer address and different
1903 // effective peer address on server side will start connection migration.
1904 const QuicSocketAddress kNewEffectivePeerAddress =
1905 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/54321);
1906 connection_.ReturnEffectivePeerAddressForNextPacket(kNewEffectivePeerAddress);
1907 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
nharper46833c32019-05-15 21:33:05 -07001908 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001909 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1910 EXPECT_EQ(kNewEffectivePeerAddress, connection_.effective_peer_address());
1911
1912 // Process another packet with a different direct peer address and the same
1913 // effective peer address on server side will not start connection migration.
1914 const QuicSocketAddress kNewPeerAddress =
1915 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
1916 connection_.ReturnEffectivePeerAddressForNextPacket(kNewEffectivePeerAddress);
1917 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
1918 // ack_frame is used to complete the migration started by the last packet, we
1919 // need to make sure a new migration does not start after the previous one is
1920 // completed.
1921 QuicAckFrame ack_frame = InitAckFrame(1);
1922 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
1923 ProcessFramePacketWithAddresses(QuicFrame(&ack_frame), kSelfAddress,
1924 kNewPeerAddress);
1925 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1926 EXPECT_EQ(kNewEffectivePeerAddress, connection_.effective_peer_address());
1927
1928 // Process another packet with different direct peer address and different
1929 // effective peer address on server side will start connection migration.
1930 const QuicSocketAddress kNewerEffectivePeerAddress =
1931 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/65432);
1932 const QuicSocketAddress kFinalPeerAddress =
1933 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/34567);
1934 connection_.ReturnEffectivePeerAddressForNextPacket(
1935 kNewerEffectivePeerAddress);
1936 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
nharper46833c32019-05-15 21:33:05 -07001937 ProcessFramePacketWithAddresses(frame, kSelfAddress, kFinalPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001938 EXPECT_EQ(kFinalPeerAddress, connection_.peer_address());
1939 EXPECT_EQ(kNewerEffectivePeerAddress, connection_.effective_peer_address());
1940 EXPECT_EQ(PORT_CHANGE, connection_.active_effective_peer_migration_type());
1941
1942 // While the previous migration is ongoing, process another packet with the
1943 // same direct peer address and different effective peer address on server
1944 // side will start a new connection migration.
1945 const QuicSocketAddress kNewestEffectivePeerAddress =
1946 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/65430);
1947 connection_.ReturnEffectivePeerAddressForNextPacket(
1948 kNewestEffectivePeerAddress);
1949 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
1950 EXPECT_CALL(*send_algorithm_, OnConnectionMigration()).Times(1);
nharper46833c32019-05-15 21:33:05 -07001951 ProcessFramePacketWithAddresses(frame, kSelfAddress, kFinalPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001952 EXPECT_EQ(kFinalPeerAddress, connection_.peer_address());
1953 EXPECT_EQ(kNewestEffectivePeerAddress, connection_.effective_peer_address());
1954 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
1955 connection_.active_effective_peer_migration_type());
1956}
1957
1958TEST_P(QuicConnectionTest, ReceivePaddedPingAtServer) {
1959 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1960 set_perspective(Perspective::IS_SERVER);
1961 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1962 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1963
1964 // Clear direct_peer_address.
1965 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1966 // Clear effective_peer_address, it is the same as direct_peer_address for
1967 // this test.
1968 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1969 QuicSocketAddress());
1970 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1971
nharper46833c32019-05-15 21:33:05 -07001972 QuicFrame frame;
1973 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1974 frame = QuicFrame(&crypto_frame_);
1975 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1976 } else {
1977 frame = QuicFrame(QuicStreamFrame(
1978 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
1979 0u, QuicStringPiece()));
1980 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1981 }
1982 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001983 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1984 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1985
1986 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyi83161e42019-08-19 09:06:25 -07001987 EXPECT_CALL(visitor_, OnPacketReceived(_, _, false)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001988
1989 // Process a padded PING or PATH CHALLENGE packet with no peer address change
1990 // on server side will be ignored.
1991 OwningSerializedPacketPointer probing_packet;
fkastenholz305e1732019-06-18 05:01:22 -07001992 if (VersionHasIetfQuicFrames(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001993 QuicPathFrameBuffer payload = {
1994 {0xde, 0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xfe}};
1995 probing_packet =
1996 QuicPacketCreatorPeer::SerializePathChallengeConnectivityProbingPacket(
1997 &peer_creator_, &payload);
1998 } else {
1999 probing_packet = QuicPacketCreatorPeer::SerializeConnectivityProbingPacket(
2000 &peer_creator_);
2001 }
2002 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2003 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2004 probing_packet->encrypted_length),
2005 clock_.Now()));
2006
2007 uint64_t num_probing_received =
2008 connection_.GetStats().num_connectivity_probing_received;
2009 ProcessReceivedPacket(kSelfAddress, kPeerAddress, *received);
2010
2011 EXPECT_EQ(num_probing_received,
2012 connection_.GetStats().num_connectivity_probing_received);
2013 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2014 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2015}
2016
2017TEST_P(QuicConnectionTest, WriteOutOfOrderQueuedPackets) {
2018 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
fayangc31c9952019-06-05 13:54:48 -07002019 if (!IsDefaultTestConfiguration()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002020 return;
2021 }
2022
2023 set_perspective(Perspective::IS_CLIENT);
2024
2025 BlockOnNextWrite();
2026
2027 QuicStreamId stream_id = 2;
2028 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
2029
2030 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2031
2032 writer_->SetWritable();
2033 connection_.SendConnectivityProbingPacket(writer_.get(),
2034 connection_.peer_address());
fayang2ce66082019-10-02 06:29:04 -07002035 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
2036 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
2037 connection_.OnCanWrite();
2038 return;
2039 }
fkastenholz5d880a92019-06-21 09:01:56 -07002040 EXPECT_CALL(visitor_,
2041 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002042 EXPECT_QUIC_BUG(connection_.OnCanWrite(),
2043 "Attempt to write packet:1 after:2");
2044 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07002045 TestConnectionCloseQuicErrorCode(QUIC_INTERNAL_ERROR);
2046 const std::vector<QuicConnectionCloseFrame>& connection_close_frames =
2047 writer_->connection_close_frames();
fkastenholz488a4622019-08-26 06:24:46 -07002048 EXPECT_EQ("Packet written out of order.",
2049 connection_close_frames[0].error_details);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002050}
2051
2052TEST_P(QuicConnectionTest, DiscardQueuedPacketsAfterConnectionClose) {
2053 // Regression test for b/74073386.
2054 {
2055 InSequence seq;
rch39c88ab2019-10-16 19:24:40 -07002056 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2057 .Times(AtLeast(1));
2058 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002059 }
2060
2061 set_perspective(Perspective::IS_CLIENT);
2062
2063 writer_->SimulateNextPacketTooLarge();
2064
2065 // This packet write should fail, which should cause the connection to close
2066 // after sending a connection close packet, then the failed packet should be
2067 // queued.
2068 connection_.SendStreamDataWithString(/*id=*/2, "foo", 0, NO_FIN);
2069
2070 EXPECT_FALSE(connection_.connected());
fayang2ce66082019-10-02 06:29:04 -07002071 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
2072 // No need to buffer packets.
2073 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2074 } else {
2075 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2076 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002077
2078 EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
2079 connection_.OnCanWrite();
fayang0f0c4e62019-07-16 08:55:54 -07002080 EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002081}
2082
2083TEST_P(QuicConnectionTest, ReceiveConnectivityProbingAtServer) {
2084 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2085 set_perspective(Perspective::IS_SERVER);
2086 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2087 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2088
2089 // Clear direct_peer_address.
2090 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2091 // Clear effective_peer_address, it is the same as direct_peer_address for
2092 // this test.
2093 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2094 QuicSocketAddress());
2095 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2096
nharper46833c32019-05-15 21:33:05 -07002097 QuicFrame frame;
2098 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2099 frame = QuicFrame(&crypto_frame_);
2100 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2101 } else {
2102 frame = QuicFrame(QuicStreamFrame(
2103 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
2104 0u, QuicStringPiece()));
2105 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2106 }
2107 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002108 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2109 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2110
2111 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyi83161e42019-08-19 09:06:25 -07002112 EXPECT_CALL(visitor_, OnPacketReceived(_, _, true)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002113
2114 // Process a padded PING packet from a new peer address on server side
2115 // is effectively receiving a connectivity probing.
2116 const QuicSocketAddress kNewPeerAddress =
2117 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2118
2119 OwningSerializedPacketPointer probing_packet = ConstructProbingPacket();
2120 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2121 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2122 probing_packet->encrypted_length),
2123 clock_.Now()));
2124
2125 uint64_t num_probing_received =
2126 connection_.GetStats().num_connectivity_probing_received;
2127 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2128
2129 EXPECT_EQ(num_probing_received + 1,
2130 connection_.GetStats().num_connectivity_probing_received);
2131 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2132 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2133
2134 // Process another packet with the old peer address on server side will not
2135 // start peer migration.
2136 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
nharper46833c32019-05-15 21:33:05 -07002137 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002138 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2139 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2140}
2141
2142TEST_P(QuicConnectionTest, ReceiveReorderedConnectivityProbingAtServer) {
2143 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2144 set_perspective(Perspective::IS_SERVER);
2145 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2146 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2147
2148 // Clear direct_peer_address.
2149 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2150 // Clear effective_peer_address, it is the same as direct_peer_address for
2151 // this test.
2152 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2153 QuicSocketAddress());
2154 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2155
nharper46833c32019-05-15 21:33:05 -07002156 QuicFrame frame;
2157 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2158 frame = QuicFrame(&crypto_frame_);
2159 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2160 } else {
2161 frame = QuicFrame(QuicStreamFrame(
2162 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
2163 0u, QuicStringPiece()));
2164 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2165 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002166 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
nharper46833c32019-05-15 21:33:05 -07002167 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002168 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2169 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2170
2171 // Decrease packet number to simulate out-of-order packets.
2172 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 4);
2173
2174 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyi83161e42019-08-19 09:06:25 -07002175 EXPECT_CALL(visitor_, OnPacketReceived(_, _, true)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002176
2177 // Process a padded PING packet from a new peer address on server side
2178 // is effectively receiving a connectivity probing, even if a newer packet has
2179 // been received before this one.
2180 const QuicSocketAddress kNewPeerAddress =
2181 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2182
2183 OwningSerializedPacketPointer probing_packet = ConstructProbingPacket();
2184 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2185 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2186 probing_packet->encrypted_length),
2187 clock_.Now()));
2188
2189 uint64_t num_probing_received =
2190 connection_.GetStats().num_connectivity_probing_received;
2191 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2192
2193 EXPECT_EQ(num_probing_received + 1,
2194 connection_.GetStats().num_connectivity_probing_received);
2195 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2196 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2197}
2198
2199TEST_P(QuicConnectionTest, MigrateAfterProbingAtServer) {
2200 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2201 set_perspective(Perspective::IS_SERVER);
2202 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2203 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2204
2205 // Clear direct_peer_address.
2206 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2207 // Clear effective_peer_address, it is the same as direct_peer_address for
2208 // this test.
2209 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2210 QuicSocketAddress());
2211 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2212
nharper46833c32019-05-15 21:33:05 -07002213 QuicFrame frame;
2214 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2215 frame = QuicFrame(&crypto_frame_);
2216 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2217 } else {
2218 frame = QuicFrame(QuicStreamFrame(
2219 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
2220 0u, QuicStringPiece()));
2221 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2222 }
2223 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002224 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2225 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2226
2227 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyi83161e42019-08-19 09:06:25 -07002228 EXPECT_CALL(visitor_, OnPacketReceived(_, _, true)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002229
2230 // Process a padded PING packet from a new peer address on server side
2231 // is effectively receiving a connectivity probing.
2232 const QuicSocketAddress kNewPeerAddress =
2233 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2234
2235 OwningSerializedPacketPointer probing_packet = ConstructProbingPacket();
2236 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2237 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2238 probing_packet->encrypted_length),
2239 clock_.Now()));
2240 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2241 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2242 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2243
2244 // Process another non-probing packet with the new peer address on server
2245 // side will start peer migration.
2246 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2247
nharper46833c32019-05-15 21:33:05 -07002248 ProcessFramePacketWithAddresses(frame, kSelfAddress, kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002249 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2250 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2251}
2252
2253TEST_P(QuicConnectionTest, ReceivePaddedPingAtClient) {
2254 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2255 set_perspective(Perspective::IS_CLIENT);
2256 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2257
2258 // Clear direct_peer_address.
2259 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2260 // Clear effective_peer_address, it is the same as direct_peer_address for
2261 // this test.
2262 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2263 QuicSocketAddress());
2264 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2265
nharper46833c32019-05-15 21:33:05 -07002266 QuicFrame frame;
2267 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2268 frame = QuicFrame(&crypto_frame_);
2269 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2270 } else {
2271 frame = QuicFrame(QuicStreamFrame(
2272 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
2273 0u, QuicStringPiece()));
2274 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2275 }
2276 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002277 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2278 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2279
2280 // Client takes all padded PING packet as speculative connectivity
2281 // probing packet, and reports to visitor.
2282 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyi83161e42019-08-19 09:06:25 -07002283 EXPECT_CALL(visitor_, OnPacketReceived(_, _, false)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002284
2285 OwningSerializedPacketPointer probing_packet = ConstructProbingPacket();
2286 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2287 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2288 probing_packet->encrypted_length),
2289 clock_.Now()));
2290 uint64_t num_probing_received =
2291 connection_.GetStats().num_connectivity_probing_received;
2292 ProcessReceivedPacket(kSelfAddress, kPeerAddress, *received);
2293
2294 EXPECT_EQ(num_probing_received,
2295 connection_.GetStats().num_connectivity_probing_received);
2296 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2297 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2298}
2299
2300TEST_P(QuicConnectionTest, ReceiveConnectivityProbingAtClient) {
2301 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2302 set_perspective(Perspective::IS_CLIENT);
2303 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2304
2305 // Clear direct_peer_address.
2306 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2307 // Clear effective_peer_address, it is the same as direct_peer_address for
2308 // this test.
2309 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2310 QuicSocketAddress());
2311 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2312
nharper46833c32019-05-15 21:33:05 -07002313 QuicFrame frame;
2314 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2315 frame = QuicFrame(&crypto_frame_);
2316 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2317 } else {
2318 frame = QuicFrame(QuicStreamFrame(
2319 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
2320 0u, QuicStringPiece()));
2321 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2322 }
2323 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002324 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2325 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2326
2327 // Process a padded PING packet with a different self address on client side
2328 // is effectively receiving a connectivity probing.
2329 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyi83161e42019-08-19 09:06:25 -07002330 EXPECT_CALL(visitor_, OnPacketReceived(_, _, true)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002331
2332 const QuicSocketAddress kNewSelfAddress =
2333 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2334
2335 OwningSerializedPacketPointer probing_packet = ConstructProbingPacket();
2336 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2337 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2338 probing_packet->encrypted_length),
2339 clock_.Now()));
2340 uint64_t num_probing_received =
2341 connection_.GetStats().num_connectivity_probing_received;
2342 ProcessReceivedPacket(kNewSelfAddress, kPeerAddress, *received);
2343
2344 EXPECT_EQ(num_probing_received + 1,
2345 connection_.GetStats().num_connectivity_probing_received);
2346 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2347 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2348}
2349
2350TEST_P(QuicConnectionTest, PeerAddressChangeAtClient) {
2351 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2352 set_perspective(Perspective::IS_CLIENT);
2353 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2354
2355 // Clear direct_peer_address.
2356 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2357 // Clear effective_peer_address, it is the same as direct_peer_address for
2358 // this test.
2359 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2360 QuicSocketAddress());
2361 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2362
nharper46833c32019-05-15 21:33:05 -07002363 QuicFrame frame;
2364 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2365 frame = QuicFrame(&crypto_frame_);
2366 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2367 } else {
2368 frame = QuicFrame(QuicStreamFrame(
2369 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
2370 0u, QuicStringPiece()));
2371 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2372 }
2373 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002374 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2375 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2376
2377 // Process another packet with a different peer address on client side will
2378 // only update peer address.
2379 const QuicSocketAddress kNewPeerAddress =
2380 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2381 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
nharper46833c32019-05-15 21:33:05 -07002382 ProcessFramePacketWithAddresses(frame, kSelfAddress, kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002383 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2384 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2385}
2386
2387TEST_P(QuicConnectionTest, MaxPacketSize) {
2388 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2389 EXPECT_EQ(1350u, connection_.max_packet_length());
2390}
2391
2392TEST_P(QuicConnectionTest, SmallerServerMaxPacketSize) {
2393 TestConnection connection(TestConnectionId(), kPeerAddress, helper_.get(),
2394 alarm_factory_.get(), writer_.get(),
2395 Perspective::IS_SERVER, version());
2396 EXPECT_EQ(Perspective::IS_SERVER, connection.perspective());
2397 EXPECT_EQ(1000u, connection.max_packet_length());
2398}
2399
2400TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSize) {
2401 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2402
2403 set_perspective(Perspective::IS_SERVER);
2404 connection_.SetMaxPacketLength(1000);
2405
2406 QuicPacketHeader header;
2407 header.destination_connection_id = connection_id_;
2408 header.version_flag = true;
nharper21af28e2019-06-17 15:54:34 -07002409 header.packet_number = QuicPacketNumber(12);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002410
2411 if (QuicVersionHasLongHeaderLengths(
2412 peer_framer_.version().transport_version)) {
2413 header.long_packet_type = INITIAL;
2414 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
2415 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
2416 }
2417
2418 QuicFrames frames;
2419 QuicPaddingFrame padding;
nharper46833c32019-05-15 21:33:05 -07002420 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2421 frames.push_back(QuicFrame(&crypto_frame_));
2422 } else {
2423 frames.push_back(QuicFrame(frame1_));
2424 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002425 frames.push_back(QuicFrame(padding));
2426 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
dschinazi66dea072019-04-09 11:41:06 -07002427 char buffer[kMaxOutgoingPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07002428 size_t encrypted_length =
2429 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12),
dschinazi66dea072019-04-09 11:41:06 -07002430 *packet, buffer, kMaxOutgoingPacketSize);
2431 EXPECT_EQ(kMaxOutgoingPacketSize, encrypted_length);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002432
2433 framer_.set_version(version());
nharper46833c32019-05-15 21:33:05 -07002434 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2435 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
2436 } else {
2437 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2438 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002439 connection_.ProcessUdpPacket(
2440 kSelfAddress, kPeerAddress,
2441 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
2442
dschinazi66dea072019-04-09 11:41:06 -07002443 EXPECT_EQ(kMaxOutgoingPacketSize, connection_.max_packet_length());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002444}
2445
2446TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSizeWhileWriterLimited) {
2447 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2448
2449 const QuicByteCount lower_max_packet_size = 1240;
2450 writer_->set_max_packet_size(lower_max_packet_size);
2451 set_perspective(Perspective::IS_SERVER);
2452 connection_.SetMaxPacketLength(1000);
2453 EXPECT_EQ(1000u, connection_.max_packet_length());
2454
2455 QuicPacketHeader header;
2456 header.destination_connection_id = connection_id_;
2457 header.version_flag = true;
nharper21af28e2019-06-17 15:54:34 -07002458 header.packet_number = QuicPacketNumber(12);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002459
2460 if (QuicVersionHasLongHeaderLengths(
2461 peer_framer_.version().transport_version)) {
2462 header.long_packet_type = INITIAL;
2463 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
2464 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
2465 }
2466
2467 QuicFrames frames;
2468 QuicPaddingFrame padding;
nharper46833c32019-05-15 21:33:05 -07002469 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2470 frames.push_back(QuicFrame(&crypto_frame_));
2471 } else {
2472 frames.push_back(QuicFrame(frame1_));
2473 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002474 frames.push_back(QuicFrame(padding));
2475 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
dschinazi66dea072019-04-09 11:41:06 -07002476 char buffer[kMaxOutgoingPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07002477 size_t encrypted_length =
2478 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12),
dschinazi66dea072019-04-09 11:41:06 -07002479 *packet, buffer, kMaxOutgoingPacketSize);
2480 EXPECT_EQ(kMaxOutgoingPacketSize, encrypted_length);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002481
2482 framer_.set_version(version());
nharper46833c32019-05-15 21:33:05 -07002483 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2484 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
2485 } else {
2486 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2487 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002488 connection_.ProcessUdpPacket(
2489 kSelfAddress, kPeerAddress,
2490 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
2491
2492 // Here, the limit imposed by the writer is lower than the size of the packet
2493 // received, so the writer max packet size is used.
2494 EXPECT_EQ(lower_max_packet_size, connection_.max_packet_length());
2495}
2496
2497TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriter) {
2498 const QuicByteCount lower_max_packet_size = 1240;
2499 writer_->set_max_packet_size(lower_max_packet_size);
2500
2501 static_assert(lower_max_packet_size < kDefaultMaxPacketSize,
2502 "Default maximum packet size is too low");
2503 connection_.SetMaxPacketLength(kDefaultMaxPacketSize);
2504
2505 EXPECT_EQ(lower_max_packet_size, connection_.max_packet_length());
2506}
2507
2508TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriterForNewConnection) {
2509 const QuicConnectionId connection_id = TestConnectionId(17);
2510 const QuicByteCount lower_max_packet_size = 1240;
2511 writer_->set_max_packet_size(lower_max_packet_size);
2512 TestConnection connection(connection_id, kPeerAddress, helper_.get(),
2513 alarm_factory_.get(), writer_.get(),
2514 Perspective::IS_CLIENT, version());
2515 EXPECT_EQ(Perspective::IS_CLIENT, connection.perspective());
2516 EXPECT_EQ(lower_max_packet_size, connection.max_packet_length());
2517}
2518
2519TEST_P(QuicConnectionTest, PacketsInOrder) {
2520 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2521
2522 ProcessPacket(1);
fayangc31c9952019-06-05 13:54:48 -07002523 EXPECT_EQ(QuicPacketNumber(1u), LargestAcked(connection_.ack_frame()));
2524 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002525
2526 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07002527 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(connection_.ack_frame()));
2528 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002529
2530 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002531 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
2532 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002533}
2534
2535TEST_P(QuicConnectionTest, PacketsOutOfOrder) {
2536 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2537
2538 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002539 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002540 EXPECT_TRUE(IsMissing(2));
2541 EXPECT_TRUE(IsMissing(1));
2542
2543 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07002544 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002545 EXPECT_FALSE(IsMissing(2));
2546 EXPECT_TRUE(IsMissing(1));
2547
2548 ProcessPacket(1);
fayangc31c9952019-06-05 13:54:48 -07002549 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002550 EXPECT_FALSE(IsMissing(2));
2551 EXPECT_FALSE(IsMissing(1));
2552}
2553
2554TEST_P(QuicConnectionTest, DuplicatePacket) {
2555 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2556
2557 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002558 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002559 EXPECT_TRUE(IsMissing(2));
2560 EXPECT_TRUE(IsMissing(1));
2561
2562 // Send packet 3 again, but do not set the expectation that
2563 // the visitor OnStreamFrame() will be called.
2564 ProcessDataPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002565 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002566 EXPECT_TRUE(IsMissing(2));
2567 EXPECT_TRUE(IsMissing(1));
2568}
2569
2570TEST_P(QuicConnectionTest, PacketsOutOfOrderWithAdditionsAndLeastAwaiting) {
QUICHE teamcd098022019-03-22 18:49:55 -07002571 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2572 return;
2573 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002574 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2575
2576 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002577 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002578 EXPECT_TRUE(IsMissing(2));
2579 EXPECT_TRUE(IsMissing(1));
2580
2581 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07002582 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002583 EXPECT_TRUE(IsMissing(1));
2584
2585 ProcessPacket(5);
fayangc31c9952019-06-05 13:54:48 -07002586 EXPECT_EQ(QuicPacketNumber(5u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002587 EXPECT_TRUE(IsMissing(1));
2588 EXPECT_TRUE(IsMissing(4));
2589
2590 // Pretend at this point the client has gotten acks for 2 and 3 and 1 is a
2591 // packet the peer will not retransmit. It indicates this by sending 'least
2592 // awaiting' is 4. The connection should then realize 1 will not be
2593 // retransmitted, and will remove it from the missing list.
2594 QuicAckFrame frame = InitAckFrame(1);
2595 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
2596 ProcessAckPacket(6, &frame);
2597
2598 // Force an ack to be sent.
2599 SendAckPacketToPeer();
2600 EXPECT_TRUE(IsMissing(4));
2601}
2602
QUICHE teama6ef0a62019-03-07 20:34:33 -05002603TEST_P(QuicConnectionTest, RejectUnencryptedStreamData) {
2604 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
2605 if (!IsDefaultTestConfiguration()) {
2606 return;
2607 }
2608
2609 // Process an unencrypted packet from the non-crypto stream.
2610 frame1_.stream_id = 3;
2611 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fkastenholz5d880a92019-06-21 09:01:56 -07002612 EXPECT_CALL(visitor_,
2613 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
nharper2c9f02a2019-05-08 10:25:50 -07002614 EXPECT_QUIC_PEER_BUG(ProcessDataPacketAtLevel(1, false, ENCRYPTION_INITIAL),
2615 "");
fkastenholz5d880a92019-06-21 09:01:56 -07002616 TestConnectionCloseQuicErrorCode(QUIC_UNENCRYPTED_STREAM_DATA);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002617}
2618
2619TEST_P(QuicConnectionTest, OutOfOrderReceiptCausesAckSend) {
2620 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2621
2622 ProcessPacket(3);
fayang6dba4902019-06-17 10:04:23 -07002623 // Should not cause an ack.
2624 EXPECT_EQ(0u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002625
2626 ProcessPacket(2);
fayang6dba4902019-06-17 10:04:23 -07002627 // Should ack immediately, since this fills the last hole.
2628 EXPECT_EQ(1u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002629
2630 ProcessPacket(1);
2631 // Should ack immediately, since this fills the last hole.
fayang6dba4902019-06-17 10:04:23 -07002632 EXPECT_EQ(2u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002633
2634 ProcessPacket(4);
2635 // Should not cause an ack.
fayang6dba4902019-06-17 10:04:23 -07002636 EXPECT_EQ(2u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002637}
2638
2639TEST_P(QuicConnectionTest, OutOfOrderAckReceiptCausesNoAck) {
2640 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2641
2642 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
2643 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
2644 EXPECT_EQ(2u, writer_->packets_write_attempts());
2645
2646 QuicAckFrame ack1 = InitAckFrame(1);
2647 QuicAckFrame ack2 = InitAckFrame(2);
2648 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2649 ProcessAckPacket(2, &ack2);
2650 // Should ack immediately since we have missing packets.
2651 EXPECT_EQ(2u, writer_->packets_write_attempts());
2652
2653 ProcessAckPacket(1, &ack1);
2654 // Should not ack an ack filling a missing packet.
2655 EXPECT_EQ(2u, writer_->packets_write_attempts());
2656}
2657
2658TEST_P(QuicConnectionTest, AckReceiptCausesAckSend) {
2659 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2660 QuicPacketNumber original, second;
2661
2662 QuicByteCount packet_size =
2663 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &original); // 1st packet.
2664 SendStreamDataToPeer(3, "bar", 3, NO_FIN, &second); // 2nd packet.
2665
2666 QuicAckFrame frame = InitAckFrame({{second, second + 1}});
2667 // First nack triggers early retransmit.
2668 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07002669 lost_packets.push_back(LostPacket(original, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002670 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
2671 .WillOnce(SetArgPointee<5>(lost_packets));
2672 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2673 QuicPacketNumber retransmission;
2674 // Packet 1 is short header for IETF QUIC because the encryption level
2675 // switched to ENCRYPTION_FORWARD_SECURE in SendStreamDataToPeer.
fayangd4291e42019-05-30 10:31:21 -07002676 EXPECT_CALL(*send_algorithm_,
2677 OnPacketSent(_, _, _,
2678 VersionHasIetfInvariantHeader(
2679 GetParam().version.transport_version)
2680 ? packet_size
2681 : packet_size - kQuicVersionSize,
2682 _))
QUICHE teama6ef0a62019-03-07 20:34:33 -05002683 .WillOnce(SaveArg<2>(&retransmission));
2684
2685 ProcessAckPacket(&frame);
2686
2687 QuicAckFrame frame2 = ConstructAckFrame(retransmission, original);
2688 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2689 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
2690 ProcessAckPacket(&frame2);
2691
2692 // Now if the peer sends an ack which still reports the retransmitted packet
2693 // as missing, that will bundle an ack with data after two acks in a row
2694 // indicate the high water mark needs to be raised.
2695 EXPECT_CALL(*send_algorithm_,
2696 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA));
2697 connection_.SendStreamDataWithString(3, "foo", 6, NO_FIN);
2698 // No ack sent.
nharper55fa6132019-05-07 19:37:21 -07002699 size_t padding_frame_count = writer_->padding_frames().size();
2700 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002701 EXPECT_EQ(1u, writer_->stream_frames().size());
2702
2703 // No more packet loss for the rest of the test.
2704 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
2705 .Times(AnyNumber());
2706 ProcessAckPacket(&frame2);
2707 EXPECT_CALL(*send_algorithm_,
2708 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA));
fayang03916692019-05-22 17:57:18 -07002709 connection_.SendStreamDataWithString(3, "foofoofoo", 9, NO_FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002710 // Ack bundled.
2711 if (GetParam().no_stop_waiting) {
fayange8b0cab2019-07-17 14:23:07 -07002712 if (GetQuicReloadableFlag(quic_simplify_stop_waiting)) {
2713 // Do not ACK acks.
2714 EXPECT_EQ(1u, writer_->frame_count());
2715 } else {
2716 EXPECT_EQ(2u, writer_->frame_count());
2717 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002718 } else {
2719 EXPECT_EQ(3u, writer_->frame_count());
2720 }
2721 EXPECT_EQ(1u, writer_->stream_frames().size());
fayange8b0cab2019-07-17 14:23:07 -07002722 if (GetParam().no_stop_waiting &&
2723 GetQuicReloadableFlag(quic_simplify_stop_waiting)) {
fayang03916692019-05-22 17:57:18 -07002724 EXPECT_TRUE(writer_->ack_frames().empty());
2725 } else {
2726 EXPECT_FALSE(writer_->ack_frames().empty());
2727 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002728
2729 // But an ack with no missing packets will not send an ack.
2730 AckPacket(original, &frame2);
2731 ProcessAckPacket(&frame2);
2732 ProcessAckPacket(&frame2);
2733}
2734
2735TEST_P(QuicConnectionTest, AckSentEveryNthPacket) {
2736 connection_.set_ack_frequency_before_ack_decimation(3);
2737
2738 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2739 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(39);
2740
2741 // Expect 13 acks, every 3rd packet.
2742 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(13);
2743 // Receives packets 1 - 39.
2744 for (size_t i = 1; i <= 39; ++i) {
2745 ProcessDataPacket(i);
2746 }
2747}
2748
2749TEST_P(QuicConnectionTest, AckDecimationReducesAcks) {
2750 const size_t kMinRttMs = 40;
2751 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
2752 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
2753 QuicTime::Delta::Zero(), QuicTime::Zero());
2754 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
2755
2756 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
2757
2758 // Start ack decimation from 10th packet.
2759 connection_.set_min_received_before_ack_decimation(10);
2760
2761 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2762 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(30);
2763
2764 // Expect 6 acks: 5 acks between packets 1-10, and ack at 20.
2765 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(6);
2766 // Receives packets 1 - 29.
2767 for (size_t i = 1; i <= 29; ++i) {
2768 ProcessDataPacket(i);
2769 }
2770
2771 // We now receive the 30th packet, and so we send an ack.
2772 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2773 ProcessDataPacket(30);
2774}
2775
2776TEST_P(QuicConnectionTest, AckNeedsRetransmittableFrames) {
ianswett68cf0042019-05-09 08:37:58 -07002777 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002778 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2779 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(99);
2780
2781 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(19);
2782 // Receives packets 1 - 39.
2783 for (size_t i = 1; i <= 39; ++i) {
2784 ProcessDataPacket(i);
2785 }
2786 // Receiving Packet 40 causes 20th ack to send. Session is informed and adds
2787 // WINDOW_UPDATE.
2788 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
2789 .WillOnce(Invoke([this]() {
2790 connection_.SendControlFrame(
2791 QuicFrame(new QuicWindowUpdateFrame(1, 0, 0)));
2792 }));
2793 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2794 EXPECT_EQ(0u, writer_->window_update_frames().size());
2795 ProcessDataPacket(40);
2796 EXPECT_EQ(1u, writer_->window_update_frames().size());
2797
2798 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(9);
2799 // Receives packets 41 - 59.
2800 for (size_t i = 41; i <= 59; ++i) {
2801 ProcessDataPacket(i);
2802 }
2803 // Send a packet containing stream frame.
QUICHE team8c1daa22019-03-13 08:33:41 -07002804 SendStreamDataToPeer(
nharper46833c32019-05-15 21:33:05 -07002805 QuicUtils::GetFirstBidirectionalStreamId(
2806 connection_.version().transport_version, Perspective::IS_CLIENT),
QUICHE team8c1daa22019-03-13 08:33:41 -07002807 "bar", 0, NO_FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002808
2809 // Session will not be informed until receiving another 20 packets.
2810 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(19);
2811 for (size_t i = 60; i <= 98; ++i) {
2812 ProcessDataPacket(i);
2813 EXPECT_EQ(0u, writer_->window_update_frames().size());
2814 }
2815 // Session does not add a retransmittable frame.
2816 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
2817 .WillOnce(Invoke([this]() {
2818 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
2819 }));
2820 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2821 EXPECT_EQ(0u, writer_->ping_frames().size());
2822 ProcessDataPacket(99);
2823 EXPECT_EQ(0u, writer_->window_update_frames().size());
2824 // A ping frame will be added.
2825 EXPECT_EQ(1u, writer_->ping_frames().size());
2826}
2827
2828TEST_P(QuicConnectionTest, LeastUnackedLower) {
fayangc31c9952019-06-05 13:54:48 -07002829 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002830 return;
2831 }
2832 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2833
2834 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
2835 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
2836 SendStreamDataToPeer(1, "eep", 6, NO_FIN, nullptr);
2837
2838 // Start out saying the least unacked is 2.
2839 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
2840 ProcessStopWaitingPacket(InitStopWaitingFrame(2));
2841
2842 // Change it to 1, but lower the packet number to fake out-of-order packets.
2843 // This should be fine.
2844 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 1);
2845 // The scheduler will not process out of order acks, but all packet processing
2846 // causes the connection to try to write.
2847 if (!GetParam().no_stop_waiting) {
2848 EXPECT_CALL(visitor_, OnCanWrite());
2849 }
2850 ProcessStopWaitingPacket(InitStopWaitingFrame(1));
2851
2852 // Now claim it's one, but set the ordering so it was sent "after" the first
2853 // one. This should cause a connection error.
2854 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 7);
2855 if (!GetParam().no_stop_waiting) {
rch39c88ab2019-10-16 19:24:40 -07002856 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2857 .Times(AtLeast(1));
fkastenholz5d880a92019-06-21 09:01:56 -07002858 EXPECT_CALL(visitor_,
rch39c88ab2019-10-16 19:24:40 -07002859 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
2860 .Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002861 }
2862 ProcessStopWaitingPacket(InitStopWaitingFrame(1));
fkastenholz5d880a92019-06-21 09:01:56 -07002863 if (!GetParam().no_stop_waiting) {
2864 TestConnectionCloseQuicErrorCode(QUIC_INVALID_STOP_WAITING_DATA);
2865 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002866}
2867
2868TEST_P(QuicConnectionTest, TooManySentPackets) {
2869 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2870
2871 QuicPacketCount max_tracked_packets = 50;
2872 QuicConnectionPeer::SetMaxTrackedPackets(&connection_, max_tracked_packets);
2873
2874 const int num_packets = max_tracked_packets + 5;
2875
2876 for (int i = 0; i < num_packets; ++i) {
2877 SendStreamDataToPeer(1, "foo", 3 * i, NO_FIN, nullptr);
2878 }
2879
2880 // Ack packet 1, which leaves more than the limit outstanding.
2881 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2882 EXPECT_CALL(visitor_,
fkastenholz5d880a92019-06-21 09:01:56 -07002883 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002884
2885 // Nack the first packet and ack the rest, leaving a huge gap.
2886 QuicAckFrame frame1 = ConstructAckFrame(num_packets, 1);
2887 ProcessAckPacket(&frame1);
fkastenholz5d880a92019-06-21 09:01:56 -07002888 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002889}
2890
2891TEST_P(QuicConnectionTest, LargestObservedLower) {
2892 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2893
2894 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
2895 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
2896 SendStreamDataToPeer(1, "eep", 6, NO_FIN, nullptr);
2897 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2898
2899 // Start out saying the largest observed is 2.
2900 QuicAckFrame frame1 = InitAckFrame(1);
2901 QuicAckFrame frame2 = InitAckFrame(2);
2902 ProcessAckPacket(&frame2);
2903
fayang745c93a2019-06-21 13:43:04 -07002904 EXPECT_CALL(visitor_, OnCanWrite());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002905 ProcessAckPacket(&frame1);
2906}
2907
2908TEST_P(QuicConnectionTest, AckUnsentData) {
2909 // Ack a packet which has not been sent.
fkastenholz5d880a92019-06-21 09:01:56 -07002910 EXPECT_CALL(visitor_,
2911 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002912 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
rch39c88ab2019-10-16 19:24:40 -07002913 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002914 QuicAckFrame frame = InitAckFrame(1);
2915 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
2916 ProcessAckPacket(&frame);
fkastenholz5d880a92019-06-21 09:01:56 -07002917 TestConnectionCloseQuicErrorCode(QUIC_INVALID_ACK_DATA);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002918}
2919
2920TEST_P(QuicConnectionTest, BasicSending) {
QUICHE teamcd098022019-03-22 18:49:55 -07002921 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2922 return;
2923 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002924 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2925 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2926 ProcessDataPacket(1);
2927 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
2928 QuicPacketNumber last_packet;
2929 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
2930 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
2931 SendAckPacketToPeer(); // Packet 2
2932
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 SendAckPacketToPeer(); // Packet 3
2941 if (GetParam().no_stop_waiting) {
2942 // Expect no stop waiting frame is sent.
2943 EXPECT_FALSE(least_unacked().IsInitialized());
2944 } else {
2945 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
2946 }
2947
2948 SendStreamDataToPeer(1, "bar", 3, NO_FIN, &last_packet); // Packet 4
2949 EXPECT_EQ(QuicPacketNumber(4u), last_packet);
2950 SendAckPacketToPeer(); // Packet 5
2951 if (GetParam().no_stop_waiting) {
2952 // Expect no stop waiting frame is sent.
2953 EXPECT_FALSE(least_unacked().IsInitialized());
2954 } else {
2955 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
2956 }
2957
2958 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2959
2960 // Peer acks up to packet 3.
2961 QuicAckFrame frame = InitAckFrame(3);
2962 ProcessAckPacket(&frame);
2963 SendAckPacketToPeer(); // Packet 6
2964
2965 // As soon as we've acked one, we skip ack packets 2 and 3 and note lack of
2966 // ack for 4.
2967 if (GetParam().no_stop_waiting) {
2968 // Expect no stop waiting frame is sent.
2969 EXPECT_FALSE(least_unacked().IsInitialized());
2970 } else {
2971 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
2972 }
2973
2974 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2975
2976 // Peer acks up to packet 4, the last packet.
2977 QuicAckFrame frame2 = InitAckFrame(6);
2978 ProcessAckPacket(&frame2); // Acks don't instigate acks.
2979
2980 // Verify that we did not send an ack.
2981 EXPECT_EQ(QuicPacketNumber(6u), writer_->header().packet_number);
2982
2983 // So the last ack has not changed.
2984 if (GetParam().no_stop_waiting) {
2985 // Expect no stop waiting frame is sent.
2986 EXPECT_FALSE(least_unacked().IsInitialized());
2987 } else {
2988 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
2989 }
2990
2991 // If we force an ack, we shouldn't change our retransmit state.
2992 SendAckPacketToPeer(); // Packet 7
2993 if (GetParam().no_stop_waiting) {
2994 // Expect no stop waiting frame is sent.
2995 EXPECT_FALSE(least_unacked().IsInitialized());
2996 } else {
2997 EXPECT_EQ(QuicPacketNumber(7u), least_unacked());
2998 }
2999
3000 // But if we send more data it should.
3001 SendStreamDataToPeer(1, "eep", 6, NO_FIN, &last_packet); // Packet 8
3002 EXPECT_EQ(QuicPacketNumber(8u), last_packet);
3003 SendAckPacketToPeer(); // Packet 9
3004 if (GetParam().no_stop_waiting) {
3005 // Expect no stop waiting frame is sent.
3006 EXPECT_FALSE(least_unacked().IsInitialized());
3007 } else {
3008 EXPECT_EQ(QuicPacketNumber(7u), least_unacked());
3009 }
3010}
3011
3012// QuicConnection should record the packet sent-time prior to sending the
3013// packet.
3014TEST_P(QuicConnectionTest, RecordSentTimeBeforePacketSent) {
3015 // We're using a MockClock for the tests, so we have complete control over the
3016 // time.
3017 // Our recorded timestamp for the last packet sent time will be passed in to
3018 // the send_algorithm. Make sure that it is set to the correct value.
3019 QuicTime actual_recorded_send_time = QuicTime::Zero();
3020 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3021 .WillOnce(SaveArg<0>(&actual_recorded_send_time));
3022
3023 // First send without any pause and check the result.
3024 QuicTime expected_recorded_send_time = clock_.Now();
3025 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3026 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
3027 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
3028 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
3029
3030 // Now pause during the write, and check the results.
3031 actual_recorded_send_time = QuicTime::Zero();
3032 const QuicTime::Delta write_pause_time_delta =
3033 QuicTime::Delta::FromMilliseconds(5000);
3034 SetWritePauseTimeDelta(write_pause_time_delta);
3035 expected_recorded_send_time = clock_.Now();
3036
3037 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3038 .WillOnce(SaveArg<0>(&actual_recorded_send_time));
3039 connection_.SendStreamDataWithString(2, "baz", 0, NO_FIN);
3040 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
3041 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
3042 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
3043}
3044
3045TEST_P(QuicConnectionTest, FramePacking) {
3046 // Send two stream frames in 1 packet by queueing them.
3047 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3048 {
fayanga4b37b22019-06-18 13:37:47 -07003049 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003050 connection_.SendStreamData3();
3051 connection_.SendStreamData5();
3052 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3053 }
3054 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3055 EXPECT_FALSE(connection_.HasQueuedData());
3056
3057 // Parse the last packet and ensure it's an ack and two stream frames from
3058 // two different streams.
3059 if (GetParam().no_stop_waiting) {
3060 EXPECT_EQ(2u, writer_->frame_count());
3061 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
3062 } else {
3063 EXPECT_EQ(2u, writer_->frame_count());
3064 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
3065 }
3066
3067 EXPECT_TRUE(writer_->ack_frames().empty());
3068
3069 ASSERT_EQ(2u, writer_->stream_frames().size());
3070 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3071 writer_->stream_frames()[0]->stream_id);
3072 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3073 writer_->stream_frames()[1]->stream_id);
3074}
3075
3076TEST_P(QuicConnectionTest, FramePackingNonCryptoThenCrypto) {
3077 // Send two stream frames (one non-crypto, then one crypto) in 2 packets by
3078 // queueing them.
3079 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3080 {
3081 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
fayanga4b37b22019-06-18 13:37:47 -07003082 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003083 connection_.SendStreamData3();
3084 connection_.SendCryptoStreamData();
3085 }
3086 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3087 EXPECT_FALSE(connection_.HasQueuedData());
3088
3089 // Parse the last packet and ensure it's the crypto stream frame.
3090 EXPECT_EQ(2u, writer_->frame_count());
3091 ASSERT_EQ(1u, writer_->padding_frames().size());
QUICHE teamea740082019-03-11 17:58:43 -07003092 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003093 ASSERT_EQ(1u, writer_->stream_frames().size());
3094 EXPECT_EQ(QuicUtils::GetCryptoStreamId(connection_.transport_version()),
3095 writer_->stream_frames()[0]->stream_id);
3096 } else {
3097 EXPECT_EQ(1u, writer_->crypto_frames().size());
3098 }
3099}
3100
3101TEST_P(QuicConnectionTest, FramePackingCryptoThenNonCrypto) {
3102 // Send two stream frames (one crypto, then one non-crypto) in 2 packets by
3103 // queueing them.
3104 {
3105 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3106 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
fayanga4b37b22019-06-18 13:37:47 -07003107 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003108 connection_.SendCryptoStreamData();
3109 connection_.SendStreamData3();
3110 }
3111 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3112 EXPECT_FALSE(connection_.HasQueuedData());
3113
3114 // Parse the last packet and ensure it's the stream frame from stream 3.
nharper55fa6132019-05-07 19:37:21 -07003115 size_t padding_frame_count = writer_->padding_frames().size();
3116 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003117 ASSERT_EQ(1u, writer_->stream_frames().size());
3118 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3119 writer_->stream_frames()[0]->stream_id);
3120}
3121
3122TEST_P(QuicConnectionTest, FramePackingAckResponse) {
3123 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3124 // Process a data packet to queue up a pending ack.
fayang3451f6e2019-06-11 08:18:12 -07003125 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3126 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
3127 } else {
3128 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3129 }
3130 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
3131
QUICHE teama6ef0a62019-03-07 20:34:33 -05003132 QuicPacketNumber last_packet;
nharper46833c32019-05-15 21:33:05 -07003133 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3134 connection_.SendCryptoDataWithString("foo", 0);
3135 } else {
3136 SendStreamDataToPeer(
3137 QuicUtils::GetCryptoStreamId(connection_.transport_version()), "foo", 0,
3138 NO_FIN, &last_packet);
3139 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003140 // Verify ack is bundled with outging packet.
3141 EXPECT_FALSE(writer_->ack_frames().empty());
3142
3143 EXPECT_CALL(visitor_, OnCanWrite())
3144 .WillOnce(DoAll(IgnoreResult(InvokeWithoutArgs(
3145 &connection_, &TestConnection::SendStreamData3)),
3146 IgnoreResult(InvokeWithoutArgs(
3147 &connection_, &TestConnection::SendStreamData5))));
3148
3149 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3150
3151 // Process a data packet to cause the visitor's OnCanWrite to be invoked.
3152 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
QUICHE team8c1daa22019-03-13 08:33:41 -07003153 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07003154 std::make_unique<TaggingEncrypter>(0x01));
zhongyi546cc452019-04-12 15:27:49 -07003155 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07003156 std::make_unique<StrictTaggingDecrypter>(0x01));
nharper2c9f02a2019-05-08 10:25:50 -07003157 ProcessDataPacket(2);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003158
3159 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3160 EXPECT_FALSE(connection_.HasQueuedData());
3161
3162 // Parse the last packet and ensure it's an ack and two stream frames from
3163 // two different streams.
3164 if (GetParam().no_stop_waiting) {
3165 EXPECT_EQ(3u, writer_->frame_count());
3166 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
3167 } else {
3168 EXPECT_EQ(4u, writer_->frame_count());
3169 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3170 }
3171 EXPECT_FALSE(writer_->ack_frames().empty());
3172 ASSERT_EQ(2u, writer_->stream_frames().size());
3173 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3174 writer_->stream_frames()[0]->stream_id);
3175 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3176 writer_->stream_frames()[1]->stream_id);
3177}
3178
3179TEST_P(QuicConnectionTest, FramePackingSendv) {
nharper46833c32019-05-15 21:33:05 -07003180 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003181 // Send data in 1 packet by writing multiple blocks in a single iovector
3182 // using writev.
3183 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3184
3185 char data[] = "ABCDEF";
3186 struct iovec iov[2];
3187 iov[0].iov_base = data;
3188 iov[0].iov_len = 4;
3189 iov[1].iov_base = data + 4;
3190 iov[1].iov_len = 2;
nharper46833c32019-05-15 21:33:05 -07003191 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
3192 connection_.transport_version(), Perspective::IS_CLIENT);
3193 connection_.SaveAndSendStreamData(stream_id, iov, 2, 6, 0, NO_FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003194
3195 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3196 EXPECT_FALSE(connection_.HasQueuedData());
3197
3198 // Parse the last packet and ensure multiple iovector blocks have
3199 // been packed into a single stream frame from one stream.
nharper46833c32019-05-15 21:33:05 -07003200 EXPECT_EQ(1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003201 EXPECT_EQ(1u, writer_->stream_frames().size());
nharper46833c32019-05-15 21:33:05 -07003202 EXPECT_EQ(0u, writer_->padding_frames().size());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003203 QuicStreamFrame* frame = writer_->stream_frames()[0].get();
nharper46833c32019-05-15 21:33:05 -07003204 EXPECT_EQ(stream_id, frame->stream_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003205 EXPECT_EQ("ABCDEF", QuicStringPiece(frame->data_buffer, frame->data_length));
3206}
3207
3208TEST_P(QuicConnectionTest, FramePackingSendvQueued) {
nharper46833c32019-05-15 21:33:05 -07003209 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003210 // Try to send two stream frames in 1 packet by using writev.
3211 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3212
3213 BlockOnNextWrite();
3214 char data[] = "ABCDEF";
3215 struct iovec iov[2];
3216 iov[0].iov_base = data;
3217 iov[0].iov_len = 4;
3218 iov[1].iov_base = data + 4;
3219 iov[1].iov_len = 2;
nharper46833c32019-05-15 21:33:05 -07003220 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
3221 connection_.transport_version(), Perspective::IS_CLIENT);
3222 connection_.SaveAndSendStreamData(stream_id, iov, 2, 6, 0, NO_FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003223
3224 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3225 EXPECT_TRUE(connection_.HasQueuedData());
3226
3227 // Unblock the writes and actually send.
3228 writer_->SetWritable();
3229 connection_.OnCanWrite();
3230 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3231
3232 // Parse the last packet and ensure it's one stream frame from one stream.
nharper46833c32019-05-15 21:33:05 -07003233 EXPECT_EQ(1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003234 EXPECT_EQ(1u, writer_->stream_frames().size());
nharper46833c32019-05-15 21:33:05 -07003235 EXPECT_EQ(0u, writer_->padding_frames().size());
3236 EXPECT_EQ(stream_id, writer_->stream_frames()[0]->stream_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003237}
3238
3239TEST_P(QuicConnectionTest, SendingZeroBytes) {
3240 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3241 // Send a zero byte write with a fin using writev.
3242 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
nharper46833c32019-05-15 21:33:05 -07003243 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
3244 connection_.transport_version(), Perspective::IS_CLIENT);
3245 connection_.SaveAndSendStreamData(stream_id, nullptr, 0, 0, 0, FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003246
3247 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3248 EXPECT_FALSE(connection_.HasQueuedData());
3249
nharper55fa6132019-05-07 19:37:21 -07003250 // Padding frames are added by v99 to ensure a minimum packet size.
3251 size_t extra_padding_frames = 0;
3252 if (GetParam().version.HasHeaderProtection()) {
3253 extra_padding_frames = 1;
3254 }
3255
QUICHE teama6ef0a62019-03-07 20:34:33 -05003256 // Parse the last packet and ensure it's one stream frame from one stream.
nharper55fa6132019-05-07 19:37:21 -07003257 EXPECT_EQ(1u + extra_padding_frames, writer_->frame_count());
3258 EXPECT_EQ(extra_padding_frames, writer_->padding_frames().size());
3259 ASSERT_EQ(1u, writer_->stream_frames().size());
nharper46833c32019-05-15 21:33:05 -07003260 EXPECT_EQ(stream_id, writer_->stream_frames()[0]->stream_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003261 EXPECT_TRUE(writer_->stream_frames()[0]->fin);
3262}
3263
3264TEST_P(QuicConnectionTest, LargeSendWithPendingAck) {
3265 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3266 // Set the ack alarm by processing a ping frame.
3267 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3268
3269 // Processs a PING frame.
3270 ProcessFramePacket(QuicFrame(QuicPingFrame()));
3271 // Ensure that this has caused the ACK alarm to be set.
3272 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
3273 EXPECT_TRUE(ack_alarm->IsSet());
3274
3275 // Send data and ensure the ack is bundled.
3276 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(8);
3277 size_t len = 10000;
3278 std::unique_ptr<char[]> data_array(new char[len]);
3279 memset(data_array.get(), '?', len);
3280 struct iovec iov;
3281 iov.iov_base = data_array.get();
3282 iov.iov_len = len;
3283 QuicConsumedData consumed = connection_.SaveAndSendStreamData(
dschinazi552accc2019-06-17 17:07:34 -07003284 GetNthClientInitiatedStreamId(0, connection_.transport_version()), &iov,
3285 1, len, 0, FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003286 EXPECT_EQ(len, consumed.bytes_consumed);
3287 EXPECT_TRUE(consumed.fin_consumed);
3288 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3289 EXPECT_FALSE(connection_.HasQueuedData());
3290
3291 // Parse the last packet and ensure it's one stream frame with a fin.
3292 EXPECT_EQ(1u, writer_->frame_count());
nharper55fa6132019-05-07 19:37:21 -07003293 ASSERT_EQ(1u, writer_->stream_frames().size());
dschinazi552accc2019-06-17 17:07:34 -07003294 EXPECT_EQ(GetNthClientInitiatedStreamId(0, connection_.transport_version()),
QUICHE teama6ef0a62019-03-07 20:34:33 -05003295 writer_->stream_frames()[0]->stream_id);
3296 EXPECT_TRUE(writer_->stream_frames()[0]->fin);
3297 // Ensure the ack alarm was cancelled when the ack was sent.
3298 EXPECT_FALSE(ack_alarm->IsSet());
3299}
3300
3301TEST_P(QuicConnectionTest, OnCanWrite) {
3302 // Visitor's OnCanWrite will send data, but will have more pending writes.
3303 EXPECT_CALL(visitor_, OnCanWrite())
3304 .WillOnce(DoAll(IgnoreResult(InvokeWithoutArgs(
3305 &connection_, &TestConnection::SendStreamData3)),
3306 IgnoreResult(InvokeWithoutArgs(
3307 &connection_, &TestConnection::SendStreamData5))));
3308 {
3309 InSequence seq;
3310 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillOnce(Return(true));
3311 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
3312 .WillRepeatedly(Return(false));
3313 }
3314
3315 EXPECT_CALL(*send_algorithm_, CanSend(_))
3316 .WillRepeatedly(testing::Return(true));
3317
3318 connection_.OnCanWrite();
3319
3320 // Parse the last packet and ensure it's the two stream frames from
3321 // two different streams.
3322 EXPECT_EQ(2u, writer_->frame_count());
3323 EXPECT_EQ(2u, writer_->stream_frames().size());
3324 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3325 writer_->stream_frames()[0]->stream_id);
3326 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3327 writer_->stream_frames()[1]->stream_id);
3328}
3329
3330TEST_P(QuicConnectionTest, RetransmitOnNack) {
3331 QuicPacketNumber last_packet;
3332 QuicByteCount second_packet_size;
3333 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet); // Packet 1
3334 second_packet_size =
3335 SendStreamDataToPeer(3, "foos", 3, NO_FIN, &last_packet); // Packet 2
3336 SendStreamDataToPeer(3, "fooos", 7, NO_FIN, &last_packet); // Packet 3
3337
3338 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3339
3340 // Don't lose a packet on an ack, and nothing is retransmitted.
3341 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3342 QuicAckFrame ack_one = InitAckFrame(1);
3343 ProcessAckPacket(&ack_one);
3344
3345 // Lose a packet and ensure it triggers retransmission.
3346 QuicAckFrame nack_two = ConstructAckFrame(3, 2);
3347 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003348 lost_packets.push_back(
3349 LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003350 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3351 .WillOnce(SetArgPointee<5>(lost_packets));
3352 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3353 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3354 EXPECT_FALSE(QuicPacketCreatorPeer::SendVersionInPacket(creator_));
3355 ProcessAckPacket(&nack_two);
3356}
3357
3358TEST_P(QuicConnectionTest, DoNotSendQueuedPacketForResetStream) {
3359 // Block the connection to queue the packet.
3360 BlockOnNextWrite();
3361
3362 QuicStreamId stream_id = 2;
3363 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
3364
3365 // Now that there is a queued packet, reset the stream.
3366 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
3367
3368 // Unblock the connection and verify that only the RST_STREAM is sent.
3369 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3370 writer_->SetWritable();
3371 connection_.OnCanWrite();
3372 if (!connection_.session_decides_what_to_write()) {
3373 // OnCanWrite will cause RST_STREAM be sent again.
3374 connection_.SendControlFrame(QuicFrame(new QuicRstStreamFrame(
3375 1, stream_id, QUIC_ERROR_PROCESSING_STREAM, 14)));
3376 }
nharper55fa6132019-05-07 19:37:21 -07003377 size_t padding_frame_count = writer_->padding_frames().size();
3378 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003379 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3380}
3381
3382TEST_P(QuicConnectionTest, SendQueuedPacketForQuicRstStreamNoError) {
3383 // Block the connection to queue the packet.
3384 BlockOnNextWrite();
3385
3386 QuicStreamId stream_id = 2;
fayang2ce66082019-10-02 06:29:04 -07003387 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
3388 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3389 } else {
3390 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3391 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003392 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
3393
3394 // Now that there is a queued packet, reset the stream.
3395 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 3);
3396
3397 // Unblock the connection and verify that the RST_STREAM is sent and the data
3398 // packet is sent.
fayang2ce66082019-10-02 06:29:04 -07003399 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
3400 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3401 .Times(AtLeast(1));
3402 } else {
3403 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3404 .Times(AtLeast(2));
3405 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003406 writer_->SetWritable();
3407 connection_.OnCanWrite();
3408 if (!connection_.session_decides_what_to_write()) {
3409 // OnCanWrite will cause RST_STREAM be sent again.
3410 connection_.SendControlFrame(QuicFrame(
3411 new QuicRstStreamFrame(1, stream_id, QUIC_STREAM_NO_ERROR, 14)));
3412 }
nharper55fa6132019-05-07 19:37:21 -07003413 size_t padding_frame_count = writer_->padding_frames().size();
3414 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003415 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3416}
3417
3418TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnNack) {
3419 QuicStreamId stream_id = 2;
3420 QuicPacketNumber last_packet;
3421 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3422 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3423 SendStreamDataToPeer(stream_id, "fooos", 7, NO_FIN, &last_packet);
3424
3425 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3426 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 12);
3427
3428 // Lose a packet and ensure it does not trigger retransmission.
3429 QuicAckFrame nack_two = ConstructAckFrame(last_packet, last_packet - 1);
3430 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3431 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3432 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3433 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3434 ProcessAckPacket(&nack_two);
3435}
3436
3437TEST_P(QuicConnectionTest, RetransmitForQuicRstStreamNoErrorOnNack) {
3438 QuicStreamId stream_id = 2;
3439 QuicPacketNumber last_packet;
3440 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3441 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3442 SendStreamDataToPeer(stream_id, "fooos", 7, NO_FIN, &last_packet);
3443
3444 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3445 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 12);
3446
3447 // Lose a packet, ensure it triggers retransmission.
3448 QuicAckFrame nack_two = ConstructAckFrame(last_packet, last_packet - 1);
3449 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3450 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003451 lost_packets.push_back(LostPacket(last_packet - 1, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003452 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3453 .WillOnce(SetArgPointee<5>(lost_packets));
3454 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3455 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
3456 ProcessAckPacket(&nack_two);
3457}
3458
3459TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnRTO) {
3460 QuicStreamId stream_id = 2;
3461 QuicPacketNumber last_packet;
3462 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3463
3464 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3465 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
3466
3467 // Fire the RTO and verify that the RST_STREAM is resent, not stream data.
3468 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3469 clock_.AdvanceTime(DefaultRetransmissionTime());
3470 connection_.GetRetransmissionAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07003471 size_t padding_frame_count = writer_->padding_frames().size();
3472 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003473 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3474 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
3475}
3476
3477// Ensure that if the only data in flight is non-retransmittable, the
3478// retransmission alarm is not set.
3479TEST_P(QuicConnectionTest, CancelRetransmissionAlarmAfterResetStream) {
3480 QuicStreamId stream_id = 2;
3481 QuicPacketNumber last_data_packet;
3482 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
3483
3484 // Cancel the stream.
3485 const QuicPacketNumber rst_packet = last_data_packet + 1;
3486 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, rst_packet, _, _)).Times(1);
3487 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
3488
3489 // Ack the RST_STREAM frame (since it's retransmittable), but not the data
3490 // packet, which is no longer retransmittable since the stream was cancelled.
3491 QuicAckFrame nack_stream_data =
3492 ConstructAckFrame(rst_packet, last_data_packet);
3493 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3494 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3495 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3496 ProcessAckPacket(&nack_stream_data);
3497
3498 // Ensure that the data is still in flight, but the retransmission alarm is no
3499 // longer set.
ianswett9f459cb2019-04-21 06:39:59 -07003500 EXPECT_GT(manager_->GetBytesInFlight(), 0u);
fayange861aee2019-10-16 13:40:39 -07003501 if (connection_.session_decides_what_to_write()) {
fayang67f82272019-08-14 16:08:45 -07003502 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3503 } else {
3504 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3505 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003506}
3507
3508TEST_P(QuicConnectionTest, RetransmitForQuicRstStreamNoErrorOnRTO) {
3509 connection_.SetMaxTailLossProbes(0);
3510
3511 QuicStreamId stream_id = 2;
3512 QuicPacketNumber last_packet;
3513 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3514
3515 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3516 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 3);
3517
3518 // Fire the RTO and verify that the RST_STREAM is resent, the stream data
3519 // is sent.
3520 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(2));
3521 clock_.AdvanceTime(DefaultRetransmissionTime());
3522 connection_.GetRetransmissionAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07003523 size_t padding_frame_count = writer_->padding_frames().size();
3524 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003525 ASSERT_EQ(1u, writer_->rst_stream_frames().size());
3526 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
3527}
3528
3529TEST_P(QuicConnectionTest, DoNotSendPendingRetransmissionForResetStream) {
3530 QuicStreamId stream_id = 2;
3531 QuicPacketNumber last_packet;
3532 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3533 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3534 BlockOnNextWrite();
3535 connection_.SendStreamDataWithString(stream_id, "fooos", 7, NO_FIN);
3536
3537 // Lose a packet which will trigger a pending retransmission.
3538 QuicAckFrame ack = ConstructAckFrame(last_packet, last_packet - 1);
3539 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3540 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3541 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3542 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3543 ProcessAckPacket(&ack);
3544
3545 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 12);
3546
3547 // Unblock the connection and verify that the RST_STREAM is sent but not the
3548 // second data packet nor a retransmit.
3549 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3550 writer_->SetWritable();
3551 connection_.OnCanWrite();
3552 if (!connection_.session_decides_what_to_write()) {
3553 // OnCanWrite will cause this RST_STREAM_FRAME be sent again.
3554 connection_.SendControlFrame(QuicFrame(new QuicRstStreamFrame(
3555 1, stream_id, QUIC_ERROR_PROCESSING_STREAM, 14)));
3556 }
nharper55fa6132019-05-07 19:37:21 -07003557 size_t padding_frame_count = writer_->padding_frames().size();
3558 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
zhongyi546cc452019-04-12 15:27:49 -07003559 ASSERT_EQ(1u, writer_->rst_stream_frames().size());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003560 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
3561}
3562
3563TEST_P(QuicConnectionTest, SendPendingRetransmissionForQuicRstStreamNoError) {
3564 QuicStreamId stream_id = 2;
3565 QuicPacketNumber last_packet;
3566 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3567 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3568 BlockOnNextWrite();
3569 connection_.SendStreamDataWithString(stream_id, "fooos", 7, NO_FIN);
3570
3571 // Lose a packet which will trigger a pending retransmission.
3572 QuicAckFrame ack = ConstructAckFrame(last_packet, last_packet - 1);
3573 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3574 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003575 lost_packets.push_back(LostPacket(last_packet - 1, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003576 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3577 .WillOnce(SetArgPointee<5>(lost_packets));
3578 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3579 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3580 ProcessAckPacket(&ack);
3581
3582 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 12);
3583
3584 // Unblock the connection and verify that the RST_STREAM is sent and the
3585 // second data packet or a retransmit is sent.
3586 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(2));
3587 writer_->SetWritable();
3588 connection_.OnCanWrite();
3589 // The RST_STREAM_FRAME is sent after queued packets and pending
3590 // retransmission.
3591 connection_.SendControlFrame(QuicFrame(
3592 new QuicRstStreamFrame(1, stream_id, QUIC_STREAM_NO_ERROR, 14)));
nharper55fa6132019-05-07 19:37:21 -07003593 size_t padding_frame_count = writer_->padding_frames().size();
3594 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003595 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3596}
3597
3598TEST_P(QuicConnectionTest, RetransmitAckedPacket) {
3599 QuicPacketNumber last_packet;
3600 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
3601 SendStreamDataToPeer(1, "foos", 3, NO_FIN, &last_packet); // Packet 2
3602 SendStreamDataToPeer(1, "fooos", 7, NO_FIN, &last_packet); // Packet 3
3603
3604 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3605
3606 // Instigate a loss with an ack.
3607 QuicAckFrame nack_two = ConstructAckFrame(3, 2);
3608 // The first nack should trigger a fast retransmission, but we'll be
3609 // write blocked, so the packet will be queued.
3610 BlockOnNextWrite();
3611
3612 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003613 lost_packets.push_back(
3614 LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003615 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3616 .WillOnce(SetArgPointee<5>(lost_packets));
3617 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
fayang2ce66082019-10-02 06:29:04 -07003618 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
3619 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _))
3620 .Times(1);
3621 } else {
3622 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3623 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003624 ProcessAckPacket(&nack_two);
3625 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3626
3627 // Now, ack the previous transmission.
3628 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3629 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(false, _, _, _, _));
3630 QuicAckFrame ack_all = InitAckFrame(3);
3631 ProcessAckPacket(&ack_all);
3632
fayang2ce66082019-10-02 06:29:04 -07003633 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
3634 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _))
3635 .Times(0);
3636 } else {
3637 // Unblock the socket and attempt to send the queued packets. We will always
3638 // send the retransmission.
3639 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _))
3640 .Times(1);
3641 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003642
3643 writer_->SetWritable();
3644 connection_.OnCanWrite();
3645
3646 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3647 // We do not store retransmittable frames of this retransmission.
3648 EXPECT_FALSE(QuicConnectionPeer::HasRetransmittableFrames(&connection_, 4));
3649}
3650
3651TEST_P(QuicConnectionTest, RetransmitNackedLargestObserved) {
3652 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3653 QuicPacketNumber original, second;
3654
3655 QuicByteCount packet_size =
3656 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &original); // 1st packet.
3657 SendStreamDataToPeer(3, "bar", 3, NO_FIN, &second); // 2nd packet.
3658
3659 QuicAckFrame frame = InitAckFrame({{second, second + 1}});
3660 // The first nack should retransmit the largest observed packet.
3661 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003662 lost_packets.push_back(LostPacket(original, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003663 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3664 .WillOnce(SetArgPointee<5>(lost_packets));
3665 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3666 // Packet 1 is short header for IETF QUIC because the encryption level
3667 // switched to ENCRYPTION_FORWARD_SECURE in SendStreamDataToPeer.
fayangd4291e42019-05-30 10:31:21 -07003668 EXPECT_CALL(*send_algorithm_,
3669 OnPacketSent(_, _, _,
3670 VersionHasIetfInvariantHeader(
3671 GetParam().version.transport_version)
3672 ? packet_size
3673 : packet_size - kQuicVersionSize,
3674 _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003675 ProcessAckPacket(&frame);
3676}
3677
3678TEST_P(QuicConnectionTest, QueueAfterTwoRTOs) {
fayang62c291b2019-10-10 11:51:34 -07003679 if (connection_.PtoEnabled() ||
3680 !connection_.session_decides_what_to_write()) {
fayang5f135052019-08-22 17:59:40 -07003681 return;
3682 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003683 connection_.SetMaxTailLossProbes(0);
3684
3685 for (int i = 0; i < 10; ++i) {
3686 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3687 connection_.SendStreamDataWithString(3, "foo", i * 3, NO_FIN);
3688 }
3689
3690 // Block the writer and ensure they're queued.
3691 BlockOnNextWrite();
3692 clock_.AdvanceTime(DefaultRetransmissionTime());
fayang62c291b2019-10-10 11:51:34 -07003693 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
3694 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
fayang2ce66082019-10-02 06:29:04 -07003695 } else {
fayang62c291b2019-10-10 11:51:34 -07003696 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
fayang2ce66082019-10-02 06:29:04 -07003697 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003698 connection_.GetRetransmissionAlarm()->Fire();
3699 EXPECT_TRUE(connection_.HasQueuedData());
3700
3701 // Unblock the writer.
3702 writer_->SetWritable();
3703 clock_.AdvanceTime(QuicTime::Delta::FromMicroseconds(
3704 2 * DefaultRetransmissionTime().ToMicroseconds()));
fayang62c291b2019-10-10 11:51:34 -07003705 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
3706 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003707 } else {
fayang62c291b2019-10-10 11:51:34 -07003708 // 2 RTOs + 1 TLP, which is buggy.
3709 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003710 }
3711 connection_.GetRetransmissionAlarm()->Fire();
3712 connection_.OnCanWrite();
3713}
3714
3715TEST_P(QuicConnectionTest, WriteBlockedBufferedThenSent) {
3716 BlockOnNextWrite();
3717 writer_->set_is_write_blocked_data_buffered(true);
3718 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3719 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3720 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3721
3722 writer_->SetWritable();
3723 connection_.OnCanWrite();
3724 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3725}
3726
3727TEST_P(QuicConnectionTest, WriteBlockedThenSent) {
3728 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3729 BlockOnNextWrite();
fayang2ce66082019-10-02 06:29:04 -07003730 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
3731 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3732 } else {
3733 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3734 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003735 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
fayang2ce66082019-10-02 06:29:04 -07003736 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
3737 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3738 } else {
3739 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3740 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003741 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3742
3743 // The second packet should also be queued, in order to ensure packets are
3744 // never sent out of order.
3745 writer_->SetWritable();
fayang2ce66082019-10-02 06:29:04 -07003746 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
3747 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3748 } else {
3749 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3750 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003751 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3752 EXPECT_EQ(2u, connection_.NumQueuedPackets());
3753
3754 // Now both are sent in order when we unblock.
fayang2ce66082019-10-02 06:29:04 -07003755 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
3756 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3757 } else {
3758 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3759 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003760 connection_.OnCanWrite();
3761 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
fayang2ce66082019-10-02 06:29:04 -07003762 EXPECT_EQ(0u, connection_.NumQueuedPackets());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003763}
3764
3765TEST_P(QuicConnectionTest, RetransmitWriteBlockedAckedOriginalThenSent) {
3766 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3767 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
3768 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3769
3770 BlockOnNextWrite();
3771 writer_->set_is_write_blocked_data_buffered(true);
3772 // Simulate the retransmission alarm firing.
3773 clock_.AdvanceTime(DefaultRetransmissionTime());
3774 connection_.GetRetransmissionAlarm()->Fire();
3775
3776 // Ack the sent packet before the callback returns, which happens in
3777 // rare circumstances with write blocked sockets.
3778 QuicAckFrame ack = InitAckFrame(1);
3779 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3780 ProcessAckPacket(&ack);
3781
3782 writer_->SetWritable();
3783 connection_.OnCanWrite();
fayange861aee2019-10-16 13:40:39 -07003784 if (connection_.session_decides_what_to_write()) {
fayang67f82272019-08-14 16:08:45 -07003785 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3786 } else {
3787 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3788 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003789 EXPECT_FALSE(QuicConnectionPeer::HasRetransmittableFrames(&connection_, 2));
3790}
3791
3792TEST_P(QuicConnectionTest, AlarmsWhenWriteBlocked) {
3793 // Block the connection.
3794 BlockOnNextWrite();
3795 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
3796 EXPECT_EQ(1u, writer_->packets_write_attempts());
3797 EXPECT_TRUE(writer_->IsWriteBlocked());
3798
3799 // Set the send alarm. Fire the alarm and ensure it doesn't attempt to write.
3800 connection_.GetSendAlarm()->Set(clock_.ApproximateNow());
3801 connection_.GetSendAlarm()->Fire();
3802 EXPECT_TRUE(writer_->IsWriteBlocked());
3803 EXPECT_EQ(1u, writer_->packets_write_attempts());
3804}
3805
3806TEST_P(QuicConnectionTest, NoSendAlarmAfterProcessPacketWhenWriteBlocked) {
3807 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3808
3809 // Block the connection.
3810 BlockOnNextWrite();
3811 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
3812 EXPECT_TRUE(writer_->IsWriteBlocked());
3813 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3814 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
3815
3816 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3817 // Process packet number 1. Can not call ProcessPacket or ProcessDataPacket
3818 // here, because they will fire the alarm after QuicConnection::ProcessPacket
3819 // is returned.
3820 const uint64_t received_packet_num = 1;
3821 const bool has_stop_waiting = false;
nharperc6b99512019-09-19 11:13:48 -07003822 const EncryptionLevel level = ENCRYPTION_FORWARD_SECURE;
3823 std::unique_ptr<QuicPacket> packet(
3824 ConstructDataPacket(received_packet_num, has_stop_waiting, level));
dschinazi66dea072019-04-09 11:41:06 -07003825 char buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05003826 size_t encrypted_length =
3827 peer_framer_.EncryptPayload(level, QuicPacketNumber(received_packet_num),
dschinazi66dea072019-04-09 11:41:06 -07003828 *packet, buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003829 connection_.ProcessUdpPacket(
3830 kSelfAddress, kPeerAddress,
3831 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
3832
3833 EXPECT_TRUE(writer_->IsWriteBlocked());
3834 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
3835}
3836
3837TEST_P(QuicConnectionTest, AddToWriteBlockedListIfWriterBlockedWhenProcessing) {
3838 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3839 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
3840
3841 // Simulate the case where a shared writer gets blocked by another connection.
3842 writer_->SetWriteBlocked();
3843
3844 // Process an ACK, make sure the connection calls visitor_->OnWriteBlocked().
3845 QuicAckFrame ack1 = InitAckFrame(1);
3846 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
3847 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
3848 ProcessAckPacket(1, &ack1);
3849}
3850
3851TEST_P(QuicConnectionTest, DoNotAddToWriteBlockedListAfterDisconnect) {
3852 writer_->SetBatchMode(true);
3853 EXPECT_TRUE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07003854 // Have to explicitly grab the OnConnectionClosed frame and check
3855 // its parameters because this is a silent connection close and the
3856 // frame is not also transmitted to the peer.
3857 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
3858 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003859
3860 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
3861
3862 {
fayanga4b37b22019-06-18 13:37:47 -07003863 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003864 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
3865 ConnectionCloseBehavior::SILENT_CLOSE);
3866
3867 EXPECT_FALSE(connection_.connected());
3868 writer_->SetWriteBlocked();
3869 }
fkastenholz5d880a92019-06-21 09:01:56 -07003870 EXPECT_EQ(1, connection_close_frame_count_);
3871 EXPECT_EQ(QUIC_PEER_GOING_AWAY,
3872 saved_connection_close_frame_.quic_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003873}
3874
3875TEST_P(QuicConnectionTest, AddToWriteBlockedListIfBlockedOnFlushPackets) {
3876 writer_->SetBatchMode(true);
3877 writer_->BlockOnNextFlush();
3878
3879 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
3880 {
fayanga4b37b22019-06-18 13:37:47 -07003881 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003882 // flusher's destructor will call connection_.FlushPackets, which should add
3883 // the connection to the write blocked list.
3884 }
3885}
3886
3887TEST_P(QuicConnectionTest, NoLimitPacketsPerNack) {
3888 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3889 int offset = 0;
3890 // Send packets 1 to 15.
3891 for (int i = 0; i < 15; ++i) {
3892 SendStreamDataToPeer(1, "foo", offset, NO_FIN, nullptr);
3893 offset += 3;
3894 }
3895
3896 // Ack 15, nack 1-14.
3897
3898 QuicAckFrame nack =
3899 InitAckFrame({{QuicPacketNumber(15), QuicPacketNumber(16)}});
3900
3901 // 14 packets have been NACK'd and lost.
3902 LostPacketVector lost_packets;
3903 for (int i = 1; i < 15; ++i) {
dschinazi66dea072019-04-09 11:41:06 -07003904 lost_packets.push_back(
3905 LostPacket(QuicPacketNumber(i), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003906 }
3907 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3908 .WillOnce(SetArgPointee<5>(lost_packets));
3909 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3910 if (connection_.session_decides_what_to_write()) {
3911 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3912 } else {
3913 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(14);
3914 }
3915 ProcessAckPacket(&nack);
3916}
3917
3918// Test sending multiple acks from the connection to the session.
3919TEST_P(QuicConnectionTest, MultipleAcks) {
QUICHE teamcd098022019-03-22 18:49:55 -07003920 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3921 return;
3922 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003923 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3924 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3925 ProcessDataPacket(1);
3926 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
3927 QuicPacketNumber last_packet;
3928 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
3929 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
3930 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet); // Packet 2
3931 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
3932 SendAckPacketToPeer(); // Packet 3
3933 SendStreamDataToPeer(5, "foo", 0, NO_FIN, &last_packet); // Packet 4
3934 EXPECT_EQ(QuicPacketNumber(4u), last_packet);
3935 SendStreamDataToPeer(1, "foo", 3, NO_FIN, &last_packet); // Packet 5
3936 EXPECT_EQ(QuicPacketNumber(5u), last_packet);
3937 SendStreamDataToPeer(3, "foo", 3, NO_FIN, &last_packet); // Packet 6
3938 EXPECT_EQ(QuicPacketNumber(6u), last_packet);
3939
3940 // Client will ack packets 1, 2, [!3], 4, 5.
3941 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3942 QuicAckFrame frame1 = ConstructAckFrame(5, 3);
3943 ProcessAckPacket(&frame1);
3944
3945 // Now the client implicitly acks 3, and explicitly acks 6.
3946 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3947 QuicAckFrame frame2 = InitAckFrame(6);
3948 ProcessAckPacket(&frame2);
3949}
3950
3951TEST_P(QuicConnectionTest, DontLatchUnackedPacket) {
QUICHE teamcd098022019-03-22 18:49:55 -07003952 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3953 return;
3954 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003955 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3956 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3957 ProcessDataPacket(1);
3958 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
3959 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr); // Packet 1;
3960 // From now on, we send acks, so the send algorithm won't mark them pending.
3961 SendAckPacketToPeer(); // Packet 2
3962
3963 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3964 QuicAckFrame frame = InitAckFrame(1);
3965 ProcessAckPacket(&frame);
3966
3967 // Verify that our internal state has least-unacked as 2, because we're still
3968 // waiting for a potential ack for 2.
3969
3970 EXPECT_EQ(QuicPacketNumber(2u), stop_waiting()->least_unacked);
3971
3972 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3973 frame = InitAckFrame(2);
3974 ProcessAckPacket(&frame);
3975 EXPECT_EQ(QuicPacketNumber(3u), stop_waiting()->least_unacked);
3976
3977 // When we send an ack, we make sure our least-unacked makes sense. In this
3978 // case since we're not waiting on an ack for 2 and all packets are acked, we
3979 // set it to 3.
3980 SendAckPacketToPeer(); // Packet 3
3981 // Least_unacked remains at 3 until another ack is received.
3982 EXPECT_EQ(QuicPacketNumber(3u), stop_waiting()->least_unacked);
3983 if (GetParam().no_stop_waiting) {
3984 // Expect no stop waiting frame is sent.
3985 EXPECT_FALSE(least_unacked().IsInitialized());
3986 } else {
3987 // Check that the outgoing ack had its packet number as least_unacked.
3988 EXPECT_EQ(QuicPacketNumber(3u), least_unacked());
3989 }
3990
3991 // Ack the ack, which updates the rtt and raises the least unacked.
3992 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3993 frame = InitAckFrame(3);
3994 ProcessAckPacket(&frame);
3995
3996 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr); // Packet 4
3997 EXPECT_EQ(QuicPacketNumber(4u), stop_waiting()->least_unacked);
3998 SendAckPacketToPeer(); // Packet 5
3999 if (GetParam().no_stop_waiting) {
4000 // Expect no stop waiting frame is sent.
4001 EXPECT_FALSE(least_unacked().IsInitialized());
4002 } else {
4003 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
4004 }
4005
4006 // Send two data packets at the end, and ensure if the last one is acked,
4007 // the least unacked is raised above the ack packets.
4008 SendStreamDataToPeer(1, "bar", 6, NO_FIN, nullptr); // Packet 6
4009 SendStreamDataToPeer(1, "bar", 9, NO_FIN, nullptr); // Packet 7
4010
4011 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4012 frame = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(5)},
4013 {QuicPacketNumber(7), QuicPacketNumber(8)}});
4014 ProcessAckPacket(&frame);
4015
4016 EXPECT_EQ(QuicPacketNumber(6u), stop_waiting()->least_unacked);
4017}
4018
4019TEST_P(QuicConnectionTest, TLP) {
4020 connection_.SetMaxTailLossProbes(1);
4021
4022 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
4023 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4024 QuicTime retransmission_time =
4025 connection_.GetRetransmissionAlarm()->deadline();
4026 EXPECT_NE(QuicTime::Zero(), retransmission_time);
4027
4028 EXPECT_EQ(QuicPacketNumber(1u), writer_->header().packet_number);
4029 // Simulate the retransmission alarm firing and sending a tlp,
4030 // so send algorithm's OnRetransmissionTimeout is not called.
4031 clock_.AdvanceTime(retransmission_time - clock_.Now());
4032 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
4033 connection_.GetRetransmissionAlarm()->Fire();
4034 EXPECT_EQ(QuicPacketNumber(2u), writer_->header().packet_number);
4035 // We do not raise the high water mark yet.
4036 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4037}
4038
zhongyifbb25772019-04-10 16:54:08 -07004039TEST_P(QuicConnectionTest, TailLossProbeDelayForStreamDataInTLPR) {
fayang5f135052019-08-22 17:59:40 -07004040 if (!connection_.session_decides_what_to_write() ||
4041 connection_.PtoEnabled()) {
zhongyi1b2f7832019-06-14 13:31:34 -07004042 return;
4043 }
4044
zhongyifbb25772019-04-10 16:54:08 -07004045 // Set TLPR from QuicConfig.
4046 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4047 QuicConfig config;
4048 QuicTagVector options;
4049 options.push_back(kTLPR);
4050 config.SetConnectionOptionsToSend(options);
4051 connection_.SetFromConfig(config);
4052 connection_.SetMaxTailLossProbes(1);
4053
4054 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
4055 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4056
4057 QuicTime retransmission_time =
4058 connection_.GetRetransmissionAlarm()->deadline();
4059 EXPECT_NE(QuicTime::Zero(), retransmission_time);
4060 QuicTime::Delta expected_tlp_delay =
4061 0.5 * manager_->GetRttStats()->SmoothedOrInitialRtt();
4062 EXPECT_EQ(expected_tlp_delay, retransmission_time - clock_.Now());
4063
4064 EXPECT_EQ(QuicPacketNumber(1u), writer_->header().packet_number);
4065 // Simulate firing of the retransmission alarm and retransmit the packet.
4066 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
4067 clock_.AdvanceTime(retransmission_time - clock_.Now());
4068 connection_.GetRetransmissionAlarm()->Fire();
4069 EXPECT_EQ(QuicPacketNumber(2u), writer_->header().packet_number);
4070
4071 // We do not raise the high water mark yet.
4072 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4073}
4074
4075TEST_P(QuicConnectionTest, TailLossProbeDelayForNonStreamDataInTLPR) {
fayang5f135052019-08-22 17:59:40 -07004076 if (!connection_.session_decides_what_to_write() ||
4077 connection_.PtoEnabled()) {
zhongyi1b2f7832019-06-14 13:31:34 -07004078 return;
4079 }
4080
zhongyifbb25772019-04-10 16:54:08 -07004081 // Set TLPR from QuicConfig.
4082 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4083 QuicConfig config;
4084 QuicTagVector options;
4085 options.push_back(kTLPR);
4086 config.SetConnectionOptionsToSend(options);
4087 connection_.SetFromConfig(config);
4088 connection_.SetMaxTailLossProbes(1);
4089
4090 // Sets retransmittable on wire.
4091 const QuicTime::Delta retransmittable_on_wire_timeout =
4092 QuicTime::Delta::FromMilliseconds(50);
zhongyi79ace162019-10-21 15:57:09 -07004093 connection_.set_initial_retransmittable_on_wire_timeout(
zhongyifbb25772019-04-10 16:54:08 -07004094 retransmittable_on_wire_timeout);
4095
4096 EXPECT_TRUE(connection_.connected());
4097 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4098 .WillRepeatedly(Return(true));
4099 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
4100 EXPECT_FALSE(connection_.IsPathDegrading());
4101 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4102
4103 const char data[] = "data";
4104 size_t data_size = strlen(data);
4105 QuicStreamOffset offset = 0;
4106
4107 // Send a data packet.
4108 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
4109 offset += data_size;
4110
4111 // Path degrading alarm should be set when there is a retransmittable packet
4112 // on the wire.
4113 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
4114
4115 // Verify the path degrading delay.
4116 // First TLP with stream data.
4117 QuicTime::Delta srtt = manager_->GetRttStats()->SmoothedOrInitialRtt();
4118 QuicTime::Delta expected_delay = 0.5 * srtt;
4119 // Add 1st RTO.
4120 QuicTime::Delta retransmission_delay =
4121 QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
4122 expected_delay = expected_delay + retransmission_delay;
4123 // Add 2nd RTO.
4124 expected_delay = expected_delay + retransmission_delay * 2;
4125 EXPECT_EQ(expected_delay,
4126 QuicConnectionPeer::GetSentPacketManager(&connection_)
4127 ->GetPathDegradingDelay());
4128 ASSERT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
4129
4130 // The ping alarm is set for the ping timeout, not the shorter
4131 // retransmittable_on_wire_timeout.
4132 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004133 EXPECT_EQ(connection_.ping_timeout(),
zhongyifbb25772019-04-10 16:54:08 -07004134 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
4135
4136 // Receive an ACK for the data packet.
4137 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4138 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4139 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4140 QuicAckFrame frame =
4141 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
4142 ProcessAckPacket(&frame);
4143
4144 // Path degrading alarm should be cancelled as there is no more
4145 // reretransmittable packets on the wire.
4146 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
4147 // The ping alarm should be set to the retransmittable_on_wire_timeout.
4148 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4149 EXPECT_EQ(retransmittable_on_wire_timeout,
4150 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
4151
4152 // Simulate firing of the retransmittable on wire and send a PING.
4153 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
4154 clock_.AdvanceTime(retransmittable_on_wire_timeout);
4155 connection_.GetPingAlarm()->Fire();
4156
4157 // The retransmission alarm and the path degrading alarm should be set as
4158 // there is a retransmittable packet (PING) on the wire,
4159 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4160 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
4161
4162 // Verify the retransmission delay.
4163 QuicTime::Delta min_rto_timeout =
4164 QuicTime::Delta::FromMilliseconds(kMinRetransmissionTimeMs);
4165 srtt = manager_->GetRttStats()->SmoothedOrInitialRtt();
zhongyi9fa2be32019-09-10 12:39:01 -07004166
4167 // First TLP without unacked stream data will no longer use TLPR.
4168 expected_delay = std::max(2 * srtt, 1.5 * srtt + 0.5 * min_rto_timeout);
zhongyifbb25772019-04-10 16:54:08 -07004169 EXPECT_EQ(expected_delay,
4170 connection_.GetRetransmissionAlarm()->deadline() - clock_.Now());
4171
zhongyi1b2f7832019-06-14 13:31:34 -07004172 // Verify the path degrading delay = TLP delay + 1st RTO + 2nd RTO.
zhongyifbb25772019-04-10 16:54:08 -07004173 // Add 1st RTO.
4174 retransmission_delay =
4175 std::max(manager_->GetRttStats()->smoothed_rtt() +
4176 4 * manager_->GetRttStats()->mean_deviation(),
4177 min_rto_timeout);
4178 expected_delay = expected_delay + retransmission_delay;
4179 // Add 2nd RTO.
4180 expected_delay = expected_delay + retransmission_delay * 2;
4181 EXPECT_EQ(expected_delay,
4182 QuicConnectionPeer::GetSentPacketManager(&connection_)
4183 ->GetPathDegradingDelay());
4184
4185 // The ping alarm is set for the ping timeout, not the shorter
4186 // retransmittable_on_wire_timeout.
4187 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004188 EXPECT_EQ(connection_.ping_timeout(),
zhongyifbb25772019-04-10 16:54:08 -07004189 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
zhongyi1b2f7832019-06-14 13:31:34 -07004190
4191 // Advance a small period of time: 5ms. And receive a retransmitted ACK.
4192 // This will update the retransmission alarm, verify the retransmission delay
4193 // is correct.
4194 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4195 QuicAckFrame ack = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
4196 ProcessAckPacket(&ack);
4197
4198 // Verify the retransmission delay.
zhongyi9fa2be32019-09-10 12:39:01 -07004199 // First TLP without unacked stream data will no longer use TLPR.
4200 expected_delay = std::max(2 * srtt, 1.5 * srtt + 0.5 * min_rto_timeout);
zhongyi1b2f7832019-06-14 13:31:34 -07004201 expected_delay = expected_delay - QuicTime::Delta::FromMilliseconds(5);
4202 EXPECT_EQ(expected_delay,
4203 connection_.GetRetransmissionAlarm()->deadline() - clock_.Now());
zhongyifbb25772019-04-10 16:54:08 -07004204}
4205
QUICHE teama6ef0a62019-03-07 20:34:33 -05004206TEST_P(QuicConnectionTest, RTO) {
fayang5f135052019-08-22 17:59:40 -07004207 if (connection_.PtoEnabled()) {
4208 return;
4209 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004210 connection_.SetMaxTailLossProbes(0);
4211
4212 QuicTime default_retransmission_time =
4213 clock_.ApproximateNow() + DefaultRetransmissionTime();
4214 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
4215 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4216
4217 EXPECT_EQ(QuicPacketNumber(1u), writer_->header().packet_number);
4218 EXPECT_EQ(default_retransmission_time,
4219 connection_.GetRetransmissionAlarm()->deadline());
4220 // Simulate the retransmission alarm firing.
4221 clock_.AdvanceTime(DefaultRetransmissionTime());
4222 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
4223 connection_.GetRetransmissionAlarm()->Fire();
4224 EXPECT_EQ(QuicPacketNumber(2u), writer_->header().packet_number);
4225 // We do not raise the high water mark yet.
4226 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4227}
4228
fayanga29eb242019-07-16 12:25:38 -07004229// Regression test of b/133771183.
4230TEST_P(QuicConnectionTest, RtoWithNoDataToRetransmit) {
fayang5f135052019-08-22 17:59:40 -07004231 if (!connection_.session_decides_what_to_write() ||
4232 connection_.PtoEnabled()) {
fayanga29eb242019-07-16 12:25:38 -07004233 return;
4234 }
4235 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4236 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4237 connection_.SetMaxTailLossProbes(0);
4238
4239 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
4240 // Connection is cwnd limited.
4241 CongestionBlockWrites();
4242 // Stream gets reset.
4243 SendRstStream(3, QUIC_ERROR_PROCESSING_STREAM, 3);
4244 // Simulate the retransmission alarm firing.
4245 clock_.AdvanceTime(DefaultRetransmissionTime());
4246 // RTO fires, but there is no packet to be RTOed.
fayange861aee2019-10-16 13:40:39 -07004247 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
fayanga29eb242019-07-16 12:25:38 -07004248 connection_.GetRetransmissionAlarm()->Fire();
fayange861aee2019-10-16 13:40:39 -07004249 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
fayanga29eb242019-07-16 12:25:38 -07004250
4251 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(40);
4252 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(20);
fayange861aee2019-10-16 13:40:39 -07004253 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(false));
4254 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(1);
fayanga29eb242019-07-16 12:25:38 -07004255 // Receives packets 1 - 40.
4256 for (size_t i = 1; i <= 40; ++i) {
4257 ProcessDataPacket(i);
4258 }
4259}
4260
QUICHE teama6ef0a62019-03-07 20:34:33 -05004261TEST_P(QuicConnectionTest, RetransmitWithSameEncryptionLevel) {
4262 use_tagging_decrypter();
4263
4264 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
4265 // the end of the packet. We can test this to check which encrypter was used.
QUICHE team6987b4a2019-03-15 16:23:04 -07004266 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07004267 std::make_unique<TaggingEncrypter>(0x01));
nharper46833c32019-05-15 21:33:05 -07004268 QuicByteCount packet_size;
4269 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4270 .WillOnce(SaveArg<3>(&packet_size));
4271 connection_.SendCryptoDataWithString("foo", 0);
4272 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004273 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
4274
4275 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004276 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004277 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4278 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
4279 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
4280
4281 {
4282 InSequence s;
4283 EXPECT_CALL(*send_algorithm_,
4284 OnPacketSent(_, _, QuicPacketNumber(3), _, _));
4285 EXPECT_CALL(*send_algorithm_,
4286 OnPacketSent(_, _, QuicPacketNumber(4), _, _));
4287 }
4288
4289 // Manually mark both packets for retransmission.
4290 connection_.RetransmitUnackedPackets(ALL_UNACKED_RETRANSMISSION);
4291
QUICHE team6987b4a2019-03-15 16:23:04 -07004292 // Packet should have been sent with ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05004293 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_previous_packet());
4294
4295 // Packet should have been sent with ENCRYPTION_ZERO_RTT.
4296 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
4297}
4298
4299TEST_P(QuicConnectionTest, SendHandshakeMessages) {
4300 use_tagging_decrypter();
4301 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
4302 // the end of the packet. We can test this to check which encrypter was used.
QUICHE team6987b4a2019-03-15 16:23:04 -07004303 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07004304 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004305
4306 // Attempt to send a handshake message and have the socket block.
4307 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
4308 BlockOnNextWrite();
nharper46833c32019-05-15 21:33:05 -07004309 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004310 // The packet should be serialized, but not queued.
4311 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4312
4313 // Switch to the new encrypter.
4314 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004315 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004316 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4317
4318 // Now become writeable and flush the packets.
4319 writer_->SetWritable();
4320 EXPECT_CALL(visitor_, OnCanWrite());
4321 connection_.OnCanWrite();
4322 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4323
4324 // Verify that the handshake packet went out at the null encryption.
4325 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
4326}
4327
4328TEST_P(QuicConnectionTest,
4329 DropRetransmitsForNullEncryptedPacketAfterForwardSecure) {
4330 use_tagging_decrypter();
QUICHE team6987b4a2019-03-15 16:23:04 -07004331 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07004332 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004333 QuicPacketNumber packet_number;
4334 connection_.SendCryptoStreamData();
4335
4336 // Simulate the retransmission alarm firing and the socket blocking.
4337 BlockOnNextWrite();
4338 clock_.AdvanceTime(DefaultRetransmissionTime());
fayang2ce66082019-10-02 06:29:04 -07004339 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
4340 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4341 } else {
4342 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4343 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004344 connection_.GetRetransmissionAlarm()->Fire();
fayang2ce66082019-10-02 06:29:04 -07004345 EXPECT_EQ(1u, connection_.NumQueuedPackets());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004346
4347 // Go forward secure.
4348 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07004349 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004350 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4351 notifier_.NeuterUnencryptedData();
4352 connection_.NeuterUnencryptedPackets();
fayang2ce66082019-10-02 06:29:04 -07004353 connection_.OnHandshakeComplete();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004354
4355 EXPECT_EQ(QuicTime::Zero(), connection_.GetRetransmissionAlarm()->deadline());
4356 // Unblock the socket and ensure that no packets are sent.
4357 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4358 writer_->SetWritable();
4359 connection_.OnCanWrite();
4360}
4361
4362TEST_P(QuicConnectionTest, RetransmitPacketsWithInitialEncryption) {
4363 use_tagging_decrypter();
QUICHE team6987b4a2019-03-15 16:23:04 -07004364 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07004365 std::make_unique<TaggingEncrypter>(0x01));
QUICHE team6987b4a2019-03-15 16:23:04 -07004366 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004367
nharper46833c32019-05-15 21:33:05 -07004368 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004369
4370 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004371 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004372 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4373
4374 SendStreamDataToPeer(2, "bar", 0, NO_FIN, nullptr);
4375 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4376
4377 connection_.RetransmitUnackedPackets(ALL_INITIAL_RETRANSMISSION);
4378}
4379
4380TEST_P(QuicConnectionTest, BufferNonDecryptablePackets) {
QUICHE teamcd098022019-03-22 18:49:55 -07004381 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4382 return;
4383 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004384 // SetFromConfig is always called after construction from InitializeSession.
4385 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4386 QuicConfig config;
4387 connection_.SetFromConfig(config);
4388 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4389 use_tagging_decrypter();
4390
4391 const uint8_t tag = 0x07;
4392 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004393 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004394
4395 // Process an encrypted packet which can not yet be decrypted which should
4396 // result in the packet being buffered.
4397 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4398
4399 // Transition to the new encryption state and process another encrypted packet
4400 // which should result in the original packet being processed.
zhongyi546cc452019-04-12 15:27:49 -07004401 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004402 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004403 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4404 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004405 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004406 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(2);
4407 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4408
4409 // Finally, process a third packet and note that we do not reprocess the
4410 // buffered packet.
4411 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4412 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4413}
4414
4415TEST_P(QuicConnectionTest, TestRetransmitOrder) {
fayang5f135052019-08-22 17:59:40 -07004416 if (connection_.PtoEnabled()) {
4417 return;
4418 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004419 connection_.SetMaxTailLossProbes(0);
4420
4421 QuicByteCount first_packet_size;
4422 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4423 .WillOnce(SaveArg<3>(&first_packet_size));
4424
4425 connection_.SendStreamDataWithString(3, "first_packet", 0, NO_FIN);
4426 QuicByteCount second_packet_size;
4427 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4428 .WillOnce(SaveArg<3>(&second_packet_size));
4429 connection_.SendStreamDataWithString(3, "second_packet", 12, NO_FIN);
4430 EXPECT_NE(first_packet_size, second_packet_size);
4431 // Advance the clock by huge time to make sure packets will be retransmitted.
4432 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
4433 {
4434 InSequence s;
4435 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, first_packet_size, _));
4436 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, second_packet_size, _));
4437 }
4438 connection_.GetRetransmissionAlarm()->Fire();
4439
4440 // Advance again and expect the packets to be sent again in the same order.
4441 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(20));
4442 {
4443 InSequence s;
4444 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, first_packet_size, _));
4445 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, second_packet_size, _));
4446 }
4447 connection_.GetRetransmissionAlarm()->Fire();
4448}
4449
4450TEST_P(QuicConnectionTest, Buffer100NonDecryptablePacketsThenKeyChange) {
QUICHE teamcd098022019-03-22 18:49:55 -07004451 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4452 return;
4453 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004454 // SetFromConfig is always called after construction from InitializeSession.
4455 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4456 QuicConfig config;
4457 config.set_max_undecryptable_packets(100);
4458 connection_.SetFromConfig(config);
4459 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4460 use_tagging_decrypter();
4461
4462 const uint8_t tag = 0x07;
4463 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004464 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004465
4466 // Process an encrypted packet which can not yet be decrypted which should
4467 // result in the packet being buffered.
4468 for (uint64_t i = 1; i <= 100; ++i) {
4469 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4470 }
4471
4472 // Transition to the new encryption state and process another encrypted packet
4473 // which should result in the original packets being processed.
4474 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
zhongyi546cc452019-04-12 15:27:49 -07004475 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004476 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004477 EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
4478 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4479 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004480 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004481
4482 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(100);
4483 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
4484
4485 // Finally, process a third packet and note that we do not reprocess the
4486 // buffered packet.
4487 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4488 ProcessDataPacketAtLevel(102, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4489}
4490
4491TEST_P(QuicConnectionTest, SetRTOAfterWritingToSocket) {
4492 BlockOnNextWrite();
fayang2ce66082019-10-02 06:29:04 -07004493 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
4494 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4495 } else {
4496 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4497 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004498 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
fayang2ce66082019-10-02 06:29:04 -07004499 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
4500 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4501 } else {
4502 // Make sure that RTO is not started when the packet is queued.
4503 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4504 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004505
4506 // Test that RTO is started once we write to the socket.
4507 writer_->SetWritable();
fayang2ce66082019-10-02 06:29:04 -07004508 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
4509 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4510 } else {
4511 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4512 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004513 connection_.OnCanWrite();
4514 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4515}
4516
4517TEST_P(QuicConnectionTest, DelayRTOWithAckReceipt) {
fayang5f135052019-08-22 17:59:40 -07004518 if (connection_.PtoEnabled()) {
4519 return;
4520 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004521 connection_.SetMaxTailLossProbes(0);
4522
4523 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4524 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
4525 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
4526 connection_.SendStreamDataWithString(3, "bar", 0, NO_FIN);
4527 QuicAlarm* retransmission_alarm = connection_.GetRetransmissionAlarm();
4528 EXPECT_TRUE(retransmission_alarm->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004529 EXPECT_EQ(DefaultRetransmissionTime(),
4530 retransmission_alarm->deadline() - clock_.Now());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004531
4532 // Advance the time right before the RTO, then receive an ack for the first
4533 // packet to delay the RTO.
4534 clock_.AdvanceTime(DefaultRetransmissionTime());
4535 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4536 QuicAckFrame ack = InitAckFrame(1);
4537 ProcessAckPacket(&ack);
4538 // Now we have an RTT sample of DefaultRetransmissionTime(500ms),
4539 // so the RTO has increased to 2 * SRTT.
4540 EXPECT_TRUE(retransmission_alarm->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004541 EXPECT_EQ(retransmission_alarm->deadline() - clock_.Now(),
4542 2 * DefaultRetransmissionTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004543
4544 // Move forward past the original RTO and ensure the RTO is still pending.
4545 clock_.AdvanceTime(2 * DefaultRetransmissionTime());
4546
4547 // Ensure the second packet gets retransmitted when it finally fires.
4548 EXPECT_TRUE(retransmission_alarm->IsSet());
4549 EXPECT_EQ(retransmission_alarm->deadline(), clock_.ApproximateNow());
4550 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4551 // Manually cancel the alarm to simulate a real test.
4552 connection_.GetRetransmissionAlarm()->Fire();
4553
4554 // The new retransmitted packet number should set the RTO to a larger value
4555 // than previously.
4556 EXPECT_TRUE(retransmission_alarm->IsSet());
4557 QuicTime next_rto_time = retransmission_alarm->deadline();
4558 QuicTime expected_rto_time =
4559 connection_.sent_packet_manager().GetRetransmissionTime();
4560 EXPECT_EQ(next_rto_time, expected_rto_time);
4561}
4562
4563TEST_P(QuicConnectionTest, TestQueued) {
4564 connection_.SetMaxTailLossProbes(0);
4565
4566 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4567 BlockOnNextWrite();
4568 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4569 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4570
4571 // Unblock the writes and actually send.
4572 writer_->SetWritable();
4573 connection_.OnCanWrite();
4574 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4575}
4576
4577TEST_P(QuicConnectionTest, InitialTimeout) {
4578 EXPECT_TRUE(connection_.connected());
4579 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4580 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4581
4582 // SetFromConfig sets the initial timeouts before negotiation.
4583 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4584 QuicConfig config;
4585 connection_.SetFromConfig(config);
4586 // Subtract a second from the idle timeout on the client side.
4587 QuicTime default_timeout =
4588 clock_.ApproximateNow() +
4589 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4590 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
4591
fkastenholz5d880a92019-06-21 09:01:56 -07004592 EXPECT_CALL(visitor_,
4593 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004594 // Simulate the timeout alarm firing.
4595 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1));
4596 connection_.GetTimeoutAlarm()->Fire();
4597
4598 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4599 EXPECT_FALSE(connection_.connected());
4600
4601 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
4602 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4603 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4604 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4605 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
renjietang11e4a3d2019-05-03 11:27:26 -07004606 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07004607 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004608}
4609
4610TEST_P(QuicConnectionTest, IdleTimeoutAfterFirstSentPacket) {
4611 EXPECT_TRUE(connection_.connected());
4612 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4613 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4614
4615 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4616 QuicConfig config;
4617 connection_.SetFromConfig(config);
4618 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4619 QuicTime initial_ddl =
4620 clock_.ApproximateNow() +
4621 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4622 EXPECT_EQ(initial_ddl, connection_.GetTimeoutAlarm()->deadline());
4623 EXPECT_TRUE(connection_.connected());
4624
4625 // Advance the time and send the first packet to the peer.
4626 clock_.AdvanceTime(QuicTime::Delta::FromMicroseconds(20));
4627 QuicPacketNumber last_packet;
4628 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4629 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4630 // This will be the updated deadline for the connection to idle time out.
4631 QuicTime new_ddl = clock_.ApproximateNow() +
4632 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4633
4634 // Simulate the timeout alarm firing, the connection should not be closed as
4635 // a new packet has been sent.
fkastenholz5d880a92019-06-21 09:01:56 -07004636 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004637 QuicTime::Delta delay = initial_ddl - clock_.ApproximateNow();
4638 clock_.AdvanceTime(delay);
4639 connection_.GetTimeoutAlarm()->Fire();
4640 // Verify the timeout alarm deadline is updated.
4641 EXPECT_TRUE(connection_.connected());
4642 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4643 EXPECT_EQ(new_ddl, connection_.GetTimeoutAlarm()->deadline());
4644
4645 // Simulate the timeout alarm firing again, the connection now should be
4646 // closed.
fkastenholz5d880a92019-06-21 09:01:56 -07004647 EXPECT_CALL(visitor_,
4648 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004649 clock_.AdvanceTime(new_ddl - clock_.ApproximateNow());
4650 connection_.GetTimeoutAlarm()->Fire();
4651 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4652 EXPECT_FALSE(connection_.connected());
4653
4654 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
4655 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4656 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4657 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4658 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07004659 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004660}
4661
4662TEST_P(QuicConnectionTest, IdleTimeoutAfterSendTwoPackets) {
4663 EXPECT_TRUE(connection_.connected());
4664 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4665 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4666
4667 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4668 QuicConfig config;
4669 connection_.SetFromConfig(config);
4670 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4671 QuicTime initial_ddl =
4672 clock_.ApproximateNow() +
4673 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4674 EXPECT_EQ(initial_ddl, connection_.GetTimeoutAlarm()->deadline());
4675 EXPECT_TRUE(connection_.connected());
4676
4677 // Immediately send the first packet, this is a rare case but test code will
4678 // hit this issue often as MockClock used for tests doesn't move with code
4679 // execution until manually adjusted.
4680 QuicPacketNumber last_packet;
4681 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4682 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4683
4684 // Advance the time and send the second packet to the peer.
4685 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
4686 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4687 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
4688
zhongyic1cab062019-06-19 12:02:24 -07004689 // Simulate the timeout alarm firing, the connection will be closed.
fkastenholz5d880a92019-06-21 09:01:56 -07004690 EXPECT_CALL(visitor_,
4691 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
zhongyic1cab062019-06-19 12:02:24 -07004692 clock_.AdvanceTime(initial_ddl - clock_.ApproximateNow());
4693 connection_.GetTimeoutAlarm()->Fire();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004694
4695 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4696 EXPECT_FALSE(connection_.connected());
4697
4698 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
4699 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4700 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4701 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4702 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07004703 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004704}
4705
4706TEST_P(QuicConnectionTest, HandshakeTimeout) {
4707 // Use a shorter handshake timeout than idle timeout for this test.
4708 const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(5);
4709 connection_.SetNetworkTimeouts(timeout, timeout);
4710 EXPECT_TRUE(connection_.connected());
4711 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4712
4713 QuicTime handshake_timeout =
4714 clock_.ApproximateNow() + timeout - QuicTime::Delta::FromSeconds(1);
4715 EXPECT_EQ(handshake_timeout, connection_.GetTimeoutAlarm()->deadline());
4716 EXPECT_TRUE(connection_.connected());
4717
4718 // Send and ack new data 3 seconds later to lengthen the idle timeout.
4719 SendStreamDataToPeer(
dschinazi552accc2019-06-17 17:07:34 -07004720 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
4721 "GET /", 0, FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004722 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(3));
4723 QuicAckFrame frame = InitAckFrame(1);
4724 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4725 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4726 ProcessAckPacket(&frame);
4727
4728 // Fire early to verify it wouldn't timeout yet.
4729 connection_.GetTimeoutAlarm()->Fire();
4730 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4731 EXPECT_TRUE(connection_.connected());
4732
4733 clock_.AdvanceTime(timeout - QuicTime::Delta::FromSeconds(2));
4734
fkastenholz5d880a92019-06-21 09:01:56 -07004735 EXPECT_CALL(visitor_,
4736 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004737 // Simulate the timeout alarm firing.
4738 connection_.GetTimeoutAlarm()->Fire();
4739
4740 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4741 EXPECT_FALSE(connection_.connected());
4742
4743 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
4744 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4745 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4746 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07004747 TestConnectionCloseQuicErrorCode(QUIC_HANDSHAKE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004748}
4749
4750TEST_P(QuicConnectionTest, PingAfterSend) {
QUICHE teamcd098022019-03-22 18:49:55 -07004751 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4752 return;
4753 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004754 EXPECT_TRUE(connection_.connected());
4755 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4756 .WillRepeatedly(Return(true));
4757 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4758
4759 // Advance to 5ms, and send a packet to the peer, which will set
4760 // the ping alarm.
4761 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4762 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4763 SendStreamDataToPeer(
dschinazi552accc2019-06-17 17:07:34 -07004764 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
4765 "GET /", 0, FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004766 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004767 EXPECT_EQ(QuicTime::Delta::FromSeconds(15),
4768 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004769
4770 // Now recevie an ACK of the previous packet, which will move the
4771 // ping alarm forward.
4772 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4773 QuicAckFrame frame = InitAckFrame(1);
4774 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4775 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4776 ProcessAckPacket(&frame);
4777 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4778 // The ping timer is set slightly less than 15 seconds in the future, because
4779 // of the 1s ping timer alarm granularity.
zhongyieef848f2019-10-18 07:09:37 -07004780 EXPECT_EQ(
4781 QuicTime::Delta::FromSeconds(15) - QuicTime::Delta::FromMilliseconds(5),
4782 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004783
4784 writer_->Reset();
4785 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15));
zhongyifbb25772019-04-10 16:54:08 -07004786 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004787 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07004788 size_t padding_frame_count = writer_->padding_frames().size();
4789 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004790 ASSERT_EQ(1u, writer_->ping_frames().size());
4791 writer_->Reset();
4792
4793 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4794 .WillRepeatedly(Return(false));
4795 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4796 SendAckPacketToPeer();
4797
4798 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4799}
4800
4801TEST_P(QuicConnectionTest, ReducedPingTimeout) {
QUICHE teamcd098022019-03-22 18:49:55 -07004802 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4803 return;
4804 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004805 EXPECT_TRUE(connection_.connected());
4806 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4807 .WillRepeatedly(Return(true));
4808 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4809
4810 // Use a reduced ping timeout for this connection.
4811 connection_.set_ping_timeout(QuicTime::Delta::FromSeconds(10));
4812
4813 // Advance to 5ms, and send a packet to the peer, which will set
4814 // the ping alarm.
4815 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4816 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4817 SendStreamDataToPeer(
dschinazi552accc2019-06-17 17:07:34 -07004818 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
4819 "GET /", 0, FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004820 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004821 EXPECT_EQ(QuicTime::Delta::FromSeconds(10),
4822 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004823
4824 // Now recevie an ACK of the previous packet, which will move the
4825 // ping alarm forward.
4826 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4827 QuicAckFrame frame = InitAckFrame(1);
4828 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4829 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4830 ProcessAckPacket(&frame);
4831 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4832 // The ping timer is set slightly less than 10 seconds in the future, because
4833 // of the 1s ping timer alarm granularity.
zhongyieef848f2019-10-18 07:09:37 -07004834 EXPECT_EQ(
4835 QuicTime::Delta::FromSeconds(10) - QuicTime::Delta::FromMilliseconds(5),
4836 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004837
4838 writer_->Reset();
4839 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
4840 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
4841 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
4842 }));
4843 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07004844 size_t padding_frame_count = writer_->padding_frames().size();
4845 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004846 ASSERT_EQ(1u, writer_->ping_frames().size());
4847 writer_->Reset();
4848
4849 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4850 .WillRepeatedly(Return(false));
4851 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4852 SendAckPacketToPeer();
4853
4854 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4855}
4856
4857// Tests whether sending an MTU discovery packet to peer successfully causes the
4858// maximum packet size to increase.
4859TEST_P(QuicConnectionTest, SendMtuDiscoveryPacket) {
QUICHE teamcd098022019-03-22 18:49:55 -07004860 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4861 return;
4862 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004863 EXPECT_TRUE(connection_.connected());
4864
4865 // Send an MTU probe.
4866 const size_t new_mtu = kDefaultMaxPacketSize + 100;
4867 QuicByteCount mtu_probe_size;
4868 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4869 .WillOnce(SaveArg<3>(&mtu_probe_size));
4870 connection_.SendMtuDiscoveryPacket(new_mtu);
4871 EXPECT_EQ(new_mtu, mtu_probe_size);
4872 EXPECT_EQ(QuicPacketNumber(1u), creator_->packet_number());
4873
nharperc1bbfe62019-09-27 16:48:40 -07004874 // QuicFramer::GetMaxPlaintextSize uses the smallest max plaintext size across
4875 // all encrypters. The initial encrypter used with IETF QUIC has a 16-byte
4876 // overhead, while the NullEncrypter used throughout this test has a 12-byte
4877 // overhead. This test tests behavior that relies on computing the packet size
4878 // correctly, so by unsetting the initial encrypter, we avoid having a
4879 // mismatch between the overheads for the encrypters used. In non-test
4880 // scenarios all encrypters used for a given connection have the same
4881 // overhead, either 12 bytes for ones using Google QUIC crypto, or 16 bytes
4882 // for ones using TLS.
4883 connection_.SetEncrypter(ENCRYPTION_INITIAL, nullptr);
4884
QUICHE teama6ef0a62019-03-07 20:34:33 -05004885 // Send more than MTU worth of data. No acknowledgement was received so far,
4886 // so the MTU should be at its old value.
vasilvvc48c8712019-03-11 13:38:16 -07004887 const std::string data(kDefaultMaxPacketSize + 1, '.');
QUICHE teama6ef0a62019-03-07 20:34:33 -05004888 QuicByteCount size_before_mtu_change;
4889 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4890 .Times(2)
4891 .WillOnce(SaveArg<3>(&size_before_mtu_change))
4892 .WillOnce(Return());
4893 connection_.SendStreamDataWithString(3, data, 0, FIN);
4894 EXPECT_EQ(QuicPacketNumber(3u), creator_->packet_number());
4895 EXPECT_EQ(kDefaultMaxPacketSize, size_before_mtu_change);
4896
4897 // Acknowledge all packets so far.
4898 QuicAckFrame probe_ack = InitAckFrame(3);
4899 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4900 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4901 ProcessAckPacket(&probe_ack);
4902 EXPECT_EQ(new_mtu, connection_.max_packet_length());
4903
4904 // Send the same data again. Check that it fits into a single packet now.
4905 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4906 connection_.SendStreamDataWithString(3, data, 0, FIN);
4907 EXPECT_EQ(QuicPacketNumber(4u), creator_->packet_number());
4908}
4909
4910// Tests whether MTU discovery does not happen when it is not explicitly enabled
4911// by the connection options.
4912TEST_P(QuicConnectionTest, MtuDiscoveryDisabled) {
4913 EXPECT_TRUE(connection_.connected());
4914
4915 const QuicPacketCount packets_between_probes_base = 10;
4916 set_packets_between_probes_base(packets_between_probes_base);
4917
4918 const QuicPacketCount number_of_packets = packets_between_probes_base * 2;
4919 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
4920 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
4921 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4922 EXPECT_EQ(0u, connection_.mtu_probe_count());
4923 }
4924}
4925
wubf76cf2a2019-10-11 18:49:07 -07004926// Tests whether MTU discovery works when all probes are acknowledged on the
QUICHE teama6ef0a62019-03-07 20:34:33 -05004927// first try.
4928TEST_P(QuicConnectionTest, MtuDiscoveryEnabled) {
4929 EXPECT_TRUE(connection_.connected());
4930
nharperc6b99512019-09-19 11:13:48 -07004931 // QuicFramer::GetMaxPlaintextSize uses the smallest max plaintext size across
4932 // all encrypters. The initial encrypter used with IETF QUIC has a 16-byte
4933 // overhead, while the NullEncrypter used throughout this test has a 12-byte
4934 // overhead. This test tests behavior that relies on computing the packet size
4935 // correctly, so by unsetting the initial encrypter, we avoid having a
4936 // mismatch between the overheads for the encrypters used. In non-test
4937 // scenarios all encrypters used for a given connection have the same
4938 // overhead, either 12 bytes for ones using Google QUIC crypto, or 16 bytes
4939 // for ones using TLS.
nharperc1bbfe62019-09-27 16:48:40 -07004940 connection_.SetEncrypter(ENCRYPTION_INITIAL, nullptr);
nharperc6b99512019-09-19 11:13:48 -07004941
QUICHE teama6ef0a62019-03-07 20:34:33 -05004942 const QuicPacketCount packets_between_probes_base = 5;
4943 set_packets_between_probes_base(packets_between_probes_base);
4944
wubf76cf2a2019-10-11 18:49:07 -07004945 connection_.EnablePathMtuDiscovery(send_algorithm_);
4946
QUICHE teama6ef0a62019-03-07 20:34:33 -05004947 // Send enough packets so that the next one triggers path MTU discovery.
4948 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
4949 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
4950 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4951 }
4952
4953 // Trigger the probe.
4954 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
4955 nullptr);
4956 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4957 QuicByteCount probe_size;
4958 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4959 .WillOnce(SaveArg<3>(&probe_size));
4960 connection_.GetMtuDiscoveryAlarm()->Fire();
wubf76cf2a2019-10-11 18:49:07 -07004961 if (GetQuicReloadableFlag(quic_mtu_discovery_v2)) {
4962 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(),
4963 kMtuDiscoveryTargetPacketSizeHigh));
4964 } else {
4965 EXPECT_EQ(kMtuDiscoveryTargetPacketSizeHigh, probe_size);
4966 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004967
4968 const QuicPacketNumber probe_packet_number =
4969 FirstSendingPacketNumber() + packets_between_probes_base;
4970 ASSERT_EQ(probe_packet_number, creator_->packet_number());
4971
4972 // Acknowledge all packets sent so far.
4973 QuicAckFrame probe_ack = InitAckFrame(probe_packet_number);
4974 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
wubf76cf2a2019-10-11 18:49:07 -07004975 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
4976 .Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004977 ProcessAckPacket(&probe_ack);
wubf76cf2a2019-10-11 18:49:07 -07004978 EXPECT_EQ(probe_size, connection_.max_packet_length());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004979 EXPECT_EQ(0u, connection_.GetBytesInFlight());
4980
wubf76cf2a2019-10-11 18:49:07 -07004981 EXPECT_EQ(1u, connection_.mtu_probe_count());
4982
4983 if (!GetQuicReloadableFlag(quic_mtu_discovery_v2)) {
4984 // Send more packets, and ensure that none of them sets the alarm.
4985 for (QuicPacketCount i = 0; i < 4 * packets_between_probes_base; i++) {
4986 SendStreamDataToPeer(3, ".", packets_between_probes_base + i, NO_FIN,
4987 nullptr);
4988 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4989 }
4990
4991 return;
4992 }
4993
4994 QuicStreamOffset stream_offset = packets_between_probes_base;
4995 for (size_t num_probes = 1; num_probes < kMtuDiscoveryAttempts;
4996 ++num_probes) {
4997 // Send just enough packets without triggering the next probe.
4998 for (QuicPacketCount i = 0;
4999 i < (packets_between_probes_base << num_probes) - 1; ++i) {
5000 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5001 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5002 }
5003
5004 // Trigger the next probe.
5005 SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
5006 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5007 QuicByteCount new_probe_size;
5008 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5009 .WillOnce(SaveArg<3>(&new_probe_size));
5010 connection_.GetMtuDiscoveryAlarm()->Fire();
5011 EXPECT_THAT(new_probe_size,
5012 InRange(probe_size, kMtuDiscoveryTargetPacketSizeHigh));
5013 EXPECT_EQ(num_probes + 1, connection_.mtu_probe_count());
5014
5015 // Acknowledge all packets sent so far.
5016 QuicAckFrame probe_ack = InitAckFrame(creator_->packet_number());
5017 ProcessAckPacket(&probe_ack);
5018 EXPECT_EQ(new_probe_size, connection_.max_packet_length());
5019 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5020
5021 probe_size = new_probe_size;
5022 }
5023
5024 // The last probe size should be equal to the target.
5025 EXPECT_EQ(probe_size, kMtuDiscoveryTargetPacketSizeHigh);
5026}
5027
5028// Simulate the case where the first attempt to send a probe is write blocked,
5029// and after unblock, the second attempt returns a MSG_TOO_BIG error.
5030TEST_P(QuicConnectionTest, MtuDiscoveryWriteBlocked) {
5031 EXPECT_TRUE(connection_.connected());
5032
5033 connection_.SetEncrypter(ENCRYPTION_INITIAL, nullptr);
5034
5035 const QuicPacketCount packets_between_probes_base = 5;
5036 set_packets_between_probes_base(packets_between_probes_base);
5037
5038 connection_.EnablePathMtuDiscovery(send_algorithm_);
5039
5040 // Send enough packets so that the next one triggers path MTU discovery.
5041 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5042 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005043 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5044 }
5045
wubf76cf2a2019-10-11 18:49:07 -07005046 QuicByteCount original_max_packet_length = connection_.max_packet_length();
5047
5048 // Trigger the probe.
5049 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5050 nullptr);
5051 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5052 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
5053 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5054 }
5055 BlockOnNextWrite();
5056 EXPECT_EQ(0u, connection_.NumQueuedPackets());
5057 connection_.GetMtuDiscoveryAlarm()->Fire();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005058 EXPECT_EQ(1u, connection_.mtu_probe_count());
wubf76cf2a2019-10-11 18:49:07 -07005059 EXPECT_EQ(1u, connection_.NumQueuedPackets());
5060 ASSERT_TRUE(connection_.connected());
5061
5062 writer_->SetWritable();
5063 SimulateNextPacketTooLarge();
5064 connection_.OnCanWrite();
5065 EXPECT_EQ(0u, connection_.NumQueuedPackets());
5066 EXPECT_EQ(original_max_packet_length, connection_.max_packet_length());
5067 EXPECT_TRUE(connection_.connected());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005068}
5069
5070// Tests whether MTU discovery works correctly when the probes never get
5071// acknowledged.
5072TEST_P(QuicConnectionTest, MtuDiscoveryFailed) {
5073 EXPECT_TRUE(connection_.connected());
5074
QUICHE teama6ef0a62019-03-07 20:34:33 -05005075 // Lower the number of probes between packets in order to make the test go
5076 // much faster.
5077 const QuicPacketCount packets_between_probes_base = 5;
5078 set_packets_between_probes_base(packets_between_probes_base);
5079
wubf76cf2a2019-10-11 18:49:07 -07005080 connection_.EnablePathMtuDiscovery(send_algorithm_);
5081
5082 const QuicTime::Delta rtt = QuicTime::Delta::FromMilliseconds(100);
5083
5084 EXPECT_EQ(packets_between_probes_base,
5085 QuicConnectionPeer::GetPacketsBetweenMtuProbes(&connection_));
5086
QUICHE teama6ef0a62019-03-07 20:34:33 -05005087 // This tests sends more packets than strictly necessary to make sure that if
5088 // the connection was to send more discovery packets than needed, those would
5089 // get caught as well.
5090 const QuicPacketCount number_of_packets =
5091 packets_between_probes_base * (1 << (kMtuDiscoveryAttempts + 1));
5092 std::vector<QuicPacketNumber> mtu_discovery_packets;
5093 // Called by the first ack.
5094 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5095 // Called on many acks.
5096 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5097 .Times(AnyNumber());
5098 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
5099 SendStreamDataToPeer(3, "!", i, NO_FIN, nullptr);
5100 clock_.AdvanceTime(rtt);
5101
5102 // Receive an ACK, which marks all data packets as received, and all MTU
5103 // discovery packets as missing.
5104
5105 QuicAckFrame ack;
5106
5107 if (!mtu_discovery_packets.empty()) {
5108 QuicPacketNumber min_packet = *min_element(mtu_discovery_packets.begin(),
5109 mtu_discovery_packets.end());
5110 QuicPacketNumber max_packet = *max_element(mtu_discovery_packets.begin(),
5111 mtu_discovery_packets.end());
5112 ack.packets.AddRange(QuicPacketNumber(1), min_packet);
5113 ack.packets.AddRange(QuicPacketNumber(max_packet + 1),
5114 creator_->packet_number() + 1);
5115 ack.largest_acked = creator_->packet_number();
5116
5117 } else {
5118 ack.packets.AddRange(QuicPacketNumber(1), creator_->packet_number() + 1);
5119 ack.largest_acked = creator_->packet_number();
5120 }
5121
5122 ProcessAckPacket(&ack);
5123
5124 // Trigger MTU probe if it would be scheduled now.
5125 if (!connection_.GetMtuDiscoveryAlarm()->IsSet()) {
5126 continue;
5127 }
5128
5129 // Fire the alarm. The alarm should cause a packet to be sent.
5130 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5131 connection_.GetMtuDiscoveryAlarm()->Fire();
5132 // Record the packet number of the MTU discovery packet in order to
5133 // mark it as NACK'd.
5134 mtu_discovery_packets.push_back(creator_->packet_number());
5135 }
5136
5137 // Ensure the number of packets between probes grows exponentially by checking
5138 // it against the closed-form expression for the packet number.
5139 ASSERT_EQ(kMtuDiscoveryAttempts, mtu_discovery_packets.size());
5140 for (uint64_t i = 0; i < kMtuDiscoveryAttempts; i++) {
5141 // 2^0 + 2^1 + 2^2 + ... + 2^n = 2^(n + 1) - 1
5142 const QuicPacketCount packets_between_probes =
5143 packets_between_probes_base * ((1 << (i + 1)) - 1);
5144 EXPECT_EQ(QuicPacketNumber(packets_between_probes + (i + 1)),
5145 mtu_discovery_packets[i]);
5146 }
5147
5148 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5149 EXPECT_EQ(kDefaultMaxPacketSize, connection_.max_packet_length());
5150 EXPECT_EQ(kMtuDiscoveryAttempts, connection_.mtu_probe_count());
5151}
5152
wubf76cf2a2019-10-11 18:49:07 -07005153// Probe 3 times, the first one succeeds, then fails, then succeeds again.
5154TEST_P(QuicConnectionTest, MtuDiscoverySecondProbeFailed) {
5155 if (!GetQuicReloadableFlag(quic_mtu_discovery_v2)) {
5156 return;
5157 }
5158 EXPECT_TRUE(connection_.connected());
5159
5160 // QuicFramer::GetMaxPlaintextSize uses the smallest max plaintext size across
5161 // all encrypters. The initial encrypter used with IETF QUIC has a 16-byte
5162 // overhead, while the NullEncrypter used throughout this test has a 12-byte
5163 // overhead. This test tests behavior that relies on computing the packet size
5164 // correctly, so by unsetting the initial encrypter, we avoid having a
5165 // mismatch between the overheads for the encrypters used. In non-test
5166 // scenarios all encrypters used for a given connection have the same
5167 // overhead, either 12 bytes for ones using Google QUIC crypto, or 16 bytes
5168 // for ones using TLS.
5169 connection_.SetEncrypter(ENCRYPTION_INITIAL, nullptr);
5170
5171 const QuicPacketCount packets_between_probes_base = 5;
5172 set_packets_between_probes_base(packets_between_probes_base);
5173
5174 connection_.EnablePathMtuDiscovery(send_algorithm_);
5175
5176 // Send enough packets so that the next one triggers path MTU discovery.
5177 QuicStreamOffset stream_offset = 0;
5178 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5179 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5180 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5181 }
5182
5183 // Trigger the probe.
5184 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5185 nullptr);
5186 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5187 QuicByteCount probe_size;
5188 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5189 .WillOnce(SaveArg<3>(&probe_size));
5190 connection_.GetMtuDiscoveryAlarm()->Fire();
5191 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(),
5192 kMtuDiscoveryTargetPacketSizeHigh));
5193
5194 const QuicPacketNumber probe_packet_number =
5195 FirstSendingPacketNumber() + packets_between_probes_base;
5196 ASSERT_EQ(probe_packet_number, creator_->packet_number());
5197
5198 // Acknowledge all packets sent so far.
5199 QuicAckFrame first_ack = InitAckFrame(probe_packet_number);
5200 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5201 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5202 .Times(AnyNumber());
5203 ProcessAckPacket(&first_ack);
5204 EXPECT_EQ(probe_size, connection_.max_packet_length());
5205 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5206
5207 EXPECT_EQ(1u, connection_.mtu_probe_count());
5208
5209 // Send just enough packets without triggering the second probe.
5210 for (QuicPacketCount i = 0; i < (packets_between_probes_base << 1) - 1; ++i) {
5211 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5212 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5213 }
5214
5215 // Trigger the second probe.
5216 SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
5217 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5218 QuicByteCount second_probe_size;
5219 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5220 .WillOnce(SaveArg<3>(&second_probe_size));
5221 connection_.GetMtuDiscoveryAlarm()->Fire();
5222 EXPECT_THAT(second_probe_size,
5223 InRange(probe_size, kMtuDiscoveryTargetPacketSizeHigh));
5224 EXPECT_EQ(2u, connection_.mtu_probe_count());
5225
5226 // Acknowledge all packets sent so far, except the second probe.
5227 QuicPacketNumber second_probe_packet_number = creator_->packet_number();
5228 QuicAckFrame second_ack = InitAckFrame(second_probe_packet_number - 1);
5229 ProcessAckPacket(&first_ack);
5230 EXPECT_EQ(probe_size, connection_.max_packet_length());
5231
5232 // Send just enough packets without triggering the third probe.
5233 for (QuicPacketCount i = 0; i < (packets_between_probes_base << 2) - 1; ++i) {
5234 SendStreamDataToPeer(3, "@", stream_offset++, NO_FIN, nullptr);
5235 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5236 }
5237
5238 // Trigger the third probe.
5239 SendStreamDataToPeer(3, "#", stream_offset++, NO_FIN, nullptr);
5240 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5241 QuicByteCount third_probe_size;
5242 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5243 .WillOnce(SaveArg<3>(&third_probe_size));
5244 connection_.GetMtuDiscoveryAlarm()->Fire();
5245 EXPECT_THAT(third_probe_size, InRange(probe_size, second_probe_size));
5246 EXPECT_EQ(3u, connection_.mtu_probe_count());
5247
5248 // Acknowledge all packets sent so far, except the second probe.
5249 QuicAckFrame third_ack =
5250 ConstructAckFrame(creator_->packet_number(), second_probe_packet_number);
5251 ProcessAckPacket(&third_ack);
5252 EXPECT_EQ(third_probe_size, connection_.max_packet_length());
5253}
5254
QUICHE teama6ef0a62019-03-07 20:34:33 -05005255// Tests whether MTU discovery works when the writer has a limit on how large a
5256// packet can be.
5257TEST_P(QuicConnectionTest, MtuDiscoveryWriterLimited) {
5258 EXPECT_TRUE(connection_.connected());
5259
nharperc6b99512019-09-19 11:13:48 -07005260 // QuicFramer::GetMaxPlaintextSize uses the smallest max plaintext size across
5261 // all encrypters. The initial encrypter used with IETF QUIC has a 16-byte
5262 // overhead, while the NullEncrypter used throughout this test has a 12-byte
5263 // overhead. This test tests behavior that relies on computing the packet size
5264 // correctly, so by unsetting the initial encrypter, we avoid having a
5265 // mismatch between the overheads for the encrypters used. In non-test
5266 // scenarios all encrypters used for a given connection have the same
5267 // overhead, either 12 bytes for ones using Google QUIC crypto, or 16 bytes
5268 // for ones using TLS.
nharperc1bbfe62019-09-27 16:48:40 -07005269 connection_.SetEncrypter(ENCRYPTION_INITIAL, nullptr);
nharperc6b99512019-09-19 11:13:48 -07005270
QUICHE teama6ef0a62019-03-07 20:34:33 -05005271 const QuicByteCount mtu_limit = kMtuDiscoveryTargetPacketSizeHigh - 1;
5272 writer_->set_max_packet_size(mtu_limit);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005273
5274 const QuicPacketCount packets_between_probes_base = 5;
5275 set_packets_between_probes_base(packets_between_probes_base);
5276
wubf76cf2a2019-10-11 18:49:07 -07005277 connection_.EnablePathMtuDiscovery(send_algorithm_);
5278
QUICHE teama6ef0a62019-03-07 20:34:33 -05005279 // Send enough packets so that the next one triggers path MTU discovery.
5280 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5281 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5282 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5283 }
5284
5285 // Trigger the probe.
5286 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5287 nullptr);
5288 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5289 QuicByteCount probe_size;
5290 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5291 .WillOnce(SaveArg<3>(&probe_size));
5292 connection_.GetMtuDiscoveryAlarm()->Fire();
wubf76cf2a2019-10-11 18:49:07 -07005293 if (GetQuicReloadableFlag(quic_mtu_discovery_v2)) {
5294 EXPECT_THAT(probe_size,
5295 InRange(connection_.max_packet_length(), mtu_limit));
5296 } else {
5297 EXPECT_EQ(mtu_limit, probe_size);
5298 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005299
5300 const QuicPacketNumber probe_sequence_number =
5301 FirstSendingPacketNumber() + packets_between_probes_base;
5302 ASSERT_EQ(probe_sequence_number, creator_->packet_number());
5303
5304 // Acknowledge all packets sent so far.
5305 QuicAckFrame probe_ack = InitAckFrame(probe_sequence_number);
5306 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
wubf76cf2a2019-10-11 18:49:07 -07005307 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5308 .Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005309 ProcessAckPacket(&probe_ack);
wubf76cf2a2019-10-11 18:49:07 -07005310 EXPECT_EQ(probe_size, connection_.max_packet_length());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005311 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5312
wubf76cf2a2019-10-11 18:49:07 -07005313 EXPECT_EQ(1u, connection_.mtu_probe_count());
5314
5315 if (!GetQuicReloadableFlag(quic_mtu_discovery_v2)) {
5316 // Send more packets, and ensure that none of them sets the alarm.
5317 for (QuicPacketCount i = 0; i < 4 * packets_between_probes_base; i++) {
5318 SendStreamDataToPeer(3, ".", packets_between_probes_base + i, NO_FIN,
5319 nullptr);
5320 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5321 }
5322
5323 return;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005324 }
5325
wubf76cf2a2019-10-11 18:49:07 -07005326 QuicStreamOffset stream_offset = packets_between_probes_base;
5327 for (size_t num_probes = 1; num_probes < kMtuDiscoveryAttempts;
5328 ++num_probes) {
5329 // Send just enough packets without triggering the next probe.
5330 for (QuicPacketCount i = 0;
5331 i < (packets_between_probes_base << num_probes) - 1; ++i) {
5332 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5333 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5334 }
5335
5336 // Trigger the next probe.
5337 SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
5338 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5339 QuicByteCount new_probe_size;
5340 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5341 .WillOnce(SaveArg<3>(&new_probe_size));
5342 connection_.GetMtuDiscoveryAlarm()->Fire();
5343 EXPECT_THAT(new_probe_size, InRange(probe_size, mtu_limit));
5344 EXPECT_EQ(num_probes + 1, connection_.mtu_probe_count());
5345
5346 // Acknowledge all packets sent so far.
5347 QuicAckFrame probe_ack = InitAckFrame(creator_->packet_number());
5348 ProcessAckPacket(&probe_ack);
5349 EXPECT_EQ(new_probe_size, connection_.max_packet_length());
5350 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5351
5352 probe_size = new_probe_size;
5353 }
5354
5355 // The last probe size should be equal to the target.
5356 EXPECT_EQ(probe_size, mtu_limit);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005357}
5358
5359// Tests whether MTU discovery works when the writer returns an error despite
5360// advertising higher packet length.
5361TEST_P(QuicConnectionTest, MtuDiscoveryWriterFailed) {
5362 EXPECT_TRUE(connection_.connected());
5363
5364 const QuicByteCount mtu_limit = kMtuDiscoveryTargetPacketSizeHigh - 1;
5365 const QuicByteCount initial_mtu = connection_.max_packet_length();
5366 EXPECT_LT(initial_mtu, mtu_limit);
5367 writer_->set_max_packet_size(mtu_limit);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005368
5369 const QuicPacketCount packets_between_probes_base = 5;
5370 set_packets_between_probes_base(packets_between_probes_base);
5371
wubf76cf2a2019-10-11 18:49:07 -07005372 connection_.EnablePathMtuDiscovery(send_algorithm_);
5373
QUICHE teama6ef0a62019-03-07 20:34:33 -05005374 // Send enough packets so that the next one triggers path MTU discovery.
5375 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5376 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5377 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5378 }
5379
5380 // Trigger the probe.
5381 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5382 nullptr);
5383 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5384 writer_->SimulateNextPacketTooLarge();
5385 connection_.GetMtuDiscoveryAlarm()->Fire();
5386 ASSERT_TRUE(connection_.connected());
5387
5388 // Send more data.
5389 QuicPacketNumber probe_number = creator_->packet_number();
5390 QuicPacketCount extra_packets = packets_between_probes_base * 3;
5391 for (QuicPacketCount i = 0; i < extra_packets; i++) {
5392 connection_.EnsureWritableAndSendStreamData5();
5393 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5394 }
5395
5396 // Acknowledge all packets sent so far, except for the lost probe.
5397 QuicAckFrame probe_ack =
5398 ConstructAckFrame(creator_->packet_number(), probe_number);
5399 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5400 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5401 ProcessAckPacket(&probe_ack);
5402 EXPECT_EQ(initial_mtu, connection_.max_packet_length());
5403
5404 // Send more packets, and ensure that none of them sets the alarm.
5405 for (QuicPacketCount i = 0; i < 4 * packets_between_probes_base; i++) {
5406 connection_.EnsureWritableAndSendStreamData5();
5407 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5408 }
5409
5410 EXPECT_EQ(initial_mtu, connection_.max_packet_length());
5411 EXPECT_EQ(1u, connection_.mtu_probe_count());
5412}
5413
5414TEST_P(QuicConnectionTest, NoMtuDiscoveryAfterConnectionClosed) {
5415 EXPECT_TRUE(connection_.connected());
5416
QUICHE teama6ef0a62019-03-07 20:34:33 -05005417 const QuicPacketCount packets_between_probes_base = 10;
5418 set_packets_between_probes_base(packets_between_probes_base);
5419
wubf76cf2a2019-10-11 18:49:07 -07005420 connection_.EnablePathMtuDiscovery(send_algorithm_);
5421
QUICHE teama6ef0a62019-03-07 20:34:33 -05005422 // Send enough packets so that the next one triggers path MTU discovery.
5423 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5424 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5425 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5426 }
5427
5428 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5429 nullptr);
5430 EXPECT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5431
fkastenholz5d880a92019-06-21 09:01:56 -07005432 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005433 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
5434 ConnectionCloseBehavior::SILENT_CLOSE);
5435 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5436}
5437
5438TEST_P(QuicConnectionTest, TimeoutAfterSend) {
5439 EXPECT_TRUE(connection_.connected());
5440 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5441 QuicConfig config;
5442 connection_.SetFromConfig(config);
5443 EXPECT_FALSE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
5444
5445 const QuicTime::Delta initial_idle_timeout =
5446 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5447 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5448 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
5449
5450 // When we send a packet, the timeout will change to 5ms +
5451 // kInitialIdleTimeoutSecs.
5452 clock_.AdvanceTime(five_ms);
5453 SendStreamDataToPeer(
5454 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5455 0, FIN, nullptr);
5456 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5457
5458 // Now send more data. This will not move the timeout because
5459 // no data has been received since the previous write.
5460 clock_.AdvanceTime(five_ms);
5461 SendStreamDataToPeer(
5462 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5463 3, FIN, nullptr);
5464 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5465
5466 // The original alarm will fire. We should not time out because we had a
5467 // network event at t=5ms. The alarm will reregister.
5468 clock_.AdvanceTime(initial_idle_timeout - five_ms - five_ms);
5469 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
5470 connection_.GetTimeoutAlarm()->Fire();
5471 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5472 EXPECT_TRUE(connection_.connected());
5473 EXPECT_EQ(default_timeout + five_ms,
5474 connection_.GetTimeoutAlarm()->deadline());
5475
5476 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07005477 EXPECT_CALL(visitor_,
5478 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07005479 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005480 clock_.AdvanceTime(five_ms);
5481 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5482 connection_.GetTimeoutAlarm()->Fire();
5483 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5484 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005485 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005486}
5487
5488TEST_P(QuicConnectionTest, TimeoutAfterRetransmission) {
fayang5f135052019-08-22 17:59:40 -07005489 if (connection_.PtoEnabled()) {
5490 return;
5491 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005492 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5493 EXPECT_TRUE(connection_.connected());
5494 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5495 QuicConfig config;
5496 connection_.SetFromConfig(config);
5497 EXPECT_FALSE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
5498
5499 const QuicTime start_time = clock_.Now();
5500 const QuicTime::Delta initial_idle_timeout =
5501 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5502 QuicTime default_timeout = clock_.Now() + initial_idle_timeout;
5503
5504 connection_.SetMaxTailLossProbes(0);
5505 const QuicTime default_retransmission_time =
5506 start_time + DefaultRetransmissionTime();
5507
5508 ASSERT_LT(default_retransmission_time, default_timeout);
5509
5510 // When we send a packet, the timeout will change to 5 ms +
5511 // kInitialIdleTimeoutSecs (but it will not reschedule the alarm).
5512 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5513 const QuicTime send_time = start_time + five_ms;
5514 clock_.AdvanceTime(five_ms);
5515 ASSERT_EQ(send_time, clock_.Now());
5516 SendStreamDataToPeer(
5517 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5518 0, FIN, nullptr);
5519 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5520
5521 // Move forward 5 ms and receive a packet, which will move the timeout
5522 // forward 5 ms more (but will not reschedule the alarm).
5523 const QuicTime receive_time = send_time + five_ms;
5524 clock_.AdvanceTime(receive_time - clock_.Now());
5525 ASSERT_EQ(receive_time, clock_.Now());
5526 ProcessPacket(1);
5527
5528 // Now move forward to the retransmission time and retransmit the
5529 // packet, which should move the timeout forward again (but will not
5530 // reschedule the alarm).
5531 EXPECT_EQ(default_retransmission_time + five_ms,
5532 connection_.GetRetransmissionAlarm()->deadline());
5533 // Simulate the retransmission alarm firing.
5534 const QuicTime rto_time = send_time + DefaultRetransmissionTime();
5535 const QuicTime final_timeout = rto_time + initial_idle_timeout;
5536 clock_.AdvanceTime(rto_time - clock_.Now());
5537 ASSERT_EQ(rto_time, clock_.Now());
5538 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _));
5539 connection_.GetRetransmissionAlarm()->Fire();
5540
5541 // Advance to the original timeout and fire the alarm. The connection should
5542 // timeout, and the alarm should be registered based on the time of the
5543 // retransmission.
5544 clock_.AdvanceTime(default_timeout - clock_.Now());
5545 ASSERT_EQ(default_timeout.ToDebuggingValue(),
5546 clock_.Now().ToDebuggingValue());
5547 EXPECT_EQ(default_timeout, clock_.Now());
5548 connection_.GetTimeoutAlarm()->Fire();
5549 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5550 EXPECT_TRUE(connection_.connected());
5551 ASSERT_EQ(final_timeout.ToDebuggingValue(),
5552 connection_.GetTimeoutAlarm()->deadline().ToDebuggingValue());
5553
5554 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07005555 EXPECT_CALL(visitor_,
5556 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07005557 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005558 clock_.AdvanceTime(final_timeout - clock_.Now());
5559 EXPECT_EQ(connection_.GetTimeoutAlarm()->deadline(), clock_.Now());
5560 EXPECT_EQ(final_timeout, clock_.Now());
5561 connection_.GetTimeoutAlarm()->Fire();
5562 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5563 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005564 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005565}
5566
5567TEST_P(QuicConnectionTest, NewTimeoutAfterSendSilentClose) {
5568 // Same test as above, but complete a handshake which enables silent close,
5569 // causing no connection close packet to be sent.
5570 EXPECT_TRUE(connection_.connected());
5571 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5572 QuicConfig config;
5573
5574 // Create a handshake message that also enables silent close.
5575 CryptoHandshakeMessage msg;
vasilvvc48c8712019-03-11 13:38:16 -07005576 std::string error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005577 QuicConfig client_config;
5578 client_config.SetInitialStreamFlowControlWindowToSend(
5579 kInitialStreamFlowControlWindowForTest);
5580 client_config.SetInitialSessionFlowControlWindowToSend(
5581 kInitialSessionFlowControlWindowForTest);
5582 client_config.SetIdleNetworkTimeout(
5583 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs),
5584 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs));
fkastenholzd3a1de92019-05-15 07:00:07 -07005585 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005586 const QuicErrorCode error =
5587 config.ProcessPeerHello(msg, CLIENT, &error_details);
5588 EXPECT_EQ(QUIC_NO_ERROR, error);
5589
5590 connection_.SetFromConfig(config);
5591 EXPECT_TRUE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
5592
5593 const QuicTime::Delta default_idle_timeout =
5594 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs - 1);
5595 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5596 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5597
5598 // When we send a packet, the timeout will change to 5ms +
5599 // kInitialIdleTimeoutSecs.
5600 clock_.AdvanceTime(five_ms);
5601 SendStreamDataToPeer(
5602 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5603 0, FIN, nullptr);
5604 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5605
5606 // Now send more data. This will not move the timeout because
5607 // no data has been received since the previous write.
5608 clock_.AdvanceTime(five_ms);
5609 SendStreamDataToPeer(
5610 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5611 3, FIN, nullptr);
5612 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5613
5614 // The original alarm will fire. We should not time out because we had a
5615 // network event at t=5ms. The alarm will reregister.
5616 clock_.AdvanceTime(default_idle_timeout - five_ms - five_ms);
5617 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
5618 connection_.GetTimeoutAlarm()->Fire();
5619 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5620 EXPECT_TRUE(connection_.connected());
5621 EXPECT_EQ(default_timeout + five_ms,
5622 connection_.GetTimeoutAlarm()->deadline());
5623
5624 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07005625 // This results in a SILENT_CLOSE, so the writer will not be invoked
5626 // and will not save the frame. Grab the frame from OnConnectionClosed
5627 // directly.
5628 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
5629 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
5630
QUICHE teama6ef0a62019-03-07 20:34:33 -05005631 clock_.AdvanceTime(five_ms);
5632 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5633 connection_.GetTimeoutAlarm()->Fire();
5634 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5635 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005636 EXPECT_EQ(1, connection_close_frame_count_);
5637 EXPECT_EQ(QUIC_NETWORK_IDLE_TIMEOUT,
5638 saved_connection_close_frame_.quic_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005639}
5640
5641TEST_P(QuicConnectionTest, TimeoutAfterSendSilentCloseAndTLP) {
fayang5f135052019-08-22 17:59:40 -07005642 if (connection_.PtoEnabled()) {
5643 return;
5644 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005645 // Same test as above, but complete a handshake which enables silent close,
5646 // but sending TLPs causes the connection close to be sent.
5647 EXPECT_TRUE(connection_.connected());
5648 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5649 QuicConfig config;
5650
5651 // Create a handshake message that also enables silent close.
5652 CryptoHandshakeMessage msg;
vasilvvc48c8712019-03-11 13:38:16 -07005653 std::string error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005654 QuicConfig client_config;
5655 client_config.SetInitialStreamFlowControlWindowToSend(
5656 kInitialStreamFlowControlWindowForTest);
5657 client_config.SetInitialSessionFlowControlWindowToSend(
5658 kInitialSessionFlowControlWindowForTest);
5659 client_config.SetIdleNetworkTimeout(
5660 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs),
5661 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs));
fkastenholzd3a1de92019-05-15 07:00:07 -07005662 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005663 const QuicErrorCode error =
5664 config.ProcessPeerHello(msg, CLIENT, &error_details);
5665 EXPECT_EQ(QUIC_NO_ERROR, error);
5666
5667 connection_.SetFromConfig(config);
5668 EXPECT_TRUE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
5669
5670 const QuicTime::Delta default_idle_timeout =
5671 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs - 1);
5672 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5673 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5674
5675 // When we send a packet, the timeout will change to 5ms +
5676 // kInitialIdleTimeoutSecs.
5677 clock_.AdvanceTime(five_ms);
5678 SendStreamDataToPeer(
5679 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5680 0, FIN, nullptr);
5681 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5682
5683 // Retransmit the packet via tail loss probe.
5684 clock_.AdvanceTime(connection_.GetRetransmissionAlarm()->deadline() -
5685 clock_.Now());
5686 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _));
5687 connection_.GetRetransmissionAlarm()->Fire();
5688
5689 // This time, we should time out and send a connection close due to the TLP.
fkastenholz5d880a92019-06-21 09:01:56 -07005690 EXPECT_CALL(visitor_,
5691 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07005692 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005693 clock_.AdvanceTime(connection_.GetTimeoutAlarm()->deadline() -
5694 clock_.ApproximateNow() + five_ms);
5695 connection_.GetTimeoutAlarm()->Fire();
5696 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5697 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005698 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005699}
5700
5701TEST_P(QuicConnectionTest, TimeoutAfterSendSilentCloseWithOpenStreams) {
5702 // Same test as above, but complete a handshake which enables silent close,
5703 // but having open streams causes the connection close to be sent.
5704 EXPECT_TRUE(connection_.connected());
5705 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5706 QuicConfig config;
5707
5708 // Create a handshake message that also enables silent close.
5709 CryptoHandshakeMessage msg;
vasilvvc48c8712019-03-11 13:38:16 -07005710 std::string error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005711 QuicConfig client_config;
5712 client_config.SetInitialStreamFlowControlWindowToSend(
5713 kInitialStreamFlowControlWindowForTest);
5714 client_config.SetInitialSessionFlowControlWindowToSend(
5715 kInitialSessionFlowControlWindowForTest);
5716 client_config.SetIdleNetworkTimeout(
5717 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs),
5718 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs));
fkastenholzd3a1de92019-05-15 07:00:07 -07005719 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005720 const QuicErrorCode error =
5721 config.ProcessPeerHello(msg, CLIENT, &error_details);
5722 EXPECT_EQ(QUIC_NO_ERROR, error);
5723
5724 connection_.SetFromConfig(config);
5725 EXPECT_TRUE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
5726
5727 const QuicTime::Delta default_idle_timeout =
5728 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs - 1);
5729 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5730 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5731
5732 // When we send a packet, the timeout will change to 5ms +
5733 // kInitialIdleTimeoutSecs.
5734 clock_.AdvanceTime(five_ms);
5735 SendStreamDataToPeer(
5736 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5737 0, FIN, nullptr);
5738 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5739
5740 // Indicate streams are still open.
5741 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
5742 .WillRepeatedly(Return(true));
5743
5744 // This time, we should time out and send a connection close due to the TLP.
fkastenholz5d880a92019-06-21 09:01:56 -07005745 EXPECT_CALL(visitor_,
5746 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07005747 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005748 clock_.AdvanceTime(connection_.GetTimeoutAlarm()->deadline() -
5749 clock_.ApproximateNow() + five_ms);
5750 connection_.GetTimeoutAlarm()->Fire();
5751 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5752 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005753 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005754}
5755
5756TEST_P(QuicConnectionTest, TimeoutAfterReceive) {
5757 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5758 EXPECT_TRUE(connection_.connected());
5759 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5760 QuicConfig config;
5761 connection_.SetFromConfig(config);
5762 EXPECT_FALSE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
5763
5764 const QuicTime::Delta initial_idle_timeout =
5765 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5766 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5767 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
5768
5769 connection_.SendStreamDataWithString(
5770 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5771 0, NO_FIN);
5772 connection_.SendStreamDataWithString(
5773 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5774 3, NO_FIN);
5775
5776 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5777 clock_.AdvanceTime(five_ms);
5778
5779 // When we receive a packet, the timeout will change to 5ms +
5780 // kInitialIdleTimeoutSecs.
5781 QuicAckFrame ack = InitAckFrame(2);
5782 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5783 ProcessAckPacket(&ack);
5784
5785 // The original alarm will fire. We should not time out because we had a
5786 // network event at t=5ms. The alarm will reregister.
5787 clock_.AdvanceTime(initial_idle_timeout - five_ms);
5788 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
5789 connection_.GetTimeoutAlarm()->Fire();
5790 EXPECT_TRUE(connection_.connected());
5791 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5792 EXPECT_EQ(default_timeout + five_ms,
5793 connection_.GetTimeoutAlarm()->deadline());
5794
5795 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07005796 EXPECT_CALL(visitor_,
5797 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07005798 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005799 clock_.AdvanceTime(five_ms);
5800 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5801 connection_.GetTimeoutAlarm()->Fire();
5802 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5803 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005804 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005805}
5806
5807TEST_P(QuicConnectionTest, TimeoutAfterReceiveNotSendWhenUnacked) {
5808 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5809 EXPECT_TRUE(connection_.connected());
5810 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5811 QuicConfig config;
5812 connection_.SetFromConfig(config);
5813 EXPECT_FALSE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
5814
5815 const QuicTime::Delta initial_idle_timeout =
5816 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5817 connection_.SetNetworkTimeouts(
5818 QuicTime::Delta::Infinite(),
5819 initial_idle_timeout + QuicTime::Delta::FromSeconds(1));
5820 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5821 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
5822
5823 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5824 connection_.SendStreamDataWithString(
5825 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5826 0, NO_FIN);
5827 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5828 connection_.SendStreamDataWithString(
5829 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5830 3, NO_FIN);
5831
5832 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5833
5834 clock_.AdvanceTime(five_ms);
5835
5836 // When we receive a packet, the timeout will change to 5ms +
5837 // kInitialIdleTimeoutSecs.
5838 QuicAckFrame ack = InitAckFrame(2);
5839 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5840 ProcessAckPacket(&ack);
5841
5842 // The original alarm will fire. We should not time out because we had a
5843 // network event at t=5ms. The alarm will reregister.
5844 clock_.AdvanceTime(initial_idle_timeout - five_ms);
5845 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
5846 connection_.GetTimeoutAlarm()->Fire();
5847 EXPECT_TRUE(connection_.connected());
5848 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5849 EXPECT_EQ(default_timeout + five_ms,
5850 connection_.GetTimeoutAlarm()->deadline());
5851
5852 // Now, send packets while advancing the time and verify that the connection
5853 // eventually times out.
fkastenholz5d880a92019-06-21 09:01:56 -07005854 EXPECT_CALL(visitor_,
5855 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005856 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
5857 for (int i = 0; i < 100 && connection_.connected(); ++i) {
5858 QUIC_LOG(INFO) << "sending data packet";
5859 connection_.SendStreamDataWithString(
5860 GetNthClientInitiatedStreamId(1, connection_.transport_version()),
5861 "foo", 0, NO_FIN);
5862 connection_.GetTimeoutAlarm()->Fire();
5863 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
5864 }
5865 EXPECT_FALSE(connection_.connected());
5866 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07005867 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005868}
5869
5870TEST_P(QuicConnectionTest, TimeoutAfter5ClientRTOs) {
fayang5f135052019-08-22 17:59:40 -07005871 if (connection_.PtoEnabled()) {
5872 return;
5873 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005874 connection_.SetMaxTailLossProbes(2);
5875 EXPECT_TRUE(connection_.connected());
5876 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5877 QuicConfig config;
5878 QuicTagVector connection_options;
5879 connection_options.push_back(k5RTO);
5880 config.SetConnectionOptionsToSend(connection_options);
5881 connection_.SetFromConfig(config);
5882
5883 // Send stream data.
5884 SendStreamDataToPeer(
5885 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5886 0, FIN, nullptr);
5887
5888 // Fire the retransmission alarm 6 times, twice for TLP and 4 times for RTO.
5889 for (int i = 0; i < 6; ++i) {
5890 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5891 connection_.GetRetransmissionAlarm()->Fire();
5892 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5893 EXPECT_TRUE(connection_.connected());
5894 }
5895
5896 EXPECT_EQ(2u, connection_.sent_packet_manager().GetConsecutiveTlpCount());
5897 EXPECT_EQ(4u, connection_.sent_packet_manager().GetConsecutiveRtoCount());
5898 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07005899 EXPECT_CALL(visitor_,
5900 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07005901 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005902 connection_.GetRetransmissionAlarm()->Fire();
5903 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5904 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005905 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005906}
5907
5908TEST_P(QuicConnectionTest, SendScheduler) {
5909 // Test that if we send a packet without delay, it is not queued.
5910 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
QUICHE team8c1daa22019-03-13 08:33:41 -07005911 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07005912 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005913 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
5914 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
QUICHE team6987b4a2019-03-15 16:23:04 -07005915 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05005916 HAS_RETRANSMITTABLE_DATA, false, false);
5917 EXPECT_EQ(0u, connection_.NumQueuedPackets());
5918}
5919
5920TEST_P(QuicConnectionTest, FailToSendFirstPacket) {
5921 // Test that the connection does not crash when it fails to send the first
5922 // packet at which point self_address_ might be uninitialized.
5923 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
fkastenholz5d880a92019-06-21 09:01:56 -07005924 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
QUICHE team8c1daa22019-03-13 08:33:41 -07005925 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07005926 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005927 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
5928 writer_->SetShouldWriteFail();
QUICHE team6987b4a2019-03-15 16:23:04 -07005929 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05005930 HAS_RETRANSMITTABLE_DATA, false, false);
5931}
5932
5933TEST_P(QuicConnectionTest, SendSchedulerEAGAIN) {
5934 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
QUICHE team8c1daa22019-03-13 08:33:41 -07005935 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07005936 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005937 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
5938 BlockOnNextWrite();
5939 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _))
5940 .Times(0);
QUICHE team6987b4a2019-03-15 16:23:04 -07005941 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05005942 HAS_RETRANSMITTABLE_DATA, false, false);
5943 EXPECT_EQ(1u, connection_.NumQueuedPackets());
5944}
5945
5946TEST_P(QuicConnectionTest, TestQueueLimitsOnSendStreamData) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005947 // Queue the first packet.
ianswett3085da82019-04-04 07:24:24 -07005948 size_t payload_length = connection_.max_packet_length();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005949 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(testing::Return(false));
vasilvvc48c8712019-03-11 13:38:16 -07005950 const std::string payload(payload_length, 'a');
ianswett3085da82019-04-04 07:24:24 -07005951 QuicStreamId first_bidi_stream_id(QuicUtils::GetFirstBidirectionalStreamId(
5952 connection_.version().transport_version, Perspective::IS_CLIENT));
5953 EXPECT_EQ(0u, connection_
5954 .SendStreamDataWithString(first_bidi_stream_id, payload, 0,
5955 NO_FIN)
QUICHE teama6ef0a62019-03-07 20:34:33 -05005956 .bytes_consumed);
5957 EXPECT_EQ(0u, connection_.NumQueuedPackets());
5958}
5959
ianswett3085da82019-04-04 07:24:24 -07005960TEST_P(QuicConnectionTest, SendingThreePackets) {
ianswett3085da82019-04-04 07:24:24 -07005961 // Make the payload twice the size of the packet, so 3 packets are written.
5962 size_t total_payload_length = 2 * connection_.max_packet_length();
vasilvvc48c8712019-03-11 13:38:16 -07005963 const std::string payload(total_payload_length, 'a');
ianswett3085da82019-04-04 07:24:24 -07005964 QuicStreamId first_bidi_stream_id(QuicUtils::GetFirstBidirectionalStreamId(
5965 connection_.version().transport_version, Perspective::IS_CLIENT));
5966 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
5967 EXPECT_EQ(payload.size(), connection_
5968 .SendStreamDataWithString(first_bidi_stream_id,
5969 payload, 0, NO_FIN)
5970 .bytes_consumed);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005971}
5972
5973TEST_P(QuicConnectionTest, LoopThroughSendingPacketsWithTruncation) {
5974 set_perspective(Perspective::IS_SERVER);
fayangd4291e42019-05-30 10:31:21 -07005975 if (!VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005976 // For IETF QUIC, encryption level will be switched to FORWARD_SECURE in
5977 // SendStreamDataWithString.
5978 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
5979 }
5980 // Set up a larger payload than will fit in one packet.
vasilvvc48c8712019-03-11 13:38:16 -07005981 const std::string payload(connection_.max_packet_length(), 'a');
QUICHE teama6ef0a62019-03-07 20:34:33 -05005982 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
5983
5984 // Now send some packets with no truncation.
5985 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
5986 EXPECT_EQ(payload.size(),
5987 connection_.SendStreamDataWithString(3, payload, 0, NO_FIN)
5988 .bytes_consumed);
5989 // Track the size of the second packet here. The overhead will be the largest
5990 // we see in this test, due to the non-truncated connection id.
5991 size_t non_truncated_packet_size = writer_->last_packet_size();
5992
5993 // Change to a 0 byte connection id.
5994 QuicConfig config;
5995 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
5996 connection_.SetFromConfig(config);
5997 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
5998 EXPECT_EQ(payload.size(),
5999 connection_.SendStreamDataWithString(3, payload, 1350, NO_FIN)
6000 .bytes_consumed);
fayangd4291e42019-05-30 10:31:21 -07006001 if (VersionHasIetfInvariantHeader(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006002 // Short header packets sent from server omit connection ID already, and
6003 // stream offset size increases from 0 to 2.
6004 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() - 2);
6005 } else {
6006 // Just like above, we save 8 bytes on payload, and 8 on truncation. -2
6007 // because stream offset size is 2 instead of 0.
6008 EXPECT_EQ(non_truncated_packet_size,
6009 writer_->last_packet_size() + 8 * 2 - 2);
6010 }
6011}
6012
6013TEST_P(QuicConnectionTest, SendDelayedAck) {
6014 QuicTime ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6015 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6016 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6017 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006018 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006019 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006020 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006021 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006022 // Process a packet from the non-crypto stream.
6023 frame1_.stream_id = 3;
6024
6025 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006026 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006027 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6028 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6029
6030 // Check if delayed ack timer is running for the expected interval.
6031 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6032 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6033 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07006034 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006035 connection_.GetAckAlarm()->Fire();
6036 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006037 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006038 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006039 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006040 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6041 } else {
nharper55fa6132019-05-07 19:37:21 -07006042 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006043 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6044 }
6045 EXPECT_FALSE(writer_->ack_frames().empty());
6046 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6047}
6048
6049TEST_P(QuicConnectionTest, SendDelayedAfterQuiescence) {
6050 QuicConnectionPeer::SetFastAckAfterQuiescence(&connection_, true);
6051
6052 // The beginning of the connection counts as quiescence.
6053 QuicTime ack_time =
6054 clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
6055 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6056 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6057 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006058 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006059 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006060 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006061 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006062 // Process a packet from the non-crypto stream.
6063 frame1_.stream_id = 3;
6064
6065 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006066 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006067 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6068 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6069
6070 // Check if delayed ack timer is running for the expected interval.
6071 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6072 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6073 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07006074 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006075 connection_.GetAckAlarm()->Fire();
6076 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006077 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006078 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006079 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006080 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6081 } else {
nharper55fa6132019-05-07 19:37:21 -07006082 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006083 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6084 }
6085 EXPECT_FALSE(writer_->ack_frames().empty());
6086 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6087
6088 // Process another packet immedately after sending the ack and expect the
6089 // ack alarm to be set delayed ack time in the future.
6090 ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6091 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6092 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6093
6094 // Check if delayed ack timer is running for the expected interval.
6095 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6096 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6097 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07006098 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006099 connection_.GetAckAlarm()->Fire();
6100 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006101 padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006102 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006103 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006104 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6105 } else {
nharper55fa6132019-05-07 19:37:21 -07006106 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006107 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6108 }
6109 EXPECT_FALSE(writer_->ack_frames().empty());
6110 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6111
6112 // Wait 1 second and enesure the ack alarm is set to 1ms in the future.
6113 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
6114 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
6115 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6116 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6117
6118 // Check if delayed ack timer is running for the expected interval.
6119 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6120 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6121}
6122
6123TEST_P(QuicConnectionTest, SendDelayedAckDecimation) {
6124 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6125 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION);
6126
6127 const size_t kMinRttMs = 40;
6128 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6129 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6130 QuicTime::Delta::Zero(), QuicTime::Zero());
6131 // The ack time should be based on min_rtt/4, since it's less than the
6132 // default delayed ack time.
6133 QuicTime ack_time = clock_.ApproximateNow() +
6134 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6135 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6136 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6137 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006138 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006139 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006140 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006141 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006142 // Process a packet from the non-crypto stream.
6143 frame1_.stream_id = 3;
6144
6145 // Process all the initial packets in order so there aren't missing packets.
6146 uint64_t kFirstDecimatedPacket = 101;
6147 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6148 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6149 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6150 }
6151 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6152 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006153 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006154 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6155 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6156 ENCRYPTION_ZERO_RTT);
6157
6158 // Check if delayed ack timer is running for the expected interval.
6159 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6160 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6161
6162 // The 10th received packet causes an ack to be sent.
6163 for (int i = 0; i < 9; ++i) {
6164 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6165 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6166 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6167 ENCRYPTION_ZERO_RTT);
6168 }
6169 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07006170 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006171 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07006172 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006173 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6174 } else {
nharperc32d8ab2019-10-09 11:09:06 -07006175 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006176 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6177 }
6178 EXPECT_FALSE(writer_->ack_frames().empty());
6179 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6180}
6181
6182TEST_P(QuicConnectionTest, SendDelayedAckAckDecimationAfterQuiescence) {
6183 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6184 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION);
6185 QuicConnectionPeer::SetFastAckAfterQuiescence(&connection_, true);
6186
6187 const size_t kMinRttMs = 40;
6188 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6189 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6190 QuicTime::Delta::Zero(), QuicTime::Zero());
6191
6192 // The beginning of the connection counts as quiescence.
6193 QuicTime ack_time =
6194 clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
6195 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6196 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6197 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006198 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006199 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006200 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006201 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006202 // Process a packet from the non-crypto stream.
6203 frame1_.stream_id = 3;
6204
6205 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006206 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006207 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6208 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6209
6210 // Check if delayed ack timer is running for the expected interval.
6211 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6212 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6213 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07006214 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006215 connection_.GetAckAlarm()->Fire();
6216 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006217 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006218 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006219 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006220 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6221 } else {
nharper55fa6132019-05-07 19:37:21 -07006222 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006223 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6224 }
6225 EXPECT_FALSE(writer_->ack_frames().empty());
6226 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6227
6228 // Process another packet immedately after sending the ack and expect the
6229 // ack alarm to be set delayed ack time in the future.
6230 ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6231 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6232 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6233
6234 // Check if delayed ack timer is running for the expected interval.
6235 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6236 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6237 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07006238 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006239 connection_.GetAckAlarm()->Fire();
6240 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006241 padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006242 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006243 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006244 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6245 } else {
nharper55fa6132019-05-07 19:37:21 -07006246 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006247 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6248 }
6249 EXPECT_FALSE(writer_->ack_frames().empty());
6250 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6251
6252 // Wait 1 second and enesure the ack alarm is set to 1ms in the future.
6253 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
6254 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
6255 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6256 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6257
6258 // Check if delayed ack timer is running for the expected interval.
6259 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6260 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6261
6262 // Process enough packets to get into ack decimation behavior.
6263 // The ack time should be based on min_rtt/4, since it's less than the
6264 // default delayed ack time.
6265 ack_time = clock_.ApproximateNow() +
6266 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6267 uint64_t kFirstDecimatedPacket = 101;
6268 for (unsigned int i = 0; i < kFirstDecimatedPacket - 4; ++i) {
6269 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6270 ProcessDataPacketAtLevel(4 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6271 }
6272 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6273 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006274 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006275 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6276 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6277 ENCRYPTION_ZERO_RTT);
6278
6279 // Check if delayed ack timer is running for the expected interval.
6280 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6281 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6282
6283 // The 10th received packet causes an ack to be sent.
6284 for (int i = 0; i < 9; ++i) {
6285 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6286 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6287 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6288 ENCRYPTION_ZERO_RTT);
6289 }
6290 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07006291 padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006292 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07006293 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006294 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6295 } else {
nharperc32d8ab2019-10-09 11:09:06 -07006296 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006297 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6298 }
6299 EXPECT_FALSE(writer_->ack_frames().empty());
6300 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6301
6302 // Wait 1 second and enesure the ack alarm is set to 1ms in the future.
6303 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
6304 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
6305 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6306 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 10, !kHasStopWaiting,
6307 ENCRYPTION_ZERO_RTT);
6308
6309 // Check if delayed ack timer is running for the expected interval.
6310 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6311 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6312}
6313
6314TEST_P(QuicConnectionTest, SendDelayedAckDecimationUnlimitedAggregation) {
6315 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6316 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6317 QuicConfig config;
6318 QuicTagVector connection_options;
6319 connection_options.push_back(kACKD);
6320 // No limit on the number of packets received before sending an ack.
6321 connection_options.push_back(kAKDU);
6322 config.SetConnectionOptionsToSend(connection_options);
6323 connection_.SetFromConfig(config);
6324
6325 const size_t kMinRttMs = 40;
6326 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6327 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6328 QuicTime::Delta::Zero(), QuicTime::Zero());
6329 // The ack time should be based on min_rtt/4, since it's less than the
6330 // default delayed ack time.
6331 QuicTime ack_time = clock_.ApproximateNow() +
6332 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6333 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6334 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6335 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006336 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006337 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006338 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006339 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006340 // Process a packet from the non-crypto stream.
6341 frame1_.stream_id = 3;
6342
6343 // Process all the initial packets in order so there aren't missing packets.
6344 uint64_t kFirstDecimatedPacket = 101;
6345 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6346 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6347 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6348 }
6349 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6350 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006351 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006352 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6353 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6354 ENCRYPTION_ZERO_RTT);
6355
6356 // Check if delayed ack timer is running for the expected interval.
6357 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6358 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6359
6360 // 18 packets will not cause an ack to be sent. 19 will because when
6361 // stop waiting frames are in use, we ack every 20 packets no matter what.
6362 for (int i = 0; i < 18; ++i) {
6363 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6364 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6365 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6366 ENCRYPTION_ZERO_RTT);
6367 }
6368 // The delayed ack timer should still be set to the expected deadline.
6369 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6370 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6371}
6372
6373TEST_P(QuicConnectionTest, SendDelayedAckDecimationEighthRtt) {
6374 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6375 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION);
6376 QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
6377
6378 const size_t kMinRttMs = 40;
6379 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6380 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6381 QuicTime::Delta::Zero(), QuicTime::Zero());
6382 // The ack time should be based on min_rtt/8, since it's less than the
6383 // default delayed ack time.
6384 QuicTime ack_time = clock_.ApproximateNow() +
6385 QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
6386 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6387 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6388 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006389 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006390 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006391 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006392 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006393 // Process a packet from the non-crypto stream.
6394 frame1_.stream_id = 3;
6395
6396 // Process all the initial packets in order so there aren't missing packets.
6397 uint64_t kFirstDecimatedPacket = 101;
6398 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6399 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6400 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6401 }
6402 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6403 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006404 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006405 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6406 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6407 ENCRYPTION_ZERO_RTT);
6408
6409 // Check if delayed ack timer is running for the expected interval.
6410 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6411 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6412
6413 // The 10th received packet causes an ack to be sent.
6414 for (int i = 0; i < 9; ++i) {
6415 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6416 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6417 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6418 ENCRYPTION_ZERO_RTT);
6419 }
6420 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07006421 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006422 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07006423 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006424 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6425 } else {
nharperc32d8ab2019-10-09 11:09:06 -07006426 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006427 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6428 }
6429 EXPECT_FALSE(writer_->ack_frames().empty());
6430 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6431}
6432
6433TEST_P(QuicConnectionTest, SendDelayedAckDecimationWithReordering) {
6434 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6435 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6436
6437 const size_t kMinRttMs = 40;
6438 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6439 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6440 QuicTime::Delta::Zero(), QuicTime::Zero());
6441 // The ack time should be based on min_rtt/4, since it's less than the
6442 // default delayed ack time.
6443 QuicTime ack_time = clock_.ApproximateNow() +
6444 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6445 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6446 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6447 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006448 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006449 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006450 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006451 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006452 // Process a packet from the non-crypto stream.
6453 frame1_.stream_id = 3;
6454
6455 // Process all the initial packets in order so there aren't missing packets.
6456 uint64_t kFirstDecimatedPacket = 101;
6457 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6458 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6459 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6460 }
6461 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6462
6463 // Receive one packet out of order and then the rest in order.
6464 // The loop leaves a one packet gap between acks sent to simulate some loss.
6465 for (int j = 0; j < 3; ++j) {
6466 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6467 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6468 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 9 + (j * 11),
6469 !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6470 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
6471 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6472 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6473
6474 // The 10th received packet causes an ack to be sent.
6475 writer_->Reset();
6476 for (int i = 0; i < 9; ++i) {
6477 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6478 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6479 // The ACK shouldn't be sent until the 10th packet is processed.
6480 EXPECT_TRUE(writer_->ack_frames().empty());
6481 ProcessDataPacketAtLevel(kFirstDecimatedPacket + i + (j * 11),
6482 !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6483 }
6484 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07006485 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006486 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07006487 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006488 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6489 } else {
nharperc32d8ab2019-10-09 11:09:06 -07006490 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006491 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6492 }
6493 EXPECT_FALSE(writer_->ack_frames().empty());
6494 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6495 }
6496}
6497
6498TEST_P(QuicConnectionTest, SendDelayedAckDecimationWithLargeReordering) {
6499 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6500 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6501
6502 const size_t kMinRttMs = 40;
6503 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6504 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6505 QuicTime::Delta::Zero(), QuicTime::Zero());
6506 // The ack time should be based on min_rtt/4, since it's less than the
6507 // default delayed ack time.
6508 QuicTime ack_time = clock_.ApproximateNow() +
6509 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6510 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6511 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6512 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006513 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006514 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006515 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006516 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006517 // Process a packet from the non-crypto stream.
6518 frame1_.stream_id = 3;
6519
6520 // Process all the initial packets in order so there aren't missing packets.
6521 uint64_t kFirstDecimatedPacket = 101;
6522 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6523 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6524 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6525 }
6526 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6527 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006528 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006529 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6530 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6531 ENCRYPTION_ZERO_RTT);
6532
6533 // Check if delayed ack timer is running for the expected interval.
6534 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6535 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6536
6537 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6538 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6539 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 19, !kHasStopWaiting,
6540 ENCRYPTION_ZERO_RTT);
6541 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
6542 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6543 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6544
6545 // The 10th received packet causes an ack to be sent.
6546 for (int i = 0; i < 8; ++i) {
6547 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6548 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6549 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6550 ENCRYPTION_ZERO_RTT);
6551 }
6552 // Check that ack is sent and that delayed ack alarm is reset.
6553 if (GetParam().no_stop_waiting) {
6554 EXPECT_EQ(1u, writer_->frame_count());
6555 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6556 } else {
6557 EXPECT_EQ(2u, writer_->frame_count());
6558 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6559 }
6560 EXPECT_FALSE(writer_->ack_frames().empty());
6561 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6562
6563 // The next packet received in order will cause an immediate ack,
6564 // because it fills a hole.
6565 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6566 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6567 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 10, !kHasStopWaiting,
6568 ENCRYPTION_ZERO_RTT);
6569 // Check that ack is sent and that delayed ack alarm is reset.
6570 if (GetParam().no_stop_waiting) {
6571 EXPECT_EQ(1u, writer_->frame_count());
6572 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6573 } else {
6574 EXPECT_EQ(2u, writer_->frame_count());
6575 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6576 }
6577 EXPECT_FALSE(writer_->ack_frames().empty());
6578 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6579}
6580
6581TEST_P(QuicConnectionTest, SendDelayedAckDecimationWithReorderingEighthRtt) {
6582 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6583 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6584 QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
6585
6586 const size_t kMinRttMs = 40;
6587 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6588 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6589 QuicTime::Delta::Zero(), QuicTime::Zero());
6590 // The ack time should be based on min_rtt/8, since it's less than the
6591 // default delayed ack time.
6592 QuicTime ack_time = clock_.ApproximateNow() +
6593 QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
6594 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6595 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6596 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006597 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006598 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006599 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006600 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006601 // Process a packet from the non-crypto stream.
6602 frame1_.stream_id = 3;
6603
6604 // Process all the initial packets in order so there aren't missing packets.
6605 uint64_t kFirstDecimatedPacket = 101;
6606 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6607 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6608 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6609 }
6610 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6611 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006612 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006613 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6614 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6615 ENCRYPTION_ZERO_RTT);
6616
6617 // Check if delayed ack timer is running for the expected interval.
6618 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6619 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6620
6621 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6622 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6623 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 9, !kHasStopWaiting,
6624 ENCRYPTION_ZERO_RTT);
6625 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
6626 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6627 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6628
6629 // The 10th received packet causes an ack to be sent.
6630 for (int i = 0; i < 8; ++i) {
6631 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6632 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6633 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6634 ENCRYPTION_ZERO_RTT);
6635 }
6636 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07006637 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006638 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07006639 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006640 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6641 } else {
nharperc32d8ab2019-10-09 11:09:06 -07006642 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006643 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6644 }
6645 EXPECT_FALSE(writer_->ack_frames().empty());
6646 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6647}
6648
6649TEST_P(QuicConnectionTest,
6650 SendDelayedAckDecimationWithLargeReorderingEighthRtt) {
6651 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6652 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6653 QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
6654
6655 const size_t kMinRttMs = 40;
6656 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6657 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6658 QuicTime::Delta::Zero(), QuicTime::Zero());
6659 // The ack time should be based on min_rtt/8, since it's less than the
6660 // default delayed ack time.
6661 QuicTime ack_time = clock_.ApproximateNow() +
6662 QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
6663 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6664 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6665 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006666 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006667 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006668 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006669 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006670 // Process a packet from the non-crypto stream.
6671 frame1_.stream_id = 3;
6672
6673 // Process all the initial packets in order so there aren't missing packets.
6674 uint64_t kFirstDecimatedPacket = 101;
6675 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6676 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6677 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6678 }
6679 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6680 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006681 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006682 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6683 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6684 ENCRYPTION_ZERO_RTT);
6685
6686 // Check if delayed ack timer is running for the expected interval.
6687 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6688 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6689
6690 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6691 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6692 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 19, !kHasStopWaiting,
6693 ENCRYPTION_ZERO_RTT);
6694 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
6695 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6696 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6697
6698 // The 10th received packet causes an ack to be sent.
6699 for (int i = 0; i < 8; ++i) {
6700 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6701 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6702 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6703 ENCRYPTION_ZERO_RTT);
6704 }
6705 // Check that ack is sent and that delayed ack alarm is reset.
6706 if (GetParam().no_stop_waiting) {
6707 EXPECT_EQ(1u, writer_->frame_count());
6708 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6709 } else {
6710 EXPECT_EQ(2u, writer_->frame_count());
6711 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6712 }
6713 EXPECT_FALSE(writer_->ack_frames().empty());
6714 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6715
6716 // The next packet received in order will cause an immediate ack,
6717 // because it fills a hole.
6718 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6719 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6720 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 10, !kHasStopWaiting,
6721 ENCRYPTION_ZERO_RTT);
6722 // Check that ack is sent and that delayed ack alarm is reset.
6723 if (GetParam().no_stop_waiting) {
6724 EXPECT_EQ(1u, writer_->frame_count());
6725 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6726 } else {
6727 EXPECT_EQ(2u, writer_->frame_count());
6728 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6729 }
6730 EXPECT_FALSE(writer_->ack_frames().empty());
6731 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6732}
6733
6734TEST_P(QuicConnectionTest, SendDelayedAckOnHandshakeConfirmed) {
6735 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6736 ProcessPacket(1);
6737 // Check that ack is sent and that delayed ack alarm is set.
6738 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6739 QuicTime ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6740 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6741
6742 // Completing the handshake as the server does nothing.
6743 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_SERVER);
6744 connection_.OnHandshakeComplete();
6745 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6746 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6747
6748 // Complete the handshake as the client decreases the delayed ack time to 0ms.
6749 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_CLIENT);
6750 connection_.OnHandshakeComplete();
6751 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6752 EXPECT_EQ(clock_.ApproximateNow(), connection_.GetAckAlarm()->deadline());
6753}
6754
6755TEST_P(QuicConnectionTest, SendDelayedAckOnSecondPacket) {
6756 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6757 ProcessPacket(1);
6758 ProcessPacket(2);
6759 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006760 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006761 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006762 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006763 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6764 } else {
nharper55fa6132019-05-07 19:37:21 -07006765 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006766 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6767 }
6768 EXPECT_FALSE(writer_->ack_frames().empty());
6769 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6770}
6771
6772TEST_P(QuicConnectionTest, NoAckOnOldNacks) {
6773 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang6dba4902019-06-17 10:04:23 -07006774 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006775 ProcessPacket(2);
6776 size_t frames_per_ack = GetParam().no_stop_waiting ? 1 : 2;
QUICHE teama6ef0a62019-03-07 20:34:33 -05006777
6778 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
6779 ProcessPacket(3);
nharper55fa6132019-05-07 19:37:21 -07006780 size_t padding_frame_count = writer_->padding_frames().size();
6781 EXPECT_EQ(padding_frame_count + frames_per_ack, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006782 EXPECT_FALSE(writer_->ack_frames().empty());
6783 writer_->Reset();
6784
fayang6dba4902019-06-17 10:04:23 -07006785 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006786 ProcessPacket(4);
fayang6dba4902019-06-17 10:04:23 -07006787 EXPECT_EQ(0u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006788
6789 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
6790 ProcessPacket(5);
nharper55fa6132019-05-07 19:37:21 -07006791 padding_frame_count = writer_->padding_frames().size();
6792 EXPECT_EQ(padding_frame_count + frames_per_ack, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006793 EXPECT_FALSE(writer_->ack_frames().empty());
6794 writer_->Reset();
6795
6796 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6797 // Now only set the timer on the 6th packet, instead of sending another ack.
6798 ProcessPacket(6);
nharper55fa6132019-05-07 19:37:21 -07006799 padding_frame_count = writer_->padding_frames().size();
6800 EXPECT_EQ(padding_frame_count, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006801 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6802}
6803
6804TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingPacket) {
6805 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
QUICHE team8c1daa22019-03-13 08:33:41 -07006806 EXPECT_CALL(visitor_, OnStreamFrame(_));
6807 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07006808 std::make_unique<TaggingEncrypter>(0x01));
zhongyi546cc452019-04-12 15:27:49 -07006809 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07006810 std::make_unique<StrictTaggingDecrypter>(0x01));
nharper2c9f02a2019-05-08 10:25:50 -07006811 ProcessDataPacket(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006812 connection_.SendStreamDataWithString(
6813 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6814 0, NO_FIN);
6815 // Check that ack is bundled with outgoing data and that delayed ack
6816 // alarm is reset.
6817 if (GetParam().no_stop_waiting) {
6818 EXPECT_EQ(2u, writer_->frame_count());
6819 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6820 } else {
6821 EXPECT_EQ(3u, writer_->frame_count());
6822 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6823 }
6824 EXPECT_FALSE(writer_->ack_frames().empty());
6825 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6826}
6827
6828TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingCryptoPacket) {
6829 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayangc31c9952019-06-05 13:54:48 -07006830 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6831 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
6832 } else {
6833 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6834 }
6835 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
nharper46833c32019-05-15 21:33:05 -07006836 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006837 // Check that ack is bundled with outgoing crypto data.
6838 if (GetParam().no_stop_waiting) {
6839 EXPECT_EQ(3u, writer_->frame_count());
6840 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6841 } else {
6842 EXPECT_EQ(4u, writer_->frame_count());
6843 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6844 }
6845 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6846}
6847
6848TEST_P(QuicConnectionTest, BlockAndBufferOnFirstCHLOPacketOfTwo) {
6849 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6850 ProcessPacket(1);
6851 BlockOnNextWrite();
6852 writer_->set_is_write_blocked_data_buffered(true);
nharper46833c32019-05-15 21:33:05 -07006853 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006854 EXPECT_TRUE(writer_->IsWriteBlocked());
6855 EXPECT_FALSE(connection_.HasQueuedData());
nharper46833c32019-05-15 21:33:05 -07006856 connection_.SendCryptoDataWithString("bar", 3);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006857 EXPECT_TRUE(writer_->IsWriteBlocked());
6858 EXPECT_TRUE(connection_.HasQueuedData());
6859}
6860
6861TEST_P(QuicConnectionTest, BundleAckForSecondCHLO) {
6862 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6863 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6864 EXPECT_CALL(visitor_, OnCanWrite())
6865 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6866 &connection_, &TestConnection::SendCryptoStreamData)));
6867 // Process a packet from the crypto stream, which is frame1_'s default.
6868 // Receiving the CHLO as packet 2 first will cause the connection to
6869 // immediately send an ack, due to the packet gap.
fayangc31c9952019-06-05 13:54:48 -07006870 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6871 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
6872 } else {
6873 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6874 }
6875 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006876 // Check that ack is sent and that delayed ack alarm is reset.
6877 if (GetParam().no_stop_waiting) {
6878 EXPECT_EQ(3u, writer_->frame_count());
6879 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6880 } else {
6881 EXPECT_EQ(4u, writer_->frame_count());
6882 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6883 }
QUICHE teamea740082019-03-11 17:58:43 -07006884 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006885 EXPECT_EQ(1u, writer_->stream_frames().size());
6886 } else {
6887 EXPECT_EQ(1u, writer_->crypto_frames().size());
6888 }
6889 EXPECT_EQ(1u, writer_->padding_frames().size());
6890 ASSERT_FALSE(writer_->ack_frames().empty());
6891 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(writer_->ack_frames().front()));
6892 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6893}
6894
6895TEST_P(QuicConnectionTest, BundleAckForSecondCHLOTwoPacketReject) {
6896 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6897 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6898
6899 // Process two packets from the crypto stream, which is frame1_'s default,
6900 // simulating a 2 packet reject.
6901 {
fayangc31c9952019-06-05 13:54:48 -07006902 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6903 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
6904 } else {
6905 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6906 }
6907 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006908 // Send the new CHLO when the REJ is processed.
fayangc31c9952019-06-05 13:54:48 -07006909 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6910 EXPECT_CALL(visitor_, OnCryptoFrame(_))
6911 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6912 &connection_, &TestConnection::SendCryptoStreamData)));
6913 } else {
6914 EXPECT_CALL(visitor_, OnStreamFrame(_))
6915 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6916 &connection_, &TestConnection::SendCryptoStreamData)));
6917 }
6918 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006919 }
6920 // Check that ack is sent and that delayed ack alarm is reset.
6921 if (GetParam().no_stop_waiting) {
6922 EXPECT_EQ(3u, writer_->frame_count());
6923 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6924 } else {
6925 EXPECT_EQ(4u, writer_->frame_count());
6926 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6927 }
QUICHE teamea740082019-03-11 17:58:43 -07006928 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006929 EXPECT_EQ(1u, writer_->stream_frames().size());
6930 } else {
6931 EXPECT_EQ(1u, writer_->crypto_frames().size());
6932 }
6933 EXPECT_EQ(1u, writer_->padding_frames().size());
6934 ASSERT_FALSE(writer_->ack_frames().empty());
6935 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(writer_->ack_frames().front()));
6936 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6937}
6938
6939TEST_P(QuicConnectionTest, BundleAckWithDataOnIncomingAck) {
6940 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6941 connection_.SendStreamDataWithString(
6942 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6943 0, NO_FIN);
6944 connection_.SendStreamDataWithString(
6945 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6946 3, NO_FIN);
6947 // Ack the second packet, which will retransmit the first packet.
6948 QuicAckFrame ack = ConstructAckFrame(2, 1);
6949 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07006950 lost_packets.push_back(
6951 LostPacket(QuicPacketNumber(1), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006952 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
6953 .WillOnce(SetArgPointee<5>(lost_packets));
6954 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
6955 ProcessAckPacket(&ack);
nharper55fa6132019-05-07 19:37:21 -07006956 size_t padding_frame_count = writer_->padding_frames().size();
6957 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006958 EXPECT_EQ(1u, writer_->stream_frames().size());
6959 writer_->Reset();
6960
6961 // Now ack the retransmission, which will both raise the high water mark
6962 // and see if there is more data to send.
6963 ack = ConstructAckFrame(3, 1);
6964 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
6965 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
6966 ProcessAckPacket(&ack);
6967
6968 // Check that no packet is sent and the ack alarm isn't set.
6969 EXPECT_EQ(0u, writer_->frame_count());
6970 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6971 writer_->Reset();
6972
6973 // Send the same ack, but send both data and an ack together.
6974 ack = ConstructAckFrame(3, 1);
6975 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
6976 EXPECT_CALL(visitor_, OnCanWrite())
6977 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6978 &connection_, &TestConnection::EnsureWritableAndSendStreamData5)));
6979 ProcessAckPacket(&ack);
6980
6981 // Check that ack is bundled with outgoing data and the delayed ack
6982 // alarm is reset.
6983 if (GetParam().no_stop_waiting) {
fayange8b0cab2019-07-17 14:23:07 -07006984 if (GetQuicReloadableFlag(quic_simplify_stop_waiting)) {
6985 // Do not ACK acks.
6986 EXPECT_EQ(1u, writer_->frame_count());
6987 } else {
6988 EXPECT_EQ(2u, writer_->frame_count());
6989 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6990 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006991 } else {
6992 EXPECT_EQ(3u, writer_->frame_count());
6993 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6994 }
fayange8b0cab2019-07-17 14:23:07 -07006995 if (GetParam().no_stop_waiting &&
6996 GetQuicReloadableFlag(quic_simplify_stop_waiting)) {
fayang03916692019-05-22 17:57:18 -07006997 EXPECT_TRUE(writer_->ack_frames().empty());
6998 } else {
6999 EXPECT_FALSE(writer_->ack_frames().empty());
7000 EXPECT_EQ(QuicPacketNumber(3u),
7001 LargestAcked(writer_->ack_frames().front()));
7002 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007003 EXPECT_EQ(1u, writer_->stream_frames().size());
7004 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
7005}
7006
7007TEST_P(QuicConnectionTest, NoAckSentForClose) {
7008 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7009 ProcessPacket(1);
fkastenholz5d880a92019-06-21 09:01:56 -07007010 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
7011 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007012 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
7013 ProcessClosePacket(2);
fkastenholz5d880a92019-06-21 09:01:56 -07007014 EXPECT_EQ(1, connection_close_frame_count_);
7015 EXPECT_EQ(QUIC_PEER_GOING_AWAY,
7016 saved_connection_close_frame_.quic_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007017}
7018
7019TEST_P(QuicConnectionTest, SendWhenDisconnected) {
7020 EXPECT_TRUE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07007021 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7022 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007023 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
7024 ConnectionCloseBehavior::SILENT_CLOSE);
7025 EXPECT_FALSE(connection_.connected());
7026 EXPECT_FALSE(connection_.CanWriteStreamData());
QUICHE team8c1daa22019-03-13 08:33:41 -07007027 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07007028 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007029 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
7030 .Times(0);
QUICHE team6987b4a2019-03-15 16:23:04 -07007031 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05007032 HAS_RETRANSMITTABLE_DATA, false, false);
fkastenholz5d880a92019-06-21 09:01:56 -07007033 EXPECT_EQ(1, connection_close_frame_count_);
7034 EXPECT_EQ(QUIC_PEER_GOING_AWAY,
7035 saved_connection_close_frame_.quic_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007036}
7037
7038TEST_P(QuicConnectionTest, SendConnectivityProbingWhenDisconnected) {
7039 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
fayangc31c9952019-06-05 13:54:48 -07007040 if (!IsDefaultTestConfiguration()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007041 return;
7042 }
7043
7044 EXPECT_TRUE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07007045 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7046 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007047 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
7048 ConnectionCloseBehavior::SILENT_CLOSE);
7049 EXPECT_FALSE(connection_.connected());
7050 EXPECT_FALSE(connection_.CanWriteStreamData());
7051
7052 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
7053 .Times(0);
7054
7055 EXPECT_QUIC_BUG(connection_.SendConnectivityProbingPacket(
7056 writer_.get(), connection_.peer_address()),
7057 "Not sending connectivity probing packet as connection is "
7058 "disconnected.");
fkastenholz5d880a92019-06-21 09:01:56 -07007059 EXPECT_EQ(1, connection_close_frame_count_);
7060 EXPECT_EQ(QUIC_PEER_GOING_AWAY,
7061 saved_connection_close_frame_.quic_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007062}
7063
7064TEST_P(QuicConnectionTest, WriteBlockedAfterClientSendsConnectivityProbe) {
7065 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
7066 TestPacketWriter probing_writer(version(), &clock_);
7067 // Block next write so that sending connectivity probe will encounter a
7068 // blocked write when send a connectivity probe to the peer.
7069 probing_writer.BlockOnNextWrite();
7070 // Connection will not be marked as write blocked as connectivity probe only
7071 // affects the probing_writer which is not the default.
7072 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
7073
7074 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
7075 .Times(1);
7076 connection_.SendConnectivityProbingPacket(&probing_writer,
7077 connection_.peer_address());
7078}
7079
7080TEST_P(QuicConnectionTest, WriterBlockedAfterServerSendsConnectivityProbe) {
7081 set_perspective(Perspective::IS_SERVER);
7082 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
7083
7084 // Block next write so that sending connectivity probe will encounter a
7085 // blocked write when send a connectivity probe to the peer.
7086 writer_->BlockOnNextWrite();
7087 // Connection will be marked as write blocked as server uses the default
7088 // writer to send connectivity probes.
7089 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
7090
7091 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
7092 .Times(1);
7093 connection_.SendConnectivityProbingPacket(writer_.get(),
7094 connection_.peer_address());
7095}
7096
7097TEST_P(QuicConnectionTest, WriterErrorWhenClientSendsConnectivityProbe) {
7098 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
7099 TestPacketWriter probing_writer(version(), &clock_);
7100 probing_writer.SetShouldWriteFail();
7101
7102 // Connection should not be closed if a connectivity probe is failed to be
7103 // sent.
fkastenholz5d880a92019-06-21 09:01:56 -07007104 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007105
7106 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
7107 .Times(0);
7108 connection_.SendConnectivityProbingPacket(&probing_writer,
7109 connection_.peer_address());
7110}
7111
7112TEST_P(QuicConnectionTest, WriterErrorWhenServerSendsConnectivityProbe) {
7113 set_perspective(Perspective::IS_SERVER);
7114 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
7115
7116 writer_->SetShouldWriteFail();
7117 // Connection should not be closed if a connectivity probe is failed to be
7118 // sent.
fkastenholz5d880a92019-06-21 09:01:56 -07007119 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007120
7121 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
7122 .Times(0);
7123 connection_.SendConnectivityProbingPacket(writer_.get(),
7124 connection_.peer_address());
7125}
7126
7127TEST_P(QuicConnectionTest, PublicReset) {
fayangc31c9952019-06-05 13:54:48 -07007128 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007129 return;
7130 }
7131 QuicPublicResetPacket header;
7132 // Public reset packet in only built by server.
7133 header.connection_id = connection_id_;
7134 std::unique_ptr<QuicEncryptedPacket> packet(
7135 framer_.BuildPublicResetPacket(header));
7136 std::unique_ptr<QuicReceivedPacket> received(
7137 ConstructReceivedPacket(*packet, QuicTime::Zero()));
fkastenholz5d880a92019-06-21 09:01:56 -07007138 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
7139 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007140 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
fkastenholz5d880a92019-06-21 09:01:56 -07007141 EXPECT_EQ(1, connection_close_frame_count_);
7142 EXPECT_EQ(QUIC_PUBLIC_RESET, saved_connection_close_frame_.quic_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007143}
7144
7145TEST_P(QuicConnectionTest, IetfStatelessReset) {
fayangc31c9952019-06-05 13:54:48 -07007146 if (!VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007147 return;
7148 }
7149 const QuicUint128 kTestStatelessResetToken = 1010101;
7150 QuicConfig config;
7151 QuicConfigPeer::SetReceivedStatelessResetToken(&config,
7152 kTestStatelessResetToken);
7153 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7154 connection_.SetFromConfig(config);
7155 std::unique_ptr<QuicEncryptedPacket> packet(
7156 QuicFramer::BuildIetfStatelessResetPacket(connection_id_,
7157 kTestStatelessResetToken));
7158 std::unique_ptr<QuicReceivedPacket> received(
7159 ConstructReceivedPacket(*packet, QuicTime::Zero()));
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 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
fkastenholz5d880a92019-06-21 09:01:56 -07007163 EXPECT_EQ(1, connection_close_frame_count_);
7164 EXPECT_EQ(QUIC_PUBLIC_RESET, saved_connection_close_frame_.quic_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007165}
7166
7167TEST_P(QuicConnectionTest, GoAway) {
fkastenholz305e1732019-06-18 05:01:22 -07007168 if (VersionHasIetfQuicFrames(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007169 // GoAway is not available in version 99.
7170 return;
7171 }
7172
7173 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7174
7175 QuicGoAwayFrame goaway;
7176 goaway.last_good_stream_id = 1;
7177 goaway.error_code = QUIC_PEER_GOING_AWAY;
7178 goaway.reason_phrase = "Going away.";
7179 EXPECT_CALL(visitor_, OnGoAway(_));
7180 ProcessGoAwayPacket(&goaway);
7181}
7182
7183TEST_P(QuicConnectionTest, WindowUpdate) {
7184 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7185
7186 QuicWindowUpdateFrame window_update;
7187 window_update.stream_id = 3;
7188 window_update.byte_offset = 1234;
7189 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
7190 ProcessFramePacket(QuicFrame(&window_update));
7191}
7192
7193TEST_P(QuicConnectionTest, Blocked) {
7194 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7195
7196 QuicBlockedFrame blocked;
7197 blocked.stream_id = 3;
7198 EXPECT_CALL(visitor_, OnBlockedFrame(_));
7199 ProcessFramePacket(QuicFrame(&blocked));
7200 EXPECT_EQ(1u, connection_.GetStats().blocked_frames_received);
7201 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7202}
7203
7204TEST_P(QuicConnectionTest, ZeroBytePacket) {
7205 // Don't close the connection for zero byte packets.
fkastenholz5d880a92019-06-21 09:01:56 -07007206 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007207 QuicReceivedPacket encrypted(nullptr, 0, QuicTime::Zero());
7208 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, encrypted);
7209}
7210
7211TEST_P(QuicConnectionTest, MissingPacketsBeforeLeastUnacked) {
fayangd4291e42019-05-30 10:31:21 -07007212 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007213 return;
7214 }
7215 // Set the packet number of the ack packet to be least unacked (4).
7216 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 3);
7217 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7218 ProcessStopWaitingPacket(InitStopWaitingFrame(4));
fayangc31c9952019-06-05 13:54:48 -07007219 EXPECT_FALSE(connection_.ack_frame().packets.Empty());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007220}
7221
QUICHE teama6ef0a62019-03-07 20:34:33 -05007222TEST_P(QuicConnectionTest, ClientHandlesVersionNegotiation) {
dschinazi48ac9192019-07-31 00:07:26 -07007223 // All supported versions except the one the connection supports.
7224 ParsedQuicVersionVector versions;
7225 for (auto version : AllSupportedVersions()) {
7226 if (version != connection_.version()) {
7227 versions.push_back(version);
7228 }
7229 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007230
7231 // Send a version negotiation packet.
7232 std::unique_ptr<QuicEncryptedPacket> encrypted(
dschinazib417d602019-05-29 13:08:45 -07007233 QuicFramer::BuildVersionNegotiationPacket(
7234 connection_id_, EmptyQuicConnectionId(),
fayangd4291e42019-05-30 10:31:21 -07007235 VersionHasIetfInvariantHeader(connection_.transport_version()),
dschinazi48ac9192019-07-31 00:07:26 -07007236 connection_.version().HasLengthPrefixedConnectionIds(), versions));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007237 std::unique_ptr<QuicReceivedPacket> received(
7238 ConstructReceivedPacket(*encrypted, QuicTime::Zero()));
fkastenholz5d880a92019-06-21 09:01:56 -07007239 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7240 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
fayang95cef072019-10-10 12:44:14 -07007241 // Verify no connection close packet gets sent.
7242 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007243 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
fayang9ed391a2019-06-20 11:16:59 -07007244 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07007245 EXPECT_EQ(1, connection_close_frame_count_);
7246 EXPECT_EQ(QUIC_INVALID_VERSION,
7247 saved_connection_close_frame_.quic_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007248}
7249
7250TEST_P(QuicConnectionTest, BadVersionNegotiation) {
7251 // Send a version negotiation packet with the version the client started with.
7252 // It should be rejected.
fkastenholz5d880a92019-06-21 09:01:56 -07007253 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7254 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007255 std::unique_ptr<QuicEncryptedPacket> encrypted(
dschinazib417d602019-05-29 13:08:45 -07007256 QuicFramer::BuildVersionNegotiationPacket(
7257 connection_id_, EmptyQuicConnectionId(),
fayangd4291e42019-05-30 10:31:21 -07007258 VersionHasIetfInvariantHeader(connection_.transport_version()),
dschinazi48ac9192019-07-31 00:07:26 -07007259 connection_.version().HasLengthPrefixedConnectionIds(),
QUICHE teama6ef0a62019-03-07 20:34:33 -05007260 AllSupportedVersions()));
7261 std::unique_ptr<QuicReceivedPacket> received(
7262 ConstructReceivedPacket(*encrypted, QuicTime::Zero()));
7263 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
fkastenholz5d880a92019-06-21 09:01:56 -07007264 EXPECT_EQ(1, connection_close_frame_count_);
7265 EXPECT_EQ(QUIC_INVALID_VERSION_NEGOTIATION_PACKET,
7266 saved_connection_close_frame_.quic_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007267}
7268
7269TEST_P(QuicConnectionTest, CheckSendStats) {
fayang5f135052019-08-22 17:59:40 -07007270 if (connection_.PtoEnabled()) {
7271 return;
7272 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007273 connection_.SetMaxTailLossProbes(0);
7274
7275 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7276 connection_.SendStreamDataWithString(3, "first", 0, NO_FIN);
7277 size_t first_packet_size = writer_->last_packet_size();
7278
7279 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7280 connection_.SendStreamDataWithString(5, "second", 0, NO_FIN);
7281 size_t second_packet_size = writer_->last_packet_size();
7282
7283 // 2 retransmissions due to rto, 1 due to explicit nack.
7284 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
7285 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
7286
7287 // Retransmit due to RTO.
7288 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
7289 connection_.GetRetransmissionAlarm()->Fire();
7290
7291 // Retransmit due to explicit nacks.
7292 QuicAckFrame nack_three =
7293 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)},
7294 {QuicPacketNumber(4), QuicPacketNumber(5)}});
7295
7296 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07007297 lost_packets.push_back(
7298 LostPacket(QuicPacketNumber(1), kMaxOutgoingPacketSize));
7299 lost_packets.push_back(
7300 LostPacket(QuicPacketNumber(3), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007301 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
7302 .WillOnce(SetArgPointee<5>(lost_packets));
7303 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7304 if (!connection_.session_decides_what_to_write()) {
7305 EXPECT_CALL(visitor_, OnCanWrite());
7306 }
7307 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7308 ProcessAckPacket(&nack_three);
7309
7310 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
7311 .WillOnce(Return(QuicBandwidth::Zero()));
7312
7313 const QuicConnectionStats& stats = connection_.GetStats();
7314 // For IETF QUIC, version is not included as the encryption level switches to
7315 // FORWARD_SECURE in SendStreamDataWithString.
7316 size_t save_on_version =
fayangd4291e42019-05-30 10:31:21 -07007317 VersionHasIetfInvariantHeader(GetParam().version.transport_version)
7318 ? 0
7319 : kQuicVersionSize;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007320 EXPECT_EQ(3 * first_packet_size + 2 * second_packet_size - save_on_version,
7321 stats.bytes_sent);
7322 EXPECT_EQ(5u, stats.packets_sent);
7323 EXPECT_EQ(2 * first_packet_size + second_packet_size - save_on_version,
7324 stats.bytes_retransmitted);
7325 EXPECT_EQ(3u, stats.packets_retransmitted);
7326 EXPECT_EQ(1u, stats.rto_count);
7327 EXPECT_EQ(kDefaultMaxPacketSize, stats.max_packet_size);
7328}
7329
7330TEST_P(QuicConnectionTest, ProcessFramesIfPacketClosedConnection) {
7331 // Construct a packet with stream frame and connection close frame.
7332 QuicPacketHeader header;
dschinazi5e1a7b22019-07-31 12:23:21 -07007333 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
QUICHE team2252b702019-05-14 23:55:14 -04007334 header.source_connection_id = connection_id_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007335 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
fayangd4291e42019-05-30 10:31:21 -07007336 if (!VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04007337 header.source_connection_id_included = CONNECTION_ID_PRESENT;
7338 }
7339 } else {
7340 header.destination_connection_id = connection_id_;
fayangd4291e42019-05-30 10:31:21 -07007341 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04007342 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
7343 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007344 }
7345 header.packet_number = QuicPacketNumber(1);
7346 header.version_flag = false;
7347
fkastenholz488a4622019-08-26 06:24:46 -07007348 QuicErrorCode kQuicErrorCode = QUIC_PEER_GOING_AWAY;
7349 // This QuicConnectionCloseFrame will default to being for a Google QUIC
7350 // close. If doing IETF QUIC then set fields appropriately for CC/T or CC/A,
7351 // depending on the mapping.
fkastenholz591814c2019-09-06 12:11:46 -07007352 QuicConnectionCloseFrame qccf(peer_framer_.transport_version(),
7353 kQuicErrorCode, "",
7354 /*transport_close_frame_type=*/0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007355 QuicFrames frames;
7356 frames.push_back(QuicFrame(frame1_));
7357 frames.push_back(QuicFrame(&qccf));
7358 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
7359 EXPECT_TRUE(nullptr != packet);
dschinazi66dea072019-04-09 11:41:06 -07007360 char buffer[kMaxOutgoingPacketSize];
nharperc6b99512019-09-19 11:13:48 -07007361 size_t encrypted_length = peer_framer_.EncryptPayload(
7362 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
7363 kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007364
fkastenholz5d880a92019-06-21 09:01:56 -07007365 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
7366 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007367 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7368 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7369
7370 connection_.ProcessUdpPacket(
7371 kSelfAddress, kPeerAddress,
7372 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
fkastenholz5d880a92019-06-21 09:01:56 -07007373 EXPECT_EQ(1, connection_close_frame_count_);
7374 EXPECT_EQ(QUIC_PEER_GOING_AWAY,
fkastenholz488a4622019-08-26 06:24:46 -07007375 saved_connection_close_frame_.extracted_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007376}
7377
7378TEST_P(QuicConnectionTest, SelectMutualVersion) {
7379 connection_.SetSupportedVersions(AllSupportedVersions());
7380 // Set the connection to speak the lowest quic version.
7381 connection_.set_version(QuicVersionMin());
7382 EXPECT_EQ(QuicVersionMin(), connection_.version());
7383
7384 // Pass in available versions which includes a higher mutually supported
7385 // version. The higher mutually supported version should be selected.
7386 ParsedQuicVersionVector supported_versions = AllSupportedVersions();
7387 EXPECT_TRUE(connection_.SelectMutualVersion(supported_versions));
7388 EXPECT_EQ(QuicVersionMax(), connection_.version());
7389
7390 // Expect that the lowest version is selected.
7391 // Ensure the lowest supported version is less than the max, unless they're
7392 // the same.
7393 ParsedQuicVersionVector lowest_version_vector;
7394 lowest_version_vector.push_back(QuicVersionMin());
7395 EXPECT_TRUE(connection_.SelectMutualVersion(lowest_version_vector));
7396 EXPECT_EQ(QuicVersionMin(), connection_.version());
7397
7398 // Shouldn't be able to find a mutually supported version.
7399 ParsedQuicVersionVector unsupported_version;
7400 unsupported_version.push_back(UnsupportedQuicVersion());
7401 EXPECT_FALSE(connection_.SelectMutualVersion(unsupported_version));
7402}
7403
7404TEST_P(QuicConnectionTest, ConnectionCloseWhenWritable) {
7405 EXPECT_FALSE(writer_->IsWriteBlocked());
7406
7407 // Send a packet.
7408 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7409 EXPECT_EQ(0u, connection_.NumQueuedPackets());
7410 EXPECT_EQ(1u, writer_->packets_write_attempts());
7411
7412 TriggerConnectionClose();
rch39c88ab2019-10-16 19:24:40 -07007413 EXPECT_LE(2u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007414}
7415
7416TEST_P(QuicConnectionTest, ConnectionCloseGettingWriteBlocked) {
7417 BlockOnNextWrite();
7418 TriggerConnectionClose();
7419 EXPECT_EQ(1u, writer_->packets_write_attempts());
7420 EXPECT_TRUE(writer_->IsWriteBlocked());
7421}
7422
7423TEST_P(QuicConnectionTest, ConnectionCloseWhenWriteBlocked) {
7424 BlockOnNextWrite();
7425 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7426 EXPECT_EQ(1u, connection_.NumQueuedPackets());
7427 EXPECT_EQ(1u, writer_->packets_write_attempts());
7428 EXPECT_TRUE(writer_->IsWriteBlocked());
7429 TriggerConnectionClose();
7430 EXPECT_EQ(1u, writer_->packets_write_attempts());
7431}
7432
7433TEST_P(QuicConnectionTest, OnPacketSentDebugVisitor) {
7434 MockQuicConnectionDebugVisitor debug_visitor;
7435 connection_.set_debug_visitor(&debug_visitor);
7436
7437 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _)).Times(1);
7438 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7439
7440 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _)).Times(1);
7441 connection_.SendConnectivityProbingPacket(writer_.get(),
7442 connection_.peer_address());
7443}
7444
7445TEST_P(QuicConnectionTest, OnPacketHeaderDebugVisitor) {
7446 QuicPacketHeader header;
7447 header.packet_number = QuicPacketNumber(1);
fayangd4291e42019-05-30 10:31:21 -07007448 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007449 header.form = IETF_QUIC_LONG_HEADER_PACKET;
7450 }
7451
7452 MockQuicConnectionDebugVisitor debug_visitor;
7453 connection_.set_debug_visitor(&debug_visitor);
7454 EXPECT_CALL(debug_visitor, OnPacketHeader(Ref(header))).Times(1);
7455 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(1);
7456 EXPECT_CALL(debug_visitor, OnSuccessfulVersionNegotiation(_)).Times(1);
7457 connection_.OnPacketHeader(header);
7458}
7459
7460TEST_P(QuicConnectionTest, Pacing) {
7461 TestConnection server(connection_id_, kSelfAddress, helper_.get(),
7462 alarm_factory_.get(), writer_.get(),
7463 Perspective::IS_SERVER, version());
7464 TestConnection client(connection_id_, kPeerAddress, helper_.get(),
7465 alarm_factory_.get(), writer_.get(),
7466 Perspective::IS_CLIENT, version());
7467 EXPECT_FALSE(QuicSentPacketManagerPeer::UsingPacing(
7468 static_cast<const QuicSentPacketManager*>(
7469 &client.sent_packet_manager())));
7470 EXPECT_FALSE(QuicSentPacketManagerPeer::UsingPacing(
7471 static_cast<const QuicSentPacketManager*>(
7472 &server.sent_packet_manager())));
7473}
7474
7475TEST_P(QuicConnectionTest, WindowUpdateInstigateAcks) {
7476 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7477
7478 // Send a WINDOW_UPDATE frame.
7479 QuicWindowUpdateFrame window_update;
7480 window_update.stream_id = 3;
7481 window_update.byte_offset = 1234;
7482 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
7483 ProcessFramePacket(QuicFrame(&window_update));
7484
7485 // Ensure that this has caused the ACK alarm to be set.
7486 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
7487 EXPECT_TRUE(ack_alarm->IsSet());
7488}
7489
7490TEST_P(QuicConnectionTest, BlockedFrameInstigateAcks) {
7491 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7492
7493 // Send a BLOCKED frame.
7494 QuicBlockedFrame blocked;
7495 blocked.stream_id = 3;
7496 EXPECT_CALL(visitor_, OnBlockedFrame(_));
7497 ProcessFramePacket(QuicFrame(&blocked));
7498
7499 // Ensure that this has caused the ACK alarm to be set.
7500 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
7501 EXPECT_TRUE(ack_alarm->IsSet());
7502}
7503
7504TEST_P(QuicConnectionTest, ReevaluateTimeUntilSendOnAck) {
7505 // Enable pacing.
7506 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7507 QuicConfig config;
7508 connection_.SetFromConfig(config);
7509
7510 // Send two packets. One packet is not sufficient because if it gets acked,
7511 // there will be no packets in flight after that and the pacer will always
7512 // allow the next packet in that situation.
7513 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7514 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
7515 connection_.SendStreamDataWithString(
7516 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
7517 0, NO_FIN);
7518 connection_.SendStreamDataWithString(
7519 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "bar",
7520 3, NO_FIN);
7521 connection_.OnCanWrite();
7522
7523 // Schedule the next packet for a few milliseconds in future.
7524 QuicSentPacketManagerPeer::DisablePacerBursts(manager_);
7525 QuicTime scheduled_pacing_time =
7526 clock_.Now() + QuicTime::Delta::FromMilliseconds(5);
7527 QuicSentPacketManagerPeer::SetNextPacedPacketTime(manager_,
7528 scheduled_pacing_time);
7529
7530 // Send a packet and have it be blocked by congestion control.
7531 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(false));
7532 connection_.SendStreamDataWithString(
7533 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "baz",
7534 6, NO_FIN);
7535 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
7536
7537 // Process an ack and the send alarm will be set to the new 5ms delay.
7538 QuicAckFrame ack = InitAckFrame(1);
7539 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
7540 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7541 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
7542 ProcessAckPacket(&ack);
nharper55fa6132019-05-07 19:37:21 -07007543 size_t padding_frame_count = writer_->padding_frames().size();
7544 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007545 EXPECT_EQ(1u, writer_->stream_frames().size());
7546 EXPECT_TRUE(connection_.GetSendAlarm()->IsSet());
7547 EXPECT_EQ(scheduled_pacing_time, connection_.GetSendAlarm()->deadline());
7548 writer_->Reset();
7549}
7550
7551TEST_P(QuicConnectionTest, SendAcksImmediately) {
QUICHE teamcd098022019-03-22 18:49:55 -07007552 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7553 return;
7554 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007555 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7556 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7557 ProcessDataPacket(1);
7558 CongestionBlockWrites();
7559 SendAckPacketToPeer();
7560}
7561
7562TEST_P(QuicConnectionTest, SendPingImmediately) {
7563 MockQuicConnectionDebugVisitor debug_visitor;
7564 connection_.set_debug_visitor(&debug_visitor);
7565
7566 CongestionBlockWrites();
fayang93cc53a2019-08-22 12:47:30 -07007567 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007568 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7569 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _)).Times(1);
7570 EXPECT_CALL(debug_visitor, OnPingSent()).Times(1);
7571 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
7572 EXPECT_FALSE(connection_.HasQueuedData());
7573}
7574
7575TEST_P(QuicConnectionTest, SendBlockedImmediately) {
7576 MockQuicConnectionDebugVisitor debug_visitor;
7577 connection_.set_debug_visitor(&debug_visitor);
7578
fayang93cc53a2019-08-22 12:47:30 -07007579 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007580 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7581 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _)).Times(1);
7582 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7583 connection_.SendControlFrame(QuicFrame(new QuicBlockedFrame(1, 3)));
7584 EXPECT_EQ(1u, connection_.GetStats().blocked_frames_sent);
7585 EXPECT_FALSE(connection_.HasQueuedData());
7586}
7587
fayang93cc53a2019-08-22 12:47:30 -07007588TEST_P(QuicConnectionTest, FailedToSendBlockedFrames) {
7589 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
7590 return;
7591 }
7592 MockQuicConnectionDebugVisitor debug_visitor;
7593 connection_.set_debug_visitor(&debug_visitor);
7594 QuicBlockedFrame blocked(1, 3);
7595
7596 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
7597 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _)).Times(0);
7598 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7599 connection_.SendControlFrame(QuicFrame(&blocked));
7600 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7601 EXPECT_FALSE(connection_.HasQueuedData());
7602}
7603
QUICHE teama6ef0a62019-03-07 20:34:33 -05007604TEST_P(QuicConnectionTest, SendingUnencryptedStreamDataFails) {
7605 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
7606 if (!IsDefaultTestConfiguration()) {
7607 return;
7608 }
7609
fkastenholz5d880a92019-06-21 09:01:56 -07007610 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7611 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007612 struct iovec iov;
7613 MakeIOVector("", &iov);
7614 EXPECT_QUIC_BUG(connection_.SaveAndSendStreamData(3, &iov, 1, 0, 0, FIN),
fayang49523232019-05-03 06:28:22 -07007615 "Cannot send stream data with level: ENCRYPTION_INITIAL");
QUICHE teama6ef0a62019-03-07 20:34:33 -05007616 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07007617 EXPECT_EQ(1, connection_close_frame_count_);
7618 EXPECT_EQ(QUIC_ATTEMPT_TO_SEND_UNENCRYPTED_STREAM_DATA,
7619 saved_connection_close_frame_.quic_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007620}
7621
7622TEST_P(QuicConnectionTest, SetRetransmissionAlarmForCryptoPacket) {
7623 EXPECT_TRUE(connection_.connected());
7624 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
7625
7626 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7627 connection_.SendCryptoStreamData();
7628
7629 // Verify retransmission timer is correctly set after crypto packet has been
7630 // sent.
7631 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
7632 QuicTime retransmission_time =
7633 QuicConnectionPeer::GetSentPacketManager(&connection_)
7634 ->GetRetransmissionTime();
7635 EXPECT_NE(retransmission_time, clock_.ApproximateNow());
7636 EXPECT_EQ(retransmission_time,
7637 connection_.GetRetransmissionAlarm()->deadline());
7638
7639 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7640 connection_.GetRetransmissionAlarm()->Fire();
7641}
7642
7643TEST_P(QuicConnectionTest, PathDegradingAlarmForCryptoPacket) {
7644 EXPECT_TRUE(connection_.connected());
7645 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7646 EXPECT_FALSE(connection_.IsPathDegrading());
7647
7648 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7649 connection_.SendCryptoStreamData();
7650
7651 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7652 EXPECT_FALSE(connection_.IsPathDegrading());
7653 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7654 ->GetPathDegradingDelay();
zhongyieef848f2019-10-18 07:09:37 -07007655 EXPECT_EQ(delay, connection_.GetPathDegradingAlarm()->deadline() -
7656 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007657
7658 // Fire the path degrading alarm, path degrading signal should be sent to
7659 // the visitor.
7660 EXPECT_CALL(visitor_, OnPathDegrading());
7661 clock_.AdvanceTime(delay);
7662 connection_.GetPathDegradingAlarm()->Fire();
7663 EXPECT_TRUE(connection_.IsPathDegrading());
7664 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7665}
7666
vasilvv693d5b02019-04-09 21:58:56 -07007667// Includes regression test for b/69979024.
QUICHE teama6ef0a62019-03-07 20:34:33 -05007668TEST_P(QuicConnectionTest, PathDegradingAlarmForNonCryptoPackets) {
7669 EXPECT_TRUE(connection_.connected());
7670 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7671 EXPECT_FALSE(connection_.IsPathDegrading());
7672
7673 const char data[] = "data";
7674 size_t data_size = strlen(data);
7675 QuicStreamOffset offset = 0;
7676
7677 for (int i = 0; i < 2; ++i) {
7678 // Send a packet. Now there's a retransmittable packet on the wire, so the
7679 // path degrading alarm should be set.
7680 connection_.SendStreamDataWithString(
7681 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
7682 offset, NO_FIN);
7683 offset += data_size;
7684 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7685 // Check the deadline of the path degrading alarm.
7686 QuicTime::Delta delay =
7687 QuicConnectionPeer::GetSentPacketManager(&connection_)
7688 ->GetPathDegradingDelay();
zhongyieef848f2019-10-18 07:09:37 -07007689 EXPECT_EQ(delay, connection_.GetPathDegradingAlarm()->deadline() -
7690 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007691
7692 // Send a second packet. The path degrading alarm's deadline should remain
7693 // the same.
vasilvv693d5b02019-04-09 21:58:56 -07007694 // Regression test for b/69979024.
QUICHE teama6ef0a62019-03-07 20:34:33 -05007695 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7696 QuicTime prev_deadline = connection_.GetPathDegradingAlarm()->deadline();
7697 connection_.SendStreamDataWithString(
7698 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
7699 offset, NO_FIN);
7700 offset += data_size;
7701 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7702 EXPECT_EQ(prev_deadline, connection_.GetPathDegradingAlarm()->deadline());
7703
7704 // Now receive an ACK of the first packet. This should advance the path
7705 // degrading alarm's deadline since forward progress has been made.
7706 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7707 if (i == 0) {
7708 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7709 }
7710 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7711 QuicAckFrame frame = InitAckFrame(
7712 {{QuicPacketNumber(1u + 2u * i), QuicPacketNumber(2u + 2u * i)}});
7713 ProcessAckPacket(&frame);
7714 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7715 // Check the deadline of the path degrading alarm.
7716 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7717 ->GetPathDegradingDelay();
zhongyieef848f2019-10-18 07:09:37 -07007718 EXPECT_EQ(delay, connection_.GetPathDegradingAlarm()->deadline() -
7719 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007720
7721 if (i == 0) {
7722 // Now receive an ACK of the second packet. Since there are no more
7723 // retransmittable packets on the wire, this should cancel the path
7724 // degrading alarm.
7725 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7726 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7727 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
7728 ProcessAckPacket(&frame);
7729 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7730 } else {
7731 // Advance time to the path degrading alarm's deadline and simulate
7732 // firing the alarm.
7733 clock_.AdvanceTime(delay);
7734 EXPECT_CALL(visitor_, OnPathDegrading());
7735 connection_.GetPathDegradingAlarm()->Fire();
7736 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7737 }
7738 }
7739 EXPECT_TRUE(connection_.IsPathDegrading());
7740}
7741
7742TEST_P(QuicConnectionTest, RetransmittableOnWireSetsPingAlarm) {
7743 const QuicTime::Delta retransmittable_on_wire_timeout =
7744 QuicTime::Delta::FromMilliseconds(50);
zhongyi79ace162019-10-21 15:57:09 -07007745 connection_.set_initial_retransmittable_on_wire_timeout(
QUICHE teama6ef0a62019-03-07 20:34:33 -05007746 retransmittable_on_wire_timeout);
7747
7748 EXPECT_TRUE(connection_.connected());
7749 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7750 .WillRepeatedly(Return(true));
7751
7752 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7753 EXPECT_FALSE(connection_.IsPathDegrading());
7754 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
7755
7756 const char data[] = "data";
7757 size_t data_size = strlen(data);
7758 QuicStreamOffset offset = 0;
7759
7760 // Send a packet.
7761 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7762 offset += data_size;
7763 // Now there's a retransmittable packet on the wire, so the path degrading
7764 // alarm should be set.
7765 // The retransmittable-on-wire alarm should not be set.
7766 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7767 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7768 ->GetPathDegradingDelay();
zhongyieef848f2019-10-18 07:09:37 -07007769 EXPECT_EQ(delay, connection_.GetPathDegradingAlarm()->deadline() -
7770 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007771 ASSERT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
7772 // The ping alarm is set for the ping timeout, not the shorter
7773 // retransmittable_on_wire_timeout.
7774 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7775 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
zhongyieef848f2019-10-18 07:09:37 -07007776 EXPECT_EQ(ping_delay,
7777 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007778
7779 // Now receive an ACK of the packet.
7780 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7781 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7782 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7783 QuicAckFrame frame =
7784 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7785 ProcessAckPacket(&frame);
7786 // No more retransmittable packets on the wire, so the path degrading alarm
7787 // should be cancelled, and the ping alarm should be set to the
7788 // retransmittable_on_wire_timeout.
7789 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7790 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07007791 EXPECT_EQ(retransmittable_on_wire_timeout,
7792 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007793
7794 // Simulate firing the ping alarm and sending a PING.
7795 clock_.AdvanceTime(retransmittable_on_wire_timeout);
7796 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
7797 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
7798 }));
7799 connection_.GetPingAlarm()->Fire();
7800
7801 // Now there's a retransmittable packet (PING) on the wire, so the path
7802 // degrading alarm should be set.
7803 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7804 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7805 ->GetPathDegradingDelay();
zhongyieef848f2019-10-18 07:09:37 -07007806 EXPECT_EQ(delay, connection_.GetPathDegradingAlarm()->deadline() -
7807 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007808}
7809
7810// This test verifies that the connection marks path as degrading and does not
7811// spin timer to detect path degrading when a new packet is sent on the
7812// degraded path.
7813TEST_P(QuicConnectionTest, NoPathDegradingAlarmIfPathIsDegrading) {
7814 EXPECT_TRUE(connection_.connected());
7815 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7816 EXPECT_FALSE(connection_.IsPathDegrading());
7817
7818 const char data[] = "data";
7819 size_t data_size = strlen(data);
7820 QuicStreamOffset offset = 0;
7821
7822 // Send the first packet. Now there's a retransmittable packet on the wire, so
7823 // the path degrading alarm should be set.
7824 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7825 offset += data_size;
7826 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7827 // Check the deadline of the path degrading alarm.
7828 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7829 ->GetPathDegradingDelay();
zhongyieef848f2019-10-18 07:09:37 -07007830 EXPECT_EQ(delay, connection_.GetPathDegradingAlarm()->deadline() -
7831 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007832
7833 // Send a second packet. The path degrading alarm's deadline should remain
7834 // the same.
7835 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7836 QuicTime prev_deadline = connection_.GetPathDegradingAlarm()->deadline();
7837 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7838 offset += data_size;
7839 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7840 EXPECT_EQ(prev_deadline, connection_.GetPathDegradingAlarm()->deadline());
7841
7842 // Now receive an ACK of the first packet. This should advance the path
7843 // degrading alarm's deadline since forward progress has been made.
7844 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7845 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7846 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7847 QuicAckFrame frame =
7848 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
7849 ProcessAckPacket(&frame);
7850 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7851 // Check the deadline of the path degrading alarm.
7852 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7853 ->GetPathDegradingDelay();
zhongyieef848f2019-10-18 07:09:37 -07007854 EXPECT_EQ(delay, connection_.GetPathDegradingAlarm()->deadline() -
7855 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007856
7857 // Advance time to the path degrading alarm's deadline and simulate
7858 // firing the path degrading alarm. This path will be considered as
7859 // degrading.
7860 clock_.AdvanceTime(delay);
7861 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
7862 connection_.GetPathDegradingAlarm()->Fire();
7863 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7864 EXPECT_TRUE(connection_.IsPathDegrading());
7865
7866 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7867 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7868 // Send a third packet. The path degrading alarm is no longer set but path
7869 // should still be marked as degrading.
7870 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7871 offset += data_size;
7872 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7873 EXPECT_TRUE(connection_.IsPathDegrading());
7874}
7875
7876// This test verifies that the connection unmarks path as degrarding and spins
7877// the timer to detect future path degrading when forward progress is made
7878// after path has been marked degrading.
7879TEST_P(QuicConnectionTest, UnmarkPathDegradingOnForwardProgress) {
7880 EXPECT_TRUE(connection_.connected());
7881 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7882 EXPECT_FALSE(connection_.IsPathDegrading());
7883
7884 const char data[] = "data";
7885 size_t data_size = strlen(data);
7886 QuicStreamOffset offset = 0;
7887
7888 // Send the first packet. Now there's a retransmittable packet on the wire, so
7889 // the path degrading alarm should be set.
7890 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7891 offset += data_size;
7892 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7893 // Check the deadline of the path degrading alarm.
7894 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7895 ->GetPathDegradingDelay();
zhongyieef848f2019-10-18 07:09:37 -07007896 EXPECT_EQ(delay, connection_.GetPathDegradingAlarm()->deadline() -
7897 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007898
7899 // Send a second packet. The path degrading alarm's deadline should remain
7900 // the same.
7901 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7902 QuicTime prev_deadline = connection_.GetPathDegradingAlarm()->deadline();
7903 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7904 offset += data_size;
7905 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7906 EXPECT_EQ(prev_deadline, connection_.GetPathDegradingAlarm()->deadline());
7907
7908 // Now receive an ACK of the first packet. This should advance the path
7909 // degrading alarm's deadline since forward progress has been made.
7910 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7911 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7912 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7913 QuicAckFrame frame =
7914 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
7915 ProcessAckPacket(&frame);
7916 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7917 // Check the deadline of the path degrading alarm.
7918 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7919 ->GetPathDegradingDelay();
zhongyieef848f2019-10-18 07:09:37 -07007920 EXPECT_EQ(delay, connection_.GetPathDegradingAlarm()->deadline() -
7921 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007922
7923 // Advance time to the path degrading alarm's deadline and simulate
7924 // firing the alarm.
7925 clock_.AdvanceTime(delay);
7926 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
7927 connection_.GetPathDegradingAlarm()->Fire();
7928 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7929 EXPECT_TRUE(connection_.IsPathDegrading());
7930
7931 // Send a third packet. The path degrading alarm is no longer set but path
7932 // should still be marked as degrading.
7933 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7934 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7935 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7936 offset += data_size;
7937 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7938 EXPECT_TRUE(connection_.IsPathDegrading());
7939
7940 // Now receive an ACK of the second packet. This should unmark the path as
7941 // degrading. And will set a timer to detect new path degrading.
7942 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7943 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7944 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
7945 ProcessAckPacket(&frame);
7946 EXPECT_FALSE(connection_.IsPathDegrading());
7947 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7948}
7949
7950TEST_P(QuicConnectionTest, NoPathDegradingOnServer) {
QUICHE teamcd098022019-03-22 18:49:55 -07007951 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7952 return;
7953 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007954 set_perspective(Perspective::IS_SERVER);
7955 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
7956
7957 EXPECT_FALSE(connection_.IsPathDegrading());
7958 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7959
7960 // Send data.
7961 const char data[] = "data";
7962 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
7963 EXPECT_FALSE(connection_.IsPathDegrading());
7964 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7965
7966 // Ack data.
7967 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7968 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7969 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7970 QuicAckFrame frame =
7971 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
7972 ProcessAckPacket(&frame);
7973 EXPECT_FALSE(connection_.IsPathDegrading());
7974 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7975}
7976
7977TEST_P(QuicConnectionTest, NoPathDegradingAfterSendingAck) {
QUICHE teamcd098022019-03-22 18:49:55 -07007978 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7979 return;
7980 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007981 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7982 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7983 ProcessDataPacket(1);
7984 SendAckPacketToPeer();
7985 EXPECT_FALSE(connection_.sent_packet_manager().unacked_packets().empty());
7986 EXPECT_FALSE(connection_.sent_packet_manager().HasInFlightPackets());
7987 EXPECT_FALSE(connection_.IsPathDegrading());
7988 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7989}
7990
7991TEST_P(QuicConnectionTest, MultipleCallsToCloseConnection) {
7992 // Verifies that multiple calls to CloseConnection do not
7993 // result in multiple attempts to close the connection - it will be marked as
7994 // disconnected after the first call.
fkastenholz5d880a92019-06-21 09:01:56 -07007995 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007996 connection_.CloseConnection(QUIC_NO_ERROR, "no reason",
7997 ConnectionCloseBehavior::SILENT_CLOSE);
7998 connection_.CloseConnection(QUIC_NO_ERROR, "no reason",
7999 ConnectionCloseBehavior::SILENT_CLOSE);
8000}
8001
8002TEST_P(QuicConnectionTest, ServerReceivesChloOnNonCryptoStream) {
8003 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8004
8005 set_perspective(Perspective::IS_SERVER);
8006 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
8007
8008 CryptoHandshakeMessage message;
8009 CryptoFramer framer;
8010 message.set_tag(kCHLO);
QUICHE team3fe6a8b2019-03-14 09:10:38 -07008011 std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008012 frame1_.stream_id = 10;
8013 frame1_.data_buffer = data->data();
8014 frame1_.data_length = data->length();
8015
fkastenholz5d880a92019-06-21 09:01:56 -07008016 EXPECT_CALL(visitor_,
8017 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05008018 ForceProcessFramePacket(QuicFrame(frame1_));
fkastenholz5d880a92019-06-21 09:01:56 -07008019 TestConnectionCloseQuicErrorCode(QUIC_MAYBE_CORRUPTED_MEMORY);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008020}
8021
8022TEST_P(QuicConnectionTest, ClientReceivesRejOnNonCryptoStream) {
8023 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8024
8025 CryptoHandshakeMessage message;
8026 CryptoFramer framer;
8027 message.set_tag(kREJ);
QUICHE team3fe6a8b2019-03-14 09:10:38 -07008028 std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008029 frame1_.stream_id = 10;
8030 frame1_.data_buffer = data->data();
8031 frame1_.data_length = data->length();
8032
fkastenholz5d880a92019-06-21 09:01:56 -07008033 EXPECT_CALL(visitor_,
8034 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05008035 ForceProcessFramePacket(QuicFrame(frame1_));
fkastenholz5d880a92019-06-21 09:01:56 -07008036 TestConnectionCloseQuicErrorCode(QUIC_MAYBE_CORRUPTED_MEMORY);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008037}
8038
8039TEST_P(QuicConnectionTest, CloseConnectionOnPacketTooLarge) {
8040 SimulateNextPacketTooLarge();
8041 // A connection close packet is sent
fkastenholz5d880a92019-06-21 09:01:56 -07008042 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
QUICHE teama6ef0a62019-03-07 20:34:33 -05008043 .Times(1);
8044 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
fkastenholz5d880a92019-06-21 09:01:56 -07008045 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008046}
8047
8048TEST_P(QuicConnectionTest, AlwaysGetPacketTooLarge) {
8049 // Test even we always get packet too large, we do not infinitely try to send
8050 // close packet.
8051 AlwaysGetPacketTooLarge();
fkastenholz5d880a92019-06-21 09:01:56 -07008052 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
QUICHE teama6ef0a62019-03-07 20:34:33 -05008053 .Times(1);
8054 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
fkastenholz5d880a92019-06-21 09:01:56 -07008055 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008056}
8057
nharperef468962019-07-02 14:15:38 -07008058TEST_P(QuicConnectionTest, CloseConnectionOnQueuedWriteError) {
nharperef468962019-07-02 14:15:38 -07008059 // Regression test for crbug.com/979507.
8060 //
8061 // If we get a write error when writing queued packets, we should attempt to
8062 // send a connection close packet, but if sending that fails, it shouldn't get
8063 // queued.
8064
8065 // Queue a packet to write.
8066 BlockOnNextWrite();
8067 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
8068 EXPECT_EQ(1u, connection_.NumQueuedPackets());
8069
8070 // Configure writer to always fail.
8071 AlwaysGetPacketTooLarge();
8072
8073 // Expect that we attempt to close the connection exactly once.
8074 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
8075 .Times(1);
8076
8077 // Unblock the writes and actually send.
8078 writer_->SetWritable();
8079 connection_.OnCanWrite();
8080 EXPECT_EQ(0u, connection_.NumQueuedPackets());
8081
8082 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
8083}
8084
QUICHE teama6ef0a62019-03-07 20:34:33 -05008085// Verify that if connection has no outstanding data, it notifies the send
8086// algorithm after the write.
8087TEST_P(QuicConnectionTest, SendDataAndBecomeApplicationLimited) {
8088 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
8089 {
8090 InSequence seq;
8091 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
8092 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
8093 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
8094 .WillRepeatedly(Return(false));
8095 }
8096
8097 connection_.SendStreamData3();
8098}
8099
8100// Verify that the connection does not become app-limited if there is
8101// outstanding data to send after the write.
8102TEST_P(QuicConnectionTest, NotBecomeApplicationLimitedIfMoreDataAvailable) {
8103 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
8104 {
8105 InSequence seq;
8106 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
8107 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
8108 }
8109
8110 connection_.SendStreamData3();
8111}
8112
8113// Verify that the connection does not become app-limited after blocked write
8114// even if there is outstanding data to send after the write.
8115TEST_P(QuicConnectionTest, NotBecomeApplicationLimitedDueToWriteBlock) {
8116 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
8117 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
8118 BlockOnNextWrite();
8119
fayang2ce66082019-10-02 06:29:04 -07008120 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
8121 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8122 } else {
8123 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8124 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008125 connection_.SendStreamData3();
8126
8127 // Now unblock the writer, become congestion control blocked,
8128 // and ensure we become app-limited after writing.
8129 writer_->SetWritable();
8130 CongestionBlockWrites();
8131 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(false));
fayang2ce66082019-10-02 06:29:04 -07008132 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
8133 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8134 } else {
8135 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008136 }
fayang2ce66082019-10-02 06:29:04 -07008137 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008138 connection_.OnCanWrite();
8139}
8140
8141// Test the mode in which the link is filled up with probing retransmissions if
8142// the connection becomes application-limited.
8143TEST_P(QuicConnectionTest, SendDataWhenApplicationLimited) {
8144 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8145 EXPECT_CALL(*send_algorithm_, ShouldSendProbingPacket())
8146 .WillRepeatedly(Return(true));
8147 {
8148 InSequence seq;
8149 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
8150 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
8151 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
8152 .WillRepeatedly(Return(false));
8153 }
QUICHE teamb8343252019-04-29 13:58:01 -07008154 EXPECT_CALL(visitor_, SendProbingData()).WillRepeatedly([this] {
8155 return connection_.sent_packet_manager().MaybeRetransmitOldestPacket(
8156 PROBING_RETRANSMISSION);
8157 });
QUICHE teama6ef0a62019-03-07 20:34:33 -05008158 // Fix congestion window to be 20,000 bytes.
8159 EXPECT_CALL(*send_algorithm_, CanSend(Ge(20000u)))
8160 .WillRepeatedly(Return(false));
8161 EXPECT_CALL(*send_algorithm_, CanSend(Lt(20000u)))
8162 .WillRepeatedly(Return(true));
8163
8164 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
8165 ASSERT_EQ(0u, connection_.GetStats().packets_sent);
8166 connection_.set_fill_up_link_during_probing(true);
8167 connection_.OnHandshakeComplete();
8168 connection_.SendStreamData3();
8169
8170 // We expect a lot of packets from a 20 kbyte window.
8171 EXPECT_GT(connection_.GetStats().packets_sent, 10u);
8172 // Ensure that the packets are padded.
8173 QuicByteCount average_packet_size =
8174 connection_.GetStats().bytes_sent / connection_.GetStats().packets_sent;
8175 EXPECT_GT(average_packet_size, 1000u);
8176
8177 // Acknowledge all packets sent, except for the last one.
8178 QuicAckFrame ack = InitAckFrame(
8179 connection_.sent_packet_manager().GetLargestSentPacket() - 1);
8180 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
8181 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8182
8183 // Ensure that since we no longer have retransmittable bytes in flight, this
8184 // will not cause any responses to be sent.
8185 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8186 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
8187 ProcessAckPacket(&ack);
8188}
8189
8190TEST_P(QuicConnectionTest, DonotForceSendingAckOnPacketTooLarge) {
8191 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8192 // Send an ack by simulating delayed ack alarm firing.
8193 ProcessPacket(1);
8194 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
8195 EXPECT_TRUE(ack_alarm->IsSet());
8196 connection_.GetAckAlarm()->Fire();
8197 // Simulate data packet causes write error.
fkastenholz5d880a92019-06-21 09:01:56 -07008198 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05008199 SimulateNextPacketTooLarge();
8200 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
8201 EXPECT_EQ(1u, writer_->frame_count());
8202 EXPECT_FALSE(writer_->connection_close_frames().empty());
8203 // Ack frame is not bundled in connection close packet.
8204 EXPECT_TRUE(writer_->ack_frames().empty());
fkastenholz5d880a92019-06-21 09:01:56 -07008205 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008206}
8207
QUICHE teama6ef0a62019-03-07 20:34:33 -05008208// Regression test for b/63620844.
8209TEST_P(QuicConnectionTest, FailedToWriteHandshakePacket) {
8210 SimulateNextPacketTooLarge();
fkastenholz5d880a92019-06-21 09:01:56 -07008211 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
QUICHE teama6ef0a62019-03-07 20:34:33 -05008212 .Times(1);
fkastenholz5d880a92019-06-21 09:01:56 -07008213
QUICHE teama6ef0a62019-03-07 20:34:33 -05008214 connection_.SendCryptoStreamData();
fkastenholz5d880a92019-06-21 09:01:56 -07008215 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008216}
8217
8218TEST_P(QuicConnectionTest, MaxPacingRate) {
8219 EXPECT_EQ(0, connection_.MaxPacingRate().ToBytesPerSecond());
8220 connection_.SetMaxPacingRate(QuicBandwidth::FromBytesPerSecond(100));
8221 EXPECT_EQ(100, connection_.MaxPacingRate().ToBytesPerSecond());
8222}
8223
8224TEST_P(QuicConnectionTest, ClientAlwaysSendConnectionId) {
8225 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
8226 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8227 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
8228 EXPECT_EQ(CONNECTION_ID_PRESENT,
8229 writer_->last_packet_header().destination_connection_id_included);
8230
8231 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8232 QuicConfig config;
8233 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
8234 connection_.SetFromConfig(config);
8235
8236 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8237 connection_.SendStreamDataWithString(3, "bar", 3, NO_FIN);
8238 // Verify connection id is still sent in the packet.
8239 EXPECT_EQ(CONNECTION_ID_PRESENT,
8240 writer_->last_packet_header().destination_connection_id_included);
8241}
8242
8243TEST_P(QuicConnectionTest, SendProbingRetransmissions) {
8244 MockQuicConnectionDebugVisitor debug_visitor;
8245 connection_.set_debug_visitor(&debug_visitor);
8246
8247 const QuicStreamId stream_id = 2;
8248 QuicPacketNumber last_packet;
8249 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
8250 SendStreamDataToPeer(stream_id, "bar", 3, NO_FIN, &last_packet);
8251 SendStreamDataToPeer(stream_id, "test", 6, NO_FIN, &last_packet);
8252
8253 const QuicByteCount old_bytes_in_flight =
8254 connection_.sent_packet_manager().GetBytesInFlight();
8255
8256 // Allow 9 probing retransmissions to be sent.
8257 {
8258 InSequence seq;
8259 EXPECT_CALL(*send_algorithm_, CanSend(_))
8260 .Times(9 * 2)
8261 .WillRepeatedly(Return(true));
8262 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(Return(false));
8263 }
8264 // Expect them retransmitted in cyclic order (foo, bar, test, foo, bar...).
8265 QuicPacketCount sent_count = 0;
8266 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _))
8267 .WillRepeatedly(Invoke([this, &sent_count](const SerializedPacket&,
8268 QuicPacketNumber,
8269 TransmissionType, QuicTime) {
8270 ASSERT_EQ(1u, writer_->stream_frames().size());
8271 // Identify the frames by stream offset (0, 3, 6, 0, 3...).
8272 EXPECT_EQ(3 * (sent_count % 3), writer_->stream_frames()[0]->offset);
8273 sent_count++;
8274 }));
8275 EXPECT_CALL(*send_algorithm_, ShouldSendProbingPacket())
8276 .WillRepeatedly(Return(true));
QUICHE teamb8343252019-04-29 13:58:01 -07008277 EXPECT_CALL(visitor_, SendProbingData()).WillRepeatedly([this] {
8278 return connection_.sent_packet_manager().MaybeRetransmitOldestPacket(
8279 PROBING_RETRANSMISSION);
8280 });
QUICHE teama6ef0a62019-03-07 20:34:33 -05008281
8282 connection_.SendProbingRetransmissions();
8283
8284 // Ensure that the in-flight has increased.
8285 const QuicByteCount new_bytes_in_flight =
8286 connection_.sent_packet_manager().GetBytesInFlight();
8287 EXPECT_GT(new_bytes_in_flight, old_bytes_in_flight);
8288}
8289
8290// Ensure that SendProbingRetransmissions() does not retransmit anything when
8291// there are no outstanding packets.
8292TEST_P(QuicConnectionTest,
8293 SendProbingRetransmissionsFailsWhenNothingToRetransmit) {
8294 ASSERT_TRUE(connection_.sent_packet_manager().unacked_packets().empty());
8295
8296 MockQuicConnectionDebugVisitor debug_visitor;
8297 connection_.set_debug_visitor(&debug_visitor);
8298 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _)).Times(0);
8299 EXPECT_CALL(*send_algorithm_, ShouldSendProbingPacket())
8300 .WillRepeatedly(Return(true));
QUICHE teamb8343252019-04-29 13:58:01 -07008301 EXPECT_CALL(visitor_, SendProbingData()).WillRepeatedly([this] {
8302 return connection_.sent_packet_manager().MaybeRetransmitOldestPacket(
8303 PROBING_RETRANSMISSION);
8304 });
QUICHE teama6ef0a62019-03-07 20:34:33 -05008305
8306 connection_.SendProbingRetransmissions();
8307}
8308
8309TEST_P(QuicConnectionTest, PingAfterLastRetransmittablePacketAcked) {
8310 const QuicTime::Delta retransmittable_on_wire_timeout =
8311 QuicTime::Delta::FromMilliseconds(50);
zhongyi79ace162019-10-21 15:57:09 -07008312 connection_.set_initial_retransmittable_on_wire_timeout(
QUICHE teama6ef0a62019-03-07 20:34:33 -05008313 retransmittable_on_wire_timeout);
8314
8315 EXPECT_TRUE(connection_.connected());
8316 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8317 .WillRepeatedly(Return(true));
8318
8319 const char data[] = "data";
8320 size_t data_size = strlen(data);
8321 QuicStreamOffset offset = 0;
8322
8323 // Advance 5ms, send a retransmittable packet to the peer.
8324 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8325 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8326 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8327 offset += data_size;
8328 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8329 // The ping alarm is set for the ping timeout, not the shorter
8330 // retransmittable_on_wire_timeout.
8331 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8332 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
zhongyieef848f2019-10-18 07:09:37 -07008333 EXPECT_EQ(ping_delay,
8334 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008335
8336 // Advance 5ms, send a second retransmittable packet to the peer.
8337 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8338 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8339 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8340 offset += data_size;
8341 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8342
8343 // Now receive an ACK of the first packet. This should not set the
8344 // retransmittable-on-wire alarm since packet 2 is still on the wire.
8345 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8346 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8347 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8348 QuicAckFrame frame =
8349 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8350 ProcessAckPacket(&frame);
8351 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8352 // The ping alarm is set for the ping timeout, not the shorter
8353 // retransmittable_on_wire_timeout.
8354 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8355 // The ping alarm has a 1 second granularity, and the clock has been advanced
8356 // 10ms since it was originally set.
zhongyieef848f2019-10-18 07:09:37 -07008357 EXPECT_EQ(ping_delay - QuicTime::Delta::FromMilliseconds(10),
8358 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008359
8360 // Now receive an ACK of the second packet. This should set the
8361 // retransmittable-on-wire alarm now that no retransmittable packets are on
8362 // the wire.
8363 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8364 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8365 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8366 ProcessAckPacket(&frame);
8367 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07008368 EXPECT_EQ(retransmittable_on_wire_timeout,
8369 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008370
8371 // Now receive a duplicate ACK of the second packet. This should not update
8372 // the ping alarm.
8373 QuicTime prev_deadline = connection_.GetPingAlarm()->deadline();
8374 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8375 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8376 ProcessAckPacket(&frame);
8377 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8378 EXPECT_EQ(prev_deadline, connection_.GetPingAlarm()->deadline());
8379
8380 // Now receive a non-ACK packet. This should not update the ping alarm.
8381 prev_deadline = connection_.GetPingAlarm()->deadline();
8382 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8383 ProcessPacket(4);
8384 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8385 EXPECT_EQ(prev_deadline, connection_.GetPingAlarm()->deadline());
8386
8387 // Simulate the alarm firing and check that a PING is sent.
8388 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8389 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
8390 }));
8391 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07008392 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05008393 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07008394 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008395 } else {
nharper55fa6132019-05-07 19:37:21 -07008396 EXPECT_EQ(padding_frame_count + 3u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008397 }
8398 ASSERT_EQ(1u, writer_->ping_frames().size());
8399}
8400
8401TEST_P(QuicConnectionTest, NoPingIfRetransmittablePacketSent) {
8402 const QuicTime::Delta retransmittable_on_wire_timeout =
8403 QuicTime::Delta::FromMilliseconds(50);
zhongyi79ace162019-10-21 15:57:09 -07008404 connection_.set_initial_retransmittable_on_wire_timeout(
QUICHE teama6ef0a62019-03-07 20:34:33 -05008405 retransmittable_on_wire_timeout);
8406
8407 EXPECT_TRUE(connection_.connected());
8408 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8409 .WillRepeatedly(Return(true));
8410
8411 const char data[] = "data";
8412 size_t data_size = strlen(data);
8413 QuicStreamOffset offset = 0;
8414
8415 // Advance 5ms, send a retransmittable packet to the peer.
8416 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8417 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8418 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8419 offset += data_size;
8420 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8421 // The ping alarm is set for the ping timeout, not the shorter
8422 // retransmittable_on_wire_timeout.
8423 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8424 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
zhongyieef848f2019-10-18 07:09:37 -07008425 EXPECT_EQ(ping_delay,
8426 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008427
8428 // Now receive an ACK of the first packet. This should set the
8429 // retransmittable-on-wire alarm now that no retransmittable packets are on
8430 // the wire.
8431 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8432 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8433 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8434 QuicAckFrame frame =
8435 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8436 ProcessAckPacket(&frame);
8437 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07008438 EXPECT_EQ(retransmittable_on_wire_timeout,
8439 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008440
8441 // Before the alarm fires, send another retransmittable packet. This should
8442 // cancel the retransmittable-on-wire alarm since now there's a
8443 // retransmittable packet on the wire.
8444 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8445 offset += data_size;
8446 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8447
8448 // Now receive an ACK of the second packet. This should set the
8449 // retransmittable-on-wire alarm now that no retransmittable packets are on
8450 // the wire.
8451 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8452 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8453 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8454 ProcessAckPacket(&frame);
8455 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07008456 EXPECT_EQ(retransmittable_on_wire_timeout,
8457 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008458
8459 // Simulate the alarm firing and check that a PING is sent.
8460 writer_->Reset();
8461 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8462 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
8463 }));
8464 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07008465 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05008466 if (GetParam().no_stop_waiting) {
fayange8b0cab2019-07-17 14:23:07 -07008467 if (GetQuicReloadableFlag(quic_simplify_stop_waiting)) {
8468 // Do not ACK acks.
8469 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
8470 } else {
8471 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
8472 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008473 } else {
nharper55fa6132019-05-07 19:37:21 -07008474 EXPECT_EQ(padding_frame_count + 3u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008475 }
8476 ASSERT_EQ(1u, writer_->ping_frames().size());
8477}
8478
zhongyi79ace162019-10-21 15:57:09 -07008479// When there is no stream data received but are open streams, send the
8480// first few consecutive pings with aggressive retransmittable-on-wire
8481// timeout. Exponentially back off the retransmittable-on-wire ping timeout
8482// afterwards until it exceeds the default ping timeout.
8483TEST_P(QuicConnectionTest, BackOffRetransmittableOnWireTimeout) {
8484 int max_aggressive_retransmittable_on_wire_ping_count = 5;
8485 SetQuicFlag(FLAGS_quic_max_aggressive_retransmittable_on_wire_ping_count,
8486 max_aggressive_retransmittable_on_wire_ping_count);
8487 const QuicTime::Delta initial_retransmittable_on_wire_timeout =
8488 QuicTime::Delta::FromMilliseconds(200);
8489 connection_.set_initial_retransmittable_on_wire_timeout(
8490 initial_retransmittable_on_wire_timeout);
8491
8492 EXPECT_TRUE(connection_.connected());
8493 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8494 .WillRepeatedly(Return(true));
8495
8496 const char data[] = "data";
8497 // Advance 5ms, send a retransmittable data packet to the peer.
8498 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8499 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8500 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
8501 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8502 // The ping alarm is set for the ping timeout, not the shorter
8503 // retransmittable_on_wire_timeout.
8504 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8505 EXPECT_EQ(connection_.ping_timeout(),
8506 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8507
8508 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
8509 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
8510 .Times(AnyNumber());
8511
8512 // Verify that the first few consecutive retransmittable on wire pings are
8513 // sent with aggressive timeout.
8514 for (int i = 0; i <= max_aggressive_retransmittable_on_wire_ping_count; i++) {
8515 // Receive an ACK of the previous packet. This should set the ping alarm
8516 // with the initial retransmittable-on-wire timeout.
8517 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8518 QuicPacketNumber ack_num = creator_->packet_number();
8519 QuicAckFrame frame = InitAckFrame(
8520 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8521 ProcessAckPacket(&frame);
8522 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8523 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8524 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8525 // Simulate the alarm firing and check that a PING is sent.
8526 writer_->Reset();
8527 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8528 SendPing();
8529 }));
8530 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8531 connection_.GetPingAlarm()->Fire();
8532 }
8533
8534 QuicTime::Delta retransmittable_on_wire_timeout =
8535 initial_retransmittable_on_wire_timeout;
8536
8537 // Verify subsequent pings are sent with timeout that is exponentially backed
8538 // off.
8539 while (retransmittable_on_wire_timeout * 2 < connection_.ping_timeout()) {
8540 // Receive an ACK for the previous PING. This should set the
8541 // ping alarm with backed off retransmittable-on-wire timeout.
8542 retransmittable_on_wire_timeout = retransmittable_on_wire_timeout * 2;
8543 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8544 QuicPacketNumber ack_num = creator_->packet_number();
8545 QuicAckFrame frame = InitAckFrame(
8546 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8547 ProcessAckPacket(&frame);
8548 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8549 EXPECT_EQ(retransmittable_on_wire_timeout,
8550 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8551
8552 // Simulate the alarm firing and check that a PING is sent.
8553 writer_->Reset();
8554 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8555 SendPing();
8556 }));
8557 clock_.AdvanceTime(retransmittable_on_wire_timeout);
8558 connection_.GetPingAlarm()->Fire();
8559 }
8560
8561 // The ping alarm is set with default ping timeout.
8562 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8563 EXPECT_EQ(connection_.ping_timeout(),
8564 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8565
8566 // Receive an ACK for the previous PING. The ping alarm is set with an
8567 // earlier deadline.
8568 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8569 QuicPacketNumber ack_num = creator_->packet_number();
8570 QuicAckFrame frame = InitAckFrame(
8571 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8572 ProcessAckPacket(&frame);
8573 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8574 EXPECT_EQ(connection_.ping_timeout() - QuicTime::Delta::FromMilliseconds(5),
8575 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8576}
8577
8578// This test verify that the count of consecutive aggressive pings is reset
8579// when new data is received. And it also verifies the connection resets
8580// the exponential back-off of the retransmittable-on-wire ping timeout
8581// after receiving new stream data.
8582TEST_P(QuicConnectionTest, ResetBackOffRetransmitableOnWireTimeout) {
8583 int max_aggressive_retransmittable_on_wire_ping_count = 3;
8584 SetQuicFlag(FLAGS_quic_max_aggressive_retransmittable_on_wire_ping_count, 3);
8585 const QuicTime::Delta initial_retransmittable_on_wire_timeout =
8586 QuicTime::Delta::FromMilliseconds(200);
8587 connection_.set_initial_retransmittable_on_wire_timeout(
8588 initial_retransmittable_on_wire_timeout);
8589
8590 EXPECT_TRUE(connection_.connected());
8591 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8592 .WillRepeatedly(Return(true));
8593 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
8594 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
8595 .Times(AnyNumber());
8596
8597 const char data[] = "data";
8598 // Advance 5ms, send a retransmittable data packet to the peer.
8599 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8600 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8601 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
8602 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8603 // The ping alarm is set for the ping timeout, not the shorter
8604 // retransmittable_on_wire_timeout.
8605 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8606 EXPECT_EQ(connection_.ping_timeout(),
8607 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8608
8609 // Receive an ACK of the first packet. This should set the ping alarm with
8610 // initial retransmittable-on-wire timeout since there is no retransmittable
8611 // packet on the wire.
8612 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8613 QuicAckFrame frame =
8614 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8615 ProcessAckPacket(&frame);
8616 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8617 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8618 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8619
8620 // Simulate the alarm firing and check that a PING is sent.
8621 writer_->Reset();
8622 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
8623 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8624 connection_.GetPingAlarm()->Fire();
8625
8626 // Receive an ACK for the previous PING. Ping alarm will be set with
8627 // aggressive timeout.
8628 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8629 QuicPacketNumber ack_num = creator_->packet_number();
8630 frame = InitAckFrame(
8631 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8632 ProcessAckPacket(&frame);
8633 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8634 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8635 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8636
8637 // Process a data packet.
8638 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
8639 ProcessDataPacket(peer_creator_.packet_number() + 1);
8640 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_,
8641 peer_creator_.packet_number() + 1);
8642 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8643 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8644
8645 // Verify the count of consecutive aggressive pings is reset.
8646 for (int i = 0; i < max_aggressive_retransmittable_on_wire_ping_count; i++) {
8647 // Receive an ACK of the previous packet. This should set the ping alarm
8648 // with the initial retransmittable-on-wire timeout.
8649 QuicPacketNumber ack_num = creator_->packet_number();
8650 QuicAckFrame frame = InitAckFrame(
8651 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8652 ProcessAckPacket(&frame);
8653 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8654 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8655 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8656 // Simulate the alarm firing and check that a PING is sent.
8657 writer_->Reset();
8658 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8659 SendPing();
8660 }));
8661 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8662 connection_.GetPingAlarm()->Fire();
8663 // Advance 5ms to receive next packet.
8664 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8665 }
8666
8667 // Receive another ACK for the previous PING. This should set the
8668 // ping alarm with backed off retransmittable-on-wire timeout.
8669 ack_num = creator_->packet_number();
8670 frame = InitAckFrame(
8671 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8672 ProcessAckPacket(&frame);
8673 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8674 EXPECT_EQ(initial_retransmittable_on_wire_timeout * 2,
8675 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8676
8677 writer_->Reset();
8678 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
8679 clock_.AdvanceTime(2 * initial_retransmittable_on_wire_timeout);
8680 connection_.GetPingAlarm()->Fire();
8681
8682 // Process another data packet and a new ACK packet. The ping alarm is set
8683 // with aggressive ping timeout again.
8684 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
8685 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8686 ProcessDataPacket(peer_creator_.packet_number() + 1);
8687 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_,
8688 peer_creator_.packet_number() + 1);
8689 ack_num = creator_->packet_number();
8690 frame = InitAckFrame(
8691 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8692 ProcessAckPacket(&frame);
8693 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8694 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8695 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8696}
8697
QUICHE teama6ef0a62019-03-07 20:34:33 -05008698TEST_P(QuicConnectionTest, OnForwardProgressConfirmed) {
8699 EXPECT_CALL(visitor_, OnForwardProgressConfirmed()).Times(Exactly(0));
8700 EXPECT_TRUE(connection_.connected());
8701
8702 const char data[] = "data";
8703 size_t data_size = strlen(data);
8704 QuicStreamOffset offset = 0;
8705
8706 // Send two packets.
8707 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8708 offset += data_size;
8709 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8710 offset += data_size;
8711
8712 // Ack packet 1. This increases the largest_acked to 1, so
8713 // OnForwardProgressConfirmed() should be called
8714 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8715 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8716 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8717 EXPECT_CALL(visitor_, OnForwardProgressConfirmed());
8718 QuicAckFrame frame =
8719 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8720 ProcessAckPacket(&frame);
8721
8722 // Ack packet 1 again. largest_acked remains at 1, so
8723 // OnForwardProgressConfirmed() should not be called.
8724 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8725 frame = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8726 ProcessAckPacket(&frame);
8727
8728 // Ack packet 2. This increases the largest_acked to 2, so
8729 // OnForwardProgressConfirmed() should be called.
8730 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8731 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8732 EXPECT_CALL(visitor_, OnForwardProgressConfirmed());
8733 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8734 ProcessAckPacket(&frame);
8735}
8736
8737TEST_P(QuicConnectionTest, ValidStatelessResetToken) {
8738 const QuicUint128 kTestToken = 1010101;
8739 const QuicUint128 kWrongTestToken = 1010100;
8740 QuicConfig config;
8741 // No token has been received.
8742 EXPECT_FALSE(connection_.IsValidStatelessResetToken(kTestToken));
8743
8744 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(2);
8745 // Token is different from received token.
8746 QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestToken);
8747 connection_.SetFromConfig(config);
8748 EXPECT_FALSE(connection_.IsValidStatelessResetToken(kWrongTestToken));
8749
8750 QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestToken);
8751 connection_.SetFromConfig(config);
8752 EXPECT_TRUE(connection_.IsValidStatelessResetToken(kTestToken));
8753}
8754
8755TEST_P(QuicConnectionTest, WriteBlockedWithInvalidAck) {
8756 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang2ce66082019-10-02 06:29:04 -07008757 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
8758 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
8759 } else {
8760 EXPECT_CALL(visitor_, OnConnectionClosed(_, _))
8761 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
8762 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008763 BlockOnNextWrite();
fayang2ce66082019-10-02 06:29:04 -07008764 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
8765 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8766 } else {
8767 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8768 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008769 connection_.SendStreamDataWithString(5, "foo", 0, FIN);
8770 // This causes connection to be closed because packet 1 has not been sent yet.
8771 QuicAckFrame frame = InitAckFrame(1);
fayang2ce66082019-10-02 06:29:04 -07008772 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
8773 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
8774 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008775 ProcessAckPacket(1, &frame);
fayang2ce66082019-10-02 06:29:04 -07008776 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
8777 EXPECT_EQ(0, connection_close_frame_count_);
8778 } else {
8779 EXPECT_EQ(1, connection_close_frame_count_);
8780 EXPECT_EQ(QUIC_INVALID_ACK_DATA,
8781 saved_connection_close_frame_.quic_error_code);
8782 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008783}
8784
8785TEST_P(QuicConnectionTest, SendMessage) {
fayangc31c9952019-06-05 13:54:48 -07008786 if (!VersionSupportsMessageFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008787 return;
8788 }
ianswettb239f862019-04-05 09:15:06 -07008789 std::string message(connection_.GetCurrentLargestMessagePayload() * 2, 'a');
QUICHE teama6ef0a62019-03-07 20:34:33 -05008790 QuicStringPiece message_data(message);
8791 QuicMemSliceStorage storage(nullptr, 0, nullptr, 0);
8792 {
fayanga4b37b22019-06-18 13:37:47 -07008793 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008794 connection_.SendStreamData3();
8795 // Send a message which cannot fit into current open packet, and 2 packets
8796 // get sent, one contains stream frame, and the other only contains the
8797 // message frame.
8798 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
8799 EXPECT_EQ(
8800 MESSAGE_STATUS_SUCCESS,
8801 connection_.SendMessage(
8802 1, MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(),
ianswettb239f862019-04-05 09:15:06 -07008803 QuicStringPiece(
8804 message_data.data(),
8805 connection_.GetCurrentLargestMessagePayload()),
QUICHE teama6ef0a62019-03-07 20:34:33 -05008806 &storage)));
8807 }
8808 // Fail to send a message if connection is congestion control blocked.
8809 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(Return(false));
8810 EXPECT_EQ(
8811 MESSAGE_STATUS_BLOCKED,
8812 connection_.SendMessage(
8813 2, MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(),
8814 "message", &storage)));
8815
8816 // Always fail to send a message which cannot fit into one packet.
8817 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8818 EXPECT_EQ(
8819 MESSAGE_STATUS_TOO_LARGE,
8820 connection_.SendMessage(
ianswettb239f862019-04-05 09:15:06 -07008821 3, MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(),
8822 QuicStringPiece(
8823 message_data.data(),
8824 connection_.GetCurrentLargestMessagePayload() + 1),
8825 &storage)));
QUICHE teama6ef0a62019-03-07 20:34:33 -05008826}
8827
8828// Test to check that the path challenge/path response logic works
8829// correctly. This test is only for version-99
8830TEST_P(QuicConnectionTest, PathChallengeResponse) {
fkastenholz305e1732019-06-18 05:01:22 -07008831 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008832 return;
8833 }
8834 // First check if we can probe from server to client and back
8835 set_perspective(Perspective::IS_SERVER);
8836 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
8837
8838 // Create and send the probe request (PATH_CHALLENGE frame).
8839 // SendConnectivityProbingPacket ends up calling
8840 // TestPacketWriter::WritePacket() which in turns receives and parses the
8841 // packet by calling framer_.ProcessPacket() -- which in turn calls
8842 // SimpleQuicFramer::OnPathChallengeFrame(). SimpleQuicFramer saves
8843 // the packet in writer_->path_challenge_frames()
8844 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8845 connection_.SendConnectivityProbingPacket(writer_.get(),
8846 connection_.peer_address());
8847 // Save the random contents of the challenge for later comparison to the
8848 // response.
nharper55fa6132019-05-07 19:37:21 -07008849 ASSERT_GE(writer_->path_challenge_frames().size(), 1u);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008850 QuicPathFrameBuffer challenge_data =
8851 writer_->path_challenge_frames().front().data_buffer;
8852
8853 // Normally, QuicConnection::OnPathChallengeFrame and OnPaddingFrame would be
8854 // called and it will perform actions to ensure that the rest of the protocol
8855 // is performed (specifically, call UpdatePacketContent to say that this is a
8856 // path challenge so that when QuicConnection::OnPacketComplete is called
8857 // (again, out of the framer), the response is generated). Simulate those
8858 // calls so that the right internal state is set up for generating
8859 // the response.
8860 EXPECT_TRUE(connection_.OnPathChallengeFrame(
8861 writer_->path_challenge_frames().front()));
8862 EXPECT_TRUE(connection_.OnPaddingFrame(writer_->padding_frames().front()));
8863 // Cause the response to be created and sent. Result is that the response
8864 // should be stashed in writer's path_response_frames.
8865 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8866 connection_.SendConnectivityProbingResponsePacket(connection_.peer_address());
8867
8868 // The final check is to ensure that the random data in the response matches
8869 // the random data from the challenge.
8870 EXPECT_EQ(0, memcmp(&challenge_data,
8871 &(writer_->path_response_frames().front().data_buffer),
8872 sizeof(challenge_data)));
8873}
8874
8875// Regression test for b/110259444
8876TEST_P(QuicConnectionTest, DoNotScheduleSpuriousAckAlarm) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008877 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8878 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
8879 writer_->SetWriteBlocked();
8880
8881 ProcessPacket(1);
8882 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
8883 // Verify ack alarm is set.
8884 EXPECT_TRUE(ack_alarm->IsSet());
8885 // Fire the ack alarm, verify no packet is sent because the writer is blocked.
8886 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8887 connection_.GetAckAlarm()->Fire();
8888
8889 writer_->SetWritable();
8890 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8891 ProcessPacket(2);
8892 // Verify ack alarm is not set.
8893 EXPECT_FALSE(ack_alarm->IsSet());
8894}
8895
8896TEST_P(QuicConnectionTest, DisablePacingOffloadConnectionOptions) {
8897 EXPECT_FALSE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
8898 writer_->set_supports_release_time(true);
8899 QuicConfig config;
8900 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8901 connection_.SetFromConfig(config);
8902 EXPECT_TRUE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
8903
8904 QuicTagVector connection_options;
8905 connection_options.push_back(kNPCO);
8906 config.SetConnectionOptionsToSend(connection_options);
8907 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8908 connection_.SetFromConfig(config);
8909 // Verify pacing offload is disabled.
8910 EXPECT_FALSE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
8911}
8912
8913// Regression test for b/110259444
8914// Get a path response without having issued a path challenge...
8915TEST_P(QuicConnectionTest, OrphanPathResponse) {
8916 QuicPathFrameBuffer data = {{0, 1, 2, 3, 4, 5, 6, 7}};
8917
8918 QuicPathResponseFrame frame(99, data);
8919 EXPECT_TRUE(connection_.OnPathResponseFrame(frame));
8920 // If PATH_RESPONSE was accepted (payload matches the payload saved
8921 // in QuicConnection::transmitted_connectivity_probe_payload_) then
8922 // current_packet_content_ would be set to FIRST_FRAME_IS_PING.
8923 // Since this PATH_RESPONSE does not match, current_packet_content_
8924 // must not be FIRST_FRAME_IS_PING.
8925 EXPECT_NE(QuicConnection::FIRST_FRAME_IS_PING,
8926 QuicConnectionPeer::GetCurrentPacketContent(&connection_));
8927}
8928
8929// Regression test for b/120791670
8930TEST_P(QuicConnectionTest, StopProcessingGQuicPacketInIetfQuicConnection) {
8931 // This test mimics a problematic scenario where an IETF QUIC connection
8932 // receives a Google QUIC packet and continue processing it using Google QUIC
8933 // wire format.
fayangd4291e42019-05-30 10:31:21 -07008934 if (!VersionHasIetfInvariantHeader(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008935 return;
8936 }
8937 set_perspective(Perspective::IS_SERVER);
nharper46833c32019-05-15 21:33:05 -07008938 QuicFrame frame;
8939 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
8940 frame = QuicFrame(&crypto_frame_);
8941 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
8942 } else {
8943 frame = QuicFrame(QuicStreamFrame(
8944 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
8945 0u, QuicStringPiece()));
8946 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
8947 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008948 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
nharper46833c32019-05-15 21:33:05 -07008949 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008950
8951 // Let connection process a Google QUIC packet.
8952 peer_framer_.set_version_for_tests(
8953 ParsedQuicVersion(PROTOCOL_QUIC_CRYPTO, QUIC_VERSION_43));
QUICHE team8c1daa22019-03-13 08:33:41 -07008954 std::unique_ptr<QuicPacket> packet(
QUICHE team6987b4a2019-03-15 16:23:04 -07008955 ConstructDataPacket(2, !kHasStopWaiting, ENCRYPTION_INITIAL));
dschinazi66dea072019-04-09 11:41:06 -07008956 char buffer[kMaxOutgoingPacketSize];
8957 size_t encrypted_length =
8958 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(2),
8959 *packet, buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008960 // Make sure no stream frame is processed.
8961 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(0);
8962 connection_.ProcessUdpPacket(
8963 kSelfAddress, kPeerAddress,
8964 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
8965
8966 EXPECT_EQ(2u, connection_.GetStats().packets_received);
8967 EXPECT_EQ(1u, connection_.GetStats().packets_processed);
8968}
8969
8970TEST_P(QuicConnectionTest, AcceptPacketNumberZero) {
fkastenholz305e1732019-06-18 05:01:22 -07008971 if (!VersionHasIetfQuicFrames(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008972 return;
8973 }
8974 // Set first_sending_packet_number to be 0 to allow successfully processing
8975 // acks which ack packet number 0.
8976 QuicFramerPeer::SetFirstSendingPacketNumber(writer_->framer()->framer(), 0);
8977 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8978
8979 ProcessPacket(0);
fayangc31c9952019-06-05 13:54:48 -07008980 EXPECT_EQ(QuicPacketNumber(0), LargestAcked(connection_.ack_frame()));
8981 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008982
8983 ProcessPacket(1);
fayangc31c9952019-06-05 13:54:48 -07008984 EXPECT_EQ(QuicPacketNumber(1), LargestAcked(connection_.ack_frame()));
8985 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008986
8987 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07008988 EXPECT_EQ(QuicPacketNumber(2), LargestAcked(connection_.ack_frame()));
8989 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008990}
8991
QUICHE teamcd098022019-03-22 18:49:55 -07008992TEST_P(QuicConnectionTest, MultiplePacketNumberSpacesBasicSending) {
8993 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8994 return;
8995 }
8996 use_tagging_decrypter();
8997 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07008998 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teamcd098022019-03-22 18:49:55 -07008999
9000 connection_.SendCryptoStreamData();
9001 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9002 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
9003 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
9004 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9005 QuicAckFrame frame1 = InitAckFrame(1);
9006 // Received ACK for packet 1.
9007 ProcessFramePacketAtLevel(30, QuicFrame(&frame1), ENCRYPTION_INITIAL);
9008
9009 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(4);
9010 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
9011 NO_FIN);
9012 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 4,
9013 NO_FIN);
9014 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
9015 8, NO_FIN);
9016 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
9017 12, FIN);
9018 // Received ACK for packets 2, 4, 5.
9019 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
9020 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
9021 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9022 QuicAckFrame frame2 =
9023 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)},
9024 {QuicPacketNumber(4), QuicPacketNumber(6)}});
9025 // Make sure although the same packet number is used, but they are in
9026 // different packet number spaces.
9027 ProcessFramePacketAtLevel(30, QuicFrame(&frame2), ENCRYPTION_FORWARD_SECURE);
9028}
9029
9030TEST_P(QuicConnectionTest, PeerAcksPacketsInWrongPacketNumberSpace) {
9031 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
9032 return;
9033 }
9034 use_tagging_decrypter();
9035 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07009036 std::make_unique<TaggingEncrypter>(0x01));
rch39c88ab2019-10-16 19:24:40 -07009037 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
9038 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teamcd098022019-03-22 18:49:55 -07009039
9040 connection_.SendCryptoStreamData();
9041 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9042 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
9043 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
9044 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9045 QuicAckFrame frame1 = InitAckFrame(1);
9046 // Received ACK for packet 1.
9047 ProcessFramePacketAtLevel(30, QuicFrame(&frame1), ENCRYPTION_INITIAL);
9048
9049 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
9050 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
9051 NO_FIN);
9052 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 4,
9053 NO_FIN);
9054
9055 // Received ACK for packets 2 and 3 in wrong packet number space.
9056 QuicAckFrame invalid_ack =
9057 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(4)}});
fkastenholz5d880a92019-06-21 09:01:56 -07009058 EXPECT_CALL(visitor_,
9059 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07009060 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teamcd098022019-03-22 18:49:55 -07009061 ProcessFramePacketAtLevel(300, QuicFrame(&invalid_ack), ENCRYPTION_INITIAL);
fkastenholz5d880a92019-06-21 09:01:56 -07009062 TestConnectionCloseQuicErrorCode(QUIC_INVALID_ACK_DATA);
QUICHE teamcd098022019-03-22 18:49:55 -07009063}
9064
9065TEST_P(QuicConnectionTest, MultiplePacketNumberSpacesBasicReceiving) {
9066 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
9067 return;
9068 }
9069 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
nharper46833c32019-05-15 21:33:05 -07009070 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9071 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9072 }
QUICHE teamcd098022019-03-22 18:49:55 -07009073 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
9074 use_tagging_decrypter();
9075 // Receives packet 1000 in initial data.
nharper46833c32019-05-15 21:33:05 -07009076 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
QUICHE teamcd098022019-03-22 18:49:55 -07009077 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
9078 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07009079 std::make_unique<TaggingEncrypter>(0x02));
zhongyi546cc452019-04-12 15:27:49 -07009080 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07009081 std::make_unique<StrictTaggingDecrypter>(0x02));
QUICHE teamcd098022019-03-22 18:49:55 -07009082 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07009083 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teamcd098022019-03-22 18:49:55 -07009084 // Receives packet 1000 in application data.
9085 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
9086 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
9087 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
9088 NO_FIN);
9089 // Verify application data ACK gets bundled with outgoing data.
9090 EXPECT_EQ(2u, writer_->frame_count());
9091 // Make sure ACK alarm is still set because initial data is not ACKed.
9092 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
9093 // Receive packet 1001 in application data.
9094 ProcessDataPacketAtLevel(1001, false, ENCRYPTION_ZERO_RTT);
9095 clock_.AdvanceTime(DefaultRetransmissionTime());
9096 // Simulates ACK alarm fires and verify two ACKs are flushed.
9097 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
9098 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07009099 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teamcd098022019-03-22 18:49:55 -07009100 connection_.GetAckAlarm()->Fire();
9101 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
9102 // Receives more packets in application data.
9103 ProcessDataPacketAtLevel(1002, false, ENCRYPTION_ZERO_RTT);
9104 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
9105
9106 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07009107 std::make_unique<TaggingEncrypter>(0x02));
zhongyi546cc452019-04-12 15:27:49 -07009108 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07009109 std::make_unique<StrictTaggingDecrypter>(0x02));
QUICHE teamcd098022019-03-22 18:49:55 -07009110 // Verify zero rtt and forward secure packets get acked in the same packet.
9111 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
nharper2c9f02a2019-05-08 10:25:50 -07009112 ProcessDataPacket(1003);
QUICHE teamcd098022019-03-22 18:49:55 -07009113 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
9114}
9115
QUICHE team552f71f2019-03-23 15:37:59 -07009116TEST_P(QuicConnectionTest, CancelAckAlarmOnWriteBlocked) {
9117 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
9118 return;
9119 }
9120 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
nharper46833c32019-05-15 21:33:05 -07009121 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9122 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9123 }
QUICHE team552f71f2019-03-23 15:37:59 -07009124 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
9125 use_tagging_decrypter();
9126 // Receives packet 1000 in initial data.
nharper46833c32019-05-15 21:33:05 -07009127 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
QUICHE team552f71f2019-03-23 15:37:59 -07009128 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
9129 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07009130 std::make_unique<TaggingEncrypter>(0x02));
zhongyi546cc452019-04-12 15:27:49 -07009131 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07009132 std::make_unique<StrictTaggingDecrypter>(0x02));
QUICHE team552f71f2019-03-23 15:37:59 -07009133 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07009134 std::make_unique<TaggingEncrypter>(0x02));
QUICHE team552f71f2019-03-23 15:37:59 -07009135 // Receives packet 1000 in application data.
9136 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
9137 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
9138
9139 writer_->SetWriteBlocked();
9140 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AnyNumber());
9141 // Simulates ACK alarm fires and verify no ACK is flushed because of write
9142 // blocked.
9143 clock_.AdvanceTime(DefaultDelayedAckTime());
9144 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9145 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07009146 std::make_unique<TaggingEncrypter>(0x02));
QUICHE team552f71f2019-03-23 15:37:59 -07009147 connection_.GetAckAlarm()->Fire();
9148 // Verify ACK alarm is not set.
9149 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
9150
9151 writer_->SetWritable();
9152 // Verify 2 ACKs are sent when connection gets unblocked.
9153 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
9154 connection_.OnCanWrite();
9155 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
9156}
9157
dschinazi346b7ce2019-06-05 01:38:18 -07009158// Make sure a packet received with the right client connection ID is processed.
9159TEST_P(QuicConnectionTest, ValidClientConnectionId) {
dschinazi346b7ce2019-06-05 01:38:18 -07009160 if (!framer_.version().SupportsClientConnectionIds()) {
9161 return;
9162 }
9163 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9164 connection_.set_client_connection_id(TestConnectionId(0x33));
9165 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_FORWARD_SECURE);
9166 header.destination_connection_id = TestConnectionId(0x33);
9167 header.destination_connection_id_included = CONNECTION_ID_PRESENT;
9168 header.source_connection_id_included = CONNECTION_ID_ABSENT;
9169 QuicFrames frames;
9170 QuicPingFrame ping_frame;
9171 QuicPaddingFrame padding_frame;
9172 frames.push_back(QuicFrame(ping_frame));
9173 frames.push_back(QuicFrame(padding_frame));
9174 std::unique_ptr<QuicPacket> packet =
9175 BuildUnsizedDataPacket(&framer_, header, frames);
9176 char buffer[kMaxOutgoingPacketSize];
9177 size_t encrypted_length = peer_framer_.EncryptPayload(
9178 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
9179 kMaxOutgoingPacketSize);
9180 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9181 false);
9182 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9183 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9184 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9185}
9186
9187// Make sure a packet received with a different client connection ID is dropped.
9188TEST_P(QuicConnectionTest, InvalidClientConnectionId) {
dschinazi346b7ce2019-06-05 01:38:18 -07009189 if (!framer_.version().SupportsClientConnectionIds()) {
9190 return;
9191 }
9192 connection_.set_client_connection_id(TestConnectionId(0x33));
9193 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_FORWARD_SECURE);
9194 header.destination_connection_id = TestConnectionId(0xbad);
9195 header.destination_connection_id_included = CONNECTION_ID_PRESENT;
9196 header.source_connection_id_included = CONNECTION_ID_ABSENT;
9197 QuicFrames frames;
9198 QuicPingFrame ping_frame;
9199 QuicPaddingFrame padding_frame;
9200 frames.push_back(QuicFrame(ping_frame));
9201 frames.push_back(QuicFrame(padding_frame));
9202 std::unique_ptr<QuicPacket> packet =
9203 BuildUnsizedDataPacket(&framer_, header, frames);
9204 char buffer[kMaxOutgoingPacketSize];
9205 size_t encrypted_length = peer_framer_.EncryptPayload(
9206 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
9207 kMaxOutgoingPacketSize);
9208 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9209 false);
9210 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9211 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9212 EXPECT_EQ(1u, connection_.GetStats().packets_dropped);
9213}
9214
9215// Make sure the first packet received with a different client connection ID on
9216// the server is processed and it changes the client connection ID.
9217TEST_P(QuicConnectionTest, UpdateClientConnectionIdFromFirstPacket) {
dschinazi346b7ce2019-06-05 01:38:18 -07009218 if (!framer_.version().SupportsClientConnectionIds()) {
9219 return;
9220 }
9221 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9222 set_perspective(Perspective::IS_SERVER);
9223 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_INITIAL);
9224 header.source_connection_id = TestConnectionId(0x33);
9225 header.source_connection_id_included = CONNECTION_ID_PRESENT;
9226 QuicFrames frames;
9227 QuicPingFrame ping_frame;
9228 QuicPaddingFrame padding_frame;
9229 frames.push_back(QuicFrame(ping_frame));
9230 frames.push_back(QuicFrame(padding_frame));
9231 std::unique_ptr<QuicPacket> packet =
9232 BuildUnsizedDataPacket(&framer_, header, frames);
9233 char buffer[kMaxOutgoingPacketSize];
nharperc6b99512019-09-19 11:13:48 -07009234 size_t encrypted_length =
9235 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(1),
9236 *packet, buffer, kMaxOutgoingPacketSize);
dschinazi346b7ce2019-06-05 01:38:18 -07009237 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9238 false);
9239 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9240 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9241 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9242 EXPECT_EQ(TestConnectionId(0x33), connection_.client_connection_id());
9243}
9244
fayang40ec3ac2019-06-05 09:07:54 -07009245// Regression test for b/134416344.
9246TEST_P(QuicConnectionTest, CheckConnectedBeforeFlush) {
9247 // This test mimics a scenario where a connection processes 2 packets and the
9248 // 2nd packet contains connection close frame. When the 2nd flusher goes out
9249 // of scope, a delayed ACK is pending, and ACK alarm should not be scheduled
9250 // because connection is disconnected.
9251 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fkastenholz5d880a92019-06-21 09:01:56 -07009252 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
fayang40ec3ac2019-06-05 09:07:54 -07009253 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
fkastenholz88d08f42019-09-06 07:38:04 -07009254 const QuicErrorCode kErrorCode = QUIC_INTERNAL_ERROR;
fayang40ec3ac2019-06-05 09:07:54 -07009255 std::unique_ptr<QuicConnectionCloseFrame> connection_close_frame(
fkastenholz591814c2019-09-06 12:11:46 -07009256 new QuicConnectionCloseFrame(connection_.transport_version(), kErrorCode,
9257 "",
9258 /*transport_close_frame_type=*/0));
9259
fayang40ec3ac2019-06-05 09:07:54 -07009260 // Received 2 packets.
9261 QuicFrame frame;
9262 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9263 frame = QuicFrame(&crypto_frame_);
9264 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9265 } else {
9266 frame = QuicFrame(QuicStreamFrame(
9267 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
9268 0u, QuicStringPiece()));
9269 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
9270 }
9271 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
9272 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
9273 EXPECT_TRUE(ack_alarm->IsSet());
9274 ProcessFramePacketWithAddresses(QuicFrame(connection_close_frame.get()),
9275 kSelfAddress, kPeerAddress);
fayang0f0c4e62019-07-16 08:55:54 -07009276 // Verify ack alarm is not set.
9277 EXPECT_FALSE(ack_alarm->IsSet());
fayang40ec3ac2019-06-05 09:07:54 -07009278}
9279
dschinazi8d551132019-08-02 19:17:16 -07009280// Verify that a packet containing three coalesced packets is parsed correctly.
9281TEST_P(QuicConnectionTest, CoalescedPacket) {
9282 if (!QuicVersionHasLongHeaderLengths(connection_.transport_version())) {
9283 // Coalesced packets can only be encoded using long header lengths.
9284 return;
9285 }
9286 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9287 EXPECT_TRUE(connection_.connected());
9288 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9289 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(3);
9290 } else {
9291 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(3);
9292 }
9293
9294 uint64_t packet_numbers[3] = {1, 2, 3};
9295 EncryptionLevel encryption_levels[3] = {
9296 ENCRYPTION_INITIAL, ENCRYPTION_INITIAL, ENCRYPTION_FORWARD_SECURE};
9297 char buffer[kMaxOutgoingPacketSize] = {};
9298 size_t total_encrypted_length = 0;
9299 for (int i = 0; i < 3; i++) {
9300 QuicPacketHeader header =
9301 ConstructPacketHeader(packet_numbers[i], encryption_levels[i]);
9302 QuicFrames frames;
9303 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9304 frames.push_back(QuicFrame(&crypto_frame_));
9305 } else {
9306 frames.push_back(QuicFrame(frame1_));
9307 }
9308 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
9309 peer_creator_.set_encryption_level(encryption_levels[i]);
9310 size_t encrypted_length = peer_framer_.EncryptPayload(
9311 encryption_levels[i], QuicPacketNumber(packet_numbers[i]), *packet,
9312 buffer + total_encrypted_length,
9313 sizeof(buffer) - total_encrypted_length);
9314 EXPECT_GT(encrypted_length, 0u);
9315 total_encrypted_length += encrypted_length;
9316 }
9317 connection_.ProcessUdpPacket(
9318 kSelfAddress, kPeerAddress,
9319 QuicReceivedPacket(buffer, total_encrypted_length, clock_.Now(), false));
9320 if (connection_.GetSendAlarm()->IsSet()) {
9321 connection_.GetSendAlarm()->Fire();
9322 }
9323
9324 EXPECT_TRUE(connection_.connected());
9325}
9326
dschinazi66fc0242019-08-16 10:00:25 -07009327// Regression test for crbug.com/992831.
9328TEST_P(QuicConnectionTest, CoalescedPacketThatSavesFrames) {
9329 if (!QuicVersionHasLongHeaderLengths(connection_.transport_version())) {
9330 // Coalesced packets can only be encoded using long header lengths.
9331 return;
9332 }
9333 if (connection_.SupportsMultiplePacketNumberSpaces()) {
9334 // TODO(b/129151114) Enable this test with multiple packet number spaces.
9335 return;
9336 }
9337 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9338 EXPECT_TRUE(connection_.connected());
9339 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9340 EXPECT_CALL(visitor_, OnCryptoFrame(_))
9341 .Times(3)
9342 .WillRepeatedly([this](const QuicCryptoFrame& /*frame*/) {
9343 // QuicFrame takes ownership of the QuicBlockedFrame.
9344 connection_.SendControlFrame(QuicFrame(new QuicBlockedFrame(1, 3)));
9345 });
9346 } else {
9347 EXPECT_CALL(visitor_, OnStreamFrame(_))
9348 .Times(3)
9349 .WillRepeatedly([this](const QuicStreamFrame& /*frame*/) {
9350 // QuicFrame takes ownership of the QuicBlockedFrame.
9351 connection_.SendControlFrame(QuicFrame(new QuicBlockedFrame(1, 3)));
9352 });
9353 }
9354
9355 uint64_t packet_numbers[3] = {1, 2, 3};
9356 EncryptionLevel encryption_levels[3] = {
9357 ENCRYPTION_INITIAL, ENCRYPTION_INITIAL, ENCRYPTION_FORWARD_SECURE};
9358 char buffer[kMaxOutgoingPacketSize] = {};
9359 size_t total_encrypted_length = 0;
9360 for (int i = 0; i < 3; i++) {
9361 QuicPacketHeader header =
9362 ConstructPacketHeader(packet_numbers[i], encryption_levels[i]);
9363 QuicFrames frames;
9364 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9365 frames.push_back(QuicFrame(&crypto_frame_));
9366 } else {
9367 frames.push_back(QuicFrame(frame1_));
9368 }
9369 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
9370 peer_creator_.set_encryption_level(encryption_levels[i]);
9371 size_t encrypted_length = peer_framer_.EncryptPayload(
9372 encryption_levels[i], QuicPacketNumber(packet_numbers[i]), *packet,
9373 buffer + total_encrypted_length,
9374 sizeof(buffer) - total_encrypted_length);
9375 EXPECT_GT(encrypted_length, 0u);
9376 total_encrypted_length += encrypted_length;
9377 }
9378 connection_.ProcessUdpPacket(
9379 kSelfAddress, kPeerAddress,
9380 QuicReceivedPacket(buffer, total_encrypted_length, clock_.Now(), false));
9381 if (connection_.GetSendAlarm()->IsSet()) {
9382 connection_.GetSendAlarm()->Fire();
9383 }
9384
9385 EXPECT_TRUE(connection_.connected());
9386
9387 SendAckPacketToPeer();
9388}
9389
fayangd3016832019-08-08 07:24:45 -07009390// Regresstion test for b/138962304.
9391TEST_P(QuicConnectionTest, RtoAndWriteBlocked) {
fayange861aee2019-10-16 13:40:39 -07009392 if (!connection_.session_decides_what_to_write()) {
fayangd3016832019-08-08 07:24:45 -07009393 return;
9394 }
9395 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9396
9397 QuicStreamId stream_id = 2;
9398 QuicPacketNumber last_data_packet;
9399 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
9400 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9401
9402 // Writer gets blocked.
9403 writer_->SetWriteBlocked();
9404
9405 // Cancel the stream.
9406 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9407 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
fayang67f82272019-08-14 16:08:45 -07009408 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
9409 .WillRepeatedly(
9410 Invoke(&notifier_, &SimpleSessionNotifier::WillingToWrite));
fayangd3016832019-08-08 07:24:45 -07009411 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9412
9413 // Retransmission timer fires in RTO mode.
9414 connection_.GetRetransmissionAlarm()->Fire();
9415 // Verify no packets get flushed when writer is blocked.
9416 EXPECT_EQ(0u, connection_.NumQueuedPackets());
9417}
9418
9419// Regresstion test for b/138962304.
9420TEST_P(QuicConnectionTest, TlpAndWriteBlocked) {
fayange861aee2019-10-16 13:40:39 -07009421 if (!connection_.session_decides_what_to_write()) {
fayangd3016832019-08-08 07:24:45 -07009422 return;
9423 }
9424 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9425 connection_.SetMaxTailLossProbes(1);
9426
9427 QuicStreamId stream_id = 2;
9428 QuicPacketNumber last_data_packet;
9429 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
9430 SendStreamDataToPeer(4, "foo", 0, NO_FIN, &last_data_packet);
9431 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9432
9433 // Writer gets blocked.
9434 writer_->SetWriteBlocked();
9435
9436 // Cancel stream 2.
9437 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9438 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
9439 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9440
fayang2ce66082019-10-02 06:29:04 -07009441 if (GetQuicReloadableFlag(quic_treat_queued_packets_as_sent)) {
9442 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9443 } else {
9444 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9445 }
fayangd3016832019-08-08 07:24:45 -07009446 // Retransmission timer fires in TLP mode.
9447 connection_.GetRetransmissionAlarm()->Fire();
9448 // Verify one packets is forced flushed when writer is blocked.
9449 EXPECT_EQ(1u, connection_.NumQueuedPackets());
9450}
9451
fayang67f82272019-08-14 16:08:45 -07009452// Regresstion test for b/139375344.
9453TEST_P(QuicConnectionTest, RtoForcesSendingPing) {
fayange861aee2019-10-16 13:40:39 -07009454 if (!connection_.session_decides_what_to_write() ||
fayang5f135052019-08-22 17:59:40 -07009455 connection_.PtoEnabled()) {
fayang67f82272019-08-14 16:08:45 -07009456 return;
9457 }
9458 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9459 connection_.SetMaxTailLossProbes(2);
9460 EXPECT_EQ(0u, connection_.GetStats().tlp_count);
9461 EXPECT_EQ(0u, connection_.GetStats().rto_count);
9462
9463 SendStreamDataToPeer(2, "foo", 0, NO_FIN, nullptr);
9464 QuicTime retransmission_time =
9465 connection_.GetRetransmissionAlarm()->deadline();
9466 EXPECT_NE(QuicTime::Zero(), retransmission_time);
9467 // TLP fires.
9468 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
9469 clock_.AdvanceTime(retransmission_time - clock_.Now());
9470 connection_.GetRetransmissionAlarm()->Fire();
9471 EXPECT_EQ(1u, connection_.GetStats().tlp_count);
9472 EXPECT_EQ(0u, connection_.GetStats().rto_count);
9473 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9474
9475 // Packet 1 gets acked.
9476 QuicAckFrame frame = InitAckFrame(1);
9477 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
9478 ProcessAckPacket(1, &frame);
9479 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9480 retransmission_time = connection_.GetRetransmissionAlarm()->deadline();
9481
9482 // RTO fires, verify a PING packet gets sent because there is no data to send.
9483 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(3), _, _));
9484 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
9485 clock_.AdvanceTime(retransmission_time - clock_.Now());
9486 connection_.GetRetransmissionAlarm()->Fire();
9487 EXPECT_EQ(1u, connection_.GetStats().tlp_count);
9488 EXPECT_EQ(1u, connection_.GetStats().rto_count);
9489 EXPECT_EQ(1u, writer_->ping_frames().size());
9490}
9491
fayangce0a3162019-08-15 09:05:36 -07009492TEST_P(QuicConnectionTest, ProbeTimeout) {
fayange861aee2019-10-16 13:40:39 -07009493 if (!connection_.session_decides_what_to_write()) {
fayangce0a3162019-08-15 09:05:36 -07009494 return;
9495 }
9496 SetQuicReloadableFlag(quic_enable_pto, true);
fayangce0a3162019-08-15 09:05:36 -07009497 QuicConfig config;
9498 QuicTagVector connection_options;
9499 connection_options.push_back(k2PTO);
9500 config.SetConnectionOptionsToSend(connection_options);
9501 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9502 connection_.SetFromConfig(config);
9503 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9504
9505 QuicStreamId stream_id = 2;
9506 QuicPacketNumber last_packet;
9507 SendStreamDataToPeer(stream_id, "foooooo", 0, NO_FIN, &last_packet);
9508 SendStreamDataToPeer(stream_id, "foooooo", 7, NO_FIN, &last_packet);
9509 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9510
9511 // Reset stream.
9512 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9513 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9514
9515 // Fire the PTO and verify only the RST_STREAM is resent, not stream data.
9516 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9517 connection_.GetRetransmissionAlarm()->Fire();
9518 EXPECT_EQ(0u, writer_->stream_frames().size());
9519 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
9520 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9521}
9522
fayang97ce41e2019-10-07 08:37:29 -07009523TEST_P(QuicConnectionTest, CloseConnectionAfter6ClientPTOs) {
fayange861aee2019-10-16 13:40:39 -07009524 if (!connection_.session_decides_what_to_write()) {
fayang97ce41e2019-10-07 08:37:29 -07009525 return;
9526 }
9527 SetQuicReloadableFlag(quic_enable_pto, true);
9528 QuicConfig config;
9529 QuicTagVector connection_options;
9530 connection_options.push_back(k1PTO);
9531 connection_options.push_back(k6PTO);
9532 config.SetConnectionOptionsToSend(connection_options);
9533 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9534 connection_.SetFromConfig(config);
9535 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9536
9537 // Send stream data.
9538 SendStreamDataToPeer(
9539 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
9540 0, FIN, nullptr);
9541
9542 // 5PTO + 1 connection close.
rch39c88ab2019-10-16 19:24:40 -07009543 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(6));
fayang97ce41e2019-10-07 08:37:29 -07009544
9545 // Fire the retransmission alarm 5 times.
9546 for (int i = 0; i < 5; ++i) {
9547 connection_.GetRetransmissionAlarm()->Fire();
9548 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
9549 EXPECT_TRUE(connection_.connected());
9550 }
9551
9552 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveTlpCount());
9553 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveRtoCount());
9554 EXPECT_EQ(5u, connection_.sent_packet_manager().GetConsecutivePtoCount());
9555 // Closes connection on 6th PTO.
9556 EXPECT_CALL(visitor_,
9557 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
9558 connection_.GetRetransmissionAlarm()->Fire();
9559 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
9560 EXPECT_FALSE(connection_.connected());
9561 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
9562}
9563
fayangce0a3162019-08-15 09:05:36 -07009564TEST_P(QuicConnectionTest, CloseConnectionAfter7ClientPTOs) {
fayange861aee2019-10-16 13:40:39 -07009565 if (!connection_.session_decides_what_to_write()) {
fayangce0a3162019-08-15 09:05:36 -07009566 return;
9567 }
9568 SetQuicReloadableFlag(quic_enable_pto, true);
9569 QuicConfig config;
9570 QuicTagVector connection_options;
9571 connection_options.push_back(k2PTO);
9572 connection_options.push_back(k7PTO);
9573 config.SetConnectionOptionsToSend(connection_options);
9574 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9575 connection_.SetFromConfig(config);
9576 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9577
9578 // Send stream data.
9579 SendStreamDataToPeer(
9580 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
9581 0, FIN, nullptr);
9582
9583 // Fire the retransmission alarm 6 times.
9584 for (int i = 0; i < 6; ++i) {
9585 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
9586 connection_.GetRetransmissionAlarm()->Fire();
9587 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
9588 EXPECT_TRUE(connection_.connected());
9589 }
9590
9591 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveTlpCount());
9592 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveRtoCount());
9593 EXPECT_EQ(6u, connection_.sent_packet_manager().GetConsecutivePtoCount());
9594 // Closes connection on 7th PTO.
9595 EXPECT_CALL(visitor_,
9596 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07009597 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
fayangce0a3162019-08-15 09:05:36 -07009598 connection_.GetRetransmissionAlarm()->Fire();
9599 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
9600 EXPECT_FALSE(connection_.connected());
9601 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
9602}
9603
9604TEST_P(QuicConnectionTest, CloseConnectionAfter8ClientPTOs) {
fayange861aee2019-10-16 13:40:39 -07009605 if (!connection_.session_decides_what_to_write()) {
fayangce0a3162019-08-15 09:05:36 -07009606 return;
9607 }
9608 SetQuicReloadableFlag(quic_enable_pto, true);
9609 QuicConfig config;
9610 QuicTagVector connection_options;
9611 connection_options.push_back(k2PTO);
9612 connection_options.push_back(k8PTO);
9613 config.SetConnectionOptionsToSend(connection_options);
9614 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9615 connection_.SetFromConfig(config);
9616 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9617
9618 // Send stream data.
9619 SendStreamDataToPeer(
9620 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
9621 0, FIN, nullptr);
9622
9623 // Fire the retransmission alarm 7 times.
9624 for (int i = 0; i < 7; ++i) {
9625 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
9626 connection_.GetRetransmissionAlarm()->Fire();
9627 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
9628 EXPECT_TRUE(connection_.connected());
9629 }
9630
9631 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveTlpCount());
9632 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveRtoCount());
9633 EXPECT_EQ(7u, connection_.sent_packet_manager().GetConsecutivePtoCount());
9634 // Closes connection on 8th PTO.
9635 EXPECT_CALL(visitor_,
9636 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07009637 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
fayangce0a3162019-08-15 09:05:36 -07009638 connection_.GetRetransmissionAlarm()->Fire();
9639 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
9640 EXPECT_FALSE(connection_.connected());
9641 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
9642}
9643
fayang5f135052019-08-22 17:59:40 -07009644TEST_P(QuicConnectionTest, DeprecateHandshakeMode) {
9645 if (!connection_.version().SupportsAntiAmplificationLimit()) {
9646 return;
9647 }
9648 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9649 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9650
9651 // Send CHLO.
9652 connection_.SendCryptoStreamData();
9653 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9654
9655 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
9656 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
9657 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9658 QuicAckFrame frame1 = InitAckFrame(1);
9659 // Received ACK for packet 1.
9660 ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL);
9661
9662 // Verify retransmission alarm is still set because handshake is not
9663 // confirmed although there is nothing in flight.
9664 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9665 EXPECT_EQ(0u, connection_.GetStats().pto_count);
9666 EXPECT_EQ(0u, connection_.GetStats().crypto_retransmit_count);
9667
9668 // PTO fires, verify a PING packet gets sent because there is no data to send.
9669 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
9670 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
9671 connection_.GetRetransmissionAlarm()->Fire();
9672 EXPECT_EQ(1u, connection_.GetStats().pto_count);
9673 EXPECT_EQ(0u, connection_.GetStats().crypto_retransmit_count);
9674 EXPECT_EQ(1u, writer_->ping_frames().size());
9675}
9676
9677TEST_P(QuicConnectionTest, AntiAmplificationLimit) {
9678 if (!connection_.version().SupportsAntiAmplificationLimit()) {
9679 return;
9680 }
9681 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9682 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9683
9684 set_perspective(Perspective::IS_SERVER);
9685 // Verify no data can be sent at the beginning because bytes received is 0.
9686 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9687 connection_.SendCryptoDataWithString("foo", 0);
9688 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9689
9690 // Receives packet 1.
9691 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
9692
9693 const size_t anti_amplification_factor =
9694 GetQuicFlag(FLAGS_quic_anti_amplification_factor);
9695 // Verify now packets can be sent.
9696 for (size_t i = 0; i < anti_amplification_factor; ++i) {
9697 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9698 connection_.SendCryptoDataWithString("foo", i * 3);
9699 // Verify retransmission alarm is not set if throttled by anti-amplification
9700 // limit.
9701 EXPECT_EQ(i != anti_amplification_factor - 1,
9702 connection_.GetRetransmissionAlarm()->IsSet());
9703 }
9704 // Verify server is throttled by anti-amplification limit.
9705 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9706 connection_.SendCryptoDataWithString("foo", anti_amplification_factor * 3);
9707
9708 // Receives packet 2.
9709 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
9710 // Verify more packets can be sent.
9711 for (size_t i = anti_amplification_factor; i < anti_amplification_factor * 2;
9712 ++i) {
9713 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9714 connection_.SendCryptoDataWithString("foo", i * 3);
9715 }
9716 // Verify server is throttled by anti-amplification limit.
9717 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9718 connection_.SendCryptoDataWithString("foo",
9719 2 * anti_amplification_factor * 3);
9720
9721 ProcessPacket(3);
9722 // Verify anti-amplification limit is gone after address validation.
9723 for (size_t i = 0; i < 100; ++i) {
9724 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9725 connection_.SendStreamDataWithString(3, "first", i * 0, NO_FIN);
9726 }
9727}
9728
fkastenholza3660102019-08-28 05:19:24 -07009729TEST_P(QuicConnectionTest, ConnectionCloseFrameType) {
9730 if (!VersionHasIetfQuicFrames(version().transport_version)) {
9731 // Test relevent only for IETF QUIC.
9732 return;
9733 }
9734 const QuicErrorCode kQuicErrorCode = IETF_QUIC_PROTOCOL_VIOLATION;
9735 // Use the (unknown) frame type of 9999 to avoid triggering any logic
9736 // which might be associated with the processing of a known frame type.
9737 const uint64_t kTransportCloseFrameType = 9999u;
9738 QuicFramerPeer::set_current_received_frame_type(
9739 QuicConnectionPeer::GetFramer(&connection_), kTransportCloseFrameType);
9740 // Do a transport connection close
9741 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
9742 connection_.CloseConnection(
9743 kQuicErrorCode, "Some random error message",
9744 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
9745 const std::vector<QuicConnectionCloseFrame>& connection_close_frames =
9746 writer_->connection_close_frames();
9747 ASSERT_EQ(1u, connection_close_frames.size());
9748 EXPECT_EQ(IETF_QUIC_TRANSPORT_CONNECTION_CLOSE,
9749 connection_close_frames[0].close_type);
9750 EXPECT_EQ(kQuicErrorCode, connection_close_frames[0].extracted_error_code);
9751 EXPECT_EQ(kTransportCloseFrameType,
9752 connection_close_frames[0].transport_close_frame_type);
9753}
9754
fayang0fcbf352019-08-30 11:15:58 -07009755// Regression test for b/137401387 and b/138962304.
9756TEST_P(QuicConnectionTest, RtoPacketAsTwo) {
fayange861aee2019-10-16 13:40:39 -07009757 if (!connection_.session_decides_what_to_write() ||
fayang62c291b2019-10-10 11:51:34 -07009758 connection_.PtoEnabled()) {
fayang0fcbf352019-08-30 11:15:58 -07009759 return;
9760 }
9761 connection_.SetMaxTailLossProbes(1);
9762 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
9763 std::string stream_data(3000, 's');
9764 // Send packets 1 - 66 and exhaust cwnd.
9765 for (size_t i = 0; i < 22; ++i) {
9766 // 3 packets for each stream, the first 2 are guaranteed to be full packets.
9767 SendStreamDataToPeer(i + 2, stream_data, 0, FIN, nullptr);
9768 }
9769 CongestionBlockWrites();
9770
9771 // Fires TLP. Please note, this tail loss probe has 1 byte less stream data
9772 // compared to packet 1 because packet number length increases.
9773 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(67), _, _));
9774 connection_.GetRetransmissionAlarm()->Fire();
9775 // Fires RTO. Please note, although packets 2 and 3 *should* be RTOed, but
9776 // packet 2 gets RTOed to two packets because packet number length increases.
9777 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(68), _, _));
9778 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(69), _, _));
9779 connection_.GetRetransmissionAlarm()->Fire();
9780
9781 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9782 // Resets all streams except 2 and ack packets 1 and 2. Now, packet 3 is the
9783 // only one containing retransmittable frames.
9784 for (size_t i = 1; i < 22; ++i) {
9785 notifier_.OnStreamReset(i + 2, QUIC_STREAM_CANCELLED);
9786 }
9787 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
9788 QuicAckFrame frame =
9789 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(3)}});
9790 ProcessAckPacket(1, &frame);
9791 CongestionUnblockWrites();
9792
9793 // Fires TLP, verify a PING gets sent because packet 3 is marked
9794 // RTO_RETRANSMITTED.
9795 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(70), _, _));
9796 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
9797 connection_.GetRetransmissionAlarm()->Fire();
9798}
9799
fayang4c1c2362019-09-13 07:20:01 -07009800TEST_P(QuicConnectionTest, PtoSkipsPacketNumber) {
fayange861aee2019-10-16 13:40:39 -07009801 if (!connection_.session_decides_what_to_write()) {
fayang4c1c2362019-09-13 07:20:01 -07009802 return;
9803 }
9804 SetQuicReloadableFlag(quic_enable_pto, true);
9805 SetQuicReloadableFlag(quic_skip_packet_number_for_pto, true);
9806 QuicConfig config;
9807 QuicTagVector connection_options;
9808 connection_options.push_back(k1PTO);
9809 connection_options.push_back(kPTOS);
9810 config.SetConnectionOptionsToSend(connection_options);
9811 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9812 connection_.SetFromConfig(config);
9813 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9814
9815 QuicStreamId stream_id = 2;
9816 QuicPacketNumber last_packet;
9817 SendStreamDataToPeer(stream_id, "foooooo", 0, NO_FIN, &last_packet);
9818 SendStreamDataToPeer(stream_id, "foooooo", 7, NO_FIN, &last_packet);
9819 EXPECT_EQ(QuicPacketNumber(2), last_packet);
9820 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9821
9822 // Fire PTO and verify the PTO retransmission skips one packet number.
9823 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9824 connection_.GetRetransmissionAlarm()->Fire();
9825 EXPECT_EQ(1u, writer_->stream_frames().size());
9826 EXPECT_EQ(QuicPacketNumber(4), writer_->last_packet_header().packet_number);
9827 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9828}
9829
QUICHE teama6ef0a62019-03-07 20:34:33 -05009830} // namespace
9831} // namespace test
9832} // namespace quic