blob: 534b6a37f846a6ed044a010bf0f1520130cb3e24 [file] [log] [blame]
QUICHE teama6ef0a62019-03-07 20:34:33 -05001// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "net/third_party/quiche/src/quic/core/quic_connection.h"
6
7#include <errno.h>
zhongyi546cc452019-04-12 15:27:49 -07008
QUICHE teama6ef0a62019-03-07 20:34:33 -05009#include <memory>
10#include <ostream>
zhongyi9e843642019-04-12 09:04:54 -070011#include <string>
zhongyi546cc452019-04-12 15:27:49 -070012#include <utility>
zhongyi9e843642019-04-12 09:04:54 -070013
QUICHE teama6ef0a62019-03-07 20:34:33 -050014#include "net/third_party/quiche/src/quic/core/congestion_control/loss_detection_interface.h"
15#include "net/third_party/quiche/src/quic/core/congestion_control/send_algorithm_interface.h"
zhongyi546cc452019-04-12 15:27:49 -070016#include "net/third_party/quiche/src/quic/core/crypto/null_decrypter.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050017#include "net/third_party/quiche/src/quic/core/crypto/null_encrypter.h"
18#include "net/third_party/quiche/src/quic/core/crypto/quic_decrypter.h"
19#include "net/third_party/quiche/src/quic/core/crypto/quic_encrypter.h"
20#include "net/third_party/quiche/src/quic/core/quic_connection_id.h"
21#include "net/third_party/quiche/src/quic/core/quic_packets.h"
22#include "net/third_party/quiche/src/quic/core/quic_simple_buffer_allocator.h"
23#include "net/third_party/quiche/src/quic/core/quic_types.h"
24#include "net/third_party/quiche/src/quic/core/quic_utils.h"
25#include "net/third_party/quiche/src/quic/platform/api/quic_error_code_wrappers.h"
26#include "net/third_party/quiche/src/quic/platform/api/quic_expect_bug.h"
27#include "net/third_party/quiche/src/quic/platform/api/quic_flags.h"
28#include "net/third_party/quiche/src/quic/platform/api/quic_logging.h"
29#include "net/third_party/quiche/src/quic/platform/api/quic_ptr_util.h"
30#include "net/third_party/quiche/src/quic/platform/api/quic_reference_counted.h"
31#include "net/third_party/quiche/src/quic/platform/api/quic_str_cat.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050032#include "net/third_party/quiche/src/quic/platform/api/quic_string_piece.h"
33#include "net/third_party/quiche/src/quic/platform/api/quic_test.h"
34#include "net/third_party/quiche/src/quic/test_tools/mock_clock.h"
35#include "net/third_party/quiche/src/quic/test_tools/mock_random.h"
36#include "net/third_party/quiche/src/quic/test_tools/quic_config_peer.h"
37#include "net/third_party/quiche/src/quic/test_tools/quic_connection_peer.h"
38#include "net/third_party/quiche/src/quic/test_tools/quic_framer_peer.h"
39#include "net/third_party/quiche/src/quic/test_tools/quic_packet_creator_peer.h"
40#include "net/third_party/quiche/src/quic/test_tools/quic_packet_generator_peer.h"
41#include "net/third_party/quiche/src/quic/test_tools/quic_sent_packet_manager_peer.h"
42#include "net/third_party/quiche/src/quic/test_tools/quic_test_utils.h"
43#include "net/third_party/quiche/src/quic/test_tools/simple_data_producer.h"
44#include "net/third_party/quiche/src/quic/test_tools/simple_quic_framer.h"
45#include "net/third_party/quiche/src/quic/test_tools/simple_session_notifier.h"
46
47using testing::_;
48using testing::AnyNumber;
49using testing::AtLeast;
50using testing::DoAll;
51using testing::Exactly;
52using testing::Ge;
53using testing::IgnoreResult;
54using testing::InSequence;
55using testing::Invoke;
56using testing::InvokeWithoutArgs;
57using testing::Lt;
58using testing::Ref;
59using testing::Return;
60using testing::SaveArg;
61using testing::SetArgPointee;
62using testing::StrictMock;
63
64namespace quic {
65namespace test {
66namespace {
67
nharper55fa6132019-05-07 19:37:21 -070068const char data1[] = "foo data";
69const char data2[] = "bar data";
QUICHE teama6ef0a62019-03-07 20:34:33 -050070
71const bool kHasStopWaiting = true;
72
73const int kDefaultRetransmissionTimeMs = 500;
74
QUICHE team548d51b2019-03-14 10:06:54 -070075DiversificationNonce kTestDiversificationNonce = {
76 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a',
77 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b',
78 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b',
79};
80
QUICHE teama6ef0a62019-03-07 20:34:33 -050081const QuicSocketAddress kPeerAddress =
82 QuicSocketAddress(QuicIpAddress::Loopback6(),
83 /*port=*/12345);
84const QuicSocketAddress kSelfAddress =
85 QuicSocketAddress(QuicIpAddress::Loopback6(),
86 /*port=*/443);
87
88Perspective InvertPerspective(Perspective perspective) {
89 return perspective == Perspective::IS_CLIENT ? Perspective::IS_SERVER
90 : Perspective::IS_CLIENT;
91}
92
93QuicStreamId GetNthClientInitiatedStreamId(int n,
94 QuicTransportVersion version) {
dschinazi552accc2019-06-17 17:07:34 -070095 return QuicUtils::GetFirstBidirectionalStreamId(version,
96 Perspective::IS_CLIENT) +
97 n * 2;
QUICHE teama6ef0a62019-03-07 20:34:33 -050098}
99
QUICHE team8c1daa22019-03-13 08:33:41 -0700100QuicLongHeaderType EncryptionlevelToLongHeaderType(EncryptionLevel level) {
101 switch (level) {
QUICHE team6987b4a2019-03-15 16:23:04 -0700102 case ENCRYPTION_INITIAL:
QUICHE team8c1daa22019-03-13 08:33:41 -0700103 return INITIAL;
QUICHE team88ea0082019-03-15 10:05:26 -0700104 case ENCRYPTION_HANDSHAKE:
105 return HANDSHAKE;
QUICHE team8c1daa22019-03-13 08:33:41 -0700106 case ENCRYPTION_ZERO_RTT:
107 return ZERO_RTT_PROTECTED;
108 case ENCRYPTION_FORWARD_SECURE:
109 DCHECK(false);
110 return INVALID_PACKET_TYPE;
111 default:
112 DCHECK(false);
113 return INVALID_PACKET_TYPE;
114 }
115}
116
QUICHE teama6ef0a62019-03-07 20:34:33 -0500117// TaggingEncrypter appends kTagSize bytes of |tag| to the end of each message.
118class TaggingEncrypter : public QuicEncrypter {
119 public:
120 explicit TaggingEncrypter(uint8_t tag) : tag_(tag) {}
121 TaggingEncrypter(const TaggingEncrypter&) = delete;
122 TaggingEncrypter& operator=(const TaggingEncrypter&) = delete;
123
124 ~TaggingEncrypter() override {}
125
126 // QuicEncrypter interface.
dschinazi17d42422019-06-18 16:35:07 -0700127 bool SetKey(QuicStringPiece /*key*/) override { return true; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500128
dschinazi17d42422019-06-18 16:35:07 -0700129 bool SetNoncePrefix(QuicStringPiece /*nonce_prefix*/) override {
130 return true;
131 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500132
dschinazi17d42422019-06-18 16:35:07 -0700133 bool SetIV(QuicStringPiece /*iv*/) override { return true; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500134
dschinazi17d42422019-06-18 16:35:07 -0700135 bool SetHeaderProtectionKey(QuicStringPiece /*key*/) override { return true; }
QUICHE team2d187972019-03-19 16:23:47 -0700136
dschinazi17d42422019-06-18 16:35:07 -0700137 bool EncryptPacket(uint64_t /*packet_number*/,
138 QuicStringPiece /*associated_data*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500139 QuicStringPiece plaintext,
140 char* output,
141 size_t* output_length,
142 size_t max_output_length) override {
143 const size_t len = plaintext.size() + kTagSize;
144 if (max_output_length < len) {
145 return false;
146 }
147 // Memmove is safe for inplace encryption.
148 memmove(output, plaintext.data(), plaintext.size());
149 output += plaintext.size();
150 memset(output, tag_, kTagSize);
151 *output_length = len;
152 return true;
153 }
154
dschinazi17d42422019-06-18 16:35:07 -0700155 std::string GenerateHeaderProtectionMask(
156 QuicStringPiece /*sample*/) override {
QUICHE team2d187972019-03-19 16:23:47 -0700157 return std::string(5, 0);
158 }
159
QUICHE teama6ef0a62019-03-07 20:34:33 -0500160 size_t GetKeySize() const override { return 0; }
161 size_t GetNoncePrefixSize() const override { return 0; }
162 size_t GetIVSize() const override { return 0; }
163
164 size_t GetMaxPlaintextSize(size_t ciphertext_size) const override {
165 return ciphertext_size - kTagSize;
166 }
167
168 size_t GetCiphertextSize(size_t plaintext_size) const override {
169 return plaintext_size + kTagSize;
170 }
171
172 QuicStringPiece GetKey() const override { return QuicStringPiece(); }
173
174 QuicStringPiece GetNoncePrefix() const override { return QuicStringPiece(); }
175
176 private:
177 enum {
178 kTagSize = 12,
179 };
180
181 const uint8_t tag_;
182};
183
184// TaggingDecrypter ensures that the final kTagSize bytes of the message all
185// have the same value and then removes them.
186class TaggingDecrypter : public QuicDecrypter {
187 public:
188 ~TaggingDecrypter() override {}
189
190 // QuicDecrypter interface
dschinazi17d42422019-06-18 16:35:07 -0700191 bool SetKey(QuicStringPiece /*key*/) override { return true; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500192
dschinazi17d42422019-06-18 16:35:07 -0700193 bool SetNoncePrefix(QuicStringPiece /*nonce_prefix*/) override {
194 return true;
195 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500196
dschinazi17d42422019-06-18 16:35:07 -0700197 bool SetIV(QuicStringPiece /*iv*/) override { return true; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500198
dschinazi17d42422019-06-18 16:35:07 -0700199 bool SetHeaderProtectionKey(QuicStringPiece /*key*/) override { return true; }
QUICHE team2d187972019-03-19 16:23:47 -0700200
dschinazi17d42422019-06-18 16:35:07 -0700201 bool SetPreliminaryKey(QuicStringPiece /*key*/) override {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500202 QUIC_BUG << "should not be called";
203 return false;
204 }
205
dschinazi17d42422019-06-18 16:35:07 -0700206 bool SetDiversificationNonce(const DiversificationNonce& /*key*/) override {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500207 return true;
208 }
209
dschinazi17d42422019-06-18 16:35:07 -0700210 bool DecryptPacket(uint64_t /*packet_number*/,
211 QuicStringPiece /*associated_data*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500212 QuicStringPiece ciphertext,
213 char* output,
214 size_t* output_length,
dschinazi17d42422019-06-18 16:35:07 -0700215 size_t /*max_output_length*/) override {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500216 if (ciphertext.size() < kTagSize) {
217 return false;
218 }
219 if (!CheckTag(ciphertext, GetTag(ciphertext))) {
220 return false;
221 }
222 *output_length = ciphertext.size() - kTagSize;
223 memcpy(output, ciphertext.data(), *output_length);
224 return true;
225 }
226
QUICHE team2d187972019-03-19 16:23:47 -0700227 std::string GenerateHeaderProtectionMask(
dschinazi17d42422019-06-18 16:35:07 -0700228 QuicDataReader* /*sample_reader*/) override {
QUICHE team2d187972019-03-19 16:23:47 -0700229 return std::string(5, 0);
230 }
231
QUICHE teama6ef0a62019-03-07 20:34:33 -0500232 size_t GetKeySize() const override { return 0; }
233 size_t GetIVSize() const override { return 0; }
234 QuicStringPiece GetKey() const override { return QuicStringPiece(); }
235 QuicStringPiece GetNoncePrefix() const override { return QuicStringPiece(); }
236 // Use a distinct value starting with 0xFFFFFF, which is never used by TLS.
237 uint32_t cipher_id() const override { return 0xFFFFFFF0; }
238
239 protected:
240 virtual uint8_t GetTag(QuicStringPiece ciphertext) {
241 return ciphertext.data()[ciphertext.size() - 1];
242 }
243
244 private:
245 enum {
246 kTagSize = 12,
247 };
248
249 bool CheckTag(QuicStringPiece ciphertext, uint8_t tag) {
250 for (size_t i = ciphertext.size() - kTagSize; i < ciphertext.size(); i++) {
251 if (ciphertext.data()[i] != tag) {
252 return false;
253 }
254 }
255
256 return true;
257 }
258};
259
260// StringTaggingDecrypter ensures that the final kTagSize bytes of the message
261// match the expected value.
262class StrictTaggingDecrypter : public TaggingDecrypter {
263 public:
264 explicit StrictTaggingDecrypter(uint8_t tag) : tag_(tag) {}
265 ~StrictTaggingDecrypter() override {}
266
267 // TaggingQuicDecrypter
dschinazi17d42422019-06-18 16:35:07 -0700268 uint8_t GetTag(QuicStringPiece /*ciphertext*/) override { return tag_; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500269
270 // Use a distinct value starting with 0xFFFFFF, which is never used by TLS.
271 uint32_t cipher_id() const override { return 0xFFFFFFF1; }
272
273 private:
274 const uint8_t tag_;
275};
276
277class TestConnectionHelper : public QuicConnectionHelperInterface {
278 public:
279 TestConnectionHelper(MockClock* clock, MockRandom* random_generator)
280 : clock_(clock), random_generator_(random_generator) {
281 clock_->AdvanceTime(QuicTime::Delta::FromSeconds(1));
282 }
283 TestConnectionHelper(const TestConnectionHelper&) = delete;
284 TestConnectionHelper& operator=(const TestConnectionHelper&) = delete;
285
286 // QuicConnectionHelperInterface
287 const QuicClock* GetClock() const override { return clock_; }
288
289 QuicRandom* GetRandomGenerator() override { return random_generator_; }
290
291 QuicBufferAllocator* GetStreamSendBufferAllocator() override {
292 return &buffer_allocator_;
293 }
294
295 private:
296 MockClock* clock_;
297 MockRandom* random_generator_;
298 SimpleBufferAllocator buffer_allocator_;
299};
300
301class TestAlarmFactory : public QuicAlarmFactory {
302 public:
303 class TestAlarm : public QuicAlarm {
304 public:
305 explicit TestAlarm(QuicArenaScopedPtr<QuicAlarm::Delegate> delegate)
306 : QuicAlarm(std::move(delegate)) {}
307
308 void SetImpl() override {}
309 void CancelImpl() override {}
310 using QuicAlarm::Fire;
311 };
312
313 TestAlarmFactory() {}
314 TestAlarmFactory(const TestAlarmFactory&) = delete;
315 TestAlarmFactory& operator=(const TestAlarmFactory&) = delete;
316
317 QuicAlarm* CreateAlarm(QuicAlarm::Delegate* delegate) override {
318 return new TestAlarm(QuicArenaScopedPtr<QuicAlarm::Delegate>(delegate));
319 }
320
321 QuicArenaScopedPtr<QuicAlarm> CreateAlarm(
322 QuicArenaScopedPtr<QuicAlarm::Delegate> delegate,
323 QuicConnectionArena* arena) override {
324 return arena->New<TestAlarm>(std::move(delegate));
325 }
326};
327
328class TestPacketWriter : public QuicPacketWriter {
329 public:
330 TestPacketWriter(ParsedQuicVersion version, MockClock* clock)
331 : version_(version),
332 framer_(SupportedVersions(version_), Perspective::IS_SERVER),
333 last_packet_size_(0),
334 write_blocked_(false),
335 write_should_fail_(false),
336 block_on_next_flush_(false),
337 block_on_next_write_(false),
338 next_packet_too_large_(false),
339 always_get_packet_too_large_(false),
340 is_write_blocked_data_buffered_(false),
341 is_batch_mode_(false),
342 final_bytes_of_last_packet_(0),
343 final_bytes_of_previous_packet_(0),
344 use_tagging_decrypter_(false),
345 packets_write_attempts_(0),
346 clock_(clock),
347 write_pause_time_delta_(QuicTime::Delta::Zero()),
dschinazi66dea072019-04-09 11:41:06 -0700348 max_packet_size_(kMaxOutgoingPacketSize),
QUICHE teama6ef0a62019-03-07 20:34:33 -0500349 supports_release_time_(false) {}
350 TestPacketWriter(const TestPacketWriter&) = delete;
351 TestPacketWriter& operator=(const TestPacketWriter&) = delete;
352
353 // QuicPacketWriter interface
354 WriteResult WritePacket(const char* buffer,
355 size_t buf_len,
dschinazi17d42422019-06-18 16:35:07 -0700356 const QuicIpAddress& /*self_address*/,
357 const QuicSocketAddress& /*peer_address*/,
358 PerPacketOptions* /*options*/) override {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500359 QuicEncryptedPacket packet(buffer, buf_len);
360 ++packets_write_attempts_;
361
362 if (packet.length() >= sizeof(final_bytes_of_last_packet_)) {
363 final_bytes_of_previous_packet_ = final_bytes_of_last_packet_;
364 memcpy(&final_bytes_of_last_packet_, packet.data() + packet.length() - 4,
365 sizeof(final_bytes_of_last_packet_));
366 }
367
368 if (use_tagging_decrypter_) {
zhongyi546cc452019-04-12 15:27:49 -0700369 if (framer_.framer()->version().KnowsWhichDecrypterToUse()) {
370 framer_.framer()->InstallDecrypter(ENCRYPTION_INITIAL,
371 QuicMakeUnique<TaggingDecrypter>());
372 framer_.framer()->InstallDecrypter(ENCRYPTION_ZERO_RTT,
373 QuicMakeUnique<TaggingDecrypter>());
374 framer_.framer()->InstallDecrypter(ENCRYPTION_FORWARD_SECURE,
375 QuicMakeUnique<TaggingDecrypter>());
376 } else {
377 framer_.framer()->SetDecrypter(ENCRYPTION_INITIAL,
378 QuicMakeUnique<TaggingDecrypter>());
379 }
380 } else if (framer_.framer()->version().KnowsWhichDecrypterToUse()) {
381 framer_.framer()->InstallDecrypter(
382 ENCRYPTION_FORWARD_SECURE,
383 QuicMakeUnique<NullDecrypter>(Perspective::IS_SERVER));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500384 }
385 EXPECT_TRUE(framer_.ProcessPacket(packet));
386 if (block_on_next_write_) {
387 write_blocked_ = true;
388 block_on_next_write_ = false;
389 }
390 if (next_packet_too_large_) {
391 next_packet_too_large_ = false;
392 return WriteResult(WRITE_STATUS_ERROR, QUIC_EMSGSIZE);
393 }
394 if (always_get_packet_too_large_) {
395 return WriteResult(WRITE_STATUS_ERROR, QUIC_EMSGSIZE);
396 }
397 if (IsWriteBlocked()) {
398 return WriteResult(is_write_blocked_data_buffered_
399 ? WRITE_STATUS_BLOCKED_DATA_BUFFERED
400 : WRITE_STATUS_BLOCKED,
401 0);
402 }
403
404 if (ShouldWriteFail()) {
405 return WriteResult(WRITE_STATUS_ERROR, 0);
406 }
407
408 last_packet_size_ = packet.length();
409 last_packet_header_ = framer_.header();
410
411 if (!write_pause_time_delta_.IsZero()) {
412 clock_->AdvanceTime(write_pause_time_delta_);
413 }
414 return WriteResult(WRITE_STATUS_OK, last_packet_size_);
415 }
416
417 bool ShouldWriteFail() { return write_should_fail_; }
418
419 bool IsWriteBlocked() const override { return write_blocked_; }
420
421 void SetWriteBlocked() { write_blocked_ = true; }
422
423 void SetWritable() override { write_blocked_ = false; }
424
425 void SetShouldWriteFail() { write_should_fail_ = true; }
426
427 QuicByteCount GetMaxPacketSize(
428 const QuicSocketAddress& /*peer_address*/) const override {
429 return max_packet_size_;
430 }
431
dschinazi61eb6432019-06-14 16:27:16 -0700432 bool SupportsReleaseTime() const override { return supports_release_time_; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500433
434 bool IsBatchMode() const override { return is_batch_mode_; }
435
dschinazi17d42422019-06-18 16:35:07 -0700436 char* GetNextWriteLocation(
437 const QuicIpAddress& /*self_address*/,
438 const QuicSocketAddress& /*peer_address*/) override {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500439 return nullptr;
440 }
441
442 WriteResult Flush() override {
443 if (block_on_next_flush_) {
444 block_on_next_flush_ = false;
445 SetWriteBlocked();
446 return WriteResult(WRITE_STATUS_BLOCKED, /*errno*/ -1);
447 }
448 return WriteResult(WRITE_STATUS_OK, 0);
449 }
450
451 void BlockOnNextFlush() { block_on_next_flush_ = true; }
452
453 void BlockOnNextWrite() { block_on_next_write_ = true; }
454
455 void SimulateNextPacketTooLarge() { next_packet_too_large_ = true; }
456
457 void AlwaysGetPacketTooLarge() { always_get_packet_too_large_ = true; }
458
459 // Sets the amount of time that the writer should before the actual write.
460 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
461 write_pause_time_delta_ = delta;
462 }
463
464 void SetBatchMode(bool new_value) { is_batch_mode_ = new_value; }
465
466 const QuicPacketHeader& header() { return framer_.header(); }
467
468 size_t frame_count() const { return framer_.num_frames(); }
469
470 const std::vector<QuicAckFrame>& ack_frames() const {
471 return framer_.ack_frames();
472 }
473
474 const std::vector<QuicStopWaitingFrame>& stop_waiting_frames() const {
475 return framer_.stop_waiting_frames();
476 }
477
478 const std::vector<QuicConnectionCloseFrame>& connection_close_frames() const {
479 return framer_.connection_close_frames();
480 }
481
482 const std::vector<QuicRstStreamFrame>& rst_stream_frames() const {
483 return framer_.rst_stream_frames();
484 }
485
486 const std::vector<std::unique_ptr<QuicStreamFrame>>& stream_frames() const {
487 return framer_.stream_frames();
488 }
489
490 const std::vector<std::unique_ptr<QuicCryptoFrame>>& crypto_frames() const {
491 return framer_.crypto_frames();
492 }
493
494 const std::vector<QuicPingFrame>& ping_frames() const {
495 return framer_.ping_frames();
496 }
497
498 const std::vector<QuicMessageFrame>& message_frames() const {
499 return framer_.message_frames();
500 }
501
502 const std::vector<QuicWindowUpdateFrame>& window_update_frames() const {
503 return framer_.window_update_frames();
504 }
505
506 const std::vector<QuicPaddingFrame>& padding_frames() const {
507 return framer_.padding_frames();
508 }
509
510 const std::vector<QuicPathChallengeFrame>& path_challenge_frames() const {
511 return framer_.path_challenge_frames();
512 }
513
514 const std::vector<QuicPathResponseFrame>& path_response_frames() const {
515 return framer_.path_response_frames();
516 }
517
518 size_t last_packet_size() { return last_packet_size_; }
519
520 const QuicPacketHeader& last_packet_header() const {
521 return last_packet_header_;
522 }
523
524 const QuicVersionNegotiationPacket* version_negotiation_packet() {
525 return framer_.version_negotiation_packet();
526 }
527
528 void set_is_write_blocked_data_buffered(bool buffered) {
529 is_write_blocked_data_buffered_ = buffered;
530 }
531
532 void set_perspective(Perspective perspective) {
533 // We invert perspective here, because the framer needs to parse packets
534 // we send.
535 QuicFramerPeer::SetPerspective(framer_.framer(),
536 InvertPerspective(perspective));
537 }
538
539 // final_bytes_of_last_packet_ returns the last four bytes of the previous
540 // packet as a little-endian, uint32_t. This is intended to be used with a
541 // TaggingEncrypter so that tests can determine which encrypter was used for
542 // a given packet.
543 uint32_t final_bytes_of_last_packet() { return final_bytes_of_last_packet_; }
544
545 // Returns the final bytes of the second to last packet.
546 uint32_t final_bytes_of_previous_packet() {
547 return final_bytes_of_previous_packet_;
548 }
549
550 void use_tagging_decrypter() { use_tagging_decrypter_ = true; }
551
552 uint32_t packets_write_attempts() { return packets_write_attempts_; }
553
554 void Reset() { framer_.Reset(); }
555
556 void SetSupportedVersions(const ParsedQuicVersionVector& versions) {
557 framer_.SetSupportedVersions(versions);
558 }
559
560 void set_max_packet_size(QuicByteCount max_packet_size) {
561 max_packet_size_ = max_packet_size;
562 }
563
564 void set_supports_release_time(bool supports_release_time) {
565 supports_release_time_ = supports_release_time;
566 }
567
568 SimpleQuicFramer* framer() { return &framer_; }
569
570 private:
571 ParsedQuicVersion version_;
572 SimpleQuicFramer framer_;
573 size_t last_packet_size_;
574 QuicPacketHeader last_packet_header_;
575 bool write_blocked_;
576 bool write_should_fail_;
577 bool block_on_next_flush_;
578 bool block_on_next_write_;
579 bool next_packet_too_large_;
580 bool always_get_packet_too_large_;
581 bool is_write_blocked_data_buffered_;
582 bool is_batch_mode_;
583 uint32_t final_bytes_of_last_packet_;
584 uint32_t final_bytes_of_previous_packet_;
585 bool use_tagging_decrypter_;
586 uint32_t packets_write_attempts_;
587 MockClock* clock_;
588 // If non-zero, the clock will pause during WritePacket for this amount of
589 // time.
590 QuicTime::Delta write_pause_time_delta_;
591 QuicByteCount max_packet_size_;
592 bool supports_release_time_;
593};
594
595class TestConnection : public QuicConnection {
596 public:
597 TestConnection(QuicConnectionId connection_id,
598 QuicSocketAddress address,
599 TestConnectionHelper* helper,
600 TestAlarmFactory* alarm_factory,
601 TestPacketWriter* writer,
602 Perspective perspective,
603 ParsedQuicVersion version)
604 : QuicConnection(connection_id,
605 address,
606 helper,
607 alarm_factory,
608 writer,
609 /* owns_writer= */ false,
610 perspective,
611 SupportedVersions(version)),
612 notifier_(nullptr) {
613 writer->set_perspective(perspective);
614 SetEncrypter(ENCRYPTION_FORWARD_SECURE,
615 QuicMakeUnique<NullEncrypter>(perspective));
616 SetDataProducer(&producer_);
617 }
618 TestConnection(const TestConnection&) = delete;
619 TestConnection& operator=(const TestConnection&) = delete;
620
QUICHE teama6ef0a62019-03-07 20:34:33 -0500621 void SetSendAlgorithm(SendAlgorithmInterface* send_algorithm) {
622 QuicConnectionPeer::SetSendAlgorithm(this, send_algorithm);
623 }
624
625 void SetLossAlgorithm(LossDetectionInterface* loss_algorithm) {
626 QuicConnectionPeer::SetLossAlgorithm(this, loss_algorithm);
627 }
628
dschinazi17d42422019-06-18 16:35:07 -0700629 void SendPacket(EncryptionLevel /*level*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500630 uint64_t packet_number,
631 std::unique_ptr<QuicPacket> packet,
632 HasRetransmittableData retransmittable,
633 bool has_ack,
634 bool has_pending_frames) {
dschinazi66dea072019-04-09 11:41:06 -0700635 char buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -0500636 size_t encrypted_length =
637 QuicConnectionPeer::GetFramer(this)->EncryptPayload(
QUICHE team6987b4a2019-03-15 16:23:04 -0700638 ENCRYPTION_INITIAL, QuicPacketNumber(packet_number), *packet,
dschinazi66dea072019-04-09 11:41:06 -0700639 buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500640 SerializedPacket serialized_packet(
641 QuicPacketNumber(packet_number), PACKET_4BYTE_PACKET_NUMBER, buffer,
642 encrypted_length, has_ack, has_pending_frames);
643 if (retransmittable == HAS_RETRANSMITTABLE_DATA) {
644 serialized_packet.retransmittable_frames.push_back(
645 QuicFrame(QuicStreamFrame()));
646 }
647 OnSerializedPacket(&serialized_packet);
648 }
649
650 QuicConsumedData SaveAndSendStreamData(QuicStreamId id,
651 const struct iovec* iov,
652 int iov_count,
653 size_t total_length,
654 QuicStreamOffset offset,
655 StreamSendingState state) {
fayanga4b37b22019-06-18 13:37:47 -0700656 ScopedPacketFlusher flusher(this);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500657 producer_.SaveStreamData(id, iov, iov_count, 0u, total_length);
658 if (notifier_ != nullptr) {
659 return notifier_->WriteOrBufferData(id, total_length, state);
660 }
661 return QuicConnection::SendStreamData(id, total_length, offset, state);
662 }
663
664 QuicConsumedData SendStreamDataWithString(QuicStreamId id,
665 QuicStringPiece data,
666 QuicStreamOffset offset,
667 StreamSendingState state) {
fayanga4b37b22019-06-18 13:37:47 -0700668 ScopedPacketFlusher flusher(this);
nharper46833c32019-05-15 21:33:05 -0700669 if (!QuicUtils::IsCryptoStreamId(transport_version(), id) &&
QUICHE team6987b4a2019-03-15 16:23:04 -0700670 this->encryption_level() == ENCRYPTION_INITIAL) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500671 this->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
672 }
673 struct iovec iov;
674 MakeIOVector(data, &iov);
675 return SaveAndSendStreamData(id, &iov, 1, data.length(), offset, state);
676 }
677
QUICHE teamcd098022019-03-22 18:49:55 -0700678 QuicConsumedData SendApplicationDataAtLevel(EncryptionLevel encryption_level,
679 QuicStreamId id,
680 QuicStringPiece data,
681 QuicStreamOffset offset,
682 StreamSendingState state) {
fayanga4b37b22019-06-18 13:37:47 -0700683 ScopedPacketFlusher flusher(this);
QUICHE teamcd098022019-03-22 18:49:55 -0700684 DCHECK(encryption_level >= ENCRYPTION_ZERO_RTT);
685 SetEncrypter(encryption_level, QuicMakeUnique<TaggingEncrypter>(0x01));
686 SetDefaultEncryptionLevel(encryption_level);
687 struct iovec iov;
688 MakeIOVector(data, &iov);
689 return SaveAndSendStreamData(id, &iov, 1, data.length(), offset, state);
690 }
691
QUICHE teama6ef0a62019-03-07 20:34:33 -0500692 QuicConsumedData SendStreamData3() {
693 return SendStreamDataWithString(
694 GetNthClientInitiatedStreamId(1, transport_version()), "food", 0,
695 NO_FIN);
696 }
697
698 QuicConsumedData SendStreamData5() {
699 return SendStreamDataWithString(
700 GetNthClientInitiatedStreamId(2, transport_version()), "food2", 0,
701 NO_FIN);
702 }
703
704 // Ensures the connection can write stream data before writing.
705 QuicConsumedData EnsureWritableAndSendStreamData5() {
706 EXPECT_TRUE(CanWriteStreamData());
707 return SendStreamData5();
708 }
709
710 // The crypto stream has special semantics so that it is not blocked by a
711 // congestion window limitation, and also so that it gets put into a separate
712 // packet (so that it is easier to reason about a crypto frame not being
713 // split needlessly across packet boundaries). As a result, we have separate
714 // tests for some cases for this stream.
715 QuicConsumedData SendCryptoStreamData() {
716 QuicStreamOffset offset = 0;
717 QuicStringPiece data("chlo");
nharper46833c32019-05-15 21:33:05 -0700718 return SendCryptoDataWithString(data, offset);
719 }
720
721 QuicConsumedData SendCryptoDataWithString(QuicStringPiece data,
722 QuicStreamOffset offset) {
QUICHE teamea740082019-03-11 17:58:43 -0700723 if (!QuicVersionUsesCryptoFrames(transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500724 return SendStreamDataWithString(
725 QuicUtils::GetCryptoStreamId(transport_version()), data, offset,
726 NO_FIN);
727 }
QUICHE team6987b4a2019-03-15 16:23:04 -0700728 producer_.SaveCryptoData(ENCRYPTION_INITIAL, offset, data);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500729 size_t bytes_written;
730 if (notifier_) {
731 bytes_written =
QUICHE team6987b4a2019-03-15 16:23:04 -0700732 notifier_->WriteCryptoData(ENCRYPTION_INITIAL, data.length(), offset);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500733 } else {
QUICHE team6987b4a2019-03-15 16:23:04 -0700734 bytes_written = QuicConnection::SendCryptoData(ENCRYPTION_INITIAL,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500735 data.length(), offset);
736 }
737 return QuicConsumedData(bytes_written, /*fin_consumed*/ false);
738 }
739
740 void set_version(ParsedQuicVersion version) {
741 QuicConnectionPeer::GetFramer(this)->set_version(version);
742 }
743
744 void SetSupportedVersions(const ParsedQuicVersionVector& versions) {
745 QuicConnectionPeer::GetFramer(this)->SetSupportedVersions(versions);
746 QuicConnectionPeer::SetNoVersionNegotiation(this, versions.size() == 1);
747 writer()->SetSupportedVersions(versions);
748 }
749
750 void set_perspective(Perspective perspective) {
751 writer()->set_perspective(perspective);
752 QuicConnectionPeer::SetPerspective(this, perspective);
753 }
754
755 // Enable path MTU discovery. Assumes that the test is performed from the
756 // client perspective and the higher value of MTU target is used.
757 void EnablePathMtuDiscovery(MockSendAlgorithm* send_algorithm) {
758 ASSERT_EQ(Perspective::IS_CLIENT, perspective());
759
760 QuicConfig config;
761 QuicTagVector connection_options;
762 connection_options.push_back(kMTUH);
763 config.SetConnectionOptionsToSend(connection_options);
764 EXPECT_CALL(*send_algorithm, SetFromConfig(_, _));
765 SetFromConfig(config);
766
767 // Normally, the pacing would be disabled in the test, but calling
768 // SetFromConfig enables it. Set nearly-infinite bandwidth to make the
769 // pacing algorithm work.
770 EXPECT_CALL(*send_algorithm, PacingRate(_))
771 .WillRepeatedly(Return(QuicBandwidth::Infinite()));
772 }
773
774 TestAlarmFactory::TestAlarm* GetAckAlarm() {
775 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
776 QuicConnectionPeer::GetAckAlarm(this));
777 }
778
779 TestAlarmFactory::TestAlarm* GetPingAlarm() {
780 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
781 QuicConnectionPeer::GetPingAlarm(this));
782 }
783
784 TestAlarmFactory::TestAlarm* GetRetransmissionAlarm() {
785 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
786 QuicConnectionPeer::GetRetransmissionAlarm(this));
787 }
788
789 TestAlarmFactory::TestAlarm* GetSendAlarm() {
790 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
791 QuicConnectionPeer::GetSendAlarm(this));
792 }
793
794 TestAlarmFactory::TestAlarm* GetTimeoutAlarm() {
795 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
796 QuicConnectionPeer::GetTimeoutAlarm(this));
797 }
798
799 TestAlarmFactory::TestAlarm* GetMtuDiscoveryAlarm() {
800 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
801 QuicConnectionPeer::GetMtuDiscoveryAlarm(this));
802 }
803
804 TestAlarmFactory::TestAlarm* GetPathDegradingAlarm() {
805 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
806 QuicConnectionPeer::GetPathDegradingAlarm(this));
807 }
808
809 TestAlarmFactory::TestAlarm* GetProcessUndecryptablePacketsAlarm() {
810 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
811 QuicConnectionPeer::GetProcessUndecryptablePacketsAlarm(this));
812 }
813
814 void SetMaxTailLossProbes(size_t max_tail_loss_probes) {
815 QuicSentPacketManagerPeer::SetMaxTailLossProbes(
816 QuicConnectionPeer::GetSentPacketManager(this), max_tail_loss_probes);
817 }
818
819 QuicByteCount GetBytesInFlight() {
ianswett9f459cb2019-04-21 06:39:59 -0700820 return QuicConnectionPeer::GetSentPacketManager(this)->GetBytesInFlight();
QUICHE teama6ef0a62019-03-07 20:34:33 -0500821 }
822
823 void set_notifier(SimpleSessionNotifier* notifier) { notifier_ = notifier; }
824
825 void ReturnEffectivePeerAddressForNextPacket(const QuicSocketAddress& addr) {
826 next_effective_peer_addr_ = QuicMakeUnique<QuicSocketAddress>(addr);
827 }
828
nharper46833c32019-05-15 21:33:05 -0700829 SimpleDataProducer* producer() { return &producer_; }
830
QUICHE teama6ef0a62019-03-07 20:34:33 -0500831 using QuicConnection::active_effective_peer_migration_type;
832 using QuicConnection::IsCurrentPacketConnectivityProbing;
833 using QuicConnection::SelectMutualVersion;
834 using QuicConnection::SendProbingRetransmissions;
835 using QuicConnection::set_defer_send_in_response_to_packets;
836
837 protected:
838 QuicSocketAddress GetEffectivePeerAddressFromCurrentPacket() const override {
839 if (next_effective_peer_addr_) {
840 return *std::move(next_effective_peer_addr_);
841 }
842 return QuicConnection::GetEffectivePeerAddressFromCurrentPacket();
843 }
844
845 private:
846 TestPacketWriter* writer() {
847 return static_cast<TestPacketWriter*>(QuicConnection::writer());
848 }
849
850 SimpleDataProducer producer_;
851
852 SimpleSessionNotifier* notifier_;
853
854 std::unique_ptr<QuicSocketAddress> next_effective_peer_addr_;
855};
856
857enum class AckResponse { kDefer, kImmediate };
858
859// Run tests with combinations of {ParsedQuicVersion, AckResponse}.
860struct TestParams {
861 TestParams(ParsedQuicVersion version,
862 AckResponse ack_response,
863 bool no_stop_waiting)
864 : version(version),
865 ack_response(ack_response),
866 no_stop_waiting(no_stop_waiting) {}
867
868 friend std::ostream& operator<<(std::ostream& os, const TestParams& p) {
869 os << "{ client_version: " << ParsedQuicVersionToString(p.version)
870 << " ack_response: "
871 << (p.ack_response == AckResponse::kDefer ? "defer" : "immediate")
872 << " no_stop_waiting: " << p.no_stop_waiting << " }";
873 return os;
874 }
875
876 ParsedQuicVersion version;
877 AckResponse ack_response;
878 bool no_stop_waiting;
879};
880
881// Constructs various test permutations.
882std::vector<TestParams> GetTestParams() {
883 QuicFlagSaver flags;
wub49855982019-05-01 14:16:26 -0700884 SetQuicFlag(FLAGS_quic_supports_tls_handshake, true);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500885 std::vector<TestParams> params;
886 ParsedQuicVersionVector all_supported_versions = AllSupportedVersions();
887 for (size_t i = 0; i < all_supported_versions.size(); ++i) {
888 for (AckResponse ack_response :
889 {AckResponse::kDefer, AckResponse::kImmediate}) {
890 for (bool no_stop_waiting : {true, false}) {
891 // After version 43, never use STOP_WAITING.
fayangd4291e42019-05-30 10:31:21 -0700892 params.push_back(
893 TestParams(all_supported_versions[i], ack_response,
894 !VersionHasIetfInvariantHeader(
895 all_supported_versions[i].transport_version)
896 ? no_stop_waiting
897 : true));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500898 }
899 }
900 }
901 return params;
902}
903
904class QuicConnectionTest : public QuicTestWithParam<TestParams> {
905 protected:
906 QuicConnectionTest()
907 : connection_id_(TestConnectionId()),
908 framer_(SupportedVersions(version()),
909 QuicTime::Zero(),
910 Perspective::IS_CLIENT,
911 connection_id_.length()),
912 send_algorithm_(new StrictMock<MockSendAlgorithm>),
913 loss_algorithm_(new MockLossAlgorithm()),
914 helper_(new TestConnectionHelper(&clock_, &random_generator_)),
915 alarm_factory_(new TestAlarmFactory()),
916 peer_framer_(SupportedVersions(version()),
917 QuicTime::Zero(),
918 Perspective::IS_SERVER,
919 connection_id_.length()),
920 peer_creator_(connection_id_,
921 &peer_framer_,
922 /*delegate=*/nullptr),
923 writer_(new TestPacketWriter(version(), &clock_)),
924 connection_(connection_id_,
925 kPeerAddress,
926 helper_.get(),
927 alarm_factory_.get(),
928 writer_.get(),
929 Perspective::IS_CLIENT,
930 version()),
931 creator_(QuicConnectionPeer::GetPacketCreator(&connection_)),
932 generator_(QuicConnectionPeer::GetPacketGenerator(&connection_)),
933 manager_(QuicConnectionPeer::GetSentPacketManager(&connection_)),
nharper46833c32019-05-15 21:33:05 -0700934 frame1_(0, false, 0, QuicStringPiece(data1)),
935 frame2_(0, false, 3, QuicStringPiece(data2)),
936 crypto_frame_(ENCRYPTION_INITIAL, 0, QuicStringPiece(data1)),
QUICHE teama6ef0a62019-03-07 20:34:33 -0500937 packet_number_length_(PACKET_4BYTE_PACKET_NUMBER),
938 connection_id_included_(CONNECTION_ID_PRESENT),
939 notifier_(&connection_) {
wub49855982019-05-01 14:16:26 -0700940 SetQuicFlag(FLAGS_quic_supports_tls_handshake, true);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500941 connection_.set_defer_send_in_response_to_packets(GetParam().ack_response ==
942 AckResponse::kDefer);
nharper2c9f02a2019-05-08 10:25:50 -0700943 for (EncryptionLevel level :
944 {ENCRYPTION_ZERO_RTT, ENCRYPTION_FORWARD_SECURE}) {
945 peer_creator_.SetEncrypter(
946 level, QuicMakeUnique<NullEncrypter>(peer_framer_.perspective()));
947 }
dschinazi6ece5002019-05-22 06:35:49 -0700948 if (version().handshake_protocol == PROTOCOL_TLS1_3) {
949 connection_.SetEncrypter(
950 ENCRYPTION_INITIAL,
951 QuicMakeUnique<NullEncrypter>(Perspective::IS_CLIENT));
952 connection_.InstallDecrypter(
953 ENCRYPTION_INITIAL,
954 QuicMakeUnique<NullDecrypter>(Perspective::IS_CLIENT));
955 }
dschinazi7b9278c2019-05-20 07:36:21 -0700956 QuicFramerPeer::SetLastSerializedServerConnectionId(
QUICHE teama6ef0a62019-03-07 20:34:33 -0500957 QuicConnectionPeer::GetFramer(&connection_), connection_id_);
fayangd4291e42019-05-30 10:31:21 -0700958 if (VersionHasIetfInvariantHeader(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500959 EXPECT_TRUE(QuicConnectionPeer::GetNoStopWaitingFrames(&connection_));
960 } else {
961 QuicConnectionPeer::SetNoStopWaitingFrames(&connection_,
962 GetParam().no_stop_waiting);
963 }
nharper46833c32019-05-15 21:33:05 -0700964 QuicStreamId stream_id;
965 if (QuicVersionUsesCryptoFrames(version().transport_version)) {
966 stream_id = QuicUtils::GetFirstBidirectionalStreamId(
967 version().transport_version, Perspective::IS_CLIENT);
968 } else {
969 stream_id = QuicUtils::GetCryptoStreamId(version().transport_version);
970 }
971 frame1_.stream_id = stream_id;
972 frame2_.stream_id = stream_id;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500973 connection_.set_visitor(&visitor_);
974 if (connection_.session_decides_what_to_write()) {
975 connection_.SetSessionNotifier(&notifier_);
976 connection_.set_notifier(&notifier_);
977 }
978 connection_.SetSendAlgorithm(send_algorithm_);
979 connection_.SetLossAlgorithm(loss_algorithm_.get());
980 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
981 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
982 .Times(AnyNumber());
983 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
984 .WillRepeatedly(Return(kDefaultTCPMSS));
985 EXPECT_CALL(*send_algorithm_, PacingRate(_))
986 .WillRepeatedly(Return(QuicBandwidth::Zero()));
987 EXPECT_CALL(*send_algorithm_, HasReliableBandwidthEstimate())
988 .Times(AnyNumber());
989 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
990 .Times(AnyNumber())
991 .WillRepeatedly(Return(QuicBandwidth::Zero()));
992 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
993 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
994 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
995 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).Times(AnyNumber());
996 EXPECT_CALL(visitor_, HasPendingHandshake()).Times(AnyNumber());
997 if (connection_.session_decides_what_to_write()) {
998 EXPECT_CALL(visitor_, OnCanWrite())
999 .WillRepeatedly(
1000 Invoke(&notifier_, &SimpleSessionNotifier::OnCanWrite));
1001 } else {
1002 EXPECT_CALL(visitor_, OnCanWrite()).Times(AnyNumber());
1003 }
1004 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
1005 .WillRepeatedly(Return(false));
1006 EXPECT_CALL(visitor_, OnCongestionWindowChange(_)).Times(AnyNumber());
1007 EXPECT_CALL(visitor_, OnConnectivityProbeReceived(_, _)).Times(AnyNumber());
1008 EXPECT_CALL(visitor_, OnForwardProgressConfirmed()).Times(AnyNumber());
1009
1010 EXPECT_CALL(*loss_algorithm_, GetLossTimeout())
1011 .WillRepeatedly(Return(QuicTime::Zero()));
1012 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
1013 .Times(AnyNumber());
zhongyi546cc452019-04-12 15:27:49 -07001014
1015 if (connection_.version().KnowsWhichDecrypterToUse()) {
1016 connection_.InstallDecrypter(
1017 ENCRYPTION_FORWARD_SECURE,
1018 QuicMakeUnique<NullDecrypter>(Perspective::IS_CLIENT));
1019 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001020 }
1021
1022 QuicConnectionTest(const QuicConnectionTest&) = delete;
1023 QuicConnectionTest& operator=(const QuicConnectionTest&) = delete;
1024
1025 ParsedQuicVersion version() { return GetParam().version; }
1026
QUICHE teama6ef0a62019-03-07 20:34:33 -05001027 QuicStopWaitingFrame* stop_waiting() {
1028 QuicConnectionPeer::PopulateStopWaitingFrame(&connection_, &stop_waiting_);
1029 return &stop_waiting_;
1030 }
1031
1032 QuicPacketNumber least_unacked() {
1033 if (writer_->stop_waiting_frames().empty()) {
1034 return QuicPacketNumber();
1035 }
1036 return writer_->stop_waiting_frames()[0].least_unacked;
1037 }
1038
1039 void use_tagging_decrypter() { writer_->use_tagging_decrypter(); }
1040
zhongyi546cc452019-04-12 15:27:49 -07001041 void SetDecrypter(EncryptionLevel level,
1042 std::unique_ptr<QuicDecrypter> decrypter) {
1043 if (connection_.version().KnowsWhichDecrypterToUse()) {
1044 connection_.InstallDecrypter(level, std::move(decrypter));
1045 connection_.RemoveDecrypter(ENCRYPTION_INITIAL);
1046 } else {
1047 connection_.SetDecrypter(level, std::move(decrypter));
1048 }
1049 }
1050
QUICHE teama6ef0a62019-03-07 20:34:33 -05001051 void ProcessPacket(uint64_t number) {
1052 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
1053 ProcessDataPacket(number);
1054 if (connection_.GetSendAlarm()->IsSet()) {
1055 connection_.GetSendAlarm()->Fire();
1056 }
1057 }
1058
1059 void ProcessReceivedPacket(const QuicSocketAddress& self_address,
1060 const QuicSocketAddress& peer_address,
1061 const QuicReceivedPacket& packet) {
1062 connection_.ProcessUdpPacket(self_address, peer_address, packet);
1063 if (connection_.GetSendAlarm()->IsSet()) {
1064 connection_.GetSendAlarm()->Fire();
1065 }
1066 }
1067
1068 void ProcessFramePacket(QuicFrame frame) {
1069 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
1070 }
1071
1072 void ProcessFramePacketWithAddresses(QuicFrame frame,
1073 QuicSocketAddress self_address,
1074 QuicSocketAddress peer_address) {
1075 QuicFrames frames;
1076 frames.push_back(QuicFrame(frame));
1077 QuicPacketCreatorPeer::SetSendVersionInPacket(
1078 &peer_creator_, connection_.perspective() == Perspective::IS_SERVER);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001079
dschinazi66dea072019-04-09 11:41:06 -07001080 char buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05001081 SerializedPacket serialized_packet =
dschinazi66dea072019-04-09 11:41:06 -07001082 QuicPacketCreatorPeer::SerializeAllFrames(
1083 &peer_creator_, frames, buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001084 connection_.ProcessUdpPacket(
1085 self_address, peer_address,
1086 QuicReceivedPacket(serialized_packet.encrypted_buffer,
1087 serialized_packet.encrypted_length, clock_.Now()));
1088 if (connection_.GetSendAlarm()->IsSet()) {
1089 connection_.GetSendAlarm()->Fire();
1090 }
1091 }
1092
1093 // Bypassing the packet creator is unrealistic, but allows us to process
1094 // packets the QuicPacketCreator won't allow us to create.
1095 void ForceProcessFramePacket(QuicFrame frame) {
1096 QuicFrames frames;
1097 frames.push_back(QuicFrame(frame));
zhongyi546cc452019-04-12 15:27:49 -07001098 bool send_version = connection_.perspective() == Perspective::IS_SERVER;
1099 if (connection_.version().KnowsWhichDecrypterToUse()) {
1100 send_version = true;
1101 }
1102 QuicPacketCreatorPeer::SetSendVersionInPacket(&peer_creator_, send_version);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001103 QuicPacketHeader header;
1104 QuicPacketCreatorPeer::FillPacketHeader(&peer_creator_, &header);
dschinazi66dea072019-04-09 11:41:06 -07001105 char encrypted_buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05001106 size_t length = peer_framer_.BuildDataPacket(
dschinazi66dea072019-04-09 11:41:06 -07001107 header, frames, encrypted_buffer, kMaxOutgoingPacketSize,
1108 ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001109 DCHECK_GT(length, 0u);
1110
1111 const size_t encrypted_length = peer_framer_.EncryptInPlace(
QUICHE team6987b4a2019-03-15 16:23:04 -07001112 ENCRYPTION_INITIAL, header.packet_number,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001113 GetStartOfEncryptedData(peer_framer_.version().transport_version,
1114 header),
dschinazi66dea072019-04-09 11:41:06 -07001115 length, kMaxOutgoingPacketSize, encrypted_buffer);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001116 DCHECK_GT(encrypted_length, 0u);
1117
1118 connection_.ProcessUdpPacket(
1119 kSelfAddress, kPeerAddress,
1120 QuicReceivedPacket(encrypted_buffer, encrypted_length, clock_.Now()));
1121 }
1122
1123 size_t ProcessFramePacketAtLevel(uint64_t number,
1124 QuicFrame frame,
1125 EncryptionLevel level) {
1126 QuicPacketHeader header;
1127 header.destination_connection_id = connection_id_;
1128 header.packet_number_length = packet_number_length_;
1129 header.destination_connection_id_included = connection_id_included_;
fayangd4291e42019-05-30 10:31:21 -07001130 if ((VersionHasIetfInvariantHeader(peer_framer_.transport_version()) ||
QUICHE team2252b702019-05-14 23:55:14 -04001131 GetQuicRestartFlag(quic_do_not_override_connection_id)) &&
QUICHE teama6ef0a62019-03-07 20:34:33 -05001132 peer_framer_.perspective() == Perspective::IS_SERVER) {
1133 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1134 }
zhongyi546cc452019-04-12 15:27:49 -07001135 if (level == ENCRYPTION_INITIAL &&
1136 peer_framer_.version().KnowsWhichDecrypterToUse()) {
1137 header.version_flag = true;
1138 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
1139 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
QUICHE team2252b702019-05-14 23:55:14 -04001140 }
1141 if ((GetQuicRestartFlag(quic_do_not_override_connection_id) ||
1142 (level == ENCRYPTION_INITIAL &&
1143 peer_framer_.version().KnowsWhichDecrypterToUse())) &&
1144 header.version_flag &&
1145 peer_framer_.perspective() == Perspective::IS_SERVER) {
1146 header.source_connection_id = connection_id_;
1147 header.source_connection_id_included = CONNECTION_ID_PRESENT;
zhongyi546cc452019-04-12 15:27:49 -07001148 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001149 header.packet_number = QuicPacketNumber(number);
1150 QuicFrames frames;
1151 frames.push_back(frame);
1152 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
QUICHE teamcd098022019-03-22 18:49:55 -07001153 // Set the correct encryption level and encrypter on peer_creator and
1154 // peer_framer, respectively.
1155 peer_creator_.set_encryption_level(level);
1156 if (QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_) >
1157 ENCRYPTION_INITIAL) {
1158 peer_framer_.SetEncrypter(
1159 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
1160 QuicMakeUnique<TaggingEncrypter>(0x01));
1161 // Set the corresponding decrypter.
zhongyi546cc452019-04-12 15:27:49 -07001162 if (connection_.version().KnowsWhichDecrypterToUse()) {
1163 connection_.InstallDecrypter(
1164 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
1165 QuicMakeUnique<StrictTaggingDecrypter>(0x01));
1166 connection_.RemoveDecrypter(ENCRYPTION_INITIAL);
1167 } else {
1168 connection_.SetDecrypter(
1169 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
1170 QuicMakeUnique<StrictTaggingDecrypter>(0x01));
1171 }
QUICHE teamcd098022019-03-22 18:49:55 -07001172 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001173
dschinazi66dea072019-04-09 11:41:06 -07001174 char buffer[kMaxOutgoingPacketSize];
1175 size_t encrypted_length =
1176 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
1177 buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001178 connection_.ProcessUdpPacket(
1179 kSelfAddress, kPeerAddress,
QUICHE teamcd098022019-03-22 18:49:55 -07001180 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1181 if (connection_.GetSendAlarm()->IsSet()) {
1182 connection_.GetSendAlarm()->Fire();
1183 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001184 return encrypted_length;
1185 }
1186
1187 size_t ProcessDataPacket(uint64_t number) {
nharper2c9f02a2019-05-08 10:25:50 -07001188 return ProcessDataPacketAtLevel(number, false, ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001189 }
1190
1191 size_t ProcessDataPacket(QuicPacketNumber packet_number) {
nharper2c9f02a2019-05-08 10:25:50 -07001192 return ProcessDataPacketAtLevel(packet_number, false,
1193 ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001194 }
1195
1196 size_t ProcessDataPacketAtLevel(QuicPacketNumber packet_number,
1197 bool has_stop_waiting,
1198 EncryptionLevel level) {
1199 return ProcessDataPacketAtLevel(packet_number.ToUint64(), has_stop_waiting,
1200 level);
1201 }
1202
dschinazi17d42422019-06-18 16:35:07 -07001203 size_t ProcessCryptoPacketAtLevel(uint64_t number,
1204 EncryptionLevel /*level*/) {
fayangc31c9952019-06-05 13:54:48 -07001205 QuicPacketHeader header = ConstructPacketHeader(number, ENCRYPTION_INITIAL);
nharper46833c32019-05-15 21:33:05 -07001206 QuicFrames frames;
1207 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1208 frames.push_back(QuicFrame(&crypto_frame_));
1209 } else {
1210 frames.push_back(QuicFrame(frame1_));
1211 }
1212 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
1213 char buffer[kMaxOutgoingPacketSize];
1214 peer_creator_.set_encryption_level(ENCRYPTION_INITIAL);
fayangc31c9952019-06-05 13:54:48 -07001215 size_t encrypted_length = peer_framer_.EncryptPayload(
1216 ENCRYPTION_INITIAL, QuicPacketNumber(number), *packet, buffer,
1217 kMaxOutgoingPacketSize);
nharper46833c32019-05-15 21:33:05 -07001218 connection_.ProcessUdpPacket(
1219 kSelfAddress, kPeerAddress,
1220 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1221 if (connection_.GetSendAlarm()->IsSet()) {
1222 connection_.GetSendAlarm()->Fire();
1223 }
1224 return encrypted_length;
1225 }
1226
QUICHE teama6ef0a62019-03-07 20:34:33 -05001227 size_t ProcessDataPacketAtLevel(uint64_t number,
1228 bool has_stop_waiting,
1229 EncryptionLevel level) {
1230 std::unique_ptr<QuicPacket> packet(
QUICHE team8c1daa22019-03-13 08:33:41 -07001231 ConstructDataPacket(number, has_stop_waiting, level));
dschinazi66dea072019-04-09 11:41:06 -07001232 char buffer[kMaxOutgoingPacketSize];
QUICHE teamcd098022019-03-22 18:49:55 -07001233 peer_creator_.set_encryption_level(level);
dschinazi66dea072019-04-09 11:41:06 -07001234 size_t encrypted_length =
1235 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
1236 buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001237 connection_.ProcessUdpPacket(
1238 kSelfAddress, kPeerAddress,
1239 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1240 if (connection_.GetSendAlarm()->IsSet()) {
1241 connection_.GetSendAlarm()->Fire();
1242 }
1243 return encrypted_length;
1244 }
1245
1246 void ProcessClosePacket(uint64_t number) {
1247 std::unique_ptr<QuicPacket> packet(ConstructClosePacket(number));
dschinazi66dea072019-04-09 11:41:06 -07001248 char buffer[kMaxOutgoingPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07001249 size_t encrypted_length = peer_framer_.EncryptPayload(
1250 ENCRYPTION_INITIAL, QuicPacketNumber(number), *packet, buffer,
dschinazi66dea072019-04-09 11:41:06 -07001251 kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001252 connection_.ProcessUdpPacket(
1253 kSelfAddress, kPeerAddress,
1254 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
1255 }
1256
1257 QuicByteCount SendStreamDataToPeer(QuicStreamId id,
1258 QuicStringPiece data,
1259 QuicStreamOffset offset,
1260 StreamSendingState state,
1261 QuicPacketNumber* last_packet) {
1262 QuicByteCount packet_size;
1263 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1264 .WillOnce(SaveArg<3>(&packet_size));
1265 connection_.SendStreamDataWithString(id, data, offset, state);
1266 if (last_packet != nullptr) {
1267 *last_packet = creator_->packet_number();
1268 }
1269 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1270 .Times(AnyNumber());
1271 return packet_size;
1272 }
1273
1274 void SendAckPacketToPeer() {
1275 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1276 {
fayanga4b37b22019-06-18 13:37:47 -07001277 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001278 connection_.SendAck();
1279 }
1280 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1281 .Times(AnyNumber());
1282 }
1283
1284 void SendRstStream(QuicStreamId id,
1285 QuicRstStreamErrorCode error,
1286 QuicStreamOffset bytes_written) {
1287 if (connection_.session_decides_what_to_write()) {
1288 notifier_.WriteOrBufferRstStream(id, error, bytes_written);
1289 connection_.OnStreamReset(id, error);
1290 return;
1291 }
1292 std::unique_ptr<QuicRstStreamFrame> rst_stream =
1293 QuicMakeUnique<QuicRstStreamFrame>(1, id, error, bytes_written);
1294 if (connection_.SendControlFrame(QuicFrame(rst_stream.get()))) {
1295 rst_stream.release();
1296 }
1297 connection_.OnStreamReset(id, error);
1298 }
1299
zhongyifbb25772019-04-10 16:54:08 -07001300 void SendPing() {
1301 if (connection_.session_decides_what_to_write()) {
1302 notifier_.WriteOrBufferPing();
1303 } else {
1304 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
1305 }
1306 }
1307
QUICHE teama6ef0a62019-03-07 20:34:33 -05001308 void ProcessAckPacket(uint64_t packet_number, QuicAckFrame* frame) {
1309 if (packet_number > 1) {
1310 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, packet_number - 1);
1311 } else {
1312 QuicPacketCreatorPeer::ClearPacketNumber(&peer_creator_);
1313 }
1314 ProcessFramePacket(QuicFrame(frame));
1315 }
1316
1317 void ProcessAckPacket(QuicAckFrame* frame) {
1318 ProcessFramePacket(QuicFrame(frame));
1319 }
1320
1321 void ProcessStopWaitingPacket(QuicStopWaitingFrame frame) {
1322 ProcessFramePacket(QuicFrame(frame));
1323 }
1324
1325 size_t ProcessStopWaitingPacketAtLevel(uint64_t number,
1326 QuicStopWaitingFrame frame,
dschinazi17d42422019-06-18 16:35:07 -07001327 EncryptionLevel /*level*/) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001328 return ProcessFramePacketAtLevel(number, QuicFrame(frame),
1329 ENCRYPTION_ZERO_RTT);
1330 }
1331
1332 void ProcessGoAwayPacket(QuicGoAwayFrame* frame) {
1333 ProcessFramePacket(QuicFrame(frame));
1334 }
1335
1336 bool IsMissing(uint64_t number) {
fayangc31c9952019-06-05 13:54:48 -07001337 return IsAwaitingPacket(connection_.ack_frame(), QuicPacketNumber(number),
QUICHE teama6ef0a62019-03-07 20:34:33 -05001338 QuicPacketNumber());
1339 }
1340
1341 std::unique_ptr<QuicPacket> ConstructPacket(const QuicPacketHeader& header,
1342 const QuicFrames& frames) {
1343 auto packet = BuildUnsizedDataPacket(&peer_framer_, header, frames);
1344 EXPECT_NE(nullptr, packet.get());
1345 return packet;
1346 }
1347
nharper46833c32019-05-15 21:33:05 -07001348 QuicPacketHeader ConstructPacketHeader(uint64_t number,
1349 EncryptionLevel level) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001350 QuicPacketHeader header;
fayangd4291e42019-05-30 10:31:21 -07001351 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version()) &&
QUICHE team8c1daa22019-03-13 08:33:41 -07001352 level < ENCRYPTION_FORWARD_SECURE) {
1353 // Set long header type accordingly.
1354 header.version_flag = true;
1355 header.long_packet_type = EncryptionlevelToLongHeaderType(level);
1356 if (QuicVersionHasLongHeaderLengths(
1357 peer_framer_.version().transport_version)) {
1358 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
1359 if (header.long_packet_type == INITIAL) {
1360 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
1361 }
1362 }
1363 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001364 // Set connection_id to peer's in memory representation as this data packet
1365 // is created by peer_framer.
QUICHE team2252b702019-05-14 23:55:14 -04001366 if (GetQuicRestartFlag(quic_do_not_override_connection_id) &&
1367 peer_framer_.perspective() == Perspective::IS_SERVER) {
1368 header.source_connection_id = connection_id_;
1369 header.source_connection_id_included = connection_id_included_;
1370 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1371 } else {
1372 header.destination_connection_id = connection_id_;
1373 header.destination_connection_id_included = connection_id_included_;
1374 }
fayangd4291e42019-05-30 10:31:21 -07001375 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version()) &&
QUICHE teama6ef0a62019-03-07 20:34:33 -05001376 peer_framer_.perspective() == Perspective::IS_SERVER) {
1377 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
QUICHE team8c1daa22019-03-13 08:33:41 -07001378 if (header.version_flag) {
1379 header.source_connection_id = connection_id_;
1380 header.source_connection_id_included = CONNECTION_ID_PRESENT;
1381 if (GetParam().version.handshake_protocol == PROTOCOL_QUIC_CRYPTO &&
1382 header.long_packet_type == ZERO_RTT_PROTECTED) {
QUICHE team548d51b2019-03-14 10:06:54 -07001383 header.nonce = &kTestDiversificationNonce;
QUICHE team8c1daa22019-03-13 08:33:41 -07001384 }
1385 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001386 }
QUICHE team2252b702019-05-14 23:55:14 -04001387 header.packet_number_length = packet_number_length_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001388 header.packet_number = QuicPacketNumber(number);
nharper46833c32019-05-15 21:33:05 -07001389 return header;
1390 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001391
nharper46833c32019-05-15 21:33:05 -07001392 std::unique_ptr<QuicPacket> ConstructDataPacket(uint64_t number,
1393 bool has_stop_waiting,
1394 EncryptionLevel level) {
1395 QuicPacketHeader header = ConstructPacketHeader(number, level);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001396 QuicFrames frames;
1397 frames.push_back(QuicFrame(frame1_));
1398 if (has_stop_waiting) {
1399 frames.push_back(QuicFrame(stop_waiting_));
1400 }
1401 return ConstructPacket(header, frames);
1402 }
1403
1404 OwningSerializedPacketPointer ConstructProbingPacket() {
fkastenholz305e1732019-06-18 05:01:22 -07001405 if (VersionHasIetfQuicFrames(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001406 QuicPathFrameBuffer payload = {
1407 {0xde, 0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xfe}};
1408 return QuicPacketCreatorPeer::
1409 SerializePathChallengeConnectivityProbingPacket(&peer_creator_,
1410 &payload);
1411 }
1412 return QuicPacketCreatorPeer::SerializeConnectivityProbingPacket(
1413 &peer_creator_);
1414 }
1415
1416 std::unique_ptr<QuicPacket> ConstructClosePacket(uint64_t number) {
1417 QuicPacketHeader header;
1418 // Set connection_id to peer's in memory representation as this connection
1419 // close packet is created by peer_framer.
QUICHE team2252b702019-05-14 23:55:14 -04001420 if (GetQuicRestartFlag(quic_do_not_override_connection_id) &&
QUICHE teama6ef0a62019-03-07 20:34:33 -05001421 peer_framer_.perspective() == Perspective::IS_SERVER) {
QUICHE team2252b702019-05-14 23:55:14 -04001422 header.source_connection_id = connection_id_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001423 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
fayangd4291e42019-05-30 10:31:21 -07001424 if (!VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04001425 header.source_connection_id_included = CONNECTION_ID_PRESENT;
1426 }
1427 } else {
1428 header.destination_connection_id = connection_id_;
fayangd4291e42019-05-30 10:31:21 -07001429 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04001430 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1431 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001432 }
1433
QUICHE team2252b702019-05-14 23:55:14 -04001434 header.packet_number = QuicPacketNumber(number);
1435
fkastenholze9d71a82019-04-09 05:12:13 -07001436 QuicConnectionCloseFrame qccf(QUIC_PEER_GOING_AWAY);
fkastenholz305e1732019-06-18 05:01:22 -07001437 if (VersionHasIetfQuicFrames(peer_framer_.transport_version())) {
1438 // Default close-type is Google QUIC. If doing IETF QUIC then
fkastenholz04bd4f32019-04-16 12:24:38 -07001439 // set close type to be IETF CC/T.
fkastenholz72f509b2019-04-10 09:17:49 -07001440 qccf.close_type = IETF_QUIC_TRANSPORT_CONNECTION_CLOSE;
1441 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001442
1443 QuicFrames frames;
1444 frames.push_back(QuicFrame(&qccf));
1445 return ConstructPacket(header, frames);
1446 }
1447
1448 QuicTime::Delta DefaultRetransmissionTime() {
1449 return QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
1450 }
1451
1452 QuicTime::Delta DefaultDelayedAckTime() {
1453 return QuicTime::Delta::FromMilliseconds(kDefaultDelayedAckTimeMs);
1454 }
1455
1456 const QuicStopWaitingFrame InitStopWaitingFrame(uint64_t least_unacked) {
1457 QuicStopWaitingFrame frame;
1458 frame.least_unacked = QuicPacketNumber(least_unacked);
1459 return frame;
1460 }
1461
1462 // Construct a ack_frame that acks all packet numbers between 1 and
1463 // |largest_acked|, except |missing|.
1464 // REQUIRES: 1 <= |missing| < |largest_acked|
1465 QuicAckFrame ConstructAckFrame(uint64_t largest_acked, uint64_t missing) {
1466 return ConstructAckFrame(QuicPacketNumber(largest_acked),
1467 QuicPacketNumber(missing));
1468 }
1469
1470 QuicAckFrame ConstructAckFrame(QuicPacketNumber largest_acked,
1471 QuicPacketNumber missing) {
1472 if (missing == QuicPacketNumber(1)) {
1473 return InitAckFrame({{missing + 1, largest_acked + 1}});
1474 }
1475 return InitAckFrame(
1476 {{QuicPacketNumber(1), missing}, {missing + 1, largest_acked + 1}});
1477 }
1478
1479 // Undo nacking a packet within the frame.
1480 void AckPacket(QuicPacketNumber arrived, QuicAckFrame* frame) {
1481 EXPECT_FALSE(frame->packets.Contains(arrived));
1482 frame->packets.Add(arrived);
1483 }
1484
1485 void TriggerConnectionClose() {
1486 // Send an erroneous packet to close the connection.
QUICHE teamcd098022019-03-22 18:49:55 -07001487 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, _,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001488 ConnectionCloseSource::FROM_SELF));
QUICHE teamcd098022019-03-22 18:49:55 -07001489 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1490 // Triggers a connection by receiving ACK of unsent packet.
1491 QuicAckFrame frame = InitAckFrame(10000);
1492 ProcessAckPacket(1, &frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001493
1494 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1495 nullptr);
1496 }
1497
1498 void BlockOnNextWrite() {
1499 writer_->BlockOnNextWrite();
1500 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
1501 }
1502
1503 void SimulateNextPacketTooLarge() { writer_->SimulateNextPacketTooLarge(); }
1504
1505 void AlwaysGetPacketTooLarge() { writer_->AlwaysGetPacketTooLarge(); }
1506
1507 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
1508 writer_->SetWritePauseTimeDelta(delta);
1509 }
1510
1511 void CongestionBlockWrites() {
1512 EXPECT_CALL(*send_algorithm_, CanSend(_))
1513 .WillRepeatedly(testing::Return(false));
1514 }
1515
1516 void CongestionUnblockWrites() {
1517 EXPECT_CALL(*send_algorithm_, CanSend(_))
1518 .WillRepeatedly(testing::Return(true));
1519 }
1520
1521 void set_perspective(Perspective perspective) {
1522 connection_.set_perspective(perspective);
1523 if (perspective == Perspective::IS_SERVER) {
1524 connection_.set_can_truncate_connection_ids(true);
1525 }
1526 QuicFramerPeer::SetPerspective(&peer_framer_,
1527 InvertPerspective(perspective));
1528 }
1529
1530 void set_packets_between_probes_base(
1531 const QuicPacketCount packets_between_probes_base) {
1532 QuicConnectionPeer::SetPacketsBetweenMtuProbes(&connection_,
1533 packets_between_probes_base);
1534 QuicConnectionPeer::SetNextMtuProbeAt(
1535 &connection_, QuicPacketNumber(packets_between_probes_base));
1536 }
1537
1538 bool IsDefaultTestConfiguration() {
1539 TestParams p = GetParam();
1540 return p.ack_response == AckResponse::kImmediate &&
1541 p.version == AllSupportedVersions()[0] && p.no_stop_waiting;
1542 }
1543
1544 QuicConnectionId connection_id_;
1545 QuicFramer framer_;
1546
1547 MockSendAlgorithm* send_algorithm_;
1548 std::unique_ptr<MockLossAlgorithm> loss_algorithm_;
1549 MockClock clock_;
1550 MockRandom random_generator_;
1551 SimpleBufferAllocator buffer_allocator_;
1552 std::unique_ptr<TestConnectionHelper> helper_;
1553 std::unique_ptr<TestAlarmFactory> alarm_factory_;
1554 QuicFramer peer_framer_;
1555 QuicPacketCreator peer_creator_;
1556 std::unique_ptr<TestPacketWriter> writer_;
1557 TestConnection connection_;
1558 QuicPacketCreator* creator_;
1559 QuicPacketGenerator* generator_;
1560 QuicSentPacketManager* manager_;
1561 StrictMock<MockQuicConnectionVisitor> visitor_;
1562
1563 QuicStreamFrame frame1_;
1564 QuicStreamFrame frame2_;
nharper46833c32019-05-15 21:33:05 -07001565 QuicCryptoFrame crypto_frame_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001566 QuicAckFrame ack_;
1567 QuicStopWaitingFrame stop_waiting_;
1568 QuicPacketNumberLength packet_number_length_;
1569 QuicConnectionIdIncluded connection_id_included_;
1570
1571 SimpleSessionNotifier notifier_;
1572};
1573
1574// Run all end to end tests with all supported versions.
1575INSTANTIATE_TEST_SUITE_P(SupportedVersion,
1576 QuicConnectionTest,
1577 ::testing::ValuesIn(GetTestParams()));
1578
1579TEST_P(QuicConnectionTest, SelfAddressChangeAtClient) {
1580 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1581
1582 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
1583 EXPECT_TRUE(connection_.connected());
1584
nharper46833c32019-05-15 21:33:05 -07001585 QuicFrame frame;
1586 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1587 frame = QuicFrame(&crypto_frame_);
1588 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1589 } else {
1590 frame = QuicFrame(QuicStreamFrame(
1591 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
1592 0u, QuicStringPiece()));
1593 EXPECT_CALL(visitor_, OnStreamFrame(_));
1594 }
1595 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001596 // Cause change in self_address.
1597 QuicIpAddress host;
1598 host.FromString("1.1.1.1");
1599 QuicSocketAddress self_address(host, 123);
nharper46833c32019-05-15 21:33:05 -07001600 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1601 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1602 } else {
1603 EXPECT_CALL(visitor_, OnStreamFrame(_));
1604 }
1605 ProcessFramePacketWithAddresses(frame, self_address, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001606 EXPECT_TRUE(connection_.connected());
1607}
1608
1609TEST_P(QuicConnectionTest, SelfAddressChangeAtServer) {
1610 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1611
1612 set_perspective(Perspective::IS_SERVER);
1613 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1614
1615 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1616 EXPECT_TRUE(connection_.connected());
1617
nharper46833c32019-05-15 21:33:05 -07001618 QuicFrame frame;
1619 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1620 frame = QuicFrame(&crypto_frame_);
1621 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1622 } else {
1623 frame = QuicFrame(QuicStreamFrame(
1624 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
1625 0u, QuicStringPiece()));
1626 EXPECT_CALL(visitor_, OnStreamFrame(_));
1627 }
1628 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001629 // Cause change in self_address.
1630 QuicIpAddress host;
1631 host.FromString("1.1.1.1");
1632 QuicSocketAddress self_address(host, 123);
1633 EXPECT_CALL(visitor_, AllowSelfAddressChange()).WillOnce(Return(false));
1634 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_ERROR_MIGRATING_ADDRESS, _, _));
nharper46833c32019-05-15 21:33:05 -07001635 ProcessFramePacketWithAddresses(frame, self_address, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001636 EXPECT_FALSE(connection_.connected());
1637}
1638
1639TEST_P(QuicConnectionTest, AllowSelfAddressChangeToMappedIpv4AddressAtServer) {
1640 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1641
1642 set_perspective(Perspective::IS_SERVER);
1643 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1644
1645 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1646 EXPECT_TRUE(connection_.connected());
1647
nharper46833c32019-05-15 21:33:05 -07001648 QuicFrame frame;
1649 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1650 frame = QuicFrame(&crypto_frame_);
1651 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(3);
1652 } else {
1653 frame = QuicFrame(QuicStreamFrame(
1654 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
1655 0u, QuicStringPiece()));
1656 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(3);
1657 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001658 QuicIpAddress host;
1659 host.FromString("1.1.1.1");
1660 QuicSocketAddress self_address1(host, 443);
nharper46833c32019-05-15 21:33:05 -07001661 ProcessFramePacketWithAddresses(frame, self_address1, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001662 // Cause self_address change to mapped Ipv4 address.
1663 QuicIpAddress host2;
1664 host2.FromString(
1665 QuicStrCat("::ffff:", connection_.self_address().host().ToString()));
1666 QuicSocketAddress self_address2(host2, connection_.self_address().port());
nharper46833c32019-05-15 21:33:05 -07001667 ProcessFramePacketWithAddresses(frame, self_address2, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001668 EXPECT_TRUE(connection_.connected());
1669 // self_address change back to Ipv4 address.
nharper46833c32019-05-15 21:33:05 -07001670 ProcessFramePacketWithAddresses(frame, self_address1, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001671 EXPECT_TRUE(connection_.connected());
1672}
1673
1674TEST_P(QuicConnectionTest, ClientAddressChangeAndPacketReordered) {
1675 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1676 set_perspective(Perspective::IS_SERVER);
1677 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1678
1679 // Clear direct_peer_address.
1680 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1681 // Clear effective_peer_address, it is the same as direct_peer_address for
1682 // this test.
1683 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1684 QuicSocketAddress());
1685
nharper46833c32019-05-15 21:33:05 -07001686 QuicFrame frame;
1687 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1688 frame = QuicFrame(&crypto_frame_);
1689 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1690 } else {
1691 frame = QuicFrame(QuicStreamFrame(
1692 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
1693 0u, QuicStringPiece()));
1694 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1695 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001696 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001697 const QuicSocketAddress kNewPeerAddress =
1698 QuicSocketAddress(QuicIpAddress::Loopback6(),
1699 /*port=*/23456);
nharper46833c32019-05-15 21:33:05 -07001700 ProcessFramePacketWithAddresses(frame, kSelfAddress, kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001701 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1702 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1703
1704 // Decrease packet number to simulate out-of-order packets.
1705 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 4);
1706 // This is an old packet, do not migrate.
1707 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
nharper46833c32019-05-15 21:33:05 -07001708 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001709 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1710 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1711}
1712
1713TEST_P(QuicConnectionTest, PeerAddressChangeAtServer) {
1714 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1715 set_perspective(Perspective::IS_SERVER);
1716 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1717 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1718
1719 // Clear direct_peer_address.
1720 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1721 // Clear effective_peer_address, it is the same as direct_peer_address for
1722 // this test.
1723 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1724 QuicSocketAddress());
1725 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1726
nharper46833c32019-05-15 21:33:05 -07001727 QuicFrame frame;
1728 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1729 frame = QuicFrame(&crypto_frame_);
1730 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1731 } else {
1732 frame = QuicFrame(QuicStreamFrame(
1733 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
1734 0u, QuicStringPiece()));
1735 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1736 }
1737 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001738 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1739 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1740
1741 // Process another packet with a different peer address on server side will
1742 // start connection migration.
1743 const QuicSocketAddress kNewPeerAddress =
1744 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
1745 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
nharper46833c32019-05-15 21:33:05 -07001746 ProcessFramePacketWithAddresses(frame, kSelfAddress, kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001747 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1748 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1749}
1750
1751TEST_P(QuicConnectionTest, EffectivePeerAddressChangeAtServer) {
1752 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1753 set_perspective(Perspective::IS_SERVER);
1754 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1755 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1756
1757 // Clear direct_peer_address.
1758 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1759 // Clear effective_peer_address, it is different from direct_peer_address for
1760 // this test.
1761 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1762 QuicSocketAddress());
1763 const QuicSocketAddress kEffectivePeerAddress =
1764 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/43210);
1765 connection_.ReturnEffectivePeerAddressForNextPacket(kEffectivePeerAddress);
1766
nharper46833c32019-05-15 21:33:05 -07001767 QuicFrame frame;
1768 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1769 frame = QuicFrame(&crypto_frame_);
1770 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1771 } else {
1772 frame = QuicFrame(QuicStreamFrame(
1773 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
1774 0u, QuicStringPiece()));
1775 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1776 }
1777 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001778 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1779 EXPECT_EQ(kEffectivePeerAddress, connection_.effective_peer_address());
1780
1781 // Process another packet with the same direct peer address and different
1782 // effective peer address on server side will start connection migration.
1783 const QuicSocketAddress kNewEffectivePeerAddress =
1784 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/54321);
1785 connection_.ReturnEffectivePeerAddressForNextPacket(kNewEffectivePeerAddress);
1786 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
nharper46833c32019-05-15 21:33:05 -07001787 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001788 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1789 EXPECT_EQ(kNewEffectivePeerAddress, connection_.effective_peer_address());
1790
1791 // Process another packet with a different direct peer address and the same
1792 // effective peer address on server side will not start connection migration.
1793 const QuicSocketAddress kNewPeerAddress =
1794 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
1795 connection_.ReturnEffectivePeerAddressForNextPacket(kNewEffectivePeerAddress);
1796 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
1797 // ack_frame is used to complete the migration started by the last packet, we
1798 // need to make sure a new migration does not start after the previous one is
1799 // completed.
1800 QuicAckFrame ack_frame = InitAckFrame(1);
1801 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
1802 ProcessFramePacketWithAddresses(QuicFrame(&ack_frame), kSelfAddress,
1803 kNewPeerAddress);
1804 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1805 EXPECT_EQ(kNewEffectivePeerAddress, connection_.effective_peer_address());
1806
1807 // Process another packet with different direct peer address and different
1808 // effective peer address on server side will start connection migration.
1809 const QuicSocketAddress kNewerEffectivePeerAddress =
1810 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/65432);
1811 const QuicSocketAddress kFinalPeerAddress =
1812 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/34567);
1813 connection_.ReturnEffectivePeerAddressForNextPacket(
1814 kNewerEffectivePeerAddress);
1815 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
nharper46833c32019-05-15 21:33:05 -07001816 ProcessFramePacketWithAddresses(frame, kSelfAddress, kFinalPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001817 EXPECT_EQ(kFinalPeerAddress, connection_.peer_address());
1818 EXPECT_EQ(kNewerEffectivePeerAddress, connection_.effective_peer_address());
1819 EXPECT_EQ(PORT_CHANGE, connection_.active_effective_peer_migration_type());
1820
1821 // While the previous migration is ongoing, process another packet with the
1822 // same direct peer address and different effective peer address on server
1823 // side will start a new connection migration.
1824 const QuicSocketAddress kNewestEffectivePeerAddress =
1825 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/65430);
1826 connection_.ReturnEffectivePeerAddressForNextPacket(
1827 kNewestEffectivePeerAddress);
1828 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
1829 EXPECT_CALL(*send_algorithm_, OnConnectionMigration()).Times(1);
nharper46833c32019-05-15 21:33:05 -07001830 ProcessFramePacketWithAddresses(frame, kSelfAddress, kFinalPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001831 EXPECT_EQ(kFinalPeerAddress, connection_.peer_address());
1832 EXPECT_EQ(kNewestEffectivePeerAddress, connection_.effective_peer_address());
1833 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
1834 connection_.active_effective_peer_migration_type());
1835}
1836
1837TEST_P(QuicConnectionTest, ReceivePaddedPingAtServer) {
1838 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1839 set_perspective(Perspective::IS_SERVER);
1840 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1841 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1842
1843 // Clear direct_peer_address.
1844 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1845 // Clear effective_peer_address, it is the same as direct_peer_address for
1846 // this test.
1847 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1848 QuicSocketAddress());
1849 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1850
nharper46833c32019-05-15 21:33:05 -07001851 QuicFrame frame;
1852 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1853 frame = QuicFrame(&crypto_frame_);
1854 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1855 } else {
1856 frame = QuicFrame(QuicStreamFrame(
1857 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
1858 0u, QuicStringPiece()));
1859 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1860 }
1861 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001862 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1863 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1864
1865 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
1866 EXPECT_CALL(visitor_, OnConnectivityProbeReceived(_, _)).Times(0);
1867
1868 // Process a padded PING or PATH CHALLENGE packet with no peer address change
1869 // on server side will be ignored.
1870 OwningSerializedPacketPointer probing_packet;
fkastenholz305e1732019-06-18 05:01:22 -07001871 if (VersionHasIetfQuicFrames(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001872 QuicPathFrameBuffer payload = {
1873 {0xde, 0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xfe}};
1874 probing_packet =
1875 QuicPacketCreatorPeer::SerializePathChallengeConnectivityProbingPacket(
1876 &peer_creator_, &payload);
1877 } else {
1878 probing_packet = QuicPacketCreatorPeer::SerializeConnectivityProbingPacket(
1879 &peer_creator_);
1880 }
1881 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
1882 QuicEncryptedPacket(probing_packet->encrypted_buffer,
1883 probing_packet->encrypted_length),
1884 clock_.Now()));
1885
1886 uint64_t num_probing_received =
1887 connection_.GetStats().num_connectivity_probing_received;
1888 ProcessReceivedPacket(kSelfAddress, kPeerAddress, *received);
1889
1890 EXPECT_EQ(num_probing_received,
1891 connection_.GetStats().num_connectivity_probing_received);
1892 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1893 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1894}
1895
1896TEST_P(QuicConnectionTest, WriteOutOfOrderQueuedPackets) {
1897 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
fayangc31c9952019-06-05 13:54:48 -07001898 if (!IsDefaultTestConfiguration()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001899 return;
1900 }
1901
1902 set_perspective(Perspective::IS_CLIENT);
1903
1904 BlockOnNextWrite();
1905
1906 QuicStreamId stream_id = 2;
1907 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
1908
1909 EXPECT_EQ(1u, connection_.NumQueuedPackets());
1910
1911 writer_->SetWritable();
1912 connection_.SendConnectivityProbingPacket(writer_.get(),
1913 connection_.peer_address());
1914
1915 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INTERNAL_ERROR,
1916 "Packet written out of order.",
1917 ConnectionCloseSource::FROM_SELF));
1918 EXPECT_QUIC_BUG(connection_.OnCanWrite(),
1919 "Attempt to write packet:1 after:2");
1920 EXPECT_FALSE(connection_.connected());
1921}
1922
1923TEST_P(QuicConnectionTest, DiscardQueuedPacketsAfterConnectionClose) {
1924 // Regression test for b/74073386.
1925 {
1926 InSequence seq;
1927 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1928 EXPECT_CALL(visitor_, OnConnectionClosed(_, _, _)).Times(1);
1929 }
1930
1931 set_perspective(Perspective::IS_CLIENT);
1932
1933 writer_->SimulateNextPacketTooLarge();
1934
1935 // This packet write should fail, which should cause the connection to close
1936 // after sending a connection close packet, then the failed packet should be
1937 // queued.
1938 connection_.SendStreamDataWithString(/*id=*/2, "foo", 0, NO_FIN);
1939
1940 EXPECT_FALSE(connection_.connected());
1941 EXPECT_EQ(1u, connection_.NumQueuedPackets());
1942
1943 EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
1944 connection_.OnCanWrite();
fayang40ec3ac2019-06-05 09:07:54 -07001945 if (GetQuicReloadableFlag(quic_check_connected_before_flush)) {
1946 EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
1947 } else {
1948 EXPECT_EQ(1u, connection_.GetStats().packets_discarded);
1949 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001950}
1951
1952TEST_P(QuicConnectionTest, ReceiveConnectivityProbingAtServer) {
1953 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1954 set_perspective(Perspective::IS_SERVER);
1955 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1956 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1957
1958 // Clear direct_peer_address.
1959 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1960 // Clear effective_peer_address, it is the same as direct_peer_address for
1961 // this test.
1962 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1963 QuicSocketAddress());
1964 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1965
nharper46833c32019-05-15 21:33:05 -07001966 QuicFrame frame;
1967 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1968 frame = QuicFrame(&crypto_frame_);
1969 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1970 } else {
1971 frame = QuicFrame(QuicStreamFrame(
1972 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
1973 0u, QuicStringPiece()));
1974 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1975 }
1976 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001977 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1978 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1979
1980 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
1981 EXPECT_CALL(visitor_, OnConnectivityProbeReceived(_, _)).Times(1);
1982
1983 // Process a padded PING packet from a new peer address on server side
1984 // is effectively receiving a connectivity probing.
1985 const QuicSocketAddress kNewPeerAddress =
1986 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
1987
1988 OwningSerializedPacketPointer probing_packet = ConstructProbingPacket();
1989 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
1990 QuicEncryptedPacket(probing_packet->encrypted_buffer,
1991 probing_packet->encrypted_length),
1992 clock_.Now()));
1993
1994 uint64_t num_probing_received =
1995 connection_.GetStats().num_connectivity_probing_received;
1996 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
1997
1998 EXPECT_EQ(num_probing_received + 1,
1999 connection_.GetStats().num_connectivity_probing_received);
2000 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2001 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2002
2003 // Process another packet with the old peer address on server side will not
2004 // start peer migration.
2005 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
nharper46833c32019-05-15 21:33:05 -07002006 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002007 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2008 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2009}
2010
2011TEST_P(QuicConnectionTest, ReceiveReorderedConnectivityProbingAtServer) {
2012 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2013 set_perspective(Perspective::IS_SERVER);
2014 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2015 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2016
2017 // Clear direct_peer_address.
2018 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2019 // Clear effective_peer_address, it is the same as direct_peer_address for
2020 // this test.
2021 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2022 QuicSocketAddress());
2023 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2024
nharper46833c32019-05-15 21:33:05 -07002025 QuicFrame frame;
2026 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2027 frame = QuicFrame(&crypto_frame_);
2028 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2029 } else {
2030 frame = QuicFrame(QuicStreamFrame(
2031 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
2032 0u, QuicStringPiece()));
2033 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2034 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002035 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
nharper46833c32019-05-15 21:33:05 -07002036 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002037 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2038 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2039
2040 // Decrease packet number to simulate out-of-order packets.
2041 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 4);
2042
2043 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2044 EXPECT_CALL(visitor_, OnConnectivityProbeReceived(_, _)).Times(1);
2045
2046 // Process a padded PING packet from a new peer address on server side
2047 // is effectively receiving a connectivity probing, even if a newer packet has
2048 // been received before this one.
2049 const QuicSocketAddress kNewPeerAddress =
2050 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2051
2052 OwningSerializedPacketPointer probing_packet = ConstructProbingPacket();
2053 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2054 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2055 probing_packet->encrypted_length),
2056 clock_.Now()));
2057
2058 uint64_t num_probing_received =
2059 connection_.GetStats().num_connectivity_probing_received;
2060 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2061
2062 EXPECT_EQ(num_probing_received + 1,
2063 connection_.GetStats().num_connectivity_probing_received);
2064 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2065 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2066}
2067
2068TEST_P(QuicConnectionTest, MigrateAfterProbingAtServer) {
2069 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2070 set_perspective(Perspective::IS_SERVER);
2071 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2072 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2073
2074 // Clear direct_peer_address.
2075 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2076 // Clear effective_peer_address, it is the same as direct_peer_address for
2077 // this test.
2078 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2079 QuicSocketAddress());
2080 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2081
nharper46833c32019-05-15 21:33:05 -07002082 QuicFrame frame;
2083 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2084 frame = QuicFrame(&crypto_frame_);
2085 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2086 } else {
2087 frame = QuicFrame(QuicStreamFrame(
2088 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
2089 0u, QuicStringPiece()));
2090 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2091 }
2092 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002093 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2094 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2095
2096 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2097 EXPECT_CALL(visitor_, OnConnectivityProbeReceived(_, _)).Times(1);
2098
2099 // Process a padded PING packet from a new peer address on server side
2100 // is effectively receiving a connectivity probing.
2101 const QuicSocketAddress kNewPeerAddress =
2102 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2103
2104 OwningSerializedPacketPointer probing_packet = ConstructProbingPacket();
2105 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2106 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2107 probing_packet->encrypted_length),
2108 clock_.Now()));
2109 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2110 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2111 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2112
2113 // Process another non-probing packet with the new peer address on server
2114 // side will start peer migration.
2115 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2116
nharper46833c32019-05-15 21:33:05 -07002117 ProcessFramePacketWithAddresses(frame, kSelfAddress, kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002118 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2119 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2120}
2121
2122TEST_P(QuicConnectionTest, ReceivePaddedPingAtClient) {
2123 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2124 set_perspective(Perspective::IS_CLIENT);
2125 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2126
2127 // Clear direct_peer_address.
2128 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2129 // Clear effective_peer_address, it is the same as direct_peer_address for
2130 // this test.
2131 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2132 QuicSocketAddress());
2133 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2134
nharper46833c32019-05-15 21:33:05 -07002135 QuicFrame frame;
2136 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2137 frame = QuicFrame(&crypto_frame_);
2138 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2139 } else {
2140 frame = QuicFrame(QuicStreamFrame(
2141 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
2142 0u, QuicStringPiece()));
2143 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2144 }
2145 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002146 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2147 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2148
2149 // Client takes all padded PING packet as speculative connectivity
2150 // probing packet, and reports to visitor.
2151 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2152 EXPECT_CALL(visitor_, OnConnectivityProbeReceived(_, _)).Times(1);
2153
2154 OwningSerializedPacketPointer probing_packet = ConstructProbingPacket();
2155 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2156 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2157 probing_packet->encrypted_length),
2158 clock_.Now()));
2159 uint64_t num_probing_received =
2160 connection_.GetStats().num_connectivity_probing_received;
2161 ProcessReceivedPacket(kSelfAddress, kPeerAddress, *received);
2162
2163 EXPECT_EQ(num_probing_received,
2164 connection_.GetStats().num_connectivity_probing_received);
2165 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2166 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2167}
2168
2169TEST_P(QuicConnectionTest, ReceiveConnectivityProbingAtClient) {
2170 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2171 set_perspective(Perspective::IS_CLIENT);
2172 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2173
2174 // Clear direct_peer_address.
2175 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2176 // Clear effective_peer_address, it is the same as direct_peer_address for
2177 // this test.
2178 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2179 QuicSocketAddress());
2180 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2181
nharper46833c32019-05-15 21:33:05 -07002182 QuicFrame frame;
2183 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2184 frame = QuicFrame(&crypto_frame_);
2185 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2186 } else {
2187 frame = QuicFrame(QuicStreamFrame(
2188 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
2189 0u, QuicStringPiece()));
2190 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2191 }
2192 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002193 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2194 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2195
2196 // Process a padded PING packet with a different self address on client side
2197 // is effectively receiving a connectivity probing.
2198 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2199 EXPECT_CALL(visitor_, OnConnectivityProbeReceived(_, _)).Times(1);
2200
2201 const QuicSocketAddress kNewSelfAddress =
2202 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2203
2204 OwningSerializedPacketPointer probing_packet = ConstructProbingPacket();
2205 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2206 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2207 probing_packet->encrypted_length),
2208 clock_.Now()));
2209 uint64_t num_probing_received =
2210 connection_.GetStats().num_connectivity_probing_received;
2211 ProcessReceivedPacket(kNewSelfAddress, kPeerAddress, *received);
2212
2213 EXPECT_EQ(num_probing_received + 1,
2214 connection_.GetStats().num_connectivity_probing_received);
2215 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2216 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2217}
2218
2219TEST_P(QuicConnectionTest, PeerAddressChangeAtClient) {
2220 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2221 set_perspective(Perspective::IS_CLIENT);
2222 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2223
2224 // Clear direct_peer_address.
2225 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2226 // Clear effective_peer_address, it is the same as direct_peer_address for
2227 // this test.
2228 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2229 QuicSocketAddress());
2230 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2231
nharper46833c32019-05-15 21:33:05 -07002232 QuicFrame frame;
2233 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2234 frame = QuicFrame(&crypto_frame_);
2235 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2236 } else {
2237 frame = QuicFrame(QuicStreamFrame(
2238 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
2239 0u, QuicStringPiece()));
2240 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2241 }
2242 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002243 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2244 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2245
2246 // Process another packet with a different peer address on client side will
2247 // only update peer address.
2248 const QuicSocketAddress kNewPeerAddress =
2249 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2250 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
nharper46833c32019-05-15 21:33:05 -07002251 ProcessFramePacketWithAddresses(frame, kSelfAddress, kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002252 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2253 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2254}
2255
2256TEST_P(QuicConnectionTest, MaxPacketSize) {
2257 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2258 EXPECT_EQ(1350u, connection_.max_packet_length());
2259}
2260
2261TEST_P(QuicConnectionTest, SmallerServerMaxPacketSize) {
2262 TestConnection connection(TestConnectionId(), kPeerAddress, helper_.get(),
2263 alarm_factory_.get(), writer_.get(),
2264 Perspective::IS_SERVER, version());
2265 EXPECT_EQ(Perspective::IS_SERVER, connection.perspective());
2266 EXPECT_EQ(1000u, connection.max_packet_length());
2267}
2268
2269TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSize) {
2270 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2271
2272 set_perspective(Perspective::IS_SERVER);
2273 connection_.SetMaxPacketLength(1000);
2274
2275 QuicPacketHeader header;
2276 header.destination_connection_id = connection_id_;
2277 header.version_flag = true;
nharper21af28e2019-06-17 15:54:34 -07002278 header.packet_number = QuicPacketNumber(12);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002279
2280 if (QuicVersionHasLongHeaderLengths(
2281 peer_framer_.version().transport_version)) {
2282 header.long_packet_type = INITIAL;
2283 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
2284 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
2285 }
2286
2287 QuicFrames frames;
2288 QuicPaddingFrame padding;
nharper46833c32019-05-15 21:33:05 -07002289 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2290 frames.push_back(QuicFrame(&crypto_frame_));
2291 } else {
2292 frames.push_back(QuicFrame(frame1_));
2293 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002294 frames.push_back(QuicFrame(padding));
2295 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
dschinazi66dea072019-04-09 11:41:06 -07002296 char buffer[kMaxOutgoingPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07002297 size_t encrypted_length =
2298 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12),
dschinazi66dea072019-04-09 11:41:06 -07002299 *packet, buffer, kMaxOutgoingPacketSize);
2300 EXPECT_EQ(kMaxOutgoingPacketSize, encrypted_length);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002301
2302 framer_.set_version(version());
nharper46833c32019-05-15 21:33:05 -07002303 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2304 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
2305 } else {
2306 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2307 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002308 connection_.ProcessUdpPacket(
2309 kSelfAddress, kPeerAddress,
2310 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
2311
dschinazi66dea072019-04-09 11:41:06 -07002312 EXPECT_EQ(kMaxOutgoingPacketSize, connection_.max_packet_length());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002313}
2314
2315TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSizeWhileWriterLimited) {
2316 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2317
2318 const QuicByteCount lower_max_packet_size = 1240;
2319 writer_->set_max_packet_size(lower_max_packet_size);
2320 set_perspective(Perspective::IS_SERVER);
2321 connection_.SetMaxPacketLength(1000);
2322 EXPECT_EQ(1000u, connection_.max_packet_length());
2323
2324 QuicPacketHeader header;
2325 header.destination_connection_id = connection_id_;
2326 header.version_flag = true;
nharper21af28e2019-06-17 15:54:34 -07002327 header.packet_number = QuicPacketNumber(12);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002328
2329 if (QuicVersionHasLongHeaderLengths(
2330 peer_framer_.version().transport_version)) {
2331 header.long_packet_type = INITIAL;
2332 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
2333 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
2334 }
2335
2336 QuicFrames frames;
2337 QuicPaddingFrame padding;
nharper46833c32019-05-15 21:33:05 -07002338 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2339 frames.push_back(QuicFrame(&crypto_frame_));
2340 } else {
2341 frames.push_back(QuicFrame(frame1_));
2342 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002343 frames.push_back(QuicFrame(padding));
2344 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
dschinazi66dea072019-04-09 11:41:06 -07002345 char buffer[kMaxOutgoingPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07002346 size_t encrypted_length =
2347 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12),
dschinazi66dea072019-04-09 11:41:06 -07002348 *packet, buffer, kMaxOutgoingPacketSize);
2349 EXPECT_EQ(kMaxOutgoingPacketSize, encrypted_length);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002350
2351 framer_.set_version(version());
nharper46833c32019-05-15 21:33:05 -07002352 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2353 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
2354 } else {
2355 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2356 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002357 connection_.ProcessUdpPacket(
2358 kSelfAddress, kPeerAddress,
2359 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
2360
2361 // Here, the limit imposed by the writer is lower than the size of the packet
2362 // received, so the writer max packet size is used.
2363 EXPECT_EQ(lower_max_packet_size, connection_.max_packet_length());
2364}
2365
2366TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriter) {
2367 const QuicByteCount lower_max_packet_size = 1240;
2368 writer_->set_max_packet_size(lower_max_packet_size);
2369
2370 static_assert(lower_max_packet_size < kDefaultMaxPacketSize,
2371 "Default maximum packet size is too low");
2372 connection_.SetMaxPacketLength(kDefaultMaxPacketSize);
2373
2374 EXPECT_EQ(lower_max_packet_size, connection_.max_packet_length());
2375}
2376
2377TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriterForNewConnection) {
2378 const QuicConnectionId connection_id = TestConnectionId(17);
2379 const QuicByteCount lower_max_packet_size = 1240;
2380 writer_->set_max_packet_size(lower_max_packet_size);
2381 TestConnection connection(connection_id, kPeerAddress, helper_.get(),
2382 alarm_factory_.get(), writer_.get(),
2383 Perspective::IS_CLIENT, version());
2384 EXPECT_EQ(Perspective::IS_CLIENT, connection.perspective());
2385 EXPECT_EQ(lower_max_packet_size, connection.max_packet_length());
2386}
2387
2388TEST_P(QuicConnectionTest, PacketsInOrder) {
2389 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2390
2391 ProcessPacket(1);
fayangc31c9952019-06-05 13:54:48 -07002392 EXPECT_EQ(QuicPacketNumber(1u), LargestAcked(connection_.ack_frame()));
2393 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002394
2395 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07002396 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(connection_.ack_frame()));
2397 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002398
2399 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002400 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
2401 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002402}
2403
2404TEST_P(QuicConnectionTest, PacketsOutOfOrder) {
2405 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2406
2407 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002408 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002409 EXPECT_TRUE(IsMissing(2));
2410 EXPECT_TRUE(IsMissing(1));
2411
2412 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07002413 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002414 EXPECT_FALSE(IsMissing(2));
2415 EXPECT_TRUE(IsMissing(1));
2416
2417 ProcessPacket(1);
fayangc31c9952019-06-05 13:54:48 -07002418 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002419 EXPECT_FALSE(IsMissing(2));
2420 EXPECT_FALSE(IsMissing(1));
2421}
2422
2423TEST_P(QuicConnectionTest, DuplicatePacket) {
2424 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2425
2426 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002427 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002428 EXPECT_TRUE(IsMissing(2));
2429 EXPECT_TRUE(IsMissing(1));
2430
2431 // Send packet 3 again, but do not set the expectation that
2432 // the visitor OnStreamFrame() will be called.
2433 ProcessDataPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002434 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002435 EXPECT_TRUE(IsMissing(2));
2436 EXPECT_TRUE(IsMissing(1));
2437}
2438
2439TEST_P(QuicConnectionTest, PacketsOutOfOrderWithAdditionsAndLeastAwaiting) {
QUICHE teamcd098022019-03-22 18:49:55 -07002440 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2441 return;
2442 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002443 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2444
2445 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002446 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002447 EXPECT_TRUE(IsMissing(2));
2448 EXPECT_TRUE(IsMissing(1));
2449
2450 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07002451 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002452 EXPECT_TRUE(IsMissing(1));
2453
2454 ProcessPacket(5);
fayangc31c9952019-06-05 13:54:48 -07002455 EXPECT_EQ(QuicPacketNumber(5u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002456 EXPECT_TRUE(IsMissing(1));
2457 EXPECT_TRUE(IsMissing(4));
2458
2459 // Pretend at this point the client has gotten acks for 2 and 3 and 1 is a
2460 // packet the peer will not retransmit. It indicates this by sending 'least
2461 // awaiting' is 4. The connection should then realize 1 will not be
2462 // retransmitted, and will remove it from the missing list.
2463 QuicAckFrame frame = InitAckFrame(1);
2464 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
2465 ProcessAckPacket(6, &frame);
2466
2467 // Force an ack to be sent.
2468 SendAckPacketToPeer();
2469 EXPECT_TRUE(IsMissing(4));
2470}
2471
2472TEST_P(QuicConnectionTest, RejectPacketTooFarOut) {
QUICHE teamcd098022019-03-22 18:49:55 -07002473 if (GetQuicReloadableFlag(quic_use_uber_received_packet_manager)) {
2474 return;
2475 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002476 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_PACKET_HEADER, _,
2477 ConnectionCloseSource::FROM_SELF));
2478
2479 // Call ProcessDataPacket rather than ProcessPacket, as we should not get a
2480 // packet call to the visitor.
fayang6dba4902019-06-17 10:04:23 -07002481 ProcessDataPacket(MaxRandomInitialPacketNumber() + 6000);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002482 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
2483 nullptr);
2484}
2485
2486TEST_P(QuicConnectionTest, RejectUnencryptedStreamData) {
2487 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
2488 if (!IsDefaultTestConfiguration()) {
2489 return;
2490 }
2491
2492 // Process an unencrypted packet from the non-crypto stream.
2493 frame1_.stream_id = 3;
2494 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2495 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_UNENCRYPTED_STREAM_DATA, _,
2496 ConnectionCloseSource::FROM_SELF));
nharper2c9f02a2019-05-08 10:25:50 -07002497 EXPECT_QUIC_PEER_BUG(ProcessDataPacketAtLevel(1, false, ENCRYPTION_INITIAL),
2498 "");
QUICHE teama6ef0a62019-03-07 20:34:33 -05002499 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
2500 nullptr);
2501 const std::vector<QuicConnectionCloseFrame>& connection_close_frames =
2502 writer_->connection_close_frames();
nharper2c9f02a2019-05-08 10:25:50 -07002503 ASSERT_EQ(1u, connection_close_frames.size());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002504 EXPECT_EQ(QUIC_UNENCRYPTED_STREAM_DATA,
fkastenholze9d71a82019-04-09 05:12:13 -07002505 connection_close_frames[0].quic_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002506}
2507
2508TEST_P(QuicConnectionTest, OutOfOrderReceiptCausesAckSend) {
2509 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2510
2511 ProcessPacket(3);
fayang6dba4902019-06-17 10:04:23 -07002512 // Should not cause an ack.
2513 EXPECT_EQ(0u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002514
2515 ProcessPacket(2);
fayang6dba4902019-06-17 10:04:23 -07002516 // Should ack immediately, since this fills the last hole.
2517 EXPECT_EQ(1u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002518
2519 ProcessPacket(1);
2520 // Should ack immediately, since this fills the last hole.
fayang6dba4902019-06-17 10:04:23 -07002521 EXPECT_EQ(2u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002522
2523 ProcessPacket(4);
2524 // Should not cause an ack.
fayang6dba4902019-06-17 10:04:23 -07002525 EXPECT_EQ(2u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002526}
2527
2528TEST_P(QuicConnectionTest, OutOfOrderAckReceiptCausesNoAck) {
2529 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2530
2531 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
2532 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
2533 EXPECT_EQ(2u, writer_->packets_write_attempts());
2534
2535 QuicAckFrame ack1 = InitAckFrame(1);
2536 QuicAckFrame ack2 = InitAckFrame(2);
2537 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2538 ProcessAckPacket(2, &ack2);
2539 // Should ack immediately since we have missing packets.
2540 EXPECT_EQ(2u, writer_->packets_write_attempts());
2541
2542 ProcessAckPacket(1, &ack1);
2543 // Should not ack an ack filling a missing packet.
2544 EXPECT_EQ(2u, writer_->packets_write_attempts());
2545}
2546
2547TEST_P(QuicConnectionTest, AckReceiptCausesAckSend) {
2548 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2549 QuicPacketNumber original, second;
2550
2551 QuicByteCount packet_size =
2552 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &original); // 1st packet.
2553 SendStreamDataToPeer(3, "bar", 3, NO_FIN, &second); // 2nd packet.
2554
2555 QuicAckFrame frame = InitAckFrame({{second, second + 1}});
2556 // First nack triggers early retransmit.
2557 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07002558 lost_packets.push_back(LostPacket(original, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002559 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
2560 .WillOnce(SetArgPointee<5>(lost_packets));
2561 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2562 QuicPacketNumber retransmission;
2563 // Packet 1 is short header for IETF QUIC because the encryption level
2564 // switched to ENCRYPTION_FORWARD_SECURE in SendStreamDataToPeer.
fayangd4291e42019-05-30 10:31:21 -07002565 EXPECT_CALL(*send_algorithm_,
2566 OnPacketSent(_, _, _,
2567 VersionHasIetfInvariantHeader(
2568 GetParam().version.transport_version)
2569 ? packet_size
2570 : packet_size - kQuicVersionSize,
2571 _))
QUICHE teama6ef0a62019-03-07 20:34:33 -05002572 .WillOnce(SaveArg<2>(&retransmission));
2573
2574 ProcessAckPacket(&frame);
2575
2576 QuicAckFrame frame2 = ConstructAckFrame(retransmission, original);
2577 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2578 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
2579 ProcessAckPacket(&frame2);
2580
2581 // Now if the peer sends an ack which still reports the retransmitted packet
2582 // as missing, that will bundle an ack with data after two acks in a row
2583 // indicate the high water mark needs to be raised.
2584 EXPECT_CALL(*send_algorithm_,
2585 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA));
2586 connection_.SendStreamDataWithString(3, "foo", 6, NO_FIN);
2587 // No ack sent.
nharper55fa6132019-05-07 19:37:21 -07002588 size_t padding_frame_count = writer_->padding_frames().size();
2589 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002590 EXPECT_EQ(1u, writer_->stream_frames().size());
2591
2592 // No more packet loss for the rest of the test.
2593 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
2594 .Times(AnyNumber());
2595 ProcessAckPacket(&frame2);
2596 EXPECT_CALL(*send_algorithm_,
2597 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA));
fayang03916692019-05-22 17:57:18 -07002598 connection_.SendStreamDataWithString(3, "foofoofoo", 9, NO_FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002599 // Ack bundled.
2600 if (GetParam().no_stop_waiting) {
fayang03916692019-05-22 17:57:18 -07002601 if (GetQuicReloadableFlag(quic_simplify_stop_waiting)) {
2602 // Do not ACK acks.
2603 EXPECT_EQ(1u, writer_->frame_count());
2604 } else {
2605 EXPECT_EQ(2u, writer_->frame_count());
2606 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002607 } else {
2608 EXPECT_EQ(3u, writer_->frame_count());
2609 }
2610 EXPECT_EQ(1u, writer_->stream_frames().size());
fayang03916692019-05-22 17:57:18 -07002611 if (GetParam().no_stop_waiting &&
2612 GetQuicReloadableFlag(quic_simplify_stop_waiting)) {
2613 EXPECT_TRUE(writer_->ack_frames().empty());
2614 } else {
2615 EXPECT_FALSE(writer_->ack_frames().empty());
2616 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002617
2618 // But an ack with no missing packets will not send an ack.
2619 AckPacket(original, &frame2);
2620 ProcessAckPacket(&frame2);
2621 ProcessAckPacket(&frame2);
2622}
2623
2624TEST_P(QuicConnectionTest, AckSentEveryNthPacket) {
2625 connection_.set_ack_frequency_before_ack_decimation(3);
2626
2627 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2628 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(39);
2629
2630 // Expect 13 acks, every 3rd packet.
2631 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(13);
2632 // Receives packets 1 - 39.
2633 for (size_t i = 1; i <= 39; ++i) {
2634 ProcessDataPacket(i);
2635 }
2636}
2637
2638TEST_P(QuicConnectionTest, AckDecimationReducesAcks) {
2639 const size_t kMinRttMs = 40;
2640 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
2641 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
2642 QuicTime::Delta::Zero(), QuicTime::Zero());
2643 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
2644
2645 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
2646
2647 // Start ack decimation from 10th packet.
2648 connection_.set_min_received_before_ack_decimation(10);
2649
2650 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2651 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(30);
2652
2653 // Expect 6 acks: 5 acks between packets 1-10, and ack at 20.
2654 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(6);
2655 // Receives packets 1 - 29.
2656 for (size_t i = 1; i <= 29; ++i) {
2657 ProcessDataPacket(i);
2658 }
2659
2660 // We now receive the 30th packet, and so we send an ack.
2661 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2662 ProcessDataPacket(30);
2663}
2664
2665TEST_P(QuicConnectionTest, AckNeedsRetransmittableFrames) {
ianswett68cf0042019-05-09 08:37:58 -07002666 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002667 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2668 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(99);
2669
2670 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(19);
2671 // Receives packets 1 - 39.
2672 for (size_t i = 1; i <= 39; ++i) {
2673 ProcessDataPacket(i);
2674 }
2675 // Receiving Packet 40 causes 20th ack to send. Session is informed and adds
2676 // WINDOW_UPDATE.
2677 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
2678 .WillOnce(Invoke([this]() {
2679 connection_.SendControlFrame(
2680 QuicFrame(new QuicWindowUpdateFrame(1, 0, 0)));
2681 }));
2682 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2683 EXPECT_EQ(0u, writer_->window_update_frames().size());
2684 ProcessDataPacket(40);
2685 EXPECT_EQ(1u, writer_->window_update_frames().size());
2686
2687 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(9);
2688 // Receives packets 41 - 59.
2689 for (size_t i = 41; i <= 59; ++i) {
2690 ProcessDataPacket(i);
2691 }
2692 // Send a packet containing stream frame.
QUICHE team8c1daa22019-03-13 08:33:41 -07002693 SendStreamDataToPeer(
nharper46833c32019-05-15 21:33:05 -07002694 QuicUtils::GetFirstBidirectionalStreamId(
2695 connection_.version().transport_version, Perspective::IS_CLIENT),
QUICHE team8c1daa22019-03-13 08:33:41 -07002696 "bar", 0, NO_FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002697
2698 // Session will not be informed until receiving another 20 packets.
2699 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(19);
2700 for (size_t i = 60; i <= 98; ++i) {
2701 ProcessDataPacket(i);
2702 EXPECT_EQ(0u, writer_->window_update_frames().size());
2703 }
2704 // Session does not add a retransmittable frame.
2705 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
2706 .WillOnce(Invoke([this]() {
2707 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
2708 }));
2709 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2710 EXPECT_EQ(0u, writer_->ping_frames().size());
2711 ProcessDataPacket(99);
2712 EXPECT_EQ(0u, writer_->window_update_frames().size());
2713 // A ping frame will be added.
2714 EXPECT_EQ(1u, writer_->ping_frames().size());
2715}
2716
2717TEST_P(QuicConnectionTest, LeastUnackedLower) {
fayangc31c9952019-06-05 13:54:48 -07002718 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002719 return;
2720 }
2721 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2722
2723 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
2724 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
2725 SendStreamDataToPeer(1, "eep", 6, NO_FIN, nullptr);
2726
2727 // Start out saying the least unacked is 2.
2728 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
2729 ProcessStopWaitingPacket(InitStopWaitingFrame(2));
2730
2731 // Change it to 1, but lower the packet number to fake out-of-order packets.
2732 // This should be fine.
2733 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 1);
2734 // The scheduler will not process out of order acks, but all packet processing
2735 // causes the connection to try to write.
2736 if (!GetParam().no_stop_waiting) {
2737 EXPECT_CALL(visitor_, OnCanWrite());
2738 }
2739 ProcessStopWaitingPacket(InitStopWaitingFrame(1));
2740
2741 // Now claim it's one, but set the ordering so it was sent "after" the first
2742 // one. This should cause a connection error.
2743 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 7);
2744 if (!GetParam().no_stop_waiting) {
2745 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2746 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_STOP_WAITING_DATA, _,
2747 ConnectionCloseSource::FROM_SELF));
2748 }
2749 ProcessStopWaitingPacket(InitStopWaitingFrame(1));
2750}
2751
2752TEST_P(QuicConnectionTest, TooManySentPackets) {
2753 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2754
2755 QuicPacketCount max_tracked_packets = 50;
2756 QuicConnectionPeer::SetMaxTrackedPackets(&connection_, max_tracked_packets);
2757
2758 const int num_packets = max_tracked_packets + 5;
2759
2760 for (int i = 0; i < num_packets; ++i) {
2761 SendStreamDataToPeer(1, "foo", 3 * i, NO_FIN, nullptr);
2762 }
2763
2764 // Ack packet 1, which leaves more than the limit outstanding.
2765 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2766 EXPECT_CALL(visitor_,
2767 OnConnectionClosed(QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS, _,
2768 ConnectionCloseSource::FROM_SELF));
2769
2770 // Nack the first packet and ack the rest, leaving a huge gap.
2771 QuicAckFrame frame1 = ConstructAckFrame(num_packets, 1);
2772 ProcessAckPacket(&frame1);
2773}
2774
2775TEST_P(QuicConnectionTest, LargestObservedLower) {
2776 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2777
2778 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
2779 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
2780 SendStreamDataToPeer(1, "eep", 6, NO_FIN, nullptr);
2781 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2782
2783 // Start out saying the largest observed is 2.
2784 QuicAckFrame frame1 = InitAckFrame(1);
2785 QuicAckFrame frame2 = InitAckFrame(2);
2786 ProcessAckPacket(&frame2);
2787
QUICHE team9929cc42019-03-13 08:17:43 -07002788 if (GetQuicReloadableFlag(quic_tolerate_reneging)) {
2789 EXPECT_CALL(visitor_, OnCanWrite());
2790 } else {
2791 // Now change it to 1, and it should cause a connection error.
2792 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, _,
2793 ConnectionCloseSource::FROM_SELF));
2794 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
2795 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002796 ProcessAckPacket(&frame1);
2797}
2798
2799TEST_P(QuicConnectionTest, AckUnsentData) {
2800 // Ack a packet which has not been sent.
2801 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, _,
2802 ConnectionCloseSource::FROM_SELF));
2803 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2804 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2805 QuicAckFrame frame = InitAckFrame(1);
2806 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
2807 ProcessAckPacket(&frame);
2808}
2809
2810TEST_P(QuicConnectionTest, BasicSending) {
QUICHE teamcd098022019-03-22 18:49:55 -07002811 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2812 return;
2813 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002814 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2815 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2816 ProcessDataPacket(1);
2817 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
2818 QuicPacketNumber last_packet;
2819 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
2820 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
2821 SendAckPacketToPeer(); // Packet 2
2822
2823 if (GetParam().no_stop_waiting) {
2824 // Expect no stop waiting frame is sent.
2825 EXPECT_FALSE(least_unacked().IsInitialized());
2826 } else {
2827 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
2828 }
2829
2830 SendAckPacketToPeer(); // Packet 3
2831 if (GetParam().no_stop_waiting) {
2832 // Expect no stop waiting frame is sent.
2833 EXPECT_FALSE(least_unacked().IsInitialized());
2834 } else {
2835 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
2836 }
2837
2838 SendStreamDataToPeer(1, "bar", 3, NO_FIN, &last_packet); // Packet 4
2839 EXPECT_EQ(QuicPacketNumber(4u), last_packet);
2840 SendAckPacketToPeer(); // Packet 5
2841 if (GetParam().no_stop_waiting) {
2842 // Expect no stop waiting frame is sent.
2843 EXPECT_FALSE(least_unacked().IsInitialized());
2844 } else {
2845 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
2846 }
2847
2848 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2849
2850 // Peer acks up to packet 3.
2851 QuicAckFrame frame = InitAckFrame(3);
2852 ProcessAckPacket(&frame);
2853 SendAckPacketToPeer(); // Packet 6
2854
2855 // As soon as we've acked one, we skip ack packets 2 and 3 and note lack of
2856 // ack for 4.
2857 if (GetParam().no_stop_waiting) {
2858 // Expect no stop waiting frame is sent.
2859 EXPECT_FALSE(least_unacked().IsInitialized());
2860 } else {
2861 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
2862 }
2863
2864 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2865
2866 // Peer acks up to packet 4, the last packet.
2867 QuicAckFrame frame2 = InitAckFrame(6);
2868 ProcessAckPacket(&frame2); // Acks don't instigate acks.
2869
2870 // Verify that we did not send an ack.
2871 EXPECT_EQ(QuicPacketNumber(6u), writer_->header().packet_number);
2872
2873 // So the last ack has not changed.
2874 if (GetParam().no_stop_waiting) {
2875 // Expect no stop waiting frame is sent.
2876 EXPECT_FALSE(least_unacked().IsInitialized());
2877 } else {
2878 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
2879 }
2880
2881 // If we force an ack, we shouldn't change our retransmit state.
2882 SendAckPacketToPeer(); // Packet 7
2883 if (GetParam().no_stop_waiting) {
2884 // Expect no stop waiting frame is sent.
2885 EXPECT_FALSE(least_unacked().IsInitialized());
2886 } else {
2887 EXPECT_EQ(QuicPacketNumber(7u), least_unacked());
2888 }
2889
2890 // But if we send more data it should.
2891 SendStreamDataToPeer(1, "eep", 6, NO_FIN, &last_packet); // Packet 8
2892 EXPECT_EQ(QuicPacketNumber(8u), last_packet);
2893 SendAckPacketToPeer(); // Packet 9
2894 if (GetParam().no_stop_waiting) {
2895 // Expect no stop waiting frame is sent.
2896 EXPECT_FALSE(least_unacked().IsInitialized());
2897 } else {
2898 EXPECT_EQ(QuicPacketNumber(7u), least_unacked());
2899 }
2900}
2901
2902// QuicConnection should record the packet sent-time prior to sending the
2903// packet.
2904TEST_P(QuicConnectionTest, RecordSentTimeBeforePacketSent) {
2905 // We're using a MockClock for the tests, so we have complete control over the
2906 // time.
2907 // Our recorded timestamp for the last packet sent time will be passed in to
2908 // the send_algorithm. Make sure that it is set to the correct value.
2909 QuicTime actual_recorded_send_time = QuicTime::Zero();
2910 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2911 .WillOnce(SaveArg<0>(&actual_recorded_send_time));
2912
2913 // First send without any pause and check the result.
2914 QuicTime expected_recorded_send_time = clock_.Now();
2915 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
2916 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
2917 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
2918 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
2919
2920 // Now pause during the write, and check the results.
2921 actual_recorded_send_time = QuicTime::Zero();
2922 const QuicTime::Delta write_pause_time_delta =
2923 QuicTime::Delta::FromMilliseconds(5000);
2924 SetWritePauseTimeDelta(write_pause_time_delta);
2925 expected_recorded_send_time = clock_.Now();
2926
2927 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2928 .WillOnce(SaveArg<0>(&actual_recorded_send_time));
2929 connection_.SendStreamDataWithString(2, "baz", 0, NO_FIN);
2930 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
2931 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
2932 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
2933}
2934
2935TEST_P(QuicConnectionTest, FramePacking) {
2936 // Send two stream frames in 1 packet by queueing them.
2937 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2938 {
fayanga4b37b22019-06-18 13:37:47 -07002939 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002940 connection_.SendStreamData3();
2941 connection_.SendStreamData5();
2942 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2943 }
2944 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2945 EXPECT_FALSE(connection_.HasQueuedData());
2946
2947 // Parse the last packet and ensure it's an ack and two stream frames from
2948 // two different streams.
2949 if (GetParam().no_stop_waiting) {
2950 EXPECT_EQ(2u, writer_->frame_count());
2951 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
2952 } else {
2953 EXPECT_EQ(2u, writer_->frame_count());
2954 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
2955 }
2956
2957 EXPECT_TRUE(writer_->ack_frames().empty());
2958
2959 ASSERT_EQ(2u, writer_->stream_frames().size());
2960 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
2961 writer_->stream_frames()[0]->stream_id);
2962 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
2963 writer_->stream_frames()[1]->stream_id);
2964}
2965
2966TEST_P(QuicConnectionTest, FramePackingNonCryptoThenCrypto) {
2967 // Send two stream frames (one non-crypto, then one crypto) in 2 packets by
2968 // queueing them.
2969 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2970 {
2971 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
fayanga4b37b22019-06-18 13:37:47 -07002972 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002973 connection_.SendStreamData3();
2974 connection_.SendCryptoStreamData();
2975 }
2976 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2977 EXPECT_FALSE(connection_.HasQueuedData());
2978
2979 // Parse the last packet and ensure it's the crypto stream frame.
2980 EXPECT_EQ(2u, writer_->frame_count());
2981 ASSERT_EQ(1u, writer_->padding_frames().size());
QUICHE teamea740082019-03-11 17:58:43 -07002982 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002983 ASSERT_EQ(1u, writer_->stream_frames().size());
2984 EXPECT_EQ(QuicUtils::GetCryptoStreamId(connection_.transport_version()),
2985 writer_->stream_frames()[0]->stream_id);
2986 } else {
2987 EXPECT_EQ(1u, writer_->crypto_frames().size());
2988 }
2989}
2990
2991TEST_P(QuicConnectionTest, FramePackingCryptoThenNonCrypto) {
2992 // Send two stream frames (one crypto, then one non-crypto) in 2 packets by
2993 // queueing them.
2994 {
2995 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2996 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
fayanga4b37b22019-06-18 13:37:47 -07002997 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002998 connection_.SendCryptoStreamData();
2999 connection_.SendStreamData3();
3000 }
3001 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3002 EXPECT_FALSE(connection_.HasQueuedData());
3003
3004 // Parse the last packet and ensure it's the stream frame from stream 3.
nharper55fa6132019-05-07 19:37:21 -07003005 size_t padding_frame_count = writer_->padding_frames().size();
3006 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003007 ASSERT_EQ(1u, writer_->stream_frames().size());
3008 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3009 writer_->stream_frames()[0]->stream_id);
3010}
3011
3012TEST_P(QuicConnectionTest, FramePackingAckResponse) {
3013 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3014 // Process a data packet to queue up a pending ack.
fayang3451f6e2019-06-11 08:18:12 -07003015 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3016 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
3017 } else {
3018 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3019 }
3020 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
3021
QUICHE teama6ef0a62019-03-07 20:34:33 -05003022 QuicPacketNumber last_packet;
nharper46833c32019-05-15 21:33:05 -07003023 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3024 connection_.SendCryptoDataWithString("foo", 0);
3025 } else {
3026 SendStreamDataToPeer(
3027 QuicUtils::GetCryptoStreamId(connection_.transport_version()), "foo", 0,
3028 NO_FIN, &last_packet);
3029 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003030 // Verify ack is bundled with outging packet.
3031 EXPECT_FALSE(writer_->ack_frames().empty());
3032
3033 EXPECT_CALL(visitor_, OnCanWrite())
3034 .WillOnce(DoAll(IgnoreResult(InvokeWithoutArgs(
3035 &connection_, &TestConnection::SendStreamData3)),
3036 IgnoreResult(InvokeWithoutArgs(
3037 &connection_, &TestConnection::SendStreamData5))));
3038
3039 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3040
3041 // Process a data packet to cause the visitor's OnCanWrite to be invoked.
3042 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
QUICHE team8c1daa22019-03-13 08:33:41 -07003043 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
3044 QuicMakeUnique<TaggingEncrypter>(0x01));
zhongyi546cc452019-04-12 15:27:49 -07003045 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
3046 QuicMakeUnique<StrictTaggingDecrypter>(0x01));
nharper2c9f02a2019-05-08 10:25:50 -07003047 ProcessDataPacket(2);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003048
3049 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3050 EXPECT_FALSE(connection_.HasQueuedData());
3051
3052 // Parse the last packet and ensure it's an ack and two stream frames from
3053 // two different streams.
3054 if (GetParam().no_stop_waiting) {
3055 EXPECT_EQ(3u, writer_->frame_count());
3056 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
3057 } else {
3058 EXPECT_EQ(4u, writer_->frame_count());
3059 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3060 }
3061 EXPECT_FALSE(writer_->ack_frames().empty());
3062 ASSERT_EQ(2u, writer_->stream_frames().size());
3063 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3064 writer_->stream_frames()[0]->stream_id);
3065 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3066 writer_->stream_frames()[1]->stream_id);
3067}
3068
3069TEST_P(QuicConnectionTest, FramePackingSendv) {
nharper46833c32019-05-15 21:33:05 -07003070 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003071 // Send data in 1 packet by writing multiple blocks in a single iovector
3072 // using writev.
3073 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3074
3075 char data[] = "ABCDEF";
3076 struct iovec iov[2];
3077 iov[0].iov_base = data;
3078 iov[0].iov_len = 4;
3079 iov[1].iov_base = data + 4;
3080 iov[1].iov_len = 2;
nharper46833c32019-05-15 21:33:05 -07003081 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
3082 connection_.transport_version(), Perspective::IS_CLIENT);
3083 connection_.SaveAndSendStreamData(stream_id, iov, 2, 6, 0, NO_FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003084
3085 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3086 EXPECT_FALSE(connection_.HasQueuedData());
3087
3088 // Parse the last packet and ensure multiple iovector blocks have
3089 // been packed into a single stream frame from one stream.
nharper46833c32019-05-15 21:33:05 -07003090 EXPECT_EQ(1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003091 EXPECT_EQ(1u, writer_->stream_frames().size());
nharper46833c32019-05-15 21:33:05 -07003092 EXPECT_EQ(0u, writer_->padding_frames().size());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003093 QuicStreamFrame* frame = writer_->stream_frames()[0].get();
nharper46833c32019-05-15 21:33:05 -07003094 EXPECT_EQ(stream_id, frame->stream_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003095 EXPECT_EQ("ABCDEF", QuicStringPiece(frame->data_buffer, frame->data_length));
3096}
3097
3098TEST_P(QuicConnectionTest, FramePackingSendvQueued) {
nharper46833c32019-05-15 21:33:05 -07003099 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003100 // Try to send two stream frames in 1 packet by using writev.
3101 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3102
3103 BlockOnNextWrite();
3104 char data[] = "ABCDEF";
3105 struct iovec iov[2];
3106 iov[0].iov_base = data;
3107 iov[0].iov_len = 4;
3108 iov[1].iov_base = data + 4;
3109 iov[1].iov_len = 2;
nharper46833c32019-05-15 21:33:05 -07003110 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
3111 connection_.transport_version(), Perspective::IS_CLIENT);
3112 connection_.SaveAndSendStreamData(stream_id, iov, 2, 6, 0, NO_FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003113
3114 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3115 EXPECT_TRUE(connection_.HasQueuedData());
3116
3117 // Unblock the writes and actually send.
3118 writer_->SetWritable();
3119 connection_.OnCanWrite();
3120 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3121
3122 // Parse the last packet and ensure it's one stream frame from one stream.
nharper46833c32019-05-15 21:33:05 -07003123 EXPECT_EQ(1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003124 EXPECT_EQ(1u, writer_->stream_frames().size());
nharper46833c32019-05-15 21:33:05 -07003125 EXPECT_EQ(0u, writer_->padding_frames().size());
3126 EXPECT_EQ(stream_id, writer_->stream_frames()[0]->stream_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003127}
3128
3129TEST_P(QuicConnectionTest, SendingZeroBytes) {
3130 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3131 // Send a zero byte write with a fin using writev.
3132 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
nharper46833c32019-05-15 21:33:05 -07003133 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
3134 connection_.transport_version(), Perspective::IS_CLIENT);
3135 connection_.SaveAndSendStreamData(stream_id, nullptr, 0, 0, 0, FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003136
3137 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3138 EXPECT_FALSE(connection_.HasQueuedData());
3139
nharper55fa6132019-05-07 19:37:21 -07003140 // Padding frames are added by v99 to ensure a minimum packet size.
3141 size_t extra_padding_frames = 0;
3142 if (GetParam().version.HasHeaderProtection()) {
3143 extra_padding_frames = 1;
3144 }
3145
QUICHE teama6ef0a62019-03-07 20:34:33 -05003146 // Parse the last packet and ensure it's one stream frame from one stream.
nharper55fa6132019-05-07 19:37:21 -07003147 EXPECT_EQ(1u + extra_padding_frames, writer_->frame_count());
3148 EXPECT_EQ(extra_padding_frames, writer_->padding_frames().size());
3149 ASSERT_EQ(1u, writer_->stream_frames().size());
nharper46833c32019-05-15 21:33:05 -07003150 EXPECT_EQ(stream_id, writer_->stream_frames()[0]->stream_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003151 EXPECT_TRUE(writer_->stream_frames()[0]->fin);
3152}
3153
3154TEST_P(QuicConnectionTest, LargeSendWithPendingAck) {
3155 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3156 // Set the ack alarm by processing a ping frame.
3157 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3158
3159 // Processs a PING frame.
3160 ProcessFramePacket(QuicFrame(QuicPingFrame()));
3161 // Ensure that this has caused the ACK alarm to be set.
3162 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
3163 EXPECT_TRUE(ack_alarm->IsSet());
3164
3165 // Send data and ensure the ack is bundled.
3166 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(8);
3167 size_t len = 10000;
3168 std::unique_ptr<char[]> data_array(new char[len]);
3169 memset(data_array.get(), '?', len);
3170 struct iovec iov;
3171 iov.iov_base = data_array.get();
3172 iov.iov_len = len;
3173 QuicConsumedData consumed = connection_.SaveAndSendStreamData(
dschinazi552accc2019-06-17 17:07:34 -07003174 GetNthClientInitiatedStreamId(0, connection_.transport_version()), &iov,
3175 1, len, 0, FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003176 EXPECT_EQ(len, consumed.bytes_consumed);
3177 EXPECT_TRUE(consumed.fin_consumed);
3178 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3179 EXPECT_FALSE(connection_.HasQueuedData());
3180
3181 // Parse the last packet and ensure it's one stream frame with a fin.
3182 EXPECT_EQ(1u, writer_->frame_count());
nharper55fa6132019-05-07 19:37:21 -07003183 ASSERT_EQ(1u, writer_->stream_frames().size());
dschinazi552accc2019-06-17 17:07:34 -07003184 EXPECT_EQ(GetNthClientInitiatedStreamId(0, connection_.transport_version()),
QUICHE teama6ef0a62019-03-07 20:34:33 -05003185 writer_->stream_frames()[0]->stream_id);
3186 EXPECT_TRUE(writer_->stream_frames()[0]->fin);
3187 // Ensure the ack alarm was cancelled when the ack was sent.
3188 EXPECT_FALSE(ack_alarm->IsSet());
3189}
3190
3191TEST_P(QuicConnectionTest, OnCanWrite) {
3192 // Visitor's OnCanWrite will send data, but will have more pending writes.
3193 EXPECT_CALL(visitor_, OnCanWrite())
3194 .WillOnce(DoAll(IgnoreResult(InvokeWithoutArgs(
3195 &connection_, &TestConnection::SendStreamData3)),
3196 IgnoreResult(InvokeWithoutArgs(
3197 &connection_, &TestConnection::SendStreamData5))));
3198 {
3199 InSequence seq;
3200 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillOnce(Return(true));
3201 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
3202 .WillRepeatedly(Return(false));
3203 }
3204
3205 EXPECT_CALL(*send_algorithm_, CanSend(_))
3206 .WillRepeatedly(testing::Return(true));
3207
3208 connection_.OnCanWrite();
3209
3210 // Parse the last packet and ensure it's the two stream frames from
3211 // two different streams.
3212 EXPECT_EQ(2u, writer_->frame_count());
3213 EXPECT_EQ(2u, writer_->stream_frames().size());
3214 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3215 writer_->stream_frames()[0]->stream_id);
3216 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3217 writer_->stream_frames()[1]->stream_id);
3218}
3219
3220TEST_P(QuicConnectionTest, RetransmitOnNack) {
3221 QuicPacketNumber last_packet;
3222 QuicByteCount second_packet_size;
3223 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet); // Packet 1
3224 second_packet_size =
3225 SendStreamDataToPeer(3, "foos", 3, NO_FIN, &last_packet); // Packet 2
3226 SendStreamDataToPeer(3, "fooos", 7, NO_FIN, &last_packet); // Packet 3
3227
3228 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3229
3230 // Don't lose a packet on an ack, and nothing is retransmitted.
3231 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3232 QuicAckFrame ack_one = InitAckFrame(1);
3233 ProcessAckPacket(&ack_one);
3234
3235 // Lose a packet and ensure it triggers retransmission.
3236 QuicAckFrame nack_two = ConstructAckFrame(3, 2);
3237 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003238 lost_packets.push_back(
3239 LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003240 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3241 .WillOnce(SetArgPointee<5>(lost_packets));
3242 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3243 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3244 EXPECT_FALSE(QuicPacketCreatorPeer::SendVersionInPacket(creator_));
3245 ProcessAckPacket(&nack_two);
3246}
3247
3248TEST_P(QuicConnectionTest, DoNotSendQueuedPacketForResetStream) {
3249 // Block the connection to queue the packet.
3250 BlockOnNextWrite();
3251
3252 QuicStreamId stream_id = 2;
3253 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
3254
3255 // Now that there is a queued packet, reset the stream.
3256 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
3257
3258 // Unblock the connection and verify that only the RST_STREAM is sent.
3259 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3260 writer_->SetWritable();
3261 connection_.OnCanWrite();
3262 if (!connection_.session_decides_what_to_write()) {
3263 // OnCanWrite will cause RST_STREAM be sent again.
3264 connection_.SendControlFrame(QuicFrame(new QuicRstStreamFrame(
3265 1, stream_id, QUIC_ERROR_PROCESSING_STREAM, 14)));
3266 }
nharper55fa6132019-05-07 19:37:21 -07003267 size_t padding_frame_count = writer_->padding_frames().size();
3268 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003269 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3270}
3271
3272TEST_P(QuicConnectionTest, SendQueuedPacketForQuicRstStreamNoError) {
3273 // Block the connection to queue the packet.
3274 BlockOnNextWrite();
3275
3276 QuicStreamId stream_id = 2;
3277 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
3278
3279 // Now that there is a queued packet, reset the stream.
3280 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 3);
3281
3282 // Unblock the connection and verify that the RST_STREAM is sent and the data
3283 // packet is sent.
3284 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(2));
3285 writer_->SetWritable();
3286 connection_.OnCanWrite();
3287 if (!connection_.session_decides_what_to_write()) {
3288 // OnCanWrite will cause RST_STREAM be sent again.
3289 connection_.SendControlFrame(QuicFrame(
3290 new QuicRstStreamFrame(1, stream_id, QUIC_STREAM_NO_ERROR, 14)));
3291 }
nharper55fa6132019-05-07 19:37:21 -07003292 size_t padding_frame_count = writer_->padding_frames().size();
3293 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003294 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3295}
3296
3297TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnNack) {
3298 QuicStreamId stream_id = 2;
3299 QuicPacketNumber last_packet;
3300 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3301 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3302 SendStreamDataToPeer(stream_id, "fooos", 7, NO_FIN, &last_packet);
3303
3304 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3305 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 12);
3306
3307 // Lose a packet and ensure it does not trigger retransmission.
3308 QuicAckFrame nack_two = ConstructAckFrame(last_packet, last_packet - 1);
3309 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3310 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3311 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3312 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3313 ProcessAckPacket(&nack_two);
3314}
3315
3316TEST_P(QuicConnectionTest, RetransmitForQuicRstStreamNoErrorOnNack) {
3317 QuicStreamId stream_id = 2;
3318 QuicPacketNumber last_packet;
3319 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3320 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3321 SendStreamDataToPeer(stream_id, "fooos", 7, NO_FIN, &last_packet);
3322
3323 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3324 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 12);
3325
3326 // Lose a packet, ensure it triggers retransmission.
3327 QuicAckFrame nack_two = ConstructAckFrame(last_packet, last_packet - 1);
3328 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3329 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003330 lost_packets.push_back(LostPacket(last_packet - 1, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003331 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3332 .WillOnce(SetArgPointee<5>(lost_packets));
3333 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3334 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
3335 ProcessAckPacket(&nack_two);
3336}
3337
3338TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnRTO) {
3339 QuicStreamId stream_id = 2;
3340 QuicPacketNumber last_packet;
3341 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3342
3343 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3344 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
3345
3346 // Fire the RTO and verify that the RST_STREAM is resent, not stream data.
3347 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3348 clock_.AdvanceTime(DefaultRetransmissionTime());
3349 connection_.GetRetransmissionAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07003350 size_t padding_frame_count = writer_->padding_frames().size();
3351 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003352 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3353 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
3354}
3355
3356// Ensure that if the only data in flight is non-retransmittable, the
3357// retransmission alarm is not set.
3358TEST_P(QuicConnectionTest, CancelRetransmissionAlarmAfterResetStream) {
3359 QuicStreamId stream_id = 2;
3360 QuicPacketNumber last_data_packet;
3361 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
3362
3363 // Cancel the stream.
3364 const QuicPacketNumber rst_packet = last_data_packet + 1;
3365 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, rst_packet, _, _)).Times(1);
3366 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
3367
3368 // Ack the RST_STREAM frame (since it's retransmittable), but not the data
3369 // packet, which is no longer retransmittable since the stream was cancelled.
3370 QuicAckFrame nack_stream_data =
3371 ConstructAckFrame(rst_packet, last_data_packet);
3372 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3373 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3374 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3375 ProcessAckPacket(&nack_stream_data);
3376
3377 // Ensure that the data is still in flight, but the retransmission alarm is no
3378 // longer set.
ianswett9f459cb2019-04-21 06:39:59 -07003379 EXPECT_GT(manager_->GetBytesInFlight(), 0u);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003380 if (GetQuicReloadableFlag(quic_optimize_inflight_check)) {
3381 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3382 // Firing the alarm should remove all bytes_in_flight.
3383 connection_.GetRetransmissionAlarm()->Fire();
ianswett9f459cb2019-04-21 06:39:59 -07003384 EXPECT_EQ(0u, manager_->GetBytesInFlight());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003385 }
3386 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3387}
3388
3389TEST_P(QuicConnectionTest, RetransmitForQuicRstStreamNoErrorOnRTO) {
3390 connection_.SetMaxTailLossProbes(0);
3391
3392 QuicStreamId stream_id = 2;
3393 QuicPacketNumber last_packet;
3394 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3395
3396 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3397 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 3);
3398
3399 // Fire the RTO and verify that the RST_STREAM is resent, the stream data
3400 // is sent.
3401 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(2));
3402 clock_.AdvanceTime(DefaultRetransmissionTime());
3403 connection_.GetRetransmissionAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07003404 size_t padding_frame_count = writer_->padding_frames().size();
3405 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003406 ASSERT_EQ(1u, writer_->rst_stream_frames().size());
3407 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
3408}
3409
3410TEST_P(QuicConnectionTest, DoNotSendPendingRetransmissionForResetStream) {
3411 QuicStreamId stream_id = 2;
3412 QuicPacketNumber last_packet;
3413 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3414 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3415 BlockOnNextWrite();
3416 connection_.SendStreamDataWithString(stream_id, "fooos", 7, NO_FIN);
3417
3418 // Lose a packet which will trigger a pending retransmission.
3419 QuicAckFrame ack = ConstructAckFrame(last_packet, last_packet - 1);
3420 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3421 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3422 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3423 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3424 ProcessAckPacket(&ack);
3425
3426 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 12);
3427
3428 // Unblock the connection and verify that the RST_STREAM is sent but not the
3429 // second data packet nor a retransmit.
3430 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3431 writer_->SetWritable();
3432 connection_.OnCanWrite();
3433 if (!connection_.session_decides_what_to_write()) {
3434 // OnCanWrite will cause this RST_STREAM_FRAME be sent again.
3435 connection_.SendControlFrame(QuicFrame(new QuicRstStreamFrame(
3436 1, stream_id, QUIC_ERROR_PROCESSING_STREAM, 14)));
3437 }
nharper55fa6132019-05-07 19:37:21 -07003438 size_t padding_frame_count = writer_->padding_frames().size();
3439 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
zhongyi546cc452019-04-12 15:27:49 -07003440 ASSERT_EQ(1u, writer_->rst_stream_frames().size());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003441 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
3442}
3443
3444TEST_P(QuicConnectionTest, SendPendingRetransmissionForQuicRstStreamNoError) {
3445 QuicStreamId stream_id = 2;
3446 QuicPacketNumber last_packet;
3447 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3448 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3449 BlockOnNextWrite();
3450 connection_.SendStreamDataWithString(stream_id, "fooos", 7, NO_FIN);
3451
3452 // Lose a packet which will trigger a pending retransmission.
3453 QuicAckFrame ack = ConstructAckFrame(last_packet, last_packet - 1);
3454 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3455 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003456 lost_packets.push_back(LostPacket(last_packet - 1, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003457 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3458 .WillOnce(SetArgPointee<5>(lost_packets));
3459 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3460 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3461 ProcessAckPacket(&ack);
3462
3463 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 12);
3464
3465 // Unblock the connection and verify that the RST_STREAM is sent and the
3466 // second data packet or a retransmit is sent.
3467 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(2));
3468 writer_->SetWritable();
3469 connection_.OnCanWrite();
3470 // The RST_STREAM_FRAME is sent after queued packets and pending
3471 // retransmission.
3472 connection_.SendControlFrame(QuicFrame(
3473 new QuicRstStreamFrame(1, stream_id, QUIC_STREAM_NO_ERROR, 14)));
nharper55fa6132019-05-07 19:37:21 -07003474 size_t padding_frame_count = writer_->padding_frames().size();
3475 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003476 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3477}
3478
3479TEST_P(QuicConnectionTest, RetransmitAckedPacket) {
3480 QuicPacketNumber last_packet;
3481 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
3482 SendStreamDataToPeer(1, "foos", 3, NO_FIN, &last_packet); // Packet 2
3483 SendStreamDataToPeer(1, "fooos", 7, NO_FIN, &last_packet); // Packet 3
3484
3485 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3486
3487 // Instigate a loss with an ack.
3488 QuicAckFrame nack_two = ConstructAckFrame(3, 2);
3489 // The first nack should trigger a fast retransmission, but we'll be
3490 // write blocked, so the packet will be queued.
3491 BlockOnNextWrite();
3492
3493 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003494 lost_packets.push_back(
3495 LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003496 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3497 .WillOnce(SetArgPointee<5>(lost_packets));
3498 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3499 ProcessAckPacket(&nack_two);
3500 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3501
3502 // Now, ack the previous transmission.
3503 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3504 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(false, _, _, _, _));
3505 QuicAckFrame ack_all = InitAckFrame(3);
3506 ProcessAckPacket(&ack_all);
3507
3508 // Unblock the socket and attempt to send the queued packets. We will always
3509 // send the retransmission.
3510 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _))
3511 .Times(1);
3512
3513 writer_->SetWritable();
3514 connection_.OnCanWrite();
3515
3516 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3517 // We do not store retransmittable frames of this retransmission.
3518 EXPECT_FALSE(QuicConnectionPeer::HasRetransmittableFrames(&connection_, 4));
3519}
3520
3521TEST_P(QuicConnectionTest, RetransmitNackedLargestObserved) {
3522 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3523 QuicPacketNumber original, second;
3524
3525 QuicByteCount packet_size =
3526 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &original); // 1st packet.
3527 SendStreamDataToPeer(3, "bar", 3, NO_FIN, &second); // 2nd packet.
3528
3529 QuicAckFrame frame = InitAckFrame({{second, second + 1}});
3530 // The first nack should retransmit the largest observed packet.
3531 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003532 lost_packets.push_back(LostPacket(original, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003533 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3534 .WillOnce(SetArgPointee<5>(lost_packets));
3535 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3536 // Packet 1 is short header for IETF QUIC because the encryption level
3537 // switched to ENCRYPTION_FORWARD_SECURE in SendStreamDataToPeer.
fayangd4291e42019-05-30 10:31:21 -07003538 EXPECT_CALL(*send_algorithm_,
3539 OnPacketSent(_, _, _,
3540 VersionHasIetfInvariantHeader(
3541 GetParam().version.transport_version)
3542 ? packet_size
3543 : packet_size - kQuicVersionSize,
3544 _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003545 ProcessAckPacket(&frame);
3546}
3547
3548TEST_P(QuicConnectionTest, QueueAfterTwoRTOs) {
3549 connection_.SetMaxTailLossProbes(0);
3550
3551 for (int i = 0; i < 10; ++i) {
3552 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3553 connection_.SendStreamDataWithString(3, "foo", i * 3, NO_FIN);
3554 }
3555
3556 // Block the writer and ensure they're queued.
3557 BlockOnNextWrite();
3558 clock_.AdvanceTime(DefaultRetransmissionTime());
3559 // Only one packet should be retransmitted.
3560 connection_.GetRetransmissionAlarm()->Fire();
3561 EXPECT_TRUE(connection_.HasQueuedData());
3562
3563 // Unblock the writer.
3564 writer_->SetWritable();
3565 clock_.AdvanceTime(QuicTime::Delta::FromMicroseconds(
3566 2 * DefaultRetransmissionTime().ToMicroseconds()));
3567 // Retransmit already retransmitted packets event though the packet number
3568 // greater than the largest observed.
3569 if (connection_.session_decides_what_to_write()) {
3570 // 2 RTOs + 1 TLP.
3571 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
3572 } else {
3573 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3574 }
3575 connection_.GetRetransmissionAlarm()->Fire();
3576 connection_.OnCanWrite();
3577}
3578
3579TEST_P(QuicConnectionTest, WriteBlockedBufferedThenSent) {
3580 BlockOnNextWrite();
3581 writer_->set_is_write_blocked_data_buffered(true);
3582 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3583 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3584 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3585
3586 writer_->SetWritable();
3587 connection_.OnCanWrite();
3588 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3589}
3590
3591TEST_P(QuicConnectionTest, WriteBlockedThenSent) {
3592 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3593 BlockOnNextWrite();
3594 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3595 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3596 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3597
3598 // The second packet should also be queued, in order to ensure packets are
3599 // never sent out of order.
3600 writer_->SetWritable();
3601 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3602 EXPECT_EQ(2u, connection_.NumQueuedPackets());
3603
3604 // Now both are sent in order when we unblock.
3605 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3606 connection_.OnCanWrite();
3607 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3608}
3609
3610TEST_P(QuicConnectionTest, RetransmitWriteBlockedAckedOriginalThenSent) {
3611 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3612 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
3613 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3614
3615 BlockOnNextWrite();
3616 writer_->set_is_write_blocked_data_buffered(true);
3617 // Simulate the retransmission alarm firing.
3618 clock_.AdvanceTime(DefaultRetransmissionTime());
3619 connection_.GetRetransmissionAlarm()->Fire();
3620
3621 // Ack the sent packet before the callback returns, which happens in
3622 // rare circumstances with write blocked sockets.
3623 QuicAckFrame ack = InitAckFrame(1);
3624 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3625 ProcessAckPacket(&ack);
3626
3627 writer_->SetWritable();
3628 connection_.OnCanWrite();
3629 // There is now a pending packet, but with no retransmittable frames.
3630 if (GetQuicReloadableFlag(quic_optimize_inflight_check)) {
3631 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3632 // Firing the alarm should remove all bytes_in_flight.
3633 connection_.GetRetransmissionAlarm()->Fire();
ianswett9f459cb2019-04-21 06:39:59 -07003634 EXPECT_EQ(0u, manager_->GetBytesInFlight());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003635 }
3636 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3637 EXPECT_FALSE(QuicConnectionPeer::HasRetransmittableFrames(&connection_, 2));
3638}
3639
3640TEST_P(QuicConnectionTest, AlarmsWhenWriteBlocked) {
3641 // Block the connection.
3642 BlockOnNextWrite();
3643 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
3644 EXPECT_EQ(1u, writer_->packets_write_attempts());
3645 EXPECT_TRUE(writer_->IsWriteBlocked());
3646
3647 // Set the send alarm. Fire the alarm and ensure it doesn't attempt to write.
3648 connection_.GetSendAlarm()->Set(clock_.ApproximateNow());
3649 connection_.GetSendAlarm()->Fire();
3650 EXPECT_TRUE(writer_->IsWriteBlocked());
3651 EXPECT_EQ(1u, writer_->packets_write_attempts());
3652}
3653
3654TEST_P(QuicConnectionTest, NoSendAlarmAfterProcessPacketWhenWriteBlocked) {
3655 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3656
3657 // Block the connection.
3658 BlockOnNextWrite();
3659 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
3660 EXPECT_TRUE(writer_->IsWriteBlocked());
3661 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3662 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
3663
3664 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3665 // Process packet number 1. Can not call ProcessPacket or ProcessDataPacket
3666 // here, because they will fire the alarm after QuicConnection::ProcessPacket
3667 // is returned.
3668 const uint64_t received_packet_num = 1;
3669 const bool has_stop_waiting = false;
QUICHE team6987b4a2019-03-15 16:23:04 -07003670 const EncryptionLevel level = ENCRYPTION_INITIAL;
QUICHE team8c1daa22019-03-13 08:33:41 -07003671 std::unique_ptr<QuicPacket> packet(ConstructDataPacket(
nharper46833c32019-05-15 21:33:05 -07003672 received_packet_num, has_stop_waiting, ENCRYPTION_FORWARD_SECURE));
dschinazi66dea072019-04-09 11:41:06 -07003673 char buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05003674 size_t encrypted_length =
3675 peer_framer_.EncryptPayload(level, QuicPacketNumber(received_packet_num),
dschinazi66dea072019-04-09 11:41:06 -07003676 *packet, buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003677 connection_.ProcessUdpPacket(
3678 kSelfAddress, kPeerAddress,
3679 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
3680
3681 EXPECT_TRUE(writer_->IsWriteBlocked());
3682 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
3683}
3684
3685TEST_P(QuicConnectionTest, AddToWriteBlockedListIfWriterBlockedWhenProcessing) {
3686 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3687 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
3688
3689 // Simulate the case where a shared writer gets blocked by another connection.
3690 writer_->SetWriteBlocked();
3691
3692 // Process an ACK, make sure the connection calls visitor_->OnWriteBlocked().
3693 QuicAckFrame ack1 = InitAckFrame(1);
3694 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
3695 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
3696 ProcessAckPacket(1, &ack1);
3697}
3698
3699TEST_P(QuicConnectionTest, DoNotAddToWriteBlockedListAfterDisconnect) {
3700 writer_->SetBatchMode(true);
3701 EXPECT_TRUE(connection_.connected());
3702 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, _,
3703 ConnectionCloseSource::FROM_SELF));
3704
3705 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
3706
3707 {
fayanga4b37b22019-06-18 13:37:47 -07003708 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003709 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
3710 ConnectionCloseBehavior::SILENT_CLOSE);
3711
3712 EXPECT_FALSE(connection_.connected());
3713 writer_->SetWriteBlocked();
3714 }
3715}
3716
3717TEST_P(QuicConnectionTest, AddToWriteBlockedListIfBlockedOnFlushPackets) {
3718 writer_->SetBatchMode(true);
3719 writer_->BlockOnNextFlush();
3720
3721 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
3722 {
fayanga4b37b22019-06-18 13:37:47 -07003723 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003724 // flusher's destructor will call connection_.FlushPackets, which should add
3725 // the connection to the write blocked list.
3726 }
3727}
3728
3729TEST_P(QuicConnectionTest, NoLimitPacketsPerNack) {
3730 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3731 int offset = 0;
3732 // Send packets 1 to 15.
3733 for (int i = 0; i < 15; ++i) {
3734 SendStreamDataToPeer(1, "foo", offset, NO_FIN, nullptr);
3735 offset += 3;
3736 }
3737
3738 // Ack 15, nack 1-14.
3739
3740 QuicAckFrame nack =
3741 InitAckFrame({{QuicPacketNumber(15), QuicPacketNumber(16)}});
3742
3743 // 14 packets have been NACK'd and lost.
3744 LostPacketVector lost_packets;
3745 for (int i = 1; i < 15; ++i) {
dschinazi66dea072019-04-09 11:41:06 -07003746 lost_packets.push_back(
3747 LostPacket(QuicPacketNumber(i), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003748 }
3749 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3750 .WillOnce(SetArgPointee<5>(lost_packets));
3751 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3752 if (connection_.session_decides_what_to_write()) {
3753 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3754 } else {
3755 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(14);
3756 }
3757 ProcessAckPacket(&nack);
3758}
3759
3760// Test sending multiple acks from the connection to the session.
3761TEST_P(QuicConnectionTest, MultipleAcks) {
QUICHE teamcd098022019-03-22 18:49:55 -07003762 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3763 return;
3764 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003765 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3766 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3767 ProcessDataPacket(1);
3768 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
3769 QuicPacketNumber last_packet;
3770 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
3771 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
3772 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet); // Packet 2
3773 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
3774 SendAckPacketToPeer(); // Packet 3
3775 SendStreamDataToPeer(5, "foo", 0, NO_FIN, &last_packet); // Packet 4
3776 EXPECT_EQ(QuicPacketNumber(4u), last_packet);
3777 SendStreamDataToPeer(1, "foo", 3, NO_FIN, &last_packet); // Packet 5
3778 EXPECT_EQ(QuicPacketNumber(5u), last_packet);
3779 SendStreamDataToPeer(3, "foo", 3, NO_FIN, &last_packet); // Packet 6
3780 EXPECT_EQ(QuicPacketNumber(6u), last_packet);
3781
3782 // Client will ack packets 1, 2, [!3], 4, 5.
3783 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3784 QuicAckFrame frame1 = ConstructAckFrame(5, 3);
3785 ProcessAckPacket(&frame1);
3786
3787 // Now the client implicitly acks 3, and explicitly acks 6.
3788 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3789 QuicAckFrame frame2 = InitAckFrame(6);
3790 ProcessAckPacket(&frame2);
3791}
3792
3793TEST_P(QuicConnectionTest, DontLatchUnackedPacket) {
QUICHE teamcd098022019-03-22 18:49:55 -07003794 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3795 return;
3796 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003797 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3798 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3799 ProcessDataPacket(1);
3800 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
3801 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr); // Packet 1;
3802 // From now on, we send acks, so the send algorithm won't mark them pending.
3803 SendAckPacketToPeer(); // Packet 2
3804
3805 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3806 QuicAckFrame frame = InitAckFrame(1);
3807 ProcessAckPacket(&frame);
3808
3809 // Verify that our internal state has least-unacked as 2, because we're still
3810 // waiting for a potential ack for 2.
3811
3812 EXPECT_EQ(QuicPacketNumber(2u), stop_waiting()->least_unacked);
3813
3814 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3815 frame = InitAckFrame(2);
3816 ProcessAckPacket(&frame);
3817 EXPECT_EQ(QuicPacketNumber(3u), stop_waiting()->least_unacked);
3818
3819 // When we send an ack, we make sure our least-unacked makes sense. In this
3820 // case since we're not waiting on an ack for 2 and all packets are acked, we
3821 // set it to 3.
3822 SendAckPacketToPeer(); // Packet 3
3823 // Least_unacked remains at 3 until another ack is received.
3824 EXPECT_EQ(QuicPacketNumber(3u), stop_waiting()->least_unacked);
3825 if (GetParam().no_stop_waiting) {
3826 // Expect no stop waiting frame is sent.
3827 EXPECT_FALSE(least_unacked().IsInitialized());
3828 } else {
3829 // Check that the outgoing ack had its packet number as least_unacked.
3830 EXPECT_EQ(QuicPacketNumber(3u), least_unacked());
3831 }
3832
3833 // Ack the ack, which updates the rtt and raises the least unacked.
3834 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3835 frame = InitAckFrame(3);
3836 ProcessAckPacket(&frame);
3837
3838 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr); // Packet 4
3839 EXPECT_EQ(QuicPacketNumber(4u), stop_waiting()->least_unacked);
3840 SendAckPacketToPeer(); // Packet 5
3841 if (GetParam().no_stop_waiting) {
3842 // Expect no stop waiting frame is sent.
3843 EXPECT_FALSE(least_unacked().IsInitialized());
3844 } else {
3845 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
3846 }
3847
3848 // Send two data packets at the end, and ensure if the last one is acked,
3849 // the least unacked is raised above the ack packets.
3850 SendStreamDataToPeer(1, "bar", 6, NO_FIN, nullptr); // Packet 6
3851 SendStreamDataToPeer(1, "bar", 9, NO_FIN, nullptr); // Packet 7
3852
3853 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3854 frame = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(5)},
3855 {QuicPacketNumber(7), QuicPacketNumber(8)}});
3856 ProcessAckPacket(&frame);
3857
3858 EXPECT_EQ(QuicPacketNumber(6u), stop_waiting()->least_unacked);
3859}
3860
3861TEST_P(QuicConnectionTest, TLP) {
3862 connection_.SetMaxTailLossProbes(1);
3863
3864 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
3865 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
3866 QuicTime retransmission_time =
3867 connection_.GetRetransmissionAlarm()->deadline();
3868 EXPECT_NE(QuicTime::Zero(), retransmission_time);
3869
3870 EXPECT_EQ(QuicPacketNumber(1u), writer_->header().packet_number);
3871 // Simulate the retransmission alarm firing and sending a tlp,
3872 // so send algorithm's OnRetransmissionTimeout is not called.
3873 clock_.AdvanceTime(retransmission_time - clock_.Now());
3874 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
3875 connection_.GetRetransmissionAlarm()->Fire();
3876 EXPECT_EQ(QuicPacketNumber(2u), writer_->header().packet_number);
3877 // We do not raise the high water mark yet.
3878 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
3879}
3880
zhongyifbb25772019-04-10 16:54:08 -07003881TEST_P(QuicConnectionTest, TailLossProbeDelayForStreamDataInTLPR) {
zhongyi1b2f7832019-06-14 13:31:34 -07003882 if (!connection_.session_decides_what_to_write()) {
3883 return;
3884 }
3885
zhongyifbb25772019-04-10 16:54:08 -07003886 // Set TLPR from QuicConfig.
3887 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3888 QuicConfig config;
3889 QuicTagVector options;
3890 options.push_back(kTLPR);
3891 config.SetConnectionOptionsToSend(options);
3892 connection_.SetFromConfig(config);
3893 connection_.SetMaxTailLossProbes(1);
3894
3895 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
3896 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
3897
3898 QuicTime retransmission_time =
3899 connection_.GetRetransmissionAlarm()->deadline();
3900 EXPECT_NE(QuicTime::Zero(), retransmission_time);
3901 QuicTime::Delta expected_tlp_delay =
3902 0.5 * manager_->GetRttStats()->SmoothedOrInitialRtt();
3903 EXPECT_EQ(expected_tlp_delay, retransmission_time - clock_.Now());
3904
3905 EXPECT_EQ(QuicPacketNumber(1u), writer_->header().packet_number);
3906 // Simulate firing of the retransmission alarm and retransmit the packet.
3907 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
3908 clock_.AdvanceTime(retransmission_time - clock_.Now());
3909 connection_.GetRetransmissionAlarm()->Fire();
3910 EXPECT_EQ(QuicPacketNumber(2u), writer_->header().packet_number);
3911
3912 // We do not raise the high water mark yet.
3913 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
3914}
3915
3916TEST_P(QuicConnectionTest, TailLossProbeDelayForNonStreamDataInTLPR) {
zhongyi1b2f7832019-06-14 13:31:34 -07003917 if (!connection_.session_decides_what_to_write()) {
3918 return;
3919 }
3920
zhongyifbb25772019-04-10 16:54:08 -07003921 // Set TLPR from QuicConfig.
3922 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3923 QuicConfig config;
3924 QuicTagVector options;
3925 options.push_back(kTLPR);
3926 config.SetConnectionOptionsToSend(options);
3927 connection_.SetFromConfig(config);
3928 connection_.SetMaxTailLossProbes(1);
3929
3930 // Sets retransmittable on wire.
3931 const QuicTime::Delta retransmittable_on_wire_timeout =
3932 QuicTime::Delta::FromMilliseconds(50);
3933 connection_.set_retransmittable_on_wire_timeout(
3934 retransmittable_on_wire_timeout);
3935
3936 EXPECT_TRUE(connection_.connected());
3937 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
3938 .WillRepeatedly(Return(true));
3939 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
3940 EXPECT_FALSE(connection_.IsPathDegrading());
3941 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
3942
3943 const char data[] = "data";
3944 size_t data_size = strlen(data);
3945 QuicStreamOffset offset = 0;
3946
3947 // Send a data packet.
3948 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
3949 offset += data_size;
3950
3951 // Path degrading alarm should be set when there is a retransmittable packet
3952 // on the wire.
3953 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
3954
3955 // Verify the path degrading delay.
3956 // First TLP with stream data.
3957 QuicTime::Delta srtt = manager_->GetRttStats()->SmoothedOrInitialRtt();
3958 QuicTime::Delta expected_delay = 0.5 * srtt;
3959 // Add 1st RTO.
3960 QuicTime::Delta retransmission_delay =
3961 QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
3962 expected_delay = expected_delay + retransmission_delay;
3963 // Add 2nd RTO.
3964 expected_delay = expected_delay + retransmission_delay * 2;
3965 EXPECT_EQ(expected_delay,
3966 QuicConnectionPeer::GetSentPacketManager(&connection_)
3967 ->GetPathDegradingDelay());
3968 ASSERT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
3969
3970 // The ping alarm is set for the ping timeout, not the shorter
3971 // retransmittable_on_wire_timeout.
3972 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
3973 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
3974 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
3975
3976 // Receive an ACK for the data packet.
3977 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
3978 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3979 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3980 QuicAckFrame frame =
3981 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
3982 ProcessAckPacket(&frame);
3983
3984 // Path degrading alarm should be cancelled as there is no more
3985 // reretransmittable packets on the wire.
3986 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
3987 // The ping alarm should be set to the retransmittable_on_wire_timeout.
3988 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
3989 EXPECT_EQ(retransmittable_on_wire_timeout,
3990 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
3991
3992 // Simulate firing of the retransmittable on wire and send a PING.
3993 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
3994 clock_.AdvanceTime(retransmittable_on_wire_timeout);
3995 connection_.GetPingAlarm()->Fire();
3996
3997 // The retransmission alarm and the path degrading alarm should be set as
3998 // there is a retransmittable packet (PING) on the wire,
3999 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4000 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
4001
4002 // Verify the retransmission delay.
4003 QuicTime::Delta min_rto_timeout =
4004 QuicTime::Delta::FromMilliseconds(kMinRetransmissionTimeMs);
4005 srtt = manager_->GetRttStats()->SmoothedOrInitialRtt();
zhongyi1b2f7832019-06-14 13:31:34 -07004006 if (GetQuicReloadableFlag(quic_ignore_tlpr_if_no_pending_stream_data)) {
zhongyifbb25772019-04-10 16:54:08 -07004007 // First TLP without unacked stream data will no longer use TLPR.
4008 expected_delay = std::max(2 * srtt, 1.5 * srtt + 0.5 * min_rto_timeout);
4009 } else {
4010 expected_delay =
4011 std::max(QuicTime::Delta::FromMilliseconds(kMinTailLossProbeTimeoutMs),
4012 srtt * 0.5);
4013 }
4014 EXPECT_EQ(expected_delay,
4015 connection_.GetRetransmissionAlarm()->deadline() - clock_.Now());
4016
zhongyi1b2f7832019-06-14 13:31:34 -07004017 // Verify the path degrading delay = TLP delay + 1st RTO + 2nd RTO.
zhongyifbb25772019-04-10 16:54:08 -07004018 // Add 1st RTO.
4019 retransmission_delay =
4020 std::max(manager_->GetRttStats()->smoothed_rtt() +
4021 4 * manager_->GetRttStats()->mean_deviation(),
4022 min_rto_timeout);
4023 expected_delay = expected_delay + retransmission_delay;
4024 // Add 2nd RTO.
4025 expected_delay = expected_delay + retransmission_delay * 2;
4026 EXPECT_EQ(expected_delay,
4027 QuicConnectionPeer::GetSentPacketManager(&connection_)
4028 ->GetPathDegradingDelay());
4029
4030 // The ping alarm is set for the ping timeout, not the shorter
4031 // retransmittable_on_wire_timeout.
4032 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4033 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
4034 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
zhongyi1b2f7832019-06-14 13:31:34 -07004035
4036 // Advance a small period of time: 5ms. And receive a retransmitted ACK.
4037 // This will update the retransmission alarm, verify the retransmission delay
4038 // is correct.
4039 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4040 QuicAckFrame ack = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
4041 ProcessAckPacket(&ack);
4042
4043 // Verify the retransmission delay.
4044 if (GetQuicReloadableFlag(quic_ignore_tlpr_if_no_pending_stream_data)) {
4045 // First TLP without unacked stream data will no longer use TLPR.
4046 expected_delay = std::max(2 * srtt, 1.5 * srtt + 0.5 * min_rto_timeout);
4047 } else {
4048 expected_delay =
4049 std::max(QuicTime::Delta::FromMilliseconds(kMinTailLossProbeTimeoutMs),
4050 srtt * 0.5);
4051 }
4052 expected_delay = expected_delay - QuicTime::Delta::FromMilliseconds(5);
4053 EXPECT_EQ(expected_delay,
4054 connection_.GetRetransmissionAlarm()->deadline() - clock_.Now());
zhongyifbb25772019-04-10 16:54:08 -07004055}
4056
QUICHE teama6ef0a62019-03-07 20:34:33 -05004057TEST_P(QuicConnectionTest, RTO) {
4058 connection_.SetMaxTailLossProbes(0);
4059
4060 QuicTime default_retransmission_time =
4061 clock_.ApproximateNow() + DefaultRetransmissionTime();
4062 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
4063 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4064
4065 EXPECT_EQ(QuicPacketNumber(1u), writer_->header().packet_number);
4066 EXPECT_EQ(default_retransmission_time,
4067 connection_.GetRetransmissionAlarm()->deadline());
4068 // Simulate the retransmission alarm firing.
4069 clock_.AdvanceTime(DefaultRetransmissionTime());
4070 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
4071 connection_.GetRetransmissionAlarm()->Fire();
4072 EXPECT_EQ(QuicPacketNumber(2u), writer_->header().packet_number);
4073 // We do not raise the high water mark yet.
4074 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4075}
4076
4077TEST_P(QuicConnectionTest, RetransmitWithSameEncryptionLevel) {
4078 use_tagging_decrypter();
4079
4080 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
4081 // the end of the packet. We can test this to check which encrypter was used.
QUICHE team6987b4a2019-03-15 16:23:04 -07004082 connection_.SetEncrypter(ENCRYPTION_INITIAL,
QUICHE teama6ef0a62019-03-07 20:34:33 -05004083 QuicMakeUnique<TaggingEncrypter>(0x01));
nharper46833c32019-05-15 21:33:05 -07004084 QuicByteCount packet_size;
4085 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4086 .WillOnce(SaveArg<3>(&packet_size));
4087 connection_.SendCryptoDataWithString("foo", 0);
4088 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004089 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
4090
4091 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
4092 QuicMakeUnique<TaggingEncrypter>(0x02));
4093 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4094 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
4095 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
4096
4097 {
4098 InSequence s;
4099 EXPECT_CALL(*send_algorithm_,
4100 OnPacketSent(_, _, QuicPacketNumber(3), _, _));
4101 EXPECT_CALL(*send_algorithm_,
4102 OnPacketSent(_, _, QuicPacketNumber(4), _, _));
4103 }
4104
4105 // Manually mark both packets for retransmission.
4106 connection_.RetransmitUnackedPackets(ALL_UNACKED_RETRANSMISSION);
4107
QUICHE team6987b4a2019-03-15 16:23:04 -07004108 // Packet should have been sent with ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05004109 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_previous_packet());
4110
4111 // Packet should have been sent with ENCRYPTION_ZERO_RTT.
4112 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
4113}
4114
4115TEST_P(QuicConnectionTest, SendHandshakeMessages) {
4116 use_tagging_decrypter();
4117 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
4118 // the end of the packet. We can test this to check which encrypter was used.
QUICHE team6987b4a2019-03-15 16:23:04 -07004119 connection_.SetEncrypter(ENCRYPTION_INITIAL,
QUICHE teama6ef0a62019-03-07 20:34:33 -05004120 QuicMakeUnique<TaggingEncrypter>(0x01));
4121
4122 // Attempt to send a handshake message and have the socket block.
4123 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
4124 BlockOnNextWrite();
nharper46833c32019-05-15 21:33:05 -07004125 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004126 // The packet should be serialized, but not queued.
4127 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4128
4129 // Switch to the new encrypter.
4130 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
4131 QuicMakeUnique<TaggingEncrypter>(0x02));
4132 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4133
4134 // Now become writeable and flush the packets.
4135 writer_->SetWritable();
4136 EXPECT_CALL(visitor_, OnCanWrite());
4137 connection_.OnCanWrite();
4138 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4139
4140 // Verify that the handshake packet went out at the null encryption.
4141 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
4142}
4143
4144TEST_P(QuicConnectionTest,
4145 DropRetransmitsForNullEncryptedPacketAfterForwardSecure) {
4146 use_tagging_decrypter();
QUICHE team6987b4a2019-03-15 16:23:04 -07004147 connection_.SetEncrypter(ENCRYPTION_INITIAL,
QUICHE teama6ef0a62019-03-07 20:34:33 -05004148 QuicMakeUnique<TaggingEncrypter>(0x01));
4149 QuicPacketNumber packet_number;
4150 connection_.SendCryptoStreamData();
4151
4152 // Simulate the retransmission alarm firing and the socket blocking.
4153 BlockOnNextWrite();
4154 clock_.AdvanceTime(DefaultRetransmissionTime());
4155 connection_.GetRetransmissionAlarm()->Fire();
4156
4157 // Go forward secure.
4158 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
4159 QuicMakeUnique<TaggingEncrypter>(0x02));
4160 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4161 notifier_.NeuterUnencryptedData();
4162 connection_.NeuterUnencryptedPackets();
4163
4164 EXPECT_EQ(QuicTime::Zero(), connection_.GetRetransmissionAlarm()->deadline());
4165 // Unblock the socket and ensure that no packets are sent.
4166 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4167 writer_->SetWritable();
4168 connection_.OnCanWrite();
4169}
4170
4171TEST_P(QuicConnectionTest, RetransmitPacketsWithInitialEncryption) {
4172 use_tagging_decrypter();
QUICHE team6987b4a2019-03-15 16:23:04 -07004173 connection_.SetEncrypter(ENCRYPTION_INITIAL,
QUICHE teama6ef0a62019-03-07 20:34:33 -05004174 QuicMakeUnique<TaggingEncrypter>(0x01));
QUICHE team6987b4a2019-03-15 16:23:04 -07004175 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004176
nharper46833c32019-05-15 21:33:05 -07004177 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004178
4179 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
4180 QuicMakeUnique<TaggingEncrypter>(0x02));
4181 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4182
4183 SendStreamDataToPeer(2, "bar", 0, NO_FIN, nullptr);
4184 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4185
4186 connection_.RetransmitUnackedPackets(ALL_INITIAL_RETRANSMISSION);
4187}
4188
4189TEST_P(QuicConnectionTest, BufferNonDecryptablePackets) {
QUICHE teamcd098022019-03-22 18:49:55 -07004190 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4191 return;
4192 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004193 // SetFromConfig is always called after construction from InitializeSession.
4194 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4195 QuicConfig config;
4196 connection_.SetFromConfig(config);
4197 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4198 use_tagging_decrypter();
4199
4200 const uint8_t tag = 0x07;
4201 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
4202 QuicMakeUnique<TaggingEncrypter>(tag));
4203
4204 // Process an encrypted packet which can not yet be decrypted which should
4205 // result in the packet being buffered.
4206 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4207
4208 // Transition to the new encryption state and process another encrypted packet
4209 // which should result in the original packet being processed.
zhongyi546cc452019-04-12 15:27:49 -07004210 SetDecrypter(ENCRYPTION_ZERO_RTT,
4211 QuicMakeUnique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004212 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4213 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
4214 QuicMakeUnique<TaggingEncrypter>(tag));
4215 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(2);
4216 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4217
4218 // Finally, process a third packet and note that we do not reprocess the
4219 // buffered packet.
4220 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4221 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4222}
4223
4224TEST_P(QuicConnectionTest, TestRetransmitOrder) {
4225 connection_.SetMaxTailLossProbes(0);
4226
4227 QuicByteCount first_packet_size;
4228 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4229 .WillOnce(SaveArg<3>(&first_packet_size));
4230
4231 connection_.SendStreamDataWithString(3, "first_packet", 0, NO_FIN);
4232 QuicByteCount second_packet_size;
4233 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4234 .WillOnce(SaveArg<3>(&second_packet_size));
4235 connection_.SendStreamDataWithString(3, "second_packet", 12, NO_FIN);
4236 EXPECT_NE(first_packet_size, second_packet_size);
4237 // Advance the clock by huge time to make sure packets will be retransmitted.
4238 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
4239 {
4240 InSequence s;
4241 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, first_packet_size, _));
4242 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, second_packet_size, _));
4243 }
4244 connection_.GetRetransmissionAlarm()->Fire();
4245
4246 // Advance again and expect the packets to be sent again in the same order.
4247 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(20));
4248 {
4249 InSequence s;
4250 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, first_packet_size, _));
4251 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, second_packet_size, _));
4252 }
4253 connection_.GetRetransmissionAlarm()->Fire();
4254}
4255
4256TEST_P(QuicConnectionTest, Buffer100NonDecryptablePacketsThenKeyChange) {
QUICHE teamcd098022019-03-22 18:49:55 -07004257 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4258 return;
4259 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004260 // SetFromConfig is always called after construction from InitializeSession.
4261 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4262 QuicConfig config;
4263 config.set_max_undecryptable_packets(100);
4264 connection_.SetFromConfig(config);
4265 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4266 use_tagging_decrypter();
4267
4268 const uint8_t tag = 0x07;
4269 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
4270 QuicMakeUnique<TaggingEncrypter>(tag));
4271
4272 // Process an encrypted packet which can not yet be decrypted which should
4273 // result in the packet being buffered.
4274 for (uint64_t i = 1; i <= 100; ++i) {
4275 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4276 }
4277
4278 // Transition to the new encryption state and process another encrypted packet
4279 // which should result in the original packets being processed.
4280 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
zhongyi546cc452019-04-12 15:27:49 -07004281 SetDecrypter(ENCRYPTION_ZERO_RTT,
4282 QuicMakeUnique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004283 EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
4284 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4285 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
4286 QuicMakeUnique<TaggingEncrypter>(tag));
4287
4288 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(100);
4289 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
4290
4291 // Finally, process a third packet and note that we do not reprocess the
4292 // buffered packet.
4293 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4294 ProcessDataPacketAtLevel(102, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4295}
4296
4297TEST_P(QuicConnectionTest, SetRTOAfterWritingToSocket) {
4298 BlockOnNextWrite();
4299 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4300 // Make sure that RTO is not started when the packet is queued.
4301 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4302
4303 // Test that RTO is started once we write to the socket.
4304 writer_->SetWritable();
4305 connection_.OnCanWrite();
4306 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4307}
4308
4309TEST_P(QuicConnectionTest, DelayRTOWithAckReceipt) {
4310 connection_.SetMaxTailLossProbes(0);
4311
4312 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4313 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
4314 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
4315 connection_.SendStreamDataWithString(3, "bar", 0, NO_FIN);
4316 QuicAlarm* retransmission_alarm = connection_.GetRetransmissionAlarm();
4317 EXPECT_TRUE(retransmission_alarm->IsSet());
4318 EXPECT_EQ(clock_.Now() + DefaultRetransmissionTime(),
4319 retransmission_alarm->deadline());
4320
4321 // Advance the time right before the RTO, then receive an ack for the first
4322 // packet to delay the RTO.
4323 clock_.AdvanceTime(DefaultRetransmissionTime());
4324 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4325 QuicAckFrame ack = InitAckFrame(1);
4326 ProcessAckPacket(&ack);
4327 // Now we have an RTT sample of DefaultRetransmissionTime(500ms),
4328 // so the RTO has increased to 2 * SRTT.
4329 EXPECT_TRUE(retransmission_alarm->IsSet());
4330 EXPECT_EQ(retransmission_alarm->deadline(),
4331 clock_.Now() + 2 * DefaultRetransmissionTime());
4332
4333 // Move forward past the original RTO and ensure the RTO is still pending.
4334 clock_.AdvanceTime(2 * DefaultRetransmissionTime());
4335
4336 // Ensure the second packet gets retransmitted when it finally fires.
4337 EXPECT_TRUE(retransmission_alarm->IsSet());
4338 EXPECT_EQ(retransmission_alarm->deadline(), clock_.ApproximateNow());
4339 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4340 // Manually cancel the alarm to simulate a real test.
4341 connection_.GetRetransmissionAlarm()->Fire();
4342
4343 // The new retransmitted packet number should set the RTO to a larger value
4344 // than previously.
4345 EXPECT_TRUE(retransmission_alarm->IsSet());
4346 QuicTime next_rto_time = retransmission_alarm->deadline();
4347 QuicTime expected_rto_time =
4348 connection_.sent_packet_manager().GetRetransmissionTime();
4349 EXPECT_EQ(next_rto_time, expected_rto_time);
4350}
4351
4352TEST_P(QuicConnectionTest, TestQueued) {
4353 connection_.SetMaxTailLossProbes(0);
4354
4355 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4356 BlockOnNextWrite();
4357 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4358 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4359
4360 // Unblock the writes and actually send.
4361 writer_->SetWritable();
4362 connection_.OnCanWrite();
4363 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4364}
4365
4366TEST_P(QuicConnectionTest, InitialTimeout) {
4367 EXPECT_TRUE(connection_.connected());
4368 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4369 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4370
4371 // SetFromConfig sets the initial timeouts before negotiation.
4372 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4373 QuicConfig config;
4374 connection_.SetFromConfig(config);
4375 // Subtract a second from the idle timeout on the client side.
4376 QuicTime default_timeout =
4377 clock_.ApproximateNow() +
4378 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4379 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
4380
4381 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NETWORK_IDLE_TIMEOUT, _,
4382 ConnectionCloseSource::FROM_SELF));
4383 // Simulate the timeout alarm firing.
4384 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1));
4385 connection_.GetTimeoutAlarm()->Fire();
4386
4387 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4388 EXPECT_FALSE(connection_.connected());
4389
4390 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
4391 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4392 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4393 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4394 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
renjietang11e4a3d2019-05-03 11:27:26 -07004395 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004396}
4397
4398TEST_P(QuicConnectionTest, IdleTimeoutAfterFirstSentPacket) {
4399 EXPECT_TRUE(connection_.connected());
4400 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4401 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4402
4403 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4404 QuicConfig config;
4405 connection_.SetFromConfig(config);
4406 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4407 QuicTime initial_ddl =
4408 clock_.ApproximateNow() +
4409 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4410 EXPECT_EQ(initial_ddl, connection_.GetTimeoutAlarm()->deadline());
4411 EXPECT_TRUE(connection_.connected());
4412
4413 // Advance the time and send the first packet to the peer.
4414 clock_.AdvanceTime(QuicTime::Delta::FromMicroseconds(20));
4415 QuicPacketNumber last_packet;
4416 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4417 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4418 // This will be the updated deadline for the connection to idle time out.
4419 QuicTime new_ddl = clock_.ApproximateNow() +
4420 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4421
4422 // Simulate the timeout alarm firing, the connection should not be closed as
4423 // a new packet has been sent.
4424 EXPECT_CALL(visitor_, OnConnectionClosed(_, _, _)).Times(0);
4425 QuicTime::Delta delay = initial_ddl - clock_.ApproximateNow();
4426 clock_.AdvanceTime(delay);
4427 connection_.GetTimeoutAlarm()->Fire();
4428 // Verify the timeout alarm deadline is updated.
4429 EXPECT_TRUE(connection_.connected());
4430 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4431 EXPECT_EQ(new_ddl, connection_.GetTimeoutAlarm()->deadline());
4432
4433 // Simulate the timeout alarm firing again, the connection now should be
4434 // closed.
4435 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NETWORK_IDLE_TIMEOUT, _,
4436 ConnectionCloseSource::FROM_SELF));
4437 clock_.AdvanceTime(new_ddl - clock_.ApproximateNow());
4438 connection_.GetTimeoutAlarm()->Fire();
4439 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4440 EXPECT_FALSE(connection_.connected());
4441
4442 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
4443 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4444 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4445 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4446 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4447}
4448
4449TEST_P(QuicConnectionTest, IdleTimeoutAfterSendTwoPackets) {
4450 EXPECT_TRUE(connection_.connected());
4451 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4452 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4453
4454 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4455 QuicConfig config;
4456 connection_.SetFromConfig(config);
4457 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4458 QuicTime initial_ddl =
4459 clock_.ApproximateNow() +
4460 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4461 EXPECT_EQ(initial_ddl, connection_.GetTimeoutAlarm()->deadline());
4462 EXPECT_TRUE(connection_.connected());
4463
4464 // Immediately send the first packet, this is a rare case but test code will
4465 // hit this issue often as MockClock used for tests doesn't move with code
4466 // execution until manually adjusted.
4467 QuicPacketNumber last_packet;
4468 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4469 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4470
4471 // Advance the time and send the second packet to the peer.
4472 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
4473 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4474 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
4475
4476 if (GetQuicReloadableFlag(
4477 quic_fix_time_of_first_packet_sent_after_receiving)) {
4478 // Simulate the timeout alarm firing, the connection will be closed.
4479 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NETWORK_IDLE_TIMEOUT, _,
4480 ConnectionCloseSource::FROM_SELF));
4481 clock_.AdvanceTime(initial_ddl - clock_.ApproximateNow());
4482 connection_.GetTimeoutAlarm()->Fire();
4483 } else {
4484 // Simulate the timeout alarm firing, the connection will not be closed.
4485 EXPECT_CALL(visitor_, OnConnectionClosed(_, _, _)).Times(0);
4486 clock_.AdvanceTime(initial_ddl - clock_.ApproximateNow());
4487 connection_.GetTimeoutAlarm()->Fire();
4488 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4489 EXPECT_TRUE(connection_.connected());
4490
4491 // Advance another 20ms, and fire the alarm again. The connection will be
4492 // closed.
4493 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NETWORK_IDLE_TIMEOUT, _,
4494 ConnectionCloseSource::FROM_SELF));
4495 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
4496 connection_.GetTimeoutAlarm()->Fire();
4497 }
4498
4499 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4500 EXPECT_FALSE(connection_.connected());
4501
4502 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
4503 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4504 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4505 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4506 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4507}
4508
4509TEST_P(QuicConnectionTest, HandshakeTimeout) {
4510 // Use a shorter handshake timeout than idle timeout for this test.
4511 const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(5);
4512 connection_.SetNetworkTimeouts(timeout, timeout);
4513 EXPECT_TRUE(connection_.connected());
4514 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4515
4516 QuicTime handshake_timeout =
4517 clock_.ApproximateNow() + timeout - QuicTime::Delta::FromSeconds(1);
4518 EXPECT_EQ(handshake_timeout, connection_.GetTimeoutAlarm()->deadline());
4519 EXPECT_TRUE(connection_.connected());
4520
4521 // Send and ack new data 3 seconds later to lengthen the idle timeout.
4522 SendStreamDataToPeer(
dschinazi552accc2019-06-17 17:07:34 -07004523 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
4524 "GET /", 0, FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004525 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(3));
4526 QuicAckFrame frame = InitAckFrame(1);
4527 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4528 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4529 ProcessAckPacket(&frame);
4530
4531 // Fire early to verify it wouldn't timeout yet.
4532 connection_.GetTimeoutAlarm()->Fire();
4533 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4534 EXPECT_TRUE(connection_.connected());
4535
4536 clock_.AdvanceTime(timeout - QuicTime::Delta::FromSeconds(2));
4537
4538 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_HANDSHAKE_TIMEOUT, _,
4539 ConnectionCloseSource::FROM_SELF));
4540 // Simulate the timeout alarm firing.
4541 connection_.GetTimeoutAlarm()->Fire();
4542
4543 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4544 EXPECT_FALSE(connection_.connected());
4545
4546 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
4547 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4548 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4549 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4550}
4551
4552TEST_P(QuicConnectionTest, PingAfterSend) {
QUICHE teamcd098022019-03-22 18:49:55 -07004553 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4554 return;
4555 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004556 EXPECT_TRUE(connection_.connected());
4557 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4558 .WillRepeatedly(Return(true));
4559 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4560
4561 // Advance to 5ms, and send a packet to the peer, which will set
4562 // the ping alarm.
4563 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4564 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4565 SendStreamDataToPeer(
dschinazi552accc2019-06-17 17:07:34 -07004566 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
4567 "GET /", 0, FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004568 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4569 EXPECT_EQ(clock_.ApproximateNow() + QuicTime::Delta::FromSeconds(15),
4570 connection_.GetPingAlarm()->deadline());
4571
4572 // Now recevie an ACK of the previous packet, which will move the
4573 // ping alarm forward.
4574 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4575 QuicAckFrame frame = InitAckFrame(1);
4576 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4577 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4578 ProcessAckPacket(&frame);
4579 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4580 // The ping timer is set slightly less than 15 seconds in the future, because
4581 // of the 1s ping timer alarm granularity.
4582 EXPECT_EQ(clock_.ApproximateNow() + QuicTime::Delta::FromSeconds(15) -
4583 QuicTime::Delta::FromMilliseconds(5),
4584 connection_.GetPingAlarm()->deadline());
4585
4586 writer_->Reset();
4587 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15));
zhongyifbb25772019-04-10 16:54:08 -07004588 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004589 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07004590 size_t padding_frame_count = writer_->padding_frames().size();
4591 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004592 ASSERT_EQ(1u, writer_->ping_frames().size());
4593 writer_->Reset();
4594
4595 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4596 .WillRepeatedly(Return(false));
4597 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4598 SendAckPacketToPeer();
4599
4600 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4601}
4602
4603TEST_P(QuicConnectionTest, ReducedPingTimeout) {
QUICHE teamcd098022019-03-22 18:49:55 -07004604 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4605 return;
4606 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004607 EXPECT_TRUE(connection_.connected());
4608 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4609 .WillRepeatedly(Return(true));
4610 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4611
4612 // Use a reduced ping timeout for this connection.
4613 connection_.set_ping_timeout(QuicTime::Delta::FromSeconds(10));
4614
4615 // Advance to 5ms, and send a packet to the peer, which will set
4616 // the ping alarm.
4617 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4618 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4619 SendStreamDataToPeer(
dschinazi552accc2019-06-17 17:07:34 -07004620 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
4621 "GET /", 0, FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004622 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4623 EXPECT_EQ(clock_.ApproximateNow() + QuicTime::Delta::FromSeconds(10),
4624 connection_.GetPingAlarm()->deadline());
4625
4626 // Now recevie an ACK of the previous packet, which will move the
4627 // ping alarm forward.
4628 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4629 QuicAckFrame frame = InitAckFrame(1);
4630 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4631 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4632 ProcessAckPacket(&frame);
4633 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4634 // The ping timer is set slightly less than 10 seconds in the future, because
4635 // of the 1s ping timer alarm granularity.
4636 EXPECT_EQ(clock_.ApproximateNow() + QuicTime::Delta::FromSeconds(10) -
4637 QuicTime::Delta::FromMilliseconds(5),
4638 connection_.GetPingAlarm()->deadline());
4639
4640 writer_->Reset();
4641 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
4642 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
4643 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
4644 }));
4645 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07004646 size_t padding_frame_count = writer_->padding_frames().size();
4647 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004648 ASSERT_EQ(1u, writer_->ping_frames().size());
4649 writer_->Reset();
4650
4651 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4652 .WillRepeatedly(Return(false));
4653 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4654 SendAckPacketToPeer();
4655
4656 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4657}
4658
4659// Tests whether sending an MTU discovery packet to peer successfully causes the
4660// maximum packet size to increase.
4661TEST_P(QuicConnectionTest, SendMtuDiscoveryPacket) {
QUICHE teamcd098022019-03-22 18:49:55 -07004662 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4663 return;
4664 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004665 EXPECT_TRUE(connection_.connected());
4666
4667 // Send an MTU probe.
4668 const size_t new_mtu = kDefaultMaxPacketSize + 100;
4669 QuicByteCount mtu_probe_size;
4670 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4671 .WillOnce(SaveArg<3>(&mtu_probe_size));
4672 connection_.SendMtuDiscoveryPacket(new_mtu);
4673 EXPECT_EQ(new_mtu, mtu_probe_size);
4674 EXPECT_EQ(QuicPacketNumber(1u), creator_->packet_number());
4675
4676 // Send more than MTU worth of data. No acknowledgement was received so far,
4677 // so the MTU should be at its old value.
vasilvvc48c8712019-03-11 13:38:16 -07004678 const std::string data(kDefaultMaxPacketSize + 1, '.');
QUICHE teama6ef0a62019-03-07 20:34:33 -05004679 QuicByteCount size_before_mtu_change;
4680 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4681 .Times(2)
4682 .WillOnce(SaveArg<3>(&size_before_mtu_change))
4683 .WillOnce(Return());
4684 connection_.SendStreamDataWithString(3, data, 0, FIN);
4685 EXPECT_EQ(QuicPacketNumber(3u), creator_->packet_number());
4686 EXPECT_EQ(kDefaultMaxPacketSize, size_before_mtu_change);
4687
4688 // Acknowledge all packets so far.
4689 QuicAckFrame probe_ack = InitAckFrame(3);
4690 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4691 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4692 ProcessAckPacket(&probe_ack);
4693 EXPECT_EQ(new_mtu, connection_.max_packet_length());
4694
4695 // Send the same data again. Check that it fits into a single packet now.
4696 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4697 connection_.SendStreamDataWithString(3, data, 0, FIN);
4698 EXPECT_EQ(QuicPacketNumber(4u), creator_->packet_number());
4699}
4700
4701// Tests whether MTU discovery does not happen when it is not explicitly enabled
4702// by the connection options.
4703TEST_P(QuicConnectionTest, MtuDiscoveryDisabled) {
4704 EXPECT_TRUE(connection_.connected());
4705
4706 const QuicPacketCount packets_between_probes_base = 10;
4707 set_packets_between_probes_base(packets_between_probes_base);
4708
4709 const QuicPacketCount number_of_packets = packets_between_probes_base * 2;
4710 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
4711 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
4712 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4713 EXPECT_EQ(0u, connection_.mtu_probe_count());
4714 }
4715}
4716
4717// Tests whether MTU discovery works when the probe gets acknowledged on the
4718// first try.
4719TEST_P(QuicConnectionTest, MtuDiscoveryEnabled) {
4720 EXPECT_TRUE(connection_.connected());
4721
4722 connection_.EnablePathMtuDiscovery(send_algorithm_);
4723
4724 const QuicPacketCount packets_between_probes_base = 5;
4725 set_packets_between_probes_base(packets_between_probes_base);
4726
4727 // Send enough packets so that the next one triggers path MTU discovery.
4728 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
4729 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
4730 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4731 }
4732
4733 // Trigger the probe.
4734 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
4735 nullptr);
4736 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4737 QuicByteCount probe_size;
4738 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4739 .WillOnce(SaveArg<3>(&probe_size));
4740 connection_.GetMtuDiscoveryAlarm()->Fire();
4741 EXPECT_EQ(kMtuDiscoveryTargetPacketSizeHigh, probe_size);
4742
4743 const QuicPacketNumber probe_packet_number =
4744 FirstSendingPacketNumber() + packets_between_probes_base;
4745 ASSERT_EQ(probe_packet_number, creator_->packet_number());
4746
4747 // Acknowledge all packets sent so far.
4748 QuicAckFrame probe_ack = InitAckFrame(probe_packet_number);
4749 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4750 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4751 ProcessAckPacket(&probe_ack);
4752 EXPECT_EQ(kMtuDiscoveryTargetPacketSizeHigh, connection_.max_packet_length());
4753 EXPECT_EQ(0u, connection_.GetBytesInFlight());
4754
4755 // Send more packets, and ensure that none of them sets the alarm.
4756 for (QuicPacketCount i = 0; i < 4 * packets_between_probes_base; i++) {
4757 SendStreamDataToPeer(3, ".", packets_between_probes_base + i, NO_FIN,
4758 nullptr);
4759 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4760 }
4761
4762 EXPECT_EQ(1u, connection_.mtu_probe_count());
4763}
4764
4765// Tests whether MTU discovery works correctly when the probes never get
4766// acknowledged.
4767TEST_P(QuicConnectionTest, MtuDiscoveryFailed) {
4768 EXPECT_TRUE(connection_.connected());
4769
4770 connection_.EnablePathMtuDiscovery(send_algorithm_);
4771
4772 const QuicTime::Delta rtt = QuicTime::Delta::FromMilliseconds(100);
4773
4774 EXPECT_EQ(kPacketsBetweenMtuProbesBase,
4775 QuicConnectionPeer::GetPacketsBetweenMtuProbes(&connection_));
4776 // Lower the number of probes between packets in order to make the test go
4777 // much faster.
4778 const QuicPacketCount packets_between_probes_base = 5;
4779 set_packets_between_probes_base(packets_between_probes_base);
4780
4781 // This tests sends more packets than strictly necessary to make sure that if
4782 // the connection was to send more discovery packets than needed, those would
4783 // get caught as well.
4784 const QuicPacketCount number_of_packets =
4785 packets_between_probes_base * (1 << (kMtuDiscoveryAttempts + 1));
4786 std::vector<QuicPacketNumber> mtu_discovery_packets;
4787 // Called by the first ack.
4788 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4789 // Called on many acks.
4790 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
4791 .Times(AnyNumber());
4792 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
4793 SendStreamDataToPeer(3, "!", i, NO_FIN, nullptr);
4794 clock_.AdvanceTime(rtt);
4795
4796 // Receive an ACK, which marks all data packets as received, and all MTU
4797 // discovery packets as missing.
4798
4799 QuicAckFrame ack;
4800
4801 if (!mtu_discovery_packets.empty()) {
4802 QuicPacketNumber min_packet = *min_element(mtu_discovery_packets.begin(),
4803 mtu_discovery_packets.end());
4804 QuicPacketNumber max_packet = *max_element(mtu_discovery_packets.begin(),
4805 mtu_discovery_packets.end());
4806 ack.packets.AddRange(QuicPacketNumber(1), min_packet);
4807 ack.packets.AddRange(QuicPacketNumber(max_packet + 1),
4808 creator_->packet_number() + 1);
4809 ack.largest_acked = creator_->packet_number();
4810
4811 } else {
4812 ack.packets.AddRange(QuicPacketNumber(1), creator_->packet_number() + 1);
4813 ack.largest_acked = creator_->packet_number();
4814 }
4815
4816 ProcessAckPacket(&ack);
4817
4818 // Trigger MTU probe if it would be scheduled now.
4819 if (!connection_.GetMtuDiscoveryAlarm()->IsSet()) {
4820 continue;
4821 }
4822
4823 // Fire the alarm. The alarm should cause a packet to be sent.
4824 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4825 connection_.GetMtuDiscoveryAlarm()->Fire();
4826 // Record the packet number of the MTU discovery packet in order to
4827 // mark it as NACK'd.
4828 mtu_discovery_packets.push_back(creator_->packet_number());
4829 }
4830
4831 // Ensure the number of packets between probes grows exponentially by checking
4832 // it against the closed-form expression for the packet number.
4833 ASSERT_EQ(kMtuDiscoveryAttempts, mtu_discovery_packets.size());
4834 for (uint64_t i = 0; i < kMtuDiscoveryAttempts; i++) {
4835 // 2^0 + 2^1 + 2^2 + ... + 2^n = 2^(n + 1) - 1
4836 const QuicPacketCount packets_between_probes =
4837 packets_between_probes_base * ((1 << (i + 1)) - 1);
4838 EXPECT_EQ(QuicPacketNumber(packets_between_probes + (i + 1)),
4839 mtu_discovery_packets[i]);
4840 }
4841
4842 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4843 EXPECT_EQ(kDefaultMaxPacketSize, connection_.max_packet_length());
4844 EXPECT_EQ(kMtuDiscoveryAttempts, connection_.mtu_probe_count());
4845}
4846
4847// Tests whether MTU discovery works when the writer has a limit on how large a
4848// packet can be.
4849TEST_P(QuicConnectionTest, MtuDiscoveryWriterLimited) {
4850 EXPECT_TRUE(connection_.connected());
4851
4852 const QuicByteCount mtu_limit = kMtuDiscoveryTargetPacketSizeHigh - 1;
4853 writer_->set_max_packet_size(mtu_limit);
4854 connection_.EnablePathMtuDiscovery(send_algorithm_);
4855
4856 const QuicPacketCount packets_between_probes_base = 5;
4857 set_packets_between_probes_base(packets_between_probes_base);
4858
4859 // Send enough packets so that the next one triggers path MTU discovery.
4860 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
4861 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
4862 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4863 }
4864
4865 // Trigger the probe.
4866 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
4867 nullptr);
4868 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4869 QuicByteCount probe_size;
4870 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4871 .WillOnce(SaveArg<3>(&probe_size));
4872 connection_.GetMtuDiscoveryAlarm()->Fire();
4873 EXPECT_EQ(mtu_limit, probe_size);
4874
4875 const QuicPacketNumber probe_sequence_number =
4876 FirstSendingPacketNumber() + packets_between_probes_base;
4877 ASSERT_EQ(probe_sequence_number, creator_->packet_number());
4878
4879 // Acknowledge all packets sent so far.
4880 QuicAckFrame probe_ack = InitAckFrame(probe_sequence_number);
4881 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4882 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4883 ProcessAckPacket(&probe_ack);
4884 EXPECT_EQ(mtu_limit, connection_.max_packet_length());
4885 EXPECT_EQ(0u, connection_.GetBytesInFlight());
4886
4887 // Send more packets, and ensure that none of them sets the alarm.
4888 for (QuicPacketCount i = 0; i < 4 * packets_between_probes_base; i++) {
4889 SendStreamDataToPeer(3, ".", packets_between_probes_base + i, NO_FIN,
4890 nullptr);
4891 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4892 }
4893
4894 EXPECT_EQ(1u, connection_.mtu_probe_count());
4895}
4896
4897// Tests whether MTU discovery works when the writer returns an error despite
4898// advertising higher packet length.
4899TEST_P(QuicConnectionTest, MtuDiscoveryWriterFailed) {
4900 EXPECT_TRUE(connection_.connected());
4901
4902 const QuicByteCount mtu_limit = kMtuDiscoveryTargetPacketSizeHigh - 1;
4903 const QuicByteCount initial_mtu = connection_.max_packet_length();
4904 EXPECT_LT(initial_mtu, mtu_limit);
4905 writer_->set_max_packet_size(mtu_limit);
4906 connection_.EnablePathMtuDiscovery(send_algorithm_);
4907
4908 const QuicPacketCount packets_between_probes_base = 5;
4909 set_packets_between_probes_base(packets_between_probes_base);
4910
4911 // Send enough packets so that the next one triggers path MTU discovery.
4912 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
4913 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
4914 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4915 }
4916
4917 // Trigger the probe.
4918 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
4919 nullptr);
4920 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4921 writer_->SimulateNextPacketTooLarge();
4922 connection_.GetMtuDiscoveryAlarm()->Fire();
4923 ASSERT_TRUE(connection_.connected());
4924
4925 // Send more data.
4926 QuicPacketNumber probe_number = creator_->packet_number();
4927 QuicPacketCount extra_packets = packets_between_probes_base * 3;
4928 for (QuicPacketCount i = 0; i < extra_packets; i++) {
4929 connection_.EnsureWritableAndSendStreamData5();
4930 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4931 }
4932
4933 // Acknowledge all packets sent so far, except for the lost probe.
4934 QuicAckFrame probe_ack =
4935 ConstructAckFrame(creator_->packet_number(), probe_number);
4936 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4937 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4938 ProcessAckPacket(&probe_ack);
4939 EXPECT_EQ(initial_mtu, connection_.max_packet_length());
4940
4941 // Send more packets, and ensure that none of them sets the alarm.
4942 for (QuicPacketCount i = 0; i < 4 * packets_between_probes_base; i++) {
4943 connection_.EnsureWritableAndSendStreamData5();
4944 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4945 }
4946
4947 EXPECT_EQ(initial_mtu, connection_.max_packet_length());
4948 EXPECT_EQ(1u, connection_.mtu_probe_count());
4949}
4950
4951TEST_P(QuicConnectionTest, NoMtuDiscoveryAfterConnectionClosed) {
4952 EXPECT_TRUE(connection_.connected());
4953
4954 connection_.EnablePathMtuDiscovery(send_algorithm_);
4955
4956 const QuicPacketCount packets_between_probes_base = 10;
4957 set_packets_between_probes_base(packets_between_probes_base);
4958
4959 // Send enough packets so that the next one triggers path MTU discovery.
4960 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
4961 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
4962 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4963 }
4964
4965 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
4966 nullptr);
4967 EXPECT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4968
4969 EXPECT_CALL(visitor_, OnConnectionClosed(_, _, _));
4970 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
4971 ConnectionCloseBehavior::SILENT_CLOSE);
4972 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4973}
4974
4975TEST_P(QuicConnectionTest, TimeoutAfterSend) {
4976 EXPECT_TRUE(connection_.connected());
4977 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4978 QuicConfig config;
4979 connection_.SetFromConfig(config);
4980 EXPECT_FALSE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
4981
4982 const QuicTime::Delta initial_idle_timeout =
4983 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4984 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
4985 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
4986
4987 // When we send a packet, the timeout will change to 5ms +
4988 // kInitialIdleTimeoutSecs.
4989 clock_.AdvanceTime(five_ms);
4990 SendStreamDataToPeer(
4991 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
4992 0, FIN, nullptr);
4993 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
4994
4995 // Now send more data. This will not move the timeout because
4996 // no data has been received since the previous write.
4997 clock_.AdvanceTime(five_ms);
4998 SendStreamDataToPeer(
4999 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5000 3, FIN, nullptr);
5001 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5002
5003 // The original alarm will fire. We should not time out because we had a
5004 // network event at t=5ms. The alarm will reregister.
5005 clock_.AdvanceTime(initial_idle_timeout - five_ms - five_ms);
5006 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
5007 connection_.GetTimeoutAlarm()->Fire();
5008 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5009 EXPECT_TRUE(connection_.connected());
5010 EXPECT_EQ(default_timeout + five_ms,
5011 connection_.GetTimeoutAlarm()->deadline());
5012
5013 // This time, we should time out.
5014 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NETWORK_IDLE_TIMEOUT, _,
5015 ConnectionCloseSource::FROM_SELF));
5016 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5017 clock_.AdvanceTime(five_ms);
5018 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5019 connection_.GetTimeoutAlarm()->Fire();
5020 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5021 EXPECT_FALSE(connection_.connected());
5022}
5023
5024TEST_P(QuicConnectionTest, TimeoutAfterRetransmission) {
5025 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5026 EXPECT_TRUE(connection_.connected());
5027 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5028 QuicConfig config;
5029 connection_.SetFromConfig(config);
5030 EXPECT_FALSE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
5031
5032 const QuicTime start_time = clock_.Now();
5033 const QuicTime::Delta initial_idle_timeout =
5034 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5035 QuicTime default_timeout = clock_.Now() + initial_idle_timeout;
5036
5037 connection_.SetMaxTailLossProbes(0);
5038 const QuicTime default_retransmission_time =
5039 start_time + DefaultRetransmissionTime();
5040
5041 ASSERT_LT(default_retransmission_time, default_timeout);
5042
5043 // When we send a packet, the timeout will change to 5 ms +
5044 // kInitialIdleTimeoutSecs (but it will not reschedule the alarm).
5045 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5046 const QuicTime send_time = start_time + five_ms;
5047 clock_.AdvanceTime(five_ms);
5048 ASSERT_EQ(send_time, clock_.Now());
5049 SendStreamDataToPeer(
5050 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5051 0, FIN, nullptr);
5052 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5053
5054 // Move forward 5 ms and receive a packet, which will move the timeout
5055 // forward 5 ms more (but will not reschedule the alarm).
5056 const QuicTime receive_time = send_time + five_ms;
5057 clock_.AdvanceTime(receive_time - clock_.Now());
5058 ASSERT_EQ(receive_time, clock_.Now());
5059 ProcessPacket(1);
5060
5061 // Now move forward to the retransmission time and retransmit the
5062 // packet, which should move the timeout forward again (but will not
5063 // reschedule the alarm).
5064 EXPECT_EQ(default_retransmission_time + five_ms,
5065 connection_.GetRetransmissionAlarm()->deadline());
5066 // Simulate the retransmission alarm firing.
5067 const QuicTime rto_time = send_time + DefaultRetransmissionTime();
5068 const QuicTime final_timeout = rto_time + initial_idle_timeout;
5069 clock_.AdvanceTime(rto_time - clock_.Now());
5070 ASSERT_EQ(rto_time, clock_.Now());
5071 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _));
5072 connection_.GetRetransmissionAlarm()->Fire();
5073
5074 // Advance to the original timeout and fire the alarm. The connection should
5075 // timeout, and the alarm should be registered based on the time of the
5076 // retransmission.
5077 clock_.AdvanceTime(default_timeout - clock_.Now());
5078 ASSERT_EQ(default_timeout.ToDebuggingValue(),
5079 clock_.Now().ToDebuggingValue());
5080 EXPECT_EQ(default_timeout, clock_.Now());
5081 connection_.GetTimeoutAlarm()->Fire();
5082 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5083 EXPECT_TRUE(connection_.connected());
5084 ASSERT_EQ(final_timeout.ToDebuggingValue(),
5085 connection_.GetTimeoutAlarm()->deadline().ToDebuggingValue());
5086
5087 // This time, we should time out.
5088 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NETWORK_IDLE_TIMEOUT, _,
5089 ConnectionCloseSource::FROM_SELF));
5090 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5091 clock_.AdvanceTime(final_timeout - clock_.Now());
5092 EXPECT_EQ(connection_.GetTimeoutAlarm()->deadline(), clock_.Now());
5093 EXPECT_EQ(final_timeout, clock_.Now());
5094 connection_.GetTimeoutAlarm()->Fire();
5095 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5096 EXPECT_FALSE(connection_.connected());
5097}
5098
5099TEST_P(QuicConnectionTest, NewTimeoutAfterSendSilentClose) {
5100 // Same test as above, but complete a handshake which enables silent close,
5101 // causing no connection close packet to be sent.
5102 EXPECT_TRUE(connection_.connected());
5103 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5104 QuicConfig config;
5105
5106 // Create a handshake message that also enables silent close.
5107 CryptoHandshakeMessage msg;
vasilvvc48c8712019-03-11 13:38:16 -07005108 std::string error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005109 QuicConfig client_config;
5110 client_config.SetInitialStreamFlowControlWindowToSend(
5111 kInitialStreamFlowControlWindowForTest);
5112 client_config.SetInitialSessionFlowControlWindowToSend(
5113 kInitialSessionFlowControlWindowForTest);
5114 client_config.SetIdleNetworkTimeout(
5115 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs),
5116 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs));
fkastenholzd3a1de92019-05-15 07:00:07 -07005117 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005118 const QuicErrorCode error =
5119 config.ProcessPeerHello(msg, CLIENT, &error_details);
5120 EXPECT_EQ(QUIC_NO_ERROR, error);
5121
5122 connection_.SetFromConfig(config);
5123 EXPECT_TRUE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
5124
5125 const QuicTime::Delta default_idle_timeout =
5126 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs - 1);
5127 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5128 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5129
5130 // When we send a packet, the timeout will change to 5ms +
5131 // kInitialIdleTimeoutSecs.
5132 clock_.AdvanceTime(five_ms);
5133 SendStreamDataToPeer(
5134 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5135 0, FIN, nullptr);
5136 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5137
5138 // Now send more data. This will not move the timeout because
5139 // no data has been received since the previous write.
5140 clock_.AdvanceTime(five_ms);
5141 SendStreamDataToPeer(
5142 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5143 3, FIN, nullptr);
5144 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5145
5146 // The original alarm will fire. We should not time out because we had a
5147 // network event at t=5ms. The alarm will reregister.
5148 clock_.AdvanceTime(default_idle_timeout - five_ms - five_ms);
5149 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
5150 connection_.GetTimeoutAlarm()->Fire();
5151 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5152 EXPECT_TRUE(connection_.connected());
5153 EXPECT_EQ(default_timeout + five_ms,
5154 connection_.GetTimeoutAlarm()->deadline());
5155
5156 // This time, we should time out.
5157 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NETWORK_IDLE_TIMEOUT, _,
5158 ConnectionCloseSource::FROM_SELF));
5159 clock_.AdvanceTime(five_ms);
5160 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5161 connection_.GetTimeoutAlarm()->Fire();
5162 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5163 EXPECT_FALSE(connection_.connected());
5164}
5165
5166TEST_P(QuicConnectionTest, TimeoutAfterSendSilentCloseAndTLP) {
5167 // Same test as above, but complete a handshake which enables silent close,
5168 // but sending TLPs causes the connection close to be sent.
5169 EXPECT_TRUE(connection_.connected());
5170 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5171 QuicConfig config;
5172
5173 // Create a handshake message that also enables silent close.
5174 CryptoHandshakeMessage msg;
vasilvvc48c8712019-03-11 13:38:16 -07005175 std::string error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005176 QuicConfig client_config;
5177 client_config.SetInitialStreamFlowControlWindowToSend(
5178 kInitialStreamFlowControlWindowForTest);
5179 client_config.SetInitialSessionFlowControlWindowToSend(
5180 kInitialSessionFlowControlWindowForTest);
5181 client_config.SetIdleNetworkTimeout(
5182 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs),
5183 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs));
fkastenholzd3a1de92019-05-15 07:00:07 -07005184 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005185 const QuicErrorCode error =
5186 config.ProcessPeerHello(msg, CLIENT, &error_details);
5187 EXPECT_EQ(QUIC_NO_ERROR, error);
5188
5189 connection_.SetFromConfig(config);
5190 EXPECT_TRUE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
5191
5192 const QuicTime::Delta default_idle_timeout =
5193 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs - 1);
5194 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5195 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5196
5197 // When we send a packet, the timeout will change to 5ms +
5198 // kInitialIdleTimeoutSecs.
5199 clock_.AdvanceTime(five_ms);
5200 SendStreamDataToPeer(
5201 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5202 0, FIN, nullptr);
5203 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5204
5205 // Retransmit the packet via tail loss probe.
5206 clock_.AdvanceTime(connection_.GetRetransmissionAlarm()->deadline() -
5207 clock_.Now());
5208 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _));
5209 connection_.GetRetransmissionAlarm()->Fire();
5210
5211 // This time, we should time out and send a connection close due to the TLP.
5212 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NETWORK_IDLE_TIMEOUT, _,
5213 ConnectionCloseSource::FROM_SELF));
5214 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5215 clock_.AdvanceTime(connection_.GetTimeoutAlarm()->deadline() -
5216 clock_.ApproximateNow() + five_ms);
5217 connection_.GetTimeoutAlarm()->Fire();
5218 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5219 EXPECT_FALSE(connection_.connected());
5220}
5221
5222TEST_P(QuicConnectionTest, TimeoutAfterSendSilentCloseWithOpenStreams) {
5223 // Same test as above, but complete a handshake which enables silent close,
5224 // but having open streams causes the connection close to be sent.
5225 EXPECT_TRUE(connection_.connected());
5226 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5227 QuicConfig config;
5228
5229 // Create a handshake message that also enables silent close.
5230 CryptoHandshakeMessage msg;
vasilvvc48c8712019-03-11 13:38:16 -07005231 std::string error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005232 QuicConfig client_config;
5233 client_config.SetInitialStreamFlowControlWindowToSend(
5234 kInitialStreamFlowControlWindowForTest);
5235 client_config.SetInitialSessionFlowControlWindowToSend(
5236 kInitialSessionFlowControlWindowForTest);
5237 client_config.SetIdleNetworkTimeout(
5238 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs),
5239 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs));
fkastenholzd3a1de92019-05-15 07:00:07 -07005240 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005241 const QuicErrorCode error =
5242 config.ProcessPeerHello(msg, CLIENT, &error_details);
5243 EXPECT_EQ(QUIC_NO_ERROR, error);
5244
5245 connection_.SetFromConfig(config);
5246 EXPECT_TRUE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
5247
5248 const QuicTime::Delta default_idle_timeout =
5249 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs - 1);
5250 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5251 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5252
5253 // When we send a packet, the timeout will change to 5ms +
5254 // kInitialIdleTimeoutSecs.
5255 clock_.AdvanceTime(five_ms);
5256 SendStreamDataToPeer(
5257 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5258 0, FIN, nullptr);
5259 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5260
5261 // Indicate streams are still open.
5262 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
5263 .WillRepeatedly(Return(true));
5264
5265 // This time, we should time out and send a connection close due to the TLP.
5266 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NETWORK_IDLE_TIMEOUT, _,
5267 ConnectionCloseSource::FROM_SELF));
5268 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5269 clock_.AdvanceTime(connection_.GetTimeoutAlarm()->deadline() -
5270 clock_.ApproximateNow() + five_ms);
5271 connection_.GetTimeoutAlarm()->Fire();
5272 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5273 EXPECT_FALSE(connection_.connected());
5274}
5275
5276TEST_P(QuicConnectionTest, TimeoutAfterReceive) {
5277 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5278 EXPECT_TRUE(connection_.connected());
5279 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5280 QuicConfig config;
5281 connection_.SetFromConfig(config);
5282 EXPECT_FALSE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
5283
5284 const QuicTime::Delta initial_idle_timeout =
5285 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5286 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5287 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
5288
5289 connection_.SendStreamDataWithString(
5290 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5291 0, NO_FIN);
5292 connection_.SendStreamDataWithString(
5293 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5294 3, NO_FIN);
5295
5296 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5297 clock_.AdvanceTime(five_ms);
5298
5299 // When we receive a packet, the timeout will change to 5ms +
5300 // kInitialIdleTimeoutSecs.
5301 QuicAckFrame ack = InitAckFrame(2);
5302 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5303 ProcessAckPacket(&ack);
5304
5305 // The original alarm will fire. We should not time out because we had a
5306 // network event at t=5ms. The alarm will reregister.
5307 clock_.AdvanceTime(initial_idle_timeout - five_ms);
5308 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
5309 connection_.GetTimeoutAlarm()->Fire();
5310 EXPECT_TRUE(connection_.connected());
5311 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5312 EXPECT_EQ(default_timeout + five_ms,
5313 connection_.GetTimeoutAlarm()->deadline());
5314
5315 // This time, we should time out.
5316 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NETWORK_IDLE_TIMEOUT, _,
5317 ConnectionCloseSource::FROM_SELF));
5318 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5319 clock_.AdvanceTime(five_ms);
5320 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5321 connection_.GetTimeoutAlarm()->Fire();
5322 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5323 EXPECT_FALSE(connection_.connected());
5324}
5325
5326TEST_P(QuicConnectionTest, TimeoutAfterReceiveNotSendWhenUnacked) {
5327 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5328 EXPECT_TRUE(connection_.connected());
5329 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5330 QuicConfig config;
5331 connection_.SetFromConfig(config);
5332 EXPECT_FALSE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
5333
5334 const QuicTime::Delta initial_idle_timeout =
5335 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5336 connection_.SetNetworkTimeouts(
5337 QuicTime::Delta::Infinite(),
5338 initial_idle_timeout + QuicTime::Delta::FromSeconds(1));
5339 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5340 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
5341
5342 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5343 connection_.SendStreamDataWithString(
5344 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5345 0, NO_FIN);
5346 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5347 connection_.SendStreamDataWithString(
5348 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5349 3, NO_FIN);
5350
5351 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5352
5353 clock_.AdvanceTime(five_ms);
5354
5355 // When we receive a packet, the timeout will change to 5ms +
5356 // kInitialIdleTimeoutSecs.
5357 QuicAckFrame ack = InitAckFrame(2);
5358 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5359 ProcessAckPacket(&ack);
5360
5361 // The original alarm will fire. We should not time out because we had a
5362 // network event at t=5ms. The alarm will reregister.
5363 clock_.AdvanceTime(initial_idle_timeout - five_ms);
5364 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
5365 connection_.GetTimeoutAlarm()->Fire();
5366 EXPECT_TRUE(connection_.connected());
5367 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5368 EXPECT_EQ(default_timeout + five_ms,
5369 connection_.GetTimeoutAlarm()->deadline());
5370
5371 // Now, send packets while advancing the time and verify that the connection
5372 // eventually times out.
5373 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NETWORK_IDLE_TIMEOUT, _,
5374 ConnectionCloseSource::FROM_SELF));
5375 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
5376 for (int i = 0; i < 100 && connection_.connected(); ++i) {
5377 QUIC_LOG(INFO) << "sending data packet";
5378 connection_.SendStreamDataWithString(
5379 GetNthClientInitiatedStreamId(1, connection_.transport_version()),
5380 "foo", 0, NO_FIN);
5381 connection_.GetTimeoutAlarm()->Fire();
5382 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
5383 }
5384 EXPECT_FALSE(connection_.connected());
5385 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5386}
5387
5388TEST_P(QuicConnectionTest, TimeoutAfter5ClientRTOs) {
5389 connection_.SetMaxTailLossProbes(2);
5390 EXPECT_TRUE(connection_.connected());
5391 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5392 QuicConfig config;
5393 QuicTagVector connection_options;
5394 connection_options.push_back(k5RTO);
5395 config.SetConnectionOptionsToSend(connection_options);
5396 connection_.SetFromConfig(config);
5397
5398 // Send stream data.
5399 SendStreamDataToPeer(
5400 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5401 0, FIN, nullptr);
5402
5403 // Fire the retransmission alarm 6 times, twice for TLP and 4 times for RTO.
5404 for (int i = 0; i < 6; ++i) {
5405 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5406 connection_.GetRetransmissionAlarm()->Fire();
5407 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5408 EXPECT_TRUE(connection_.connected());
5409 }
5410
5411 EXPECT_EQ(2u, connection_.sent_packet_manager().GetConsecutiveTlpCount());
5412 EXPECT_EQ(4u, connection_.sent_packet_manager().GetConsecutiveRtoCount());
5413 // This time, we should time out.
5414 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_TOO_MANY_RTOS, _,
5415 ConnectionCloseSource::FROM_SELF));
5416 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5417 connection_.GetRetransmissionAlarm()->Fire();
5418 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5419 EXPECT_FALSE(connection_.connected());
5420}
5421
5422TEST_P(QuicConnectionTest, SendScheduler) {
5423 // Test that if we send a packet without delay, it is not queued.
5424 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
QUICHE team8c1daa22019-03-13 08:33:41 -07005425 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07005426 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005427 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
5428 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
QUICHE team6987b4a2019-03-15 16:23:04 -07005429 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05005430 HAS_RETRANSMITTABLE_DATA, false, false);
5431 EXPECT_EQ(0u, connection_.NumQueuedPackets());
5432}
5433
5434TEST_P(QuicConnectionTest, FailToSendFirstPacket) {
5435 // Test that the connection does not crash when it fails to send the first
5436 // packet at which point self_address_ might be uninitialized.
5437 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
5438 EXPECT_CALL(visitor_, OnConnectionClosed(_, _, _)).Times(1);
QUICHE team8c1daa22019-03-13 08:33:41 -07005439 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07005440 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005441 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
5442 writer_->SetShouldWriteFail();
QUICHE team6987b4a2019-03-15 16:23:04 -07005443 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05005444 HAS_RETRANSMITTABLE_DATA, false, false);
5445}
5446
5447TEST_P(QuicConnectionTest, SendSchedulerEAGAIN) {
5448 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
QUICHE team8c1daa22019-03-13 08:33:41 -07005449 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07005450 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005451 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
5452 BlockOnNextWrite();
5453 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _))
5454 .Times(0);
QUICHE team6987b4a2019-03-15 16:23:04 -07005455 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05005456 HAS_RETRANSMITTABLE_DATA, false, false);
5457 EXPECT_EQ(1u, connection_.NumQueuedPackets());
5458}
5459
5460TEST_P(QuicConnectionTest, TestQueueLimitsOnSendStreamData) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005461 // Queue the first packet.
ianswett3085da82019-04-04 07:24:24 -07005462 size_t payload_length = connection_.max_packet_length();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005463 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(testing::Return(false));
vasilvvc48c8712019-03-11 13:38:16 -07005464 const std::string payload(payload_length, 'a');
ianswett3085da82019-04-04 07:24:24 -07005465 QuicStreamId first_bidi_stream_id(QuicUtils::GetFirstBidirectionalStreamId(
5466 connection_.version().transport_version, Perspective::IS_CLIENT));
5467 EXPECT_EQ(0u, connection_
5468 .SendStreamDataWithString(first_bidi_stream_id, payload, 0,
5469 NO_FIN)
QUICHE teama6ef0a62019-03-07 20:34:33 -05005470 .bytes_consumed);
5471 EXPECT_EQ(0u, connection_.NumQueuedPackets());
5472}
5473
ianswett3085da82019-04-04 07:24:24 -07005474TEST_P(QuicConnectionTest, SendingThreePackets) {
ianswett3085da82019-04-04 07:24:24 -07005475 // Make the payload twice the size of the packet, so 3 packets are written.
5476 size_t total_payload_length = 2 * connection_.max_packet_length();
vasilvvc48c8712019-03-11 13:38:16 -07005477 const std::string payload(total_payload_length, 'a');
ianswett3085da82019-04-04 07:24:24 -07005478 QuicStreamId first_bidi_stream_id(QuicUtils::GetFirstBidirectionalStreamId(
5479 connection_.version().transport_version, Perspective::IS_CLIENT));
5480 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
5481 EXPECT_EQ(payload.size(), connection_
5482 .SendStreamDataWithString(first_bidi_stream_id,
5483 payload, 0, NO_FIN)
5484 .bytes_consumed);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005485}
5486
5487TEST_P(QuicConnectionTest, LoopThroughSendingPacketsWithTruncation) {
5488 set_perspective(Perspective::IS_SERVER);
fayangd4291e42019-05-30 10:31:21 -07005489 if (!VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005490 // For IETF QUIC, encryption level will be switched to FORWARD_SECURE in
5491 // SendStreamDataWithString.
5492 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
5493 }
5494 // Set up a larger payload than will fit in one packet.
vasilvvc48c8712019-03-11 13:38:16 -07005495 const std::string payload(connection_.max_packet_length(), 'a');
QUICHE teama6ef0a62019-03-07 20:34:33 -05005496 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
5497
5498 // Now send some packets with no truncation.
5499 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
5500 EXPECT_EQ(payload.size(),
5501 connection_.SendStreamDataWithString(3, payload, 0, NO_FIN)
5502 .bytes_consumed);
5503 // Track the size of the second packet here. The overhead will be the largest
5504 // we see in this test, due to the non-truncated connection id.
5505 size_t non_truncated_packet_size = writer_->last_packet_size();
5506
5507 // Change to a 0 byte connection id.
5508 QuicConfig config;
5509 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
5510 connection_.SetFromConfig(config);
5511 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
5512 EXPECT_EQ(payload.size(),
5513 connection_.SendStreamDataWithString(3, payload, 1350, NO_FIN)
5514 .bytes_consumed);
fayangd4291e42019-05-30 10:31:21 -07005515 if (VersionHasIetfInvariantHeader(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005516 // Short header packets sent from server omit connection ID already, and
5517 // stream offset size increases from 0 to 2.
5518 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() - 2);
5519 } else {
5520 // Just like above, we save 8 bytes on payload, and 8 on truncation. -2
5521 // because stream offset size is 2 instead of 0.
5522 EXPECT_EQ(non_truncated_packet_size,
5523 writer_->last_packet_size() + 8 * 2 - 2);
5524 }
5525}
5526
5527TEST_P(QuicConnectionTest, SendDelayedAck) {
5528 QuicTime ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
5529 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5530 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5531 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07005532 SetDecrypter(ENCRYPTION_ZERO_RTT,
5533 QuicMakeUnique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005534 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
5535 QuicMakeUnique<TaggingEncrypter>(tag));
5536 // Process a packet from the non-crypto stream.
5537 frame1_.stream_id = 3;
5538
5539 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07005540 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005541 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5542 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5543
5544 // Check if delayed ack timer is running for the expected interval.
5545 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5546 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5547 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07005548 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005549 connection_.GetAckAlarm()->Fire();
5550 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07005551 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005552 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07005553 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005554 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
5555 } else {
nharper55fa6132019-05-07 19:37:21 -07005556 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005557 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
5558 }
5559 EXPECT_FALSE(writer_->ack_frames().empty());
5560 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5561}
5562
5563TEST_P(QuicConnectionTest, SendDelayedAfterQuiescence) {
5564 QuicConnectionPeer::SetFastAckAfterQuiescence(&connection_, true);
5565
5566 // The beginning of the connection counts as quiescence.
5567 QuicTime ack_time =
5568 clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
5569 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5570 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5571 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07005572 SetDecrypter(ENCRYPTION_ZERO_RTT,
5573 QuicMakeUnique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005574 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
5575 QuicMakeUnique<TaggingEncrypter>(tag));
5576 // Process a packet from the non-crypto stream.
5577 frame1_.stream_id = 3;
5578
5579 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07005580 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005581 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5582 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5583
5584 // Check if delayed ack timer is running for the expected interval.
5585 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5586 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5587 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07005588 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005589 connection_.GetAckAlarm()->Fire();
5590 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07005591 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005592 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07005593 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005594 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
5595 } else {
nharper55fa6132019-05-07 19:37:21 -07005596 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005597 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
5598 }
5599 EXPECT_FALSE(writer_->ack_frames().empty());
5600 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5601
5602 // Process another packet immedately after sending the ack and expect the
5603 // ack alarm to be set delayed ack time in the future.
5604 ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
5605 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5606 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5607
5608 // Check if delayed ack timer is running for the expected interval.
5609 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5610 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5611 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07005612 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005613 connection_.GetAckAlarm()->Fire();
5614 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07005615 padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005616 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07005617 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005618 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
5619 } else {
nharper55fa6132019-05-07 19:37:21 -07005620 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005621 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
5622 }
5623 EXPECT_FALSE(writer_->ack_frames().empty());
5624 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5625
5626 // Wait 1 second and enesure the ack alarm is set to 1ms in the future.
5627 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
5628 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
5629 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5630 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5631
5632 // Check if delayed ack timer is running for the expected interval.
5633 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5634 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5635}
5636
5637TEST_P(QuicConnectionTest, SendDelayedAckDecimation) {
5638 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
5639 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION);
5640
5641 const size_t kMinRttMs = 40;
5642 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
5643 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
5644 QuicTime::Delta::Zero(), QuicTime::Zero());
5645 // The ack time should be based on min_rtt/4, since it's less than the
5646 // default delayed ack time.
5647 QuicTime ack_time = clock_.ApproximateNow() +
5648 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
5649 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5650 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5651 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07005652 SetDecrypter(ENCRYPTION_ZERO_RTT,
5653 QuicMakeUnique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005654 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
5655 QuicMakeUnique<TaggingEncrypter>(tag));
5656 // Process a packet from the non-crypto stream.
5657 frame1_.stream_id = 3;
5658
5659 // Process all the initial packets in order so there aren't missing packets.
5660 uint64_t kFirstDecimatedPacket = 101;
5661 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
5662 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5663 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5664 }
5665 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5666 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07005667 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005668 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5669 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
5670 ENCRYPTION_ZERO_RTT);
5671
5672 // Check if delayed ack timer is running for the expected interval.
5673 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5674 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5675
5676 // The 10th received packet causes an ack to be sent.
5677 for (int i = 0; i < 9; ++i) {
5678 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5679 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5680 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
5681 ENCRYPTION_ZERO_RTT);
5682 }
5683 // Check that ack is sent and that delayed ack alarm is reset.
5684 if (GetParam().no_stop_waiting) {
5685 EXPECT_EQ(1u, writer_->frame_count());
5686 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
5687 } else {
5688 EXPECT_EQ(2u, writer_->frame_count());
5689 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
5690 }
5691 EXPECT_FALSE(writer_->ack_frames().empty());
5692 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5693}
5694
5695TEST_P(QuicConnectionTest, SendDelayedAckAckDecimationAfterQuiescence) {
5696 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
5697 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION);
5698 QuicConnectionPeer::SetFastAckAfterQuiescence(&connection_, true);
5699
5700 const size_t kMinRttMs = 40;
5701 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
5702 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
5703 QuicTime::Delta::Zero(), QuicTime::Zero());
5704
5705 // The beginning of the connection counts as quiescence.
5706 QuicTime ack_time =
5707 clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
5708 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5709 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5710 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07005711 SetDecrypter(ENCRYPTION_ZERO_RTT,
5712 QuicMakeUnique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005713 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
5714 QuicMakeUnique<TaggingEncrypter>(tag));
5715 // Process a packet from the non-crypto stream.
5716 frame1_.stream_id = 3;
5717
5718 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07005719 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005720 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5721 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5722
5723 // Check if delayed ack timer is running for the expected interval.
5724 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5725 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5726 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07005727 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005728 connection_.GetAckAlarm()->Fire();
5729 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07005730 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005731 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07005732 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005733 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
5734 } else {
nharper55fa6132019-05-07 19:37:21 -07005735 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005736 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
5737 }
5738 EXPECT_FALSE(writer_->ack_frames().empty());
5739 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5740
5741 // Process another packet immedately after sending the ack and expect the
5742 // ack alarm to be set delayed ack time in the future.
5743 ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
5744 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5745 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5746
5747 // Check if delayed ack timer is running for the expected interval.
5748 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5749 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5750 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07005751 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005752 connection_.GetAckAlarm()->Fire();
5753 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07005754 padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005755 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07005756 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005757 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
5758 } else {
nharper55fa6132019-05-07 19:37:21 -07005759 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005760 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
5761 }
5762 EXPECT_FALSE(writer_->ack_frames().empty());
5763 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5764
5765 // Wait 1 second and enesure the ack alarm is set to 1ms in the future.
5766 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
5767 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
5768 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5769 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5770
5771 // Check if delayed ack timer is running for the expected interval.
5772 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5773 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5774
5775 // Process enough packets to get into ack decimation behavior.
5776 // The ack time should be based on min_rtt/4, since it's less than the
5777 // default delayed ack time.
5778 ack_time = clock_.ApproximateNow() +
5779 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
5780 uint64_t kFirstDecimatedPacket = 101;
5781 for (unsigned int i = 0; i < kFirstDecimatedPacket - 4; ++i) {
5782 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5783 ProcessDataPacketAtLevel(4 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5784 }
5785 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5786 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07005787 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005788 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5789 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
5790 ENCRYPTION_ZERO_RTT);
5791
5792 // Check if delayed ack timer is running for the expected interval.
5793 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5794 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5795
5796 // The 10th received packet causes an ack to be sent.
5797 for (int i = 0; i < 9; ++i) {
5798 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5799 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5800 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
5801 ENCRYPTION_ZERO_RTT);
5802 }
5803 // Check that ack is sent and that delayed ack alarm is reset.
5804 if (GetParam().no_stop_waiting) {
5805 EXPECT_EQ(1u, writer_->frame_count());
5806 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
5807 } else {
5808 EXPECT_EQ(2u, writer_->frame_count());
5809 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
5810 }
5811 EXPECT_FALSE(writer_->ack_frames().empty());
5812 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5813
5814 // Wait 1 second and enesure the ack alarm is set to 1ms in the future.
5815 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
5816 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
5817 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5818 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 10, !kHasStopWaiting,
5819 ENCRYPTION_ZERO_RTT);
5820
5821 // Check if delayed ack timer is running for the expected interval.
5822 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5823 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5824}
5825
5826TEST_P(QuicConnectionTest, SendDelayedAckDecimationUnlimitedAggregation) {
5827 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
5828 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5829 QuicConfig config;
5830 QuicTagVector connection_options;
5831 connection_options.push_back(kACKD);
5832 // No limit on the number of packets received before sending an ack.
5833 connection_options.push_back(kAKDU);
5834 config.SetConnectionOptionsToSend(connection_options);
5835 connection_.SetFromConfig(config);
5836
5837 const size_t kMinRttMs = 40;
5838 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
5839 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
5840 QuicTime::Delta::Zero(), QuicTime::Zero());
5841 // The ack time should be based on min_rtt/4, since it's less than the
5842 // default delayed ack time.
5843 QuicTime ack_time = clock_.ApproximateNow() +
5844 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
5845 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5846 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5847 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07005848 SetDecrypter(ENCRYPTION_ZERO_RTT,
5849 QuicMakeUnique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005850 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
5851 QuicMakeUnique<TaggingEncrypter>(tag));
5852 // Process a packet from the non-crypto stream.
5853 frame1_.stream_id = 3;
5854
5855 // Process all the initial packets in order so there aren't missing packets.
5856 uint64_t kFirstDecimatedPacket = 101;
5857 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
5858 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5859 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5860 }
5861 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5862 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07005863 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005864 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5865 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
5866 ENCRYPTION_ZERO_RTT);
5867
5868 // Check if delayed ack timer is running for the expected interval.
5869 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5870 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5871
5872 // 18 packets will not cause an ack to be sent. 19 will because when
5873 // stop waiting frames are in use, we ack every 20 packets no matter what.
5874 for (int i = 0; i < 18; ++i) {
5875 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5876 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5877 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
5878 ENCRYPTION_ZERO_RTT);
5879 }
5880 // The delayed ack timer should still be set to the expected deadline.
5881 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5882 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5883}
5884
5885TEST_P(QuicConnectionTest, SendDelayedAckDecimationEighthRtt) {
5886 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
5887 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION);
5888 QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
5889
5890 const size_t kMinRttMs = 40;
5891 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
5892 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
5893 QuicTime::Delta::Zero(), QuicTime::Zero());
5894 // The ack time should be based on min_rtt/8, since it's less than the
5895 // default delayed ack time.
5896 QuicTime ack_time = clock_.ApproximateNow() +
5897 QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
5898 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5899 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5900 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07005901 SetDecrypter(ENCRYPTION_ZERO_RTT,
5902 QuicMakeUnique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005903 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
5904 QuicMakeUnique<TaggingEncrypter>(tag));
5905 // Process a packet from the non-crypto stream.
5906 frame1_.stream_id = 3;
5907
5908 // Process all the initial packets in order so there aren't missing packets.
5909 uint64_t kFirstDecimatedPacket = 101;
5910 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
5911 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5912 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5913 }
5914 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5915 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07005916 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005917 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5918 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
5919 ENCRYPTION_ZERO_RTT);
5920
5921 // Check if delayed ack timer is running for the expected interval.
5922 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5923 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5924
5925 // The 10th received packet causes an ack to be sent.
5926 for (int i = 0; i < 9; ++i) {
5927 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5928 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5929 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
5930 ENCRYPTION_ZERO_RTT);
5931 }
5932 // Check that ack is sent and that delayed ack alarm is reset.
5933 if (GetParam().no_stop_waiting) {
5934 EXPECT_EQ(1u, writer_->frame_count());
5935 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
5936 } else {
5937 EXPECT_EQ(2u, writer_->frame_count());
5938 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
5939 }
5940 EXPECT_FALSE(writer_->ack_frames().empty());
5941 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5942}
5943
5944TEST_P(QuicConnectionTest, SendDelayedAckDecimationWithReordering) {
5945 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
5946 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
5947
5948 const size_t kMinRttMs = 40;
5949 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
5950 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
5951 QuicTime::Delta::Zero(), QuicTime::Zero());
5952 // The ack time should be based on min_rtt/4, since it's less than the
5953 // default delayed ack time.
5954 QuicTime ack_time = clock_.ApproximateNow() +
5955 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
5956 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5957 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5958 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07005959 SetDecrypter(ENCRYPTION_ZERO_RTT,
5960 QuicMakeUnique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005961 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
5962 QuicMakeUnique<TaggingEncrypter>(tag));
5963 // Process a packet from the non-crypto stream.
5964 frame1_.stream_id = 3;
5965
5966 // Process all the initial packets in order so there aren't missing packets.
5967 uint64_t kFirstDecimatedPacket = 101;
5968 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
5969 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5970 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5971 }
5972 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5973
5974 // Receive one packet out of order and then the rest in order.
5975 // The loop leaves a one packet gap between acks sent to simulate some loss.
5976 for (int j = 0; j < 3; ++j) {
5977 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
5978 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5979 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 9 + (j * 11),
5980 !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5981 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
5982 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5983 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5984
5985 // The 10th received packet causes an ack to be sent.
5986 writer_->Reset();
5987 for (int i = 0; i < 9; ++i) {
5988 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5989 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5990 // The ACK shouldn't be sent until the 10th packet is processed.
5991 EXPECT_TRUE(writer_->ack_frames().empty());
5992 ProcessDataPacketAtLevel(kFirstDecimatedPacket + i + (j * 11),
5993 !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5994 }
5995 // Check that ack is sent and that delayed ack alarm is reset.
5996 if (GetParam().no_stop_waiting) {
5997 EXPECT_EQ(1u, writer_->frame_count());
5998 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
5999 } else {
6000 EXPECT_EQ(2u, writer_->frame_count());
6001 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6002 }
6003 EXPECT_FALSE(writer_->ack_frames().empty());
6004 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6005 }
6006}
6007
6008TEST_P(QuicConnectionTest, SendDelayedAckDecimationWithLargeReordering) {
6009 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6010 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6011
6012 const size_t kMinRttMs = 40;
6013 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6014 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6015 QuicTime::Delta::Zero(), QuicTime::Zero());
6016 // The ack time should be based on min_rtt/4, since it's less than the
6017 // default delayed ack time.
6018 QuicTime ack_time = clock_.ApproximateNow() +
6019 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6020 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6021 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6022 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006023 SetDecrypter(ENCRYPTION_ZERO_RTT,
6024 QuicMakeUnique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006025 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
6026 QuicMakeUnique<TaggingEncrypter>(tag));
6027 // Process a packet from the non-crypto stream.
6028 frame1_.stream_id = 3;
6029
6030 // Process all the initial packets in order so there aren't missing packets.
6031 uint64_t kFirstDecimatedPacket = 101;
6032 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6033 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6034 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6035 }
6036 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6037 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006038 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006039 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6040 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6041 ENCRYPTION_ZERO_RTT);
6042
6043 // Check if delayed ack timer is running for the expected interval.
6044 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6045 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6046
6047 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6048 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6049 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 19, !kHasStopWaiting,
6050 ENCRYPTION_ZERO_RTT);
6051 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
6052 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6053 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6054
6055 // The 10th received packet causes an ack to be sent.
6056 for (int i = 0; i < 8; ++i) {
6057 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6058 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6059 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6060 ENCRYPTION_ZERO_RTT);
6061 }
6062 // Check that ack is sent and that delayed ack alarm is reset.
6063 if (GetParam().no_stop_waiting) {
6064 EXPECT_EQ(1u, writer_->frame_count());
6065 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6066 } else {
6067 EXPECT_EQ(2u, writer_->frame_count());
6068 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6069 }
6070 EXPECT_FALSE(writer_->ack_frames().empty());
6071 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6072
6073 // The next packet received in order will cause an immediate ack,
6074 // because it fills a hole.
6075 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6076 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6077 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 10, !kHasStopWaiting,
6078 ENCRYPTION_ZERO_RTT);
6079 // Check that ack is sent and that delayed ack alarm is reset.
6080 if (GetParam().no_stop_waiting) {
6081 EXPECT_EQ(1u, writer_->frame_count());
6082 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6083 } else {
6084 EXPECT_EQ(2u, writer_->frame_count());
6085 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6086 }
6087 EXPECT_FALSE(writer_->ack_frames().empty());
6088 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6089}
6090
6091TEST_P(QuicConnectionTest, SendDelayedAckDecimationWithReorderingEighthRtt) {
6092 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6093 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6094 QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
6095
6096 const size_t kMinRttMs = 40;
6097 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6098 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6099 QuicTime::Delta::Zero(), QuicTime::Zero());
6100 // The ack time should be based on min_rtt/8, since it's less than the
6101 // default delayed ack time.
6102 QuicTime ack_time = clock_.ApproximateNow() +
6103 QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
6104 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6105 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6106 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006107 SetDecrypter(ENCRYPTION_ZERO_RTT,
6108 QuicMakeUnique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006109 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
6110 QuicMakeUnique<TaggingEncrypter>(tag));
6111 // Process a packet from the non-crypto stream.
6112 frame1_.stream_id = 3;
6113
6114 // Process all the initial packets in order so there aren't missing packets.
6115 uint64_t kFirstDecimatedPacket = 101;
6116 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6117 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6118 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6119 }
6120 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6121 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006122 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006123 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6124 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6125 ENCRYPTION_ZERO_RTT);
6126
6127 // Check if delayed ack timer is running for the expected interval.
6128 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6129 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6130
6131 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6132 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6133 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 9, !kHasStopWaiting,
6134 ENCRYPTION_ZERO_RTT);
6135 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
6136 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6137 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6138
6139 // The 10th received packet causes an ack to be sent.
6140 for (int i = 0; i < 8; ++i) {
6141 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6142 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6143 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6144 ENCRYPTION_ZERO_RTT);
6145 }
6146 // Check that ack is sent and that delayed ack alarm is reset.
6147 if (GetParam().no_stop_waiting) {
6148 EXPECT_EQ(1u, writer_->frame_count());
6149 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6150 } else {
6151 EXPECT_EQ(2u, writer_->frame_count());
6152 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6153 }
6154 EXPECT_FALSE(writer_->ack_frames().empty());
6155 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6156}
6157
6158TEST_P(QuicConnectionTest,
6159 SendDelayedAckDecimationWithLargeReorderingEighthRtt) {
6160 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6161 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6162 QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
6163
6164 const size_t kMinRttMs = 40;
6165 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6166 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6167 QuicTime::Delta::Zero(), QuicTime::Zero());
6168 // The ack time should be based on min_rtt/8, since it's less than the
6169 // default delayed ack time.
6170 QuicTime ack_time = clock_.ApproximateNow() +
6171 QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
6172 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6173 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6174 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006175 SetDecrypter(ENCRYPTION_ZERO_RTT,
6176 QuicMakeUnique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006177 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
6178 QuicMakeUnique<TaggingEncrypter>(tag));
6179 // Process a packet from the non-crypto stream.
6180 frame1_.stream_id = 3;
6181
6182 // Process all the initial packets in order so there aren't missing packets.
6183 uint64_t kFirstDecimatedPacket = 101;
6184 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6185 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6186 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6187 }
6188 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6189 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006190 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006191 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6192 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6193 ENCRYPTION_ZERO_RTT);
6194
6195 // Check if delayed ack timer is running for the expected interval.
6196 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6197 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6198
6199 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6200 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6201 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 19, !kHasStopWaiting,
6202 ENCRYPTION_ZERO_RTT);
6203 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
6204 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6205 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6206
6207 // The 10th received packet causes an ack to be sent.
6208 for (int i = 0; i < 8; ++i) {
6209 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6210 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6211 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6212 ENCRYPTION_ZERO_RTT);
6213 }
6214 // Check that ack is sent and that delayed ack alarm is reset.
6215 if (GetParam().no_stop_waiting) {
6216 EXPECT_EQ(1u, writer_->frame_count());
6217 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6218 } else {
6219 EXPECT_EQ(2u, writer_->frame_count());
6220 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6221 }
6222 EXPECT_FALSE(writer_->ack_frames().empty());
6223 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6224
6225 // The next packet received in order will cause an immediate ack,
6226 // because it fills a hole.
6227 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6228 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6229 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 10, !kHasStopWaiting,
6230 ENCRYPTION_ZERO_RTT);
6231 // Check that ack is sent and that delayed ack alarm is reset.
6232 if (GetParam().no_stop_waiting) {
6233 EXPECT_EQ(1u, writer_->frame_count());
6234 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6235 } else {
6236 EXPECT_EQ(2u, writer_->frame_count());
6237 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6238 }
6239 EXPECT_FALSE(writer_->ack_frames().empty());
6240 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6241}
6242
6243TEST_P(QuicConnectionTest, SendDelayedAckOnHandshakeConfirmed) {
6244 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6245 ProcessPacket(1);
6246 // Check that ack is sent and that delayed ack alarm is set.
6247 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6248 QuicTime ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6249 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6250
6251 // Completing the handshake as the server does nothing.
6252 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_SERVER);
6253 connection_.OnHandshakeComplete();
6254 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6255 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6256
6257 // Complete the handshake as the client decreases the delayed ack time to 0ms.
6258 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_CLIENT);
6259 connection_.OnHandshakeComplete();
6260 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6261 EXPECT_EQ(clock_.ApproximateNow(), connection_.GetAckAlarm()->deadline());
6262}
6263
6264TEST_P(QuicConnectionTest, SendDelayedAckOnSecondPacket) {
6265 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6266 ProcessPacket(1);
6267 ProcessPacket(2);
6268 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006269 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006270 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006271 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006272 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6273 } else {
nharper55fa6132019-05-07 19:37:21 -07006274 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006275 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6276 }
6277 EXPECT_FALSE(writer_->ack_frames().empty());
6278 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6279}
6280
6281TEST_P(QuicConnectionTest, NoAckOnOldNacks) {
6282 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang6dba4902019-06-17 10:04:23 -07006283 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006284 ProcessPacket(2);
6285 size_t frames_per_ack = GetParam().no_stop_waiting ? 1 : 2;
QUICHE teama6ef0a62019-03-07 20:34:33 -05006286
6287 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
6288 ProcessPacket(3);
nharper55fa6132019-05-07 19:37:21 -07006289 size_t padding_frame_count = writer_->padding_frames().size();
6290 EXPECT_EQ(padding_frame_count + frames_per_ack, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006291 EXPECT_FALSE(writer_->ack_frames().empty());
6292 writer_->Reset();
6293
fayang6dba4902019-06-17 10:04:23 -07006294 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006295 ProcessPacket(4);
fayang6dba4902019-06-17 10:04:23 -07006296 EXPECT_EQ(0u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006297
6298 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
6299 ProcessPacket(5);
nharper55fa6132019-05-07 19:37:21 -07006300 padding_frame_count = writer_->padding_frames().size();
6301 EXPECT_EQ(padding_frame_count + frames_per_ack, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006302 EXPECT_FALSE(writer_->ack_frames().empty());
6303 writer_->Reset();
6304
6305 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6306 // Now only set the timer on the 6th packet, instead of sending another ack.
6307 ProcessPacket(6);
nharper55fa6132019-05-07 19:37:21 -07006308 padding_frame_count = writer_->padding_frames().size();
6309 EXPECT_EQ(padding_frame_count, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006310 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6311}
6312
6313TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingPacket) {
6314 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
QUICHE team8c1daa22019-03-13 08:33:41 -07006315 EXPECT_CALL(visitor_, OnStreamFrame(_));
6316 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
6317 QuicMakeUnique<TaggingEncrypter>(0x01));
zhongyi546cc452019-04-12 15:27:49 -07006318 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
6319 QuicMakeUnique<StrictTaggingDecrypter>(0x01));
nharper2c9f02a2019-05-08 10:25:50 -07006320 ProcessDataPacket(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006321 connection_.SendStreamDataWithString(
6322 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6323 0, NO_FIN);
6324 // Check that ack is bundled with outgoing data and that delayed ack
6325 // alarm is reset.
6326 if (GetParam().no_stop_waiting) {
6327 EXPECT_EQ(2u, writer_->frame_count());
6328 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6329 } else {
6330 EXPECT_EQ(3u, writer_->frame_count());
6331 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6332 }
6333 EXPECT_FALSE(writer_->ack_frames().empty());
6334 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6335}
6336
6337TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingCryptoPacket) {
6338 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayangc31c9952019-06-05 13:54:48 -07006339 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6340 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
6341 } else {
6342 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6343 }
6344 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
nharper46833c32019-05-15 21:33:05 -07006345 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006346 // Check that ack is bundled with outgoing crypto data.
6347 if (GetParam().no_stop_waiting) {
6348 EXPECT_EQ(3u, writer_->frame_count());
6349 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6350 } else {
6351 EXPECT_EQ(4u, writer_->frame_count());
6352 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6353 }
6354 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6355}
6356
6357TEST_P(QuicConnectionTest, BlockAndBufferOnFirstCHLOPacketOfTwo) {
6358 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6359 ProcessPacket(1);
6360 BlockOnNextWrite();
6361 writer_->set_is_write_blocked_data_buffered(true);
nharper46833c32019-05-15 21:33:05 -07006362 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006363 EXPECT_TRUE(writer_->IsWriteBlocked());
6364 EXPECT_FALSE(connection_.HasQueuedData());
nharper46833c32019-05-15 21:33:05 -07006365 connection_.SendCryptoDataWithString("bar", 3);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006366 EXPECT_TRUE(writer_->IsWriteBlocked());
6367 EXPECT_TRUE(connection_.HasQueuedData());
6368}
6369
6370TEST_P(QuicConnectionTest, BundleAckForSecondCHLO) {
6371 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6372 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6373 EXPECT_CALL(visitor_, OnCanWrite())
6374 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6375 &connection_, &TestConnection::SendCryptoStreamData)));
6376 // Process a packet from the crypto stream, which is frame1_'s default.
6377 // Receiving the CHLO as packet 2 first will cause the connection to
6378 // immediately send an ack, due to the packet gap.
fayangc31c9952019-06-05 13:54:48 -07006379 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6380 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
6381 } else {
6382 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6383 }
6384 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006385 // Check that ack is sent and that delayed ack alarm is reset.
6386 if (GetParam().no_stop_waiting) {
6387 EXPECT_EQ(3u, writer_->frame_count());
6388 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6389 } else {
6390 EXPECT_EQ(4u, writer_->frame_count());
6391 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6392 }
QUICHE teamea740082019-03-11 17:58:43 -07006393 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006394 EXPECT_EQ(1u, writer_->stream_frames().size());
6395 } else {
6396 EXPECT_EQ(1u, writer_->crypto_frames().size());
6397 }
6398 EXPECT_EQ(1u, writer_->padding_frames().size());
6399 ASSERT_FALSE(writer_->ack_frames().empty());
6400 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(writer_->ack_frames().front()));
6401 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6402}
6403
6404TEST_P(QuicConnectionTest, BundleAckForSecondCHLOTwoPacketReject) {
6405 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6406 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6407
6408 // Process two packets from the crypto stream, which is frame1_'s default,
6409 // simulating a 2 packet reject.
6410 {
fayangc31c9952019-06-05 13:54:48 -07006411 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6412 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
6413 } else {
6414 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6415 }
6416 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006417 // Send the new CHLO when the REJ is processed.
fayangc31c9952019-06-05 13:54:48 -07006418 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6419 EXPECT_CALL(visitor_, OnCryptoFrame(_))
6420 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6421 &connection_, &TestConnection::SendCryptoStreamData)));
6422 } else {
6423 EXPECT_CALL(visitor_, OnStreamFrame(_))
6424 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6425 &connection_, &TestConnection::SendCryptoStreamData)));
6426 }
6427 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006428 }
6429 // Check that ack is sent and that delayed ack alarm is reset.
6430 if (GetParam().no_stop_waiting) {
6431 EXPECT_EQ(3u, writer_->frame_count());
6432 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6433 } else {
6434 EXPECT_EQ(4u, writer_->frame_count());
6435 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6436 }
QUICHE teamea740082019-03-11 17:58:43 -07006437 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006438 EXPECT_EQ(1u, writer_->stream_frames().size());
6439 } else {
6440 EXPECT_EQ(1u, writer_->crypto_frames().size());
6441 }
6442 EXPECT_EQ(1u, writer_->padding_frames().size());
6443 ASSERT_FALSE(writer_->ack_frames().empty());
6444 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(writer_->ack_frames().front()));
6445 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6446}
6447
6448TEST_P(QuicConnectionTest, BundleAckWithDataOnIncomingAck) {
6449 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6450 connection_.SendStreamDataWithString(
6451 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6452 0, NO_FIN);
6453 connection_.SendStreamDataWithString(
6454 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6455 3, NO_FIN);
6456 // Ack the second packet, which will retransmit the first packet.
6457 QuicAckFrame ack = ConstructAckFrame(2, 1);
6458 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07006459 lost_packets.push_back(
6460 LostPacket(QuicPacketNumber(1), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006461 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
6462 .WillOnce(SetArgPointee<5>(lost_packets));
6463 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
6464 ProcessAckPacket(&ack);
nharper55fa6132019-05-07 19:37:21 -07006465 size_t padding_frame_count = writer_->padding_frames().size();
6466 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006467 EXPECT_EQ(1u, writer_->stream_frames().size());
6468 writer_->Reset();
6469
6470 // Now ack the retransmission, which will both raise the high water mark
6471 // and see if there is more data to send.
6472 ack = ConstructAckFrame(3, 1);
6473 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
6474 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
6475 ProcessAckPacket(&ack);
6476
6477 // Check that no packet is sent and the ack alarm isn't set.
6478 EXPECT_EQ(0u, writer_->frame_count());
6479 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6480 writer_->Reset();
6481
6482 // Send the same ack, but send both data and an ack together.
6483 ack = ConstructAckFrame(3, 1);
6484 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
6485 EXPECT_CALL(visitor_, OnCanWrite())
6486 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6487 &connection_, &TestConnection::EnsureWritableAndSendStreamData5)));
6488 ProcessAckPacket(&ack);
6489
6490 // Check that ack is bundled with outgoing data and the delayed ack
6491 // alarm is reset.
6492 if (GetParam().no_stop_waiting) {
fayang03916692019-05-22 17:57:18 -07006493 if (GetQuicReloadableFlag(quic_simplify_stop_waiting)) {
6494 // Do not ACK acks.
6495 EXPECT_EQ(1u, writer_->frame_count());
6496 } else {
6497 EXPECT_EQ(2u, writer_->frame_count());
6498 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6499 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006500 } else {
6501 EXPECT_EQ(3u, writer_->frame_count());
6502 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6503 }
fayang03916692019-05-22 17:57:18 -07006504 if (GetParam().no_stop_waiting &&
6505 GetQuicReloadableFlag(quic_simplify_stop_waiting)) {
6506 EXPECT_TRUE(writer_->ack_frames().empty());
6507 } else {
6508 EXPECT_FALSE(writer_->ack_frames().empty());
6509 EXPECT_EQ(QuicPacketNumber(3u),
6510 LargestAcked(writer_->ack_frames().front()));
6511 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006512 EXPECT_EQ(1u, writer_->stream_frames().size());
6513 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6514}
6515
6516TEST_P(QuicConnectionTest, NoAckSentForClose) {
6517 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6518 ProcessPacket(1);
6519 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, _,
6520 ConnectionCloseSource::FROM_PEER));
6521 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6522 ProcessClosePacket(2);
6523}
6524
6525TEST_P(QuicConnectionTest, SendWhenDisconnected) {
6526 EXPECT_TRUE(connection_.connected());
6527 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, _,
6528 ConnectionCloseSource::FROM_SELF));
6529 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
6530 ConnectionCloseBehavior::SILENT_CLOSE);
6531 EXPECT_FALSE(connection_.connected());
6532 EXPECT_FALSE(connection_.CanWriteStreamData());
QUICHE team8c1daa22019-03-13 08:33:41 -07006533 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07006534 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006535 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6536 .Times(0);
QUICHE team6987b4a2019-03-15 16:23:04 -07006537 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05006538 HAS_RETRANSMITTABLE_DATA, false, false);
6539}
6540
6541TEST_P(QuicConnectionTest, SendConnectivityProbingWhenDisconnected) {
6542 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
fayangc31c9952019-06-05 13:54:48 -07006543 if (!IsDefaultTestConfiguration()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006544 return;
6545 }
6546
6547 EXPECT_TRUE(connection_.connected());
6548 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, _,
6549 ConnectionCloseSource::FROM_SELF));
6550 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
6551 ConnectionCloseBehavior::SILENT_CLOSE);
6552 EXPECT_FALSE(connection_.connected());
6553 EXPECT_FALSE(connection_.CanWriteStreamData());
6554
6555 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6556 .Times(0);
6557
6558 EXPECT_QUIC_BUG(connection_.SendConnectivityProbingPacket(
6559 writer_.get(), connection_.peer_address()),
6560 "Not sending connectivity probing packet as connection is "
6561 "disconnected.");
6562}
6563
6564TEST_P(QuicConnectionTest, WriteBlockedAfterClientSendsConnectivityProbe) {
6565 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
6566 TestPacketWriter probing_writer(version(), &clock_);
6567 // Block next write so that sending connectivity probe will encounter a
6568 // blocked write when send a connectivity probe to the peer.
6569 probing_writer.BlockOnNextWrite();
6570 // Connection will not be marked as write blocked as connectivity probe only
6571 // affects the probing_writer which is not the default.
6572 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
6573
6574 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6575 .Times(1);
6576 connection_.SendConnectivityProbingPacket(&probing_writer,
6577 connection_.peer_address());
6578}
6579
6580TEST_P(QuicConnectionTest, WriterBlockedAfterServerSendsConnectivityProbe) {
6581 set_perspective(Perspective::IS_SERVER);
6582 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
6583
6584 // Block next write so that sending connectivity probe will encounter a
6585 // blocked write when send a connectivity probe to the peer.
6586 writer_->BlockOnNextWrite();
6587 // Connection will be marked as write blocked as server uses the default
6588 // writer to send connectivity probes.
6589 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
6590
6591 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6592 .Times(1);
6593 connection_.SendConnectivityProbingPacket(writer_.get(),
6594 connection_.peer_address());
6595}
6596
6597TEST_P(QuicConnectionTest, WriterErrorWhenClientSendsConnectivityProbe) {
6598 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
6599 TestPacketWriter probing_writer(version(), &clock_);
6600 probing_writer.SetShouldWriteFail();
6601
6602 // Connection should not be closed if a connectivity probe is failed to be
6603 // sent.
6604 EXPECT_CALL(visitor_, OnConnectionClosed(_, _, _)).Times(0);
6605
6606 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6607 .Times(0);
6608 connection_.SendConnectivityProbingPacket(&probing_writer,
6609 connection_.peer_address());
6610}
6611
6612TEST_P(QuicConnectionTest, WriterErrorWhenServerSendsConnectivityProbe) {
6613 set_perspective(Perspective::IS_SERVER);
6614 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
6615
6616 writer_->SetShouldWriteFail();
6617 // Connection should not be closed if a connectivity probe is failed to be
6618 // sent.
6619 EXPECT_CALL(visitor_, OnConnectionClosed(_, _, _)).Times(0);
6620
6621 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6622 .Times(0);
6623 connection_.SendConnectivityProbingPacket(writer_.get(),
6624 connection_.peer_address());
6625}
6626
6627TEST_P(QuicConnectionTest, PublicReset) {
fayangc31c9952019-06-05 13:54:48 -07006628 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006629 return;
6630 }
6631 QuicPublicResetPacket header;
6632 // Public reset packet in only built by server.
6633 header.connection_id = connection_id_;
6634 std::unique_ptr<QuicEncryptedPacket> packet(
6635 framer_.BuildPublicResetPacket(header));
6636 std::unique_ptr<QuicReceivedPacket> received(
6637 ConstructReceivedPacket(*packet, QuicTime::Zero()));
6638 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PUBLIC_RESET, _,
6639 ConnectionCloseSource::FROM_PEER));
6640 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
6641}
6642
6643TEST_P(QuicConnectionTest, IetfStatelessReset) {
fayangc31c9952019-06-05 13:54:48 -07006644 if (!VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006645 return;
6646 }
6647 const QuicUint128 kTestStatelessResetToken = 1010101;
6648 QuicConfig config;
6649 QuicConfigPeer::SetReceivedStatelessResetToken(&config,
6650 kTestStatelessResetToken);
6651 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6652 connection_.SetFromConfig(config);
6653 std::unique_ptr<QuicEncryptedPacket> packet(
6654 QuicFramer::BuildIetfStatelessResetPacket(connection_id_,
6655 kTestStatelessResetToken));
6656 std::unique_ptr<QuicReceivedPacket> received(
6657 ConstructReceivedPacket(*packet, QuicTime::Zero()));
6658 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PUBLIC_RESET, _,
6659 ConnectionCloseSource::FROM_PEER));
6660 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
6661}
6662
6663TEST_P(QuicConnectionTest, GoAway) {
fkastenholz305e1732019-06-18 05:01:22 -07006664 if (VersionHasIetfQuicFrames(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006665 // GoAway is not available in version 99.
6666 return;
6667 }
6668
6669 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6670
6671 QuicGoAwayFrame goaway;
6672 goaway.last_good_stream_id = 1;
6673 goaway.error_code = QUIC_PEER_GOING_AWAY;
6674 goaway.reason_phrase = "Going away.";
6675 EXPECT_CALL(visitor_, OnGoAway(_));
6676 ProcessGoAwayPacket(&goaway);
6677}
6678
6679TEST_P(QuicConnectionTest, WindowUpdate) {
6680 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6681
6682 QuicWindowUpdateFrame window_update;
6683 window_update.stream_id = 3;
6684 window_update.byte_offset = 1234;
6685 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
6686 ProcessFramePacket(QuicFrame(&window_update));
6687}
6688
6689TEST_P(QuicConnectionTest, Blocked) {
6690 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6691
6692 QuicBlockedFrame blocked;
6693 blocked.stream_id = 3;
6694 EXPECT_CALL(visitor_, OnBlockedFrame(_));
6695 ProcessFramePacket(QuicFrame(&blocked));
6696 EXPECT_EQ(1u, connection_.GetStats().blocked_frames_received);
6697 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
6698}
6699
6700TEST_P(QuicConnectionTest, ZeroBytePacket) {
6701 // Don't close the connection for zero byte packets.
6702 EXPECT_CALL(visitor_, OnConnectionClosed(_, _, _)).Times(0);
6703 QuicReceivedPacket encrypted(nullptr, 0, QuicTime::Zero());
6704 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, encrypted);
6705}
6706
6707TEST_P(QuicConnectionTest, MissingPacketsBeforeLeastUnacked) {
fayangd4291e42019-05-30 10:31:21 -07006708 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006709 return;
6710 }
6711 // Set the packet number of the ack packet to be least unacked (4).
6712 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 3);
6713 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6714 ProcessStopWaitingPacket(InitStopWaitingFrame(4));
fayangc31c9952019-06-05 13:54:48 -07006715 EXPECT_FALSE(connection_.ack_frame().packets.Empty());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006716}
6717
QUICHE teama6ef0a62019-03-07 20:34:33 -05006718TEST_P(QuicConnectionTest, ClientHandlesVersionNegotiation) {
dschinazi5a354c92019-05-09 12:18:53 -07006719 const bool expect_failure =
6720 GetQuicReloadableFlag(quic_no_client_conn_ver_negotiation) ||
6721 connection_.version().handshake_protocol !=
6722 QuicVersionReservedForNegotiation().handshake_protocol;
6723 // Start out with an unsupported version.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006724 QuicConnectionPeer::GetFramer(&connection_)
dschinazi5a354c92019-05-09 12:18:53 -07006725 ->set_version_for_tests(QuicVersionReservedForNegotiation());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006726
6727 // Send a version negotiation packet.
6728 std::unique_ptr<QuicEncryptedPacket> encrypted(
dschinazib417d602019-05-29 13:08:45 -07006729 QuicFramer::BuildVersionNegotiationPacket(
6730 connection_id_, EmptyQuicConnectionId(),
fayangd4291e42019-05-30 10:31:21 -07006731 VersionHasIetfInvariantHeader(connection_.transport_version()),
QUICHE teama6ef0a62019-03-07 20:34:33 -05006732 AllSupportedVersions()));
6733 std::unique_ptr<QuicReceivedPacket> received(
6734 ConstructReceivedPacket(*encrypted, QuicTime::Zero()));
dschinazi5a354c92019-05-09 12:18:53 -07006735 if (expect_failure) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006736 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_VERSION, _,
6737 ConnectionCloseSource::FROM_SELF));
6738 }
6739 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
dschinazi5a354c92019-05-09 12:18:53 -07006740 if (expect_failure) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006741 EXPECT_FALSE(connection_.connected());
6742 return;
6743 }
6744
6745 // Now force another packet. The connection should transition into
6746 // NEGOTIATED_VERSION state and tell the packet creator to StopSendingVersion.
6747 QuicPacketHeader header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05006748 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
QUICHE team2252b702019-05-14 23:55:14 -04006749 if (!GetQuicRestartFlag(quic_do_not_override_connection_id)) {
6750 header.destination_connection_id = connection_id_;
6751 } else {
6752 header.source_connection_id = connection_id_;
6753 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006754 header.packet_number = QuicPacketNumber(12);
6755 header.version_flag = false;
6756 QuicFrames frames;
6757 frames.push_back(QuicFrame(frame1_));
6758 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
dschinazi66dea072019-04-09 11:41:06 -07006759 char buffer[kMaxOutgoingPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07006760 size_t encrypted_length =
6761 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12),
dschinazi66dea072019-04-09 11:41:06 -07006762 *packet, buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006763 ASSERT_NE(0u, encrypted_length);
6764 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6765 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6766 connection_.ProcessUdpPacket(
6767 kSelfAddress, kPeerAddress,
6768 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
fayangd4291e42019-05-30 10:31:21 -07006769 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006770 // IETF QUIC stops sending version when switch to FORWARD_SECURE.
6771 EXPECT_NE(ENCRYPTION_FORWARD_SECURE, connection_.encryption_level());
6772 ASSERT_TRUE(QuicPacketCreatorPeer::SendVersionInPacket(creator_));
6773 } else {
6774 ASSERT_FALSE(QuicPacketCreatorPeer::SendVersionInPacket(creator_));
6775 }
6776}
6777
6778TEST_P(QuicConnectionTest, BadVersionNegotiation) {
6779 // Send a version negotiation packet with the version the client started with.
6780 // It should be rejected.
6781 EXPECT_CALL(visitor_,
6782 OnConnectionClosed(QUIC_INVALID_VERSION_NEGOTIATION_PACKET, _,
6783 ConnectionCloseSource::FROM_SELF));
6784 std::unique_ptr<QuicEncryptedPacket> encrypted(
dschinazib417d602019-05-29 13:08:45 -07006785 QuicFramer::BuildVersionNegotiationPacket(
6786 connection_id_, EmptyQuicConnectionId(),
fayangd4291e42019-05-30 10:31:21 -07006787 VersionHasIetfInvariantHeader(connection_.transport_version()),
QUICHE teama6ef0a62019-03-07 20:34:33 -05006788 AllSupportedVersions()));
6789 std::unique_ptr<QuicReceivedPacket> received(
6790 ConstructReceivedPacket(*encrypted, QuicTime::Zero()));
6791 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
6792}
6793
6794TEST_P(QuicConnectionTest, CheckSendStats) {
6795 connection_.SetMaxTailLossProbes(0);
6796
6797 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
6798 connection_.SendStreamDataWithString(3, "first", 0, NO_FIN);
6799 size_t first_packet_size = writer_->last_packet_size();
6800
6801 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
6802 connection_.SendStreamDataWithString(5, "second", 0, NO_FIN);
6803 size_t second_packet_size = writer_->last_packet_size();
6804
6805 // 2 retransmissions due to rto, 1 due to explicit nack.
6806 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
6807 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
6808
6809 // Retransmit due to RTO.
6810 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
6811 connection_.GetRetransmissionAlarm()->Fire();
6812
6813 // Retransmit due to explicit nacks.
6814 QuicAckFrame nack_three =
6815 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)},
6816 {QuicPacketNumber(4), QuicPacketNumber(5)}});
6817
6818 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07006819 lost_packets.push_back(
6820 LostPacket(QuicPacketNumber(1), kMaxOutgoingPacketSize));
6821 lost_packets.push_back(
6822 LostPacket(QuicPacketNumber(3), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006823 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
6824 .WillOnce(SetArgPointee<5>(lost_packets));
6825 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
6826 if (!connection_.session_decides_what_to_write()) {
6827 EXPECT_CALL(visitor_, OnCanWrite());
6828 }
6829 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6830 ProcessAckPacket(&nack_three);
6831
6832 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
6833 .WillOnce(Return(QuicBandwidth::Zero()));
6834
6835 const QuicConnectionStats& stats = connection_.GetStats();
6836 // For IETF QUIC, version is not included as the encryption level switches to
6837 // FORWARD_SECURE in SendStreamDataWithString.
6838 size_t save_on_version =
fayangd4291e42019-05-30 10:31:21 -07006839 VersionHasIetfInvariantHeader(GetParam().version.transport_version)
6840 ? 0
6841 : kQuicVersionSize;
QUICHE teama6ef0a62019-03-07 20:34:33 -05006842 EXPECT_EQ(3 * first_packet_size + 2 * second_packet_size - save_on_version,
6843 stats.bytes_sent);
6844 EXPECT_EQ(5u, stats.packets_sent);
6845 EXPECT_EQ(2 * first_packet_size + second_packet_size - save_on_version,
6846 stats.bytes_retransmitted);
6847 EXPECT_EQ(3u, stats.packets_retransmitted);
6848 EXPECT_EQ(1u, stats.rto_count);
6849 EXPECT_EQ(kDefaultMaxPacketSize, stats.max_packet_size);
6850}
6851
6852TEST_P(QuicConnectionTest, ProcessFramesIfPacketClosedConnection) {
6853 // Construct a packet with stream frame and connection close frame.
6854 QuicPacketHeader header;
QUICHE team2252b702019-05-14 23:55:14 -04006855 if (GetQuicRestartFlag(quic_do_not_override_connection_id) &&
6856 peer_framer_.perspective() == Perspective::IS_SERVER) {
6857 header.source_connection_id = connection_id_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05006858 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
fayangd4291e42019-05-30 10:31:21 -07006859 if (!VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04006860 header.source_connection_id_included = CONNECTION_ID_PRESENT;
6861 }
6862 } else {
6863 header.destination_connection_id = connection_id_;
fayangd4291e42019-05-30 10:31:21 -07006864 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04006865 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
6866 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006867 }
6868 header.packet_number = QuicPacketNumber(1);
6869 header.version_flag = false;
6870
fkastenholze9d71a82019-04-09 05:12:13 -07006871 QuicConnectionCloseFrame qccf(QUIC_PEER_GOING_AWAY);
fkastenholz305e1732019-06-18 05:01:22 -07006872 if (VersionHasIetfQuicFrames(peer_framer_.transport_version())) {
6873 // Default close-type is Google QUIC. If doing IETF QUIC then
fkastenholz04bd4f32019-04-16 12:24:38 -07006874 // set close type to be IETF CC/T.
fkastenholz72f509b2019-04-10 09:17:49 -07006875 qccf.close_type = IETF_QUIC_TRANSPORT_CONNECTION_CLOSE;
6876 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006877
6878 QuicFrames frames;
6879 frames.push_back(QuicFrame(frame1_));
6880 frames.push_back(QuicFrame(&qccf));
6881 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
6882 EXPECT_TRUE(nullptr != packet);
dschinazi66dea072019-04-09 11:41:06 -07006883 char buffer[kMaxOutgoingPacketSize];
6884 size_t encrypted_length =
6885 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(1),
6886 *packet, buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006887
6888 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, _,
6889 ConnectionCloseSource::FROM_PEER));
6890 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6891 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6892
6893 connection_.ProcessUdpPacket(
6894 kSelfAddress, kPeerAddress,
6895 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
6896}
6897
6898TEST_P(QuicConnectionTest, SelectMutualVersion) {
6899 connection_.SetSupportedVersions(AllSupportedVersions());
6900 // Set the connection to speak the lowest quic version.
6901 connection_.set_version(QuicVersionMin());
6902 EXPECT_EQ(QuicVersionMin(), connection_.version());
6903
6904 // Pass in available versions which includes a higher mutually supported
6905 // version. The higher mutually supported version should be selected.
6906 ParsedQuicVersionVector supported_versions = AllSupportedVersions();
6907 EXPECT_TRUE(connection_.SelectMutualVersion(supported_versions));
6908 EXPECT_EQ(QuicVersionMax(), connection_.version());
6909
6910 // Expect that the lowest version is selected.
6911 // Ensure the lowest supported version is less than the max, unless they're
6912 // the same.
6913 ParsedQuicVersionVector lowest_version_vector;
6914 lowest_version_vector.push_back(QuicVersionMin());
6915 EXPECT_TRUE(connection_.SelectMutualVersion(lowest_version_vector));
6916 EXPECT_EQ(QuicVersionMin(), connection_.version());
6917
6918 // Shouldn't be able to find a mutually supported version.
6919 ParsedQuicVersionVector unsupported_version;
6920 unsupported_version.push_back(UnsupportedQuicVersion());
6921 EXPECT_FALSE(connection_.SelectMutualVersion(unsupported_version));
6922}
6923
6924TEST_P(QuicConnectionTest, ConnectionCloseWhenWritable) {
6925 EXPECT_FALSE(writer_->IsWriteBlocked());
6926
6927 // Send a packet.
6928 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
6929 EXPECT_EQ(0u, connection_.NumQueuedPackets());
6930 EXPECT_EQ(1u, writer_->packets_write_attempts());
6931
6932 TriggerConnectionClose();
6933 EXPECT_EQ(2u, writer_->packets_write_attempts());
6934}
6935
6936TEST_P(QuicConnectionTest, ConnectionCloseGettingWriteBlocked) {
6937 BlockOnNextWrite();
6938 TriggerConnectionClose();
6939 EXPECT_EQ(1u, writer_->packets_write_attempts());
6940 EXPECT_TRUE(writer_->IsWriteBlocked());
6941}
6942
6943TEST_P(QuicConnectionTest, ConnectionCloseWhenWriteBlocked) {
6944 BlockOnNextWrite();
6945 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
6946 EXPECT_EQ(1u, connection_.NumQueuedPackets());
6947 EXPECT_EQ(1u, writer_->packets_write_attempts());
6948 EXPECT_TRUE(writer_->IsWriteBlocked());
6949 TriggerConnectionClose();
6950 EXPECT_EQ(1u, writer_->packets_write_attempts());
6951}
6952
6953TEST_P(QuicConnectionTest, OnPacketSentDebugVisitor) {
6954 MockQuicConnectionDebugVisitor debug_visitor;
6955 connection_.set_debug_visitor(&debug_visitor);
6956
6957 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _)).Times(1);
6958 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
6959
6960 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _)).Times(1);
6961 connection_.SendConnectivityProbingPacket(writer_.get(),
6962 connection_.peer_address());
6963}
6964
6965TEST_P(QuicConnectionTest, OnPacketHeaderDebugVisitor) {
6966 QuicPacketHeader header;
6967 header.packet_number = QuicPacketNumber(1);
fayangd4291e42019-05-30 10:31:21 -07006968 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006969 header.form = IETF_QUIC_LONG_HEADER_PACKET;
6970 }
6971
6972 MockQuicConnectionDebugVisitor debug_visitor;
6973 connection_.set_debug_visitor(&debug_visitor);
6974 EXPECT_CALL(debug_visitor, OnPacketHeader(Ref(header))).Times(1);
6975 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(1);
6976 EXPECT_CALL(debug_visitor, OnSuccessfulVersionNegotiation(_)).Times(1);
6977 connection_.OnPacketHeader(header);
6978}
6979
6980TEST_P(QuicConnectionTest, Pacing) {
6981 TestConnection server(connection_id_, kSelfAddress, helper_.get(),
6982 alarm_factory_.get(), writer_.get(),
6983 Perspective::IS_SERVER, version());
6984 TestConnection client(connection_id_, kPeerAddress, helper_.get(),
6985 alarm_factory_.get(), writer_.get(),
6986 Perspective::IS_CLIENT, version());
6987 EXPECT_FALSE(QuicSentPacketManagerPeer::UsingPacing(
6988 static_cast<const QuicSentPacketManager*>(
6989 &client.sent_packet_manager())));
6990 EXPECT_FALSE(QuicSentPacketManagerPeer::UsingPacing(
6991 static_cast<const QuicSentPacketManager*>(
6992 &server.sent_packet_manager())));
6993}
6994
6995TEST_P(QuicConnectionTest, WindowUpdateInstigateAcks) {
6996 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6997
6998 // Send a WINDOW_UPDATE frame.
6999 QuicWindowUpdateFrame window_update;
7000 window_update.stream_id = 3;
7001 window_update.byte_offset = 1234;
7002 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
7003 ProcessFramePacket(QuicFrame(&window_update));
7004
7005 // Ensure that this has caused the ACK alarm to be set.
7006 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
7007 EXPECT_TRUE(ack_alarm->IsSet());
7008}
7009
7010TEST_P(QuicConnectionTest, BlockedFrameInstigateAcks) {
7011 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7012
7013 // Send a BLOCKED frame.
7014 QuicBlockedFrame blocked;
7015 blocked.stream_id = 3;
7016 EXPECT_CALL(visitor_, OnBlockedFrame(_));
7017 ProcessFramePacket(QuicFrame(&blocked));
7018
7019 // Ensure that this has caused the ACK alarm to be set.
7020 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
7021 EXPECT_TRUE(ack_alarm->IsSet());
7022}
7023
7024TEST_P(QuicConnectionTest, ReevaluateTimeUntilSendOnAck) {
7025 // Enable pacing.
7026 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7027 QuicConfig config;
7028 connection_.SetFromConfig(config);
7029
7030 // Send two packets. One packet is not sufficient because if it gets acked,
7031 // there will be no packets in flight after that and the pacer will always
7032 // allow the next packet in that situation.
7033 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7034 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
7035 connection_.SendStreamDataWithString(
7036 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
7037 0, NO_FIN);
7038 connection_.SendStreamDataWithString(
7039 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "bar",
7040 3, NO_FIN);
7041 connection_.OnCanWrite();
7042
7043 // Schedule the next packet for a few milliseconds in future.
7044 QuicSentPacketManagerPeer::DisablePacerBursts(manager_);
7045 QuicTime scheduled_pacing_time =
7046 clock_.Now() + QuicTime::Delta::FromMilliseconds(5);
7047 QuicSentPacketManagerPeer::SetNextPacedPacketTime(manager_,
7048 scheduled_pacing_time);
7049
7050 // Send a packet and have it be blocked by congestion control.
7051 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(false));
7052 connection_.SendStreamDataWithString(
7053 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "baz",
7054 6, NO_FIN);
7055 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
7056
7057 // Process an ack and the send alarm will be set to the new 5ms delay.
7058 QuicAckFrame ack = InitAckFrame(1);
7059 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
7060 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7061 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
7062 ProcessAckPacket(&ack);
nharper55fa6132019-05-07 19:37:21 -07007063 size_t padding_frame_count = writer_->padding_frames().size();
7064 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007065 EXPECT_EQ(1u, writer_->stream_frames().size());
7066 EXPECT_TRUE(connection_.GetSendAlarm()->IsSet());
7067 EXPECT_EQ(scheduled_pacing_time, connection_.GetSendAlarm()->deadline());
7068 writer_->Reset();
7069}
7070
7071TEST_P(QuicConnectionTest, SendAcksImmediately) {
QUICHE teamcd098022019-03-22 18:49:55 -07007072 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7073 return;
7074 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007075 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7076 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7077 ProcessDataPacket(1);
7078 CongestionBlockWrites();
7079 SendAckPacketToPeer();
7080}
7081
7082TEST_P(QuicConnectionTest, SendPingImmediately) {
7083 MockQuicConnectionDebugVisitor debug_visitor;
7084 connection_.set_debug_visitor(&debug_visitor);
7085
7086 CongestionBlockWrites();
7087 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7088 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _)).Times(1);
7089 EXPECT_CALL(debug_visitor, OnPingSent()).Times(1);
7090 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
7091 EXPECT_FALSE(connection_.HasQueuedData());
7092}
7093
7094TEST_P(QuicConnectionTest, SendBlockedImmediately) {
7095 MockQuicConnectionDebugVisitor debug_visitor;
7096 connection_.set_debug_visitor(&debug_visitor);
7097
7098 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7099 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _)).Times(1);
7100 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7101 connection_.SendControlFrame(QuicFrame(new QuicBlockedFrame(1, 3)));
7102 EXPECT_EQ(1u, connection_.GetStats().blocked_frames_sent);
7103 EXPECT_FALSE(connection_.HasQueuedData());
7104}
7105
7106TEST_P(QuicConnectionTest, SendingUnencryptedStreamDataFails) {
7107 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
7108 if (!IsDefaultTestConfiguration()) {
7109 return;
7110 }
7111
7112 EXPECT_CALL(visitor_,
7113 OnConnectionClosed(QUIC_ATTEMPT_TO_SEND_UNENCRYPTED_STREAM_DATA,
7114 _, ConnectionCloseSource::FROM_SELF));
7115 struct iovec iov;
7116 MakeIOVector("", &iov);
7117 EXPECT_QUIC_BUG(connection_.SaveAndSendStreamData(3, &iov, 1, 0, 0, FIN),
fayang49523232019-05-03 06:28:22 -07007118 "Cannot send stream data with level: ENCRYPTION_INITIAL");
QUICHE teama6ef0a62019-03-07 20:34:33 -05007119 EXPECT_FALSE(connection_.connected());
7120}
7121
7122TEST_P(QuicConnectionTest, SetRetransmissionAlarmForCryptoPacket) {
7123 EXPECT_TRUE(connection_.connected());
7124 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
7125
7126 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7127 connection_.SendCryptoStreamData();
7128
7129 // Verify retransmission timer is correctly set after crypto packet has been
7130 // sent.
7131 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
7132 QuicTime retransmission_time =
7133 QuicConnectionPeer::GetSentPacketManager(&connection_)
7134 ->GetRetransmissionTime();
7135 EXPECT_NE(retransmission_time, clock_.ApproximateNow());
7136 EXPECT_EQ(retransmission_time,
7137 connection_.GetRetransmissionAlarm()->deadline());
7138
7139 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7140 connection_.GetRetransmissionAlarm()->Fire();
7141}
7142
7143TEST_P(QuicConnectionTest, PathDegradingAlarmForCryptoPacket) {
7144 EXPECT_TRUE(connection_.connected());
7145 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7146 EXPECT_FALSE(connection_.IsPathDegrading());
7147
7148 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7149 connection_.SendCryptoStreamData();
7150
7151 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7152 EXPECT_FALSE(connection_.IsPathDegrading());
7153 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7154 ->GetPathDegradingDelay();
7155 EXPECT_EQ(clock_.ApproximateNow() + delay,
7156 connection_.GetPathDegradingAlarm()->deadline());
7157
7158 // Fire the path degrading alarm, path degrading signal should be sent to
7159 // the visitor.
7160 EXPECT_CALL(visitor_, OnPathDegrading());
7161 clock_.AdvanceTime(delay);
7162 connection_.GetPathDegradingAlarm()->Fire();
7163 EXPECT_TRUE(connection_.IsPathDegrading());
7164 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7165}
7166
vasilvv693d5b02019-04-09 21:58:56 -07007167// Includes regression test for b/69979024.
QUICHE teama6ef0a62019-03-07 20:34:33 -05007168TEST_P(QuicConnectionTest, PathDegradingAlarmForNonCryptoPackets) {
7169 EXPECT_TRUE(connection_.connected());
7170 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7171 EXPECT_FALSE(connection_.IsPathDegrading());
7172
7173 const char data[] = "data";
7174 size_t data_size = strlen(data);
7175 QuicStreamOffset offset = 0;
7176
7177 for (int i = 0; i < 2; ++i) {
7178 // Send a packet. Now there's a retransmittable packet on the wire, so the
7179 // path degrading alarm should be set.
7180 connection_.SendStreamDataWithString(
7181 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
7182 offset, NO_FIN);
7183 offset += data_size;
7184 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7185 // Check the deadline of the path degrading alarm.
7186 QuicTime::Delta delay =
7187 QuicConnectionPeer::GetSentPacketManager(&connection_)
7188 ->GetPathDegradingDelay();
7189 EXPECT_EQ(clock_.ApproximateNow() + delay,
7190 connection_.GetPathDegradingAlarm()->deadline());
7191
7192 // Send a second packet. The path degrading alarm's deadline should remain
7193 // the same.
vasilvv693d5b02019-04-09 21:58:56 -07007194 // Regression test for b/69979024.
QUICHE teama6ef0a62019-03-07 20:34:33 -05007195 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7196 QuicTime prev_deadline = connection_.GetPathDegradingAlarm()->deadline();
7197 connection_.SendStreamDataWithString(
7198 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
7199 offset, NO_FIN);
7200 offset += data_size;
7201 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7202 EXPECT_EQ(prev_deadline, connection_.GetPathDegradingAlarm()->deadline());
7203
7204 // Now receive an ACK of the first packet. This should advance the path
7205 // degrading alarm's deadline since forward progress has been made.
7206 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7207 if (i == 0) {
7208 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7209 }
7210 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7211 QuicAckFrame frame = InitAckFrame(
7212 {{QuicPacketNumber(1u + 2u * i), QuicPacketNumber(2u + 2u * i)}});
7213 ProcessAckPacket(&frame);
7214 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7215 // Check the deadline of the path degrading alarm.
7216 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7217 ->GetPathDegradingDelay();
7218 EXPECT_EQ(clock_.ApproximateNow() + delay,
7219 connection_.GetPathDegradingAlarm()->deadline());
7220
7221 if (i == 0) {
7222 // Now receive an ACK of the second packet. Since there are no more
7223 // retransmittable packets on the wire, this should cancel the path
7224 // degrading alarm.
7225 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7226 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7227 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
7228 ProcessAckPacket(&frame);
7229 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7230 } else {
7231 // Advance time to the path degrading alarm's deadline and simulate
7232 // firing the alarm.
7233 clock_.AdvanceTime(delay);
7234 EXPECT_CALL(visitor_, OnPathDegrading());
7235 connection_.GetPathDegradingAlarm()->Fire();
7236 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7237 }
7238 }
7239 EXPECT_TRUE(connection_.IsPathDegrading());
7240}
7241
7242TEST_P(QuicConnectionTest, RetransmittableOnWireSetsPingAlarm) {
7243 const QuicTime::Delta retransmittable_on_wire_timeout =
7244 QuicTime::Delta::FromMilliseconds(50);
7245 connection_.set_retransmittable_on_wire_timeout(
7246 retransmittable_on_wire_timeout);
7247
7248 EXPECT_TRUE(connection_.connected());
7249 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7250 .WillRepeatedly(Return(true));
7251
7252 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7253 EXPECT_FALSE(connection_.IsPathDegrading());
7254 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
7255
7256 const char data[] = "data";
7257 size_t data_size = strlen(data);
7258 QuicStreamOffset offset = 0;
7259
7260 // Send a packet.
7261 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7262 offset += data_size;
7263 // Now there's a retransmittable packet on the wire, so the path degrading
7264 // alarm should be set.
7265 // The retransmittable-on-wire alarm should not be set.
7266 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7267 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7268 ->GetPathDegradingDelay();
7269 EXPECT_EQ(clock_.ApproximateNow() + delay,
7270 connection_.GetPathDegradingAlarm()->deadline());
7271 ASSERT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
7272 // The ping alarm is set for the ping timeout, not the shorter
7273 // retransmittable_on_wire_timeout.
7274 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7275 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
7276 EXPECT_EQ((clock_.ApproximateNow() + ping_delay),
7277 connection_.GetPingAlarm()->deadline());
7278
7279 // Now receive an ACK of the packet.
7280 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7281 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7282 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7283 QuicAckFrame frame =
7284 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7285 ProcessAckPacket(&frame);
7286 // No more retransmittable packets on the wire, so the path degrading alarm
7287 // should be cancelled, and the ping alarm should be set to the
7288 // retransmittable_on_wire_timeout.
7289 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7290 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7291 EXPECT_EQ(clock_.ApproximateNow() + retransmittable_on_wire_timeout,
7292 connection_.GetPingAlarm()->deadline());
7293
7294 // Simulate firing the ping alarm and sending a PING.
7295 clock_.AdvanceTime(retransmittable_on_wire_timeout);
7296 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
7297 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
7298 }));
7299 connection_.GetPingAlarm()->Fire();
7300
7301 // Now there's a retransmittable packet (PING) on the wire, so the path
7302 // degrading alarm should be set.
7303 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7304 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7305 ->GetPathDegradingDelay();
7306 EXPECT_EQ(clock_.ApproximateNow() + delay,
7307 connection_.GetPathDegradingAlarm()->deadline());
7308}
7309
7310// This test verifies that the connection marks path as degrading and does not
7311// spin timer to detect path degrading when a new packet is sent on the
7312// degraded path.
7313TEST_P(QuicConnectionTest, NoPathDegradingAlarmIfPathIsDegrading) {
7314 EXPECT_TRUE(connection_.connected());
7315 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7316 EXPECT_FALSE(connection_.IsPathDegrading());
7317
7318 const char data[] = "data";
7319 size_t data_size = strlen(data);
7320 QuicStreamOffset offset = 0;
7321
7322 // Send the first packet. Now there's a retransmittable packet on the wire, so
7323 // the path degrading alarm should be set.
7324 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7325 offset += data_size;
7326 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7327 // Check the deadline of the path degrading alarm.
7328 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7329 ->GetPathDegradingDelay();
7330 EXPECT_EQ(clock_.ApproximateNow() + delay,
7331 connection_.GetPathDegradingAlarm()->deadline());
7332
7333 // Send a second packet. The path degrading alarm's deadline should remain
7334 // the same.
7335 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7336 QuicTime prev_deadline = connection_.GetPathDegradingAlarm()->deadline();
7337 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7338 offset += data_size;
7339 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7340 EXPECT_EQ(prev_deadline, connection_.GetPathDegradingAlarm()->deadline());
7341
7342 // Now receive an ACK of the first packet. This should advance the path
7343 // degrading alarm's deadline since forward progress has been made.
7344 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7345 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7346 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7347 QuicAckFrame frame =
7348 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
7349 ProcessAckPacket(&frame);
7350 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7351 // Check the deadline of the path degrading alarm.
7352 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7353 ->GetPathDegradingDelay();
7354 EXPECT_EQ(clock_.ApproximateNow() + delay,
7355 connection_.GetPathDegradingAlarm()->deadline());
7356
7357 // Advance time to the path degrading alarm's deadline and simulate
7358 // firing the path degrading alarm. This path will be considered as
7359 // degrading.
7360 clock_.AdvanceTime(delay);
7361 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
7362 connection_.GetPathDegradingAlarm()->Fire();
7363 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7364 EXPECT_TRUE(connection_.IsPathDegrading());
7365
7366 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7367 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7368 // Send a third packet. The path degrading alarm is no longer set but path
7369 // should still be marked as degrading.
7370 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7371 offset += data_size;
7372 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7373 EXPECT_TRUE(connection_.IsPathDegrading());
7374}
7375
7376// This test verifies that the connection unmarks path as degrarding and spins
7377// the timer to detect future path degrading when forward progress is made
7378// after path has been marked degrading.
7379TEST_P(QuicConnectionTest, UnmarkPathDegradingOnForwardProgress) {
7380 EXPECT_TRUE(connection_.connected());
7381 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7382 EXPECT_FALSE(connection_.IsPathDegrading());
7383
7384 const char data[] = "data";
7385 size_t data_size = strlen(data);
7386 QuicStreamOffset offset = 0;
7387
7388 // Send the first packet. Now there's a retransmittable packet on the wire, so
7389 // the path degrading alarm should be set.
7390 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7391 offset += data_size;
7392 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7393 // Check the deadline of the path degrading alarm.
7394 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7395 ->GetPathDegradingDelay();
7396 EXPECT_EQ(clock_.ApproximateNow() + delay,
7397 connection_.GetPathDegradingAlarm()->deadline());
7398
7399 // Send a second packet. The path degrading alarm's deadline should remain
7400 // the same.
7401 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7402 QuicTime prev_deadline = connection_.GetPathDegradingAlarm()->deadline();
7403 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7404 offset += data_size;
7405 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7406 EXPECT_EQ(prev_deadline, connection_.GetPathDegradingAlarm()->deadline());
7407
7408 // Now receive an ACK of the first packet. This should advance the path
7409 // degrading alarm's deadline since forward progress has been made.
7410 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7411 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7412 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7413 QuicAckFrame frame =
7414 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
7415 ProcessAckPacket(&frame);
7416 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7417 // Check the deadline of the path degrading alarm.
7418 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7419 ->GetPathDegradingDelay();
7420 EXPECT_EQ(clock_.ApproximateNow() + delay,
7421 connection_.GetPathDegradingAlarm()->deadline());
7422
7423 // Advance time to the path degrading alarm's deadline and simulate
7424 // firing the alarm.
7425 clock_.AdvanceTime(delay);
7426 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
7427 connection_.GetPathDegradingAlarm()->Fire();
7428 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7429 EXPECT_TRUE(connection_.IsPathDegrading());
7430
7431 // Send a third packet. The path degrading alarm is no longer set but path
7432 // should still be marked as degrading.
7433 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7434 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7435 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7436 offset += data_size;
7437 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7438 EXPECT_TRUE(connection_.IsPathDegrading());
7439
7440 // Now receive an ACK of the second packet. This should unmark the path as
7441 // degrading. And will set a timer to detect new path degrading.
7442 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7443 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7444 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
7445 ProcessAckPacket(&frame);
7446 EXPECT_FALSE(connection_.IsPathDegrading());
7447 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7448}
7449
7450TEST_P(QuicConnectionTest, NoPathDegradingOnServer) {
QUICHE teamcd098022019-03-22 18:49:55 -07007451 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7452 return;
7453 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007454 set_perspective(Perspective::IS_SERVER);
7455 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
7456
7457 EXPECT_FALSE(connection_.IsPathDegrading());
7458 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7459
7460 // Send data.
7461 const char data[] = "data";
7462 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
7463 EXPECT_FALSE(connection_.IsPathDegrading());
7464 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7465
7466 // Ack data.
7467 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7468 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7469 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7470 QuicAckFrame frame =
7471 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
7472 ProcessAckPacket(&frame);
7473 EXPECT_FALSE(connection_.IsPathDegrading());
7474 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7475}
7476
7477TEST_P(QuicConnectionTest, NoPathDegradingAfterSendingAck) {
QUICHE teamcd098022019-03-22 18:49:55 -07007478 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7479 return;
7480 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007481 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7482 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7483 ProcessDataPacket(1);
7484 SendAckPacketToPeer();
7485 EXPECT_FALSE(connection_.sent_packet_manager().unacked_packets().empty());
7486 EXPECT_FALSE(connection_.sent_packet_manager().HasInFlightPackets());
7487 EXPECT_FALSE(connection_.IsPathDegrading());
7488 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7489}
7490
7491TEST_P(QuicConnectionTest, MultipleCallsToCloseConnection) {
7492 // Verifies that multiple calls to CloseConnection do not
7493 // result in multiple attempts to close the connection - it will be marked as
7494 // disconnected after the first call.
7495 EXPECT_CALL(visitor_, OnConnectionClosed(_, _, _)).Times(1);
7496 connection_.CloseConnection(QUIC_NO_ERROR, "no reason",
7497 ConnectionCloseBehavior::SILENT_CLOSE);
7498 connection_.CloseConnection(QUIC_NO_ERROR, "no reason",
7499 ConnectionCloseBehavior::SILENT_CLOSE);
7500}
7501
7502TEST_P(QuicConnectionTest, ServerReceivesChloOnNonCryptoStream) {
7503 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7504
7505 set_perspective(Perspective::IS_SERVER);
7506 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
7507
7508 CryptoHandshakeMessage message;
7509 CryptoFramer framer;
7510 message.set_tag(kCHLO);
QUICHE team3fe6a8b2019-03-14 09:10:38 -07007511 std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007512 frame1_.stream_id = 10;
7513 frame1_.data_buffer = data->data();
7514 frame1_.data_length = data->length();
7515
7516 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_MAYBE_CORRUPTED_MEMORY, _,
7517 ConnectionCloseSource::FROM_SELF));
7518 ForceProcessFramePacket(QuicFrame(frame1_));
7519}
7520
7521TEST_P(QuicConnectionTest, ClientReceivesRejOnNonCryptoStream) {
7522 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7523
7524 CryptoHandshakeMessage message;
7525 CryptoFramer framer;
7526 message.set_tag(kREJ);
QUICHE team3fe6a8b2019-03-14 09:10:38 -07007527 std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007528 frame1_.stream_id = 10;
7529 frame1_.data_buffer = data->data();
7530 frame1_.data_length = data->length();
7531
7532 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_MAYBE_CORRUPTED_MEMORY, _,
7533 ConnectionCloseSource::FROM_SELF));
7534 ForceProcessFramePacket(QuicFrame(frame1_));
7535}
7536
7537TEST_P(QuicConnectionTest, CloseConnectionOnPacketTooLarge) {
7538 SimulateNextPacketTooLarge();
7539 // A connection close packet is sent
7540 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PACKET_WRITE_ERROR, _,
7541 ConnectionCloseSource::FROM_SELF))
7542 .Times(1);
7543 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7544}
7545
7546TEST_P(QuicConnectionTest, AlwaysGetPacketTooLarge) {
7547 // Test even we always get packet too large, we do not infinitely try to send
7548 // close packet.
7549 AlwaysGetPacketTooLarge();
7550 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PACKET_WRITE_ERROR, _,
7551 ConnectionCloseSource::FROM_SELF))
7552 .Times(1);
7553 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7554}
7555
7556// Verify that if connection has no outstanding data, it notifies the send
7557// algorithm after the write.
7558TEST_P(QuicConnectionTest, SendDataAndBecomeApplicationLimited) {
7559 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
7560 {
7561 InSequence seq;
7562 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7563 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7564 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
7565 .WillRepeatedly(Return(false));
7566 }
7567
7568 connection_.SendStreamData3();
7569}
7570
7571// Verify that the connection does not become app-limited if there is
7572// outstanding data to send after the write.
7573TEST_P(QuicConnectionTest, NotBecomeApplicationLimitedIfMoreDataAvailable) {
7574 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
7575 {
7576 InSequence seq;
7577 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7578 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7579 }
7580
7581 connection_.SendStreamData3();
7582}
7583
7584// Verify that the connection does not become app-limited after blocked write
7585// even if there is outstanding data to send after the write.
7586TEST_P(QuicConnectionTest, NotBecomeApplicationLimitedDueToWriteBlock) {
7587 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
7588 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7589 BlockOnNextWrite();
7590
7591 connection_.SendStreamData3();
7592
7593 // Now unblock the writer, become congestion control blocked,
7594 // and ensure we become app-limited after writing.
7595 writer_->SetWritable();
7596 CongestionBlockWrites();
7597 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(false));
7598 {
7599 InSequence seq;
7600 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7601 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
7602 }
7603 connection_.OnCanWrite();
7604}
7605
7606// Test the mode in which the link is filled up with probing retransmissions if
7607// the connection becomes application-limited.
7608TEST_P(QuicConnectionTest, SendDataWhenApplicationLimited) {
7609 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7610 EXPECT_CALL(*send_algorithm_, ShouldSendProbingPacket())
7611 .WillRepeatedly(Return(true));
7612 {
7613 InSequence seq;
7614 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7615 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7616 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
7617 .WillRepeatedly(Return(false));
7618 }
QUICHE teamb8343252019-04-29 13:58:01 -07007619 EXPECT_CALL(visitor_, SendProbingData()).WillRepeatedly([this] {
7620 return connection_.sent_packet_manager().MaybeRetransmitOldestPacket(
7621 PROBING_RETRANSMISSION);
7622 });
QUICHE teama6ef0a62019-03-07 20:34:33 -05007623 // Fix congestion window to be 20,000 bytes.
7624 EXPECT_CALL(*send_algorithm_, CanSend(Ge(20000u)))
7625 .WillRepeatedly(Return(false));
7626 EXPECT_CALL(*send_algorithm_, CanSend(Lt(20000u)))
7627 .WillRepeatedly(Return(true));
7628
7629 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
7630 ASSERT_EQ(0u, connection_.GetStats().packets_sent);
7631 connection_.set_fill_up_link_during_probing(true);
7632 connection_.OnHandshakeComplete();
7633 connection_.SendStreamData3();
7634
7635 // We expect a lot of packets from a 20 kbyte window.
7636 EXPECT_GT(connection_.GetStats().packets_sent, 10u);
7637 // Ensure that the packets are padded.
7638 QuicByteCount average_packet_size =
7639 connection_.GetStats().bytes_sent / connection_.GetStats().packets_sent;
7640 EXPECT_GT(average_packet_size, 1000u);
7641
7642 // Acknowledge all packets sent, except for the last one.
7643 QuicAckFrame ack = InitAckFrame(
7644 connection_.sent_packet_manager().GetLargestSentPacket() - 1);
7645 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
7646 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7647
7648 // Ensure that since we no longer have retransmittable bytes in flight, this
7649 // will not cause any responses to be sent.
7650 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
7651 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
7652 ProcessAckPacket(&ack);
7653}
7654
7655TEST_P(QuicConnectionTest, DonotForceSendingAckOnPacketTooLarge) {
7656 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7657 // Send an ack by simulating delayed ack alarm firing.
7658 ProcessPacket(1);
7659 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
7660 EXPECT_TRUE(ack_alarm->IsSet());
7661 connection_.GetAckAlarm()->Fire();
7662 // Simulate data packet causes write error.
7663 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PACKET_WRITE_ERROR, _, _));
7664 SimulateNextPacketTooLarge();
7665 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7666 EXPECT_EQ(1u, writer_->frame_count());
7667 EXPECT_FALSE(writer_->connection_close_frames().empty());
7668 // Ack frame is not bundled in connection close packet.
7669 EXPECT_TRUE(writer_->ack_frames().empty());
7670}
7671
QUICHE teama6ef0a62019-03-07 20:34:33 -05007672// Regression test for b/63620844.
7673TEST_P(QuicConnectionTest, FailedToWriteHandshakePacket) {
7674 SimulateNextPacketTooLarge();
7675 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PACKET_WRITE_ERROR, _,
7676 ConnectionCloseSource::FROM_SELF))
7677 .Times(1);
7678 connection_.SendCryptoStreamData();
7679}
7680
7681TEST_P(QuicConnectionTest, MaxPacingRate) {
7682 EXPECT_EQ(0, connection_.MaxPacingRate().ToBytesPerSecond());
7683 connection_.SetMaxPacingRate(QuicBandwidth::FromBytesPerSecond(100));
7684 EXPECT_EQ(100, connection_.MaxPacingRate().ToBytesPerSecond());
7685}
7686
7687TEST_P(QuicConnectionTest, ClientAlwaysSendConnectionId) {
7688 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
7689 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7690 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7691 EXPECT_EQ(CONNECTION_ID_PRESENT,
7692 writer_->last_packet_header().destination_connection_id_included);
7693
7694 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7695 QuicConfig config;
7696 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
7697 connection_.SetFromConfig(config);
7698
7699 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7700 connection_.SendStreamDataWithString(3, "bar", 3, NO_FIN);
7701 // Verify connection id is still sent in the packet.
7702 EXPECT_EQ(CONNECTION_ID_PRESENT,
7703 writer_->last_packet_header().destination_connection_id_included);
7704}
7705
7706TEST_P(QuicConnectionTest, SendProbingRetransmissions) {
7707 MockQuicConnectionDebugVisitor debug_visitor;
7708 connection_.set_debug_visitor(&debug_visitor);
7709
7710 const QuicStreamId stream_id = 2;
7711 QuicPacketNumber last_packet;
7712 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
7713 SendStreamDataToPeer(stream_id, "bar", 3, NO_FIN, &last_packet);
7714 SendStreamDataToPeer(stream_id, "test", 6, NO_FIN, &last_packet);
7715
7716 const QuicByteCount old_bytes_in_flight =
7717 connection_.sent_packet_manager().GetBytesInFlight();
7718
7719 // Allow 9 probing retransmissions to be sent.
7720 {
7721 InSequence seq;
7722 EXPECT_CALL(*send_algorithm_, CanSend(_))
7723 .Times(9 * 2)
7724 .WillRepeatedly(Return(true));
7725 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(Return(false));
7726 }
7727 // Expect them retransmitted in cyclic order (foo, bar, test, foo, bar...).
7728 QuicPacketCount sent_count = 0;
7729 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _))
7730 .WillRepeatedly(Invoke([this, &sent_count](const SerializedPacket&,
7731 QuicPacketNumber,
7732 TransmissionType, QuicTime) {
7733 ASSERT_EQ(1u, writer_->stream_frames().size());
7734 // Identify the frames by stream offset (0, 3, 6, 0, 3...).
7735 EXPECT_EQ(3 * (sent_count % 3), writer_->stream_frames()[0]->offset);
7736 sent_count++;
7737 }));
7738 EXPECT_CALL(*send_algorithm_, ShouldSendProbingPacket())
7739 .WillRepeatedly(Return(true));
QUICHE teamb8343252019-04-29 13:58:01 -07007740 EXPECT_CALL(visitor_, SendProbingData()).WillRepeatedly([this] {
7741 return connection_.sent_packet_manager().MaybeRetransmitOldestPacket(
7742 PROBING_RETRANSMISSION);
7743 });
QUICHE teama6ef0a62019-03-07 20:34:33 -05007744
7745 connection_.SendProbingRetransmissions();
7746
7747 // Ensure that the in-flight has increased.
7748 const QuicByteCount new_bytes_in_flight =
7749 connection_.sent_packet_manager().GetBytesInFlight();
7750 EXPECT_GT(new_bytes_in_flight, old_bytes_in_flight);
7751}
7752
7753// Ensure that SendProbingRetransmissions() does not retransmit anything when
7754// there are no outstanding packets.
7755TEST_P(QuicConnectionTest,
7756 SendProbingRetransmissionsFailsWhenNothingToRetransmit) {
7757 ASSERT_TRUE(connection_.sent_packet_manager().unacked_packets().empty());
7758
7759 MockQuicConnectionDebugVisitor debug_visitor;
7760 connection_.set_debug_visitor(&debug_visitor);
7761 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _)).Times(0);
7762 EXPECT_CALL(*send_algorithm_, ShouldSendProbingPacket())
7763 .WillRepeatedly(Return(true));
QUICHE teamb8343252019-04-29 13:58:01 -07007764 EXPECT_CALL(visitor_, SendProbingData()).WillRepeatedly([this] {
7765 return connection_.sent_packet_manager().MaybeRetransmitOldestPacket(
7766 PROBING_RETRANSMISSION);
7767 });
QUICHE teama6ef0a62019-03-07 20:34:33 -05007768
7769 connection_.SendProbingRetransmissions();
7770}
7771
7772TEST_P(QuicConnectionTest, PingAfterLastRetransmittablePacketAcked) {
7773 const QuicTime::Delta retransmittable_on_wire_timeout =
7774 QuicTime::Delta::FromMilliseconds(50);
7775 connection_.set_retransmittable_on_wire_timeout(
7776 retransmittable_on_wire_timeout);
7777
7778 EXPECT_TRUE(connection_.connected());
7779 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7780 .WillRepeatedly(Return(true));
7781
7782 const char data[] = "data";
7783 size_t data_size = strlen(data);
7784 QuicStreamOffset offset = 0;
7785
7786 // Advance 5ms, send a retransmittable packet to the peer.
7787 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7788 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
7789 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7790 offset += data_size;
7791 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
7792 // The ping alarm is set for the ping timeout, not the shorter
7793 // retransmittable_on_wire_timeout.
7794 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7795 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
7796 EXPECT_EQ((clock_.ApproximateNow() + ping_delay),
7797 connection_.GetPingAlarm()->deadline());
7798
7799 // Advance 5ms, send a second retransmittable packet to the peer.
7800 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7801 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7802 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7803 offset += data_size;
7804 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7805
7806 // Now receive an ACK of the first packet. This should not set the
7807 // retransmittable-on-wire alarm since packet 2 is still on the wire.
7808 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7809 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7810 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7811 QuicAckFrame frame =
7812 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7813 ProcessAckPacket(&frame);
7814 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
7815 // The ping alarm is set for the ping timeout, not the shorter
7816 // retransmittable_on_wire_timeout.
7817 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7818 // The ping alarm has a 1 second granularity, and the clock has been advanced
7819 // 10ms since it was originally set.
7820 EXPECT_EQ((clock_.ApproximateNow() + ping_delay -
7821 QuicTime::Delta::FromMilliseconds(10)),
7822 connection_.GetPingAlarm()->deadline());
7823
7824 // Now receive an ACK of the second packet. This should set the
7825 // retransmittable-on-wire alarm now that no retransmittable packets are on
7826 // the wire.
7827 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7828 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7829 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
7830 ProcessAckPacket(&frame);
7831 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7832 EXPECT_EQ(clock_.ApproximateNow() + retransmittable_on_wire_timeout,
7833 connection_.GetPingAlarm()->deadline());
7834
7835 // Now receive a duplicate ACK of the second packet. This should not update
7836 // the ping alarm.
7837 QuicTime prev_deadline = connection_.GetPingAlarm()->deadline();
7838 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7839 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
7840 ProcessAckPacket(&frame);
7841 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7842 EXPECT_EQ(prev_deadline, connection_.GetPingAlarm()->deadline());
7843
7844 // Now receive a non-ACK packet. This should not update the ping alarm.
7845 prev_deadline = connection_.GetPingAlarm()->deadline();
7846 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7847 ProcessPacket(4);
7848 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7849 EXPECT_EQ(prev_deadline, connection_.GetPingAlarm()->deadline());
7850
7851 // Simulate the alarm firing and check that a PING is sent.
7852 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
7853 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
7854 }));
7855 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07007856 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05007857 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07007858 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007859 } else {
nharper55fa6132019-05-07 19:37:21 -07007860 EXPECT_EQ(padding_frame_count + 3u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007861 }
7862 ASSERT_EQ(1u, writer_->ping_frames().size());
7863}
7864
7865TEST_P(QuicConnectionTest, NoPingIfRetransmittablePacketSent) {
7866 const QuicTime::Delta retransmittable_on_wire_timeout =
7867 QuicTime::Delta::FromMilliseconds(50);
7868 connection_.set_retransmittable_on_wire_timeout(
7869 retransmittable_on_wire_timeout);
7870
7871 EXPECT_TRUE(connection_.connected());
7872 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7873 .WillRepeatedly(Return(true));
7874
7875 const char data[] = "data";
7876 size_t data_size = strlen(data);
7877 QuicStreamOffset offset = 0;
7878
7879 // Advance 5ms, send a retransmittable packet to the peer.
7880 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7881 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
7882 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7883 offset += data_size;
7884 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
7885 // The ping alarm is set for the ping timeout, not the shorter
7886 // retransmittable_on_wire_timeout.
7887 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7888 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
7889 EXPECT_EQ((clock_.ApproximateNow() + ping_delay),
7890 connection_.GetPingAlarm()->deadline());
7891
7892 // Now receive an ACK of the first packet. This should set the
7893 // retransmittable-on-wire alarm now that no retransmittable packets are on
7894 // the wire.
7895 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7896 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7897 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7898 QuicAckFrame frame =
7899 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7900 ProcessAckPacket(&frame);
7901 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7902 EXPECT_EQ(clock_.ApproximateNow() + retransmittable_on_wire_timeout,
7903 connection_.GetPingAlarm()->deadline());
7904
7905 // Before the alarm fires, send another retransmittable packet. This should
7906 // cancel the retransmittable-on-wire alarm since now there's a
7907 // retransmittable packet on the wire.
7908 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7909 offset += data_size;
7910 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7911
7912 // Now receive an ACK of the second packet. This should set the
7913 // retransmittable-on-wire alarm now that no retransmittable packets are on
7914 // the wire.
7915 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7916 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7917 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
7918 ProcessAckPacket(&frame);
7919 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7920 EXPECT_EQ(clock_.ApproximateNow() + retransmittable_on_wire_timeout,
7921 connection_.GetPingAlarm()->deadline());
7922
7923 // Simulate the alarm firing and check that a PING is sent.
7924 writer_->Reset();
7925 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
7926 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
7927 }));
7928 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07007929 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05007930 if (GetParam().no_stop_waiting) {
fayang03916692019-05-22 17:57:18 -07007931 if (GetQuicReloadableFlag(quic_simplify_stop_waiting)) {
7932 // Do not ACK acks.
7933 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
7934 } else {
7935 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
7936 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007937 } else {
nharper55fa6132019-05-07 19:37:21 -07007938 EXPECT_EQ(padding_frame_count + 3u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007939 }
7940 ASSERT_EQ(1u, writer_->ping_frames().size());
7941}
7942
7943TEST_P(QuicConnectionTest, OnForwardProgressConfirmed) {
7944 EXPECT_CALL(visitor_, OnForwardProgressConfirmed()).Times(Exactly(0));
7945 EXPECT_TRUE(connection_.connected());
7946
7947 const char data[] = "data";
7948 size_t data_size = strlen(data);
7949 QuicStreamOffset offset = 0;
7950
7951 // Send two packets.
7952 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7953 offset += data_size;
7954 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7955 offset += data_size;
7956
7957 // Ack packet 1. This increases the largest_acked to 1, so
7958 // OnForwardProgressConfirmed() should be called
7959 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7960 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7961 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7962 EXPECT_CALL(visitor_, OnForwardProgressConfirmed());
7963 QuicAckFrame frame =
7964 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7965 ProcessAckPacket(&frame);
7966
7967 // Ack packet 1 again. largest_acked remains at 1, so
7968 // OnForwardProgressConfirmed() should not be called.
7969 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7970 frame = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7971 ProcessAckPacket(&frame);
7972
7973 // Ack packet 2. This increases the largest_acked to 2, so
7974 // OnForwardProgressConfirmed() should be called.
7975 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7976 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7977 EXPECT_CALL(visitor_, OnForwardProgressConfirmed());
7978 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
7979 ProcessAckPacket(&frame);
7980}
7981
7982TEST_P(QuicConnectionTest, ValidStatelessResetToken) {
7983 const QuicUint128 kTestToken = 1010101;
7984 const QuicUint128 kWrongTestToken = 1010100;
7985 QuicConfig config;
7986 // No token has been received.
7987 EXPECT_FALSE(connection_.IsValidStatelessResetToken(kTestToken));
7988
7989 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(2);
7990 // Token is different from received token.
7991 QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestToken);
7992 connection_.SetFromConfig(config);
7993 EXPECT_FALSE(connection_.IsValidStatelessResetToken(kWrongTestToken));
7994
7995 QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestToken);
7996 connection_.SetFromConfig(config);
7997 EXPECT_TRUE(connection_.IsValidStatelessResetToken(kTestToken));
7998}
7999
8000TEST_P(QuicConnectionTest, WriteBlockedWithInvalidAck) {
8001 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8002 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, _, _));
8003
8004 BlockOnNextWrite();
8005 connection_.SendStreamDataWithString(5, "foo", 0, FIN);
8006 // This causes connection to be closed because packet 1 has not been sent yet.
8007 QuicAckFrame frame = InitAckFrame(1);
8008 ProcessAckPacket(1, &frame);
8009}
8010
8011TEST_P(QuicConnectionTest, SendMessage) {
fayangc31c9952019-06-05 13:54:48 -07008012 if (!VersionSupportsMessageFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008013 return;
8014 }
ianswettb239f862019-04-05 09:15:06 -07008015 std::string message(connection_.GetCurrentLargestMessagePayload() * 2, 'a');
QUICHE teama6ef0a62019-03-07 20:34:33 -05008016 QuicStringPiece message_data(message);
8017 QuicMemSliceStorage storage(nullptr, 0, nullptr, 0);
8018 {
fayanga4b37b22019-06-18 13:37:47 -07008019 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008020 connection_.SendStreamData3();
8021 // Send a message which cannot fit into current open packet, and 2 packets
8022 // get sent, one contains stream frame, and the other only contains the
8023 // message frame.
8024 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
8025 EXPECT_EQ(
8026 MESSAGE_STATUS_SUCCESS,
8027 connection_.SendMessage(
8028 1, MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(),
ianswettb239f862019-04-05 09:15:06 -07008029 QuicStringPiece(
8030 message_data.data(),
8031 connection_.GetCurrentLargestMessagePayload()),
QUICHE teama6ef0a62019-03-07 20:34:33 -05008032 &storage)));
8033 }
8034 // Fail to send a message if connection is congestion control blocked.
8035 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(Return(false));
8036 EXPECT_EQ(
8037 MESSAGE_STATUS_BLOCKED,
8038 connection_.SendMessage(
8039 2, MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(),
8040 "message", &storage)));
8041
8042 // Always fail to send a message which cannot fit into one packet.
8043 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8044 EXPECT_EQ(
8045 MESSAGE_STATUS_TOO_LARGE,
8046 connection_.SendMessage(
ianswettb239f862019-04-05 09:15:06 -07008047 3, MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(),
8048 QuicStringPiece(
8049 message_data.data(),
8050 connection_.GetCurrentLargestMessagePayload() + 1),
8051 &storage)));
QUICHE teama6ef0a62019-03-07 20:34:33 -05008052}
8053
8054// Test to check that the path challenge/path response logic works
8055// correctly. This test is only for version-99
8056TEST_P(QuicConnectionTest, PathChallengeResponse) {
fkastenholz305e1732019-06-18 05:01:22 -07008057 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008058 return;
8059 }
8060 // First check if we can probe from server to client and back
8061 set_perspective(Perspective::IS_SERVER);
8062 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
8063
8064 // Create and send the probe request (PATH_CHALLENGE frame).
8065 // SendConnectivityProbingPacket ends up calling
8066 // TestPacketWriter::WritePacket() which in turns receives and parses the
8067 // packet by calling framer_.ProcessPacket() -- which in turn calls
8068 // SimpleQuicFramer::OnPathChallengeFrame(). SimpleQuicFramer saves
8069 // the packet in writer_->path_challenge_frames()
8070 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8071 connection_.SendConnectivityProbingPacket(writer_.get(),
8072 connection_.peer_address());
8073 // Save the random contents of the challenge for later comparison to the
8074 // response.
nharper55fa6132019-05-07 19:37:21 -07008075 ASSERT_GE(writer_->path_challenge_frames().size(), 1u);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008076 QuicPathFrameBuffer challenge_data =
8077 writer_->path_challenge_frames().front().data_buffer;
8078
8079 // Normally, QuicConnection::OnPathChallengeFrame and OnPaddingFrame would be
8080 // called and it will perform actions to ensure that the rest of the protocol
8081 // is performed (specifically, call UpdatePacketContent to say that this is a
8082 // path challenge so that when QuicConnection::OnPacketComplete is called
8083 // (again, out of the framer), the response is generated). Simulate those
8084 // calls so that the right internal state is set up for generating
8085 // the response.
8086 EXPECT_TRUE(connection_.OnPathChallengeFrame(
8087 writer_->path_challenge_frames().front()));
8088 EXPECT_TRUE(connection_.OnPaddingFrame(writer_->padding_frames().front()));
8089 // Cause the response to be created and sent. Result is that the response
8090 // should be stashed in writer's path_response_frames.
8091 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8092 connection_.SendConnectivityProbingResponsePacket(connection_.peer_address());
8093
8094 // The final check is to ensure that the random data in the response matches
8095 // the random data from the challenge.
8096 EXPECT_EQ(0, memcmp(&challenge_data,
8097 &(writer_->path_response_frames().front().data_buffer),
8098 sizeof(challenge_data)));
8099}
8100
8101// Regression test for b/110259444
8102TEST_P(QuicConnectionTest, DoNotScheduleSpuriousAckAlarm) {
8103 SetQuicReloadableFlag(quic_fix_spurious_ack_alarm, true);
8104 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8105 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
8106 writer_->SetWriteBlocked();
8107
8108 ProcessPacket(1);
8109 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
8110 // Verify ack alarm is set.
8111 EXPECT_TRUE(ack_alarm->IsSet());
8112 // Fire the ack alarm, verify no packet is sent because the writer is blocked.
8113 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8114 connection_.GetAckAlarm()->Fire();
8115
8116 writer_->SetWritable();
8117 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8118 ProcessPacket(2);
8119 // Verify ack alarm is not set.
8120 EXPECT_FALSE(ack_alarm->IsSet());
8121}
8122
8123TEST_P(QuicConnectionTest, DisablePacingOffloadConnectionOptions) {
8124 EXPECT_FALSE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
8125 writer_->set_supports_release_time(true);
8126 QuicConfig config;
8127 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8128 connection_.SetFromConfig(config);
8129 EXPECT_TRUE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
8130
8131 QuicTagVector connection_options;
8132 connection_options.push_back(kNPCO);
8133 config.SetConnectionOptionsToSend(connection_options);
8134 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8135 connection_.SetFromConfig(config);
8136 // Verify pacing offload is disabled.
8137 EXPECT_FALSE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
8138}
8139
8140// Regression test for b/110259444
8141// Get a path response without having issued a path challenge...
8142TEST_P(QuicConnectionTest, OrphanPathResponse) {
8143 QuicPathFrameBuffer data = {{0, 1, 2, 3, 4, 5, 6, 7}};
8144
8145 QuicPathResponseFrame frame(99, data);
8146 EXPECT_TRUE(connection_.OnPathResponseFrame(frame));
8147 // If PATH_RESPONSE was accepted (payload matches the payload saved
8148 // in QuicConnection::transmitted_connectivity_probe_payload_) then
8149 // current_packet_content_ would be set to FIRST_FRAME_IS_PING.
8150 // Since this PATH_RESPONSE does not match, current_packet_content_
8151 // must not be FIRST_FRAME_IS_PING.
8152 EXPECT_NE(QuicConnection::FIRST_FRAME_IS_PING,
8153 QuicConnectionPeer::GetCurrentPacketContent(&connection_));
8154}
8155
8156// Regression test for b/120791670
8157TEST_P(QuicConnectionTest, StopProcessingGQuicPacketInIetfQuicConnection) {
8158 // This test mimics a problematic scenario where an IETF QUIC connection
8159 // receives a Google QUIC packet and continue processing it using Google QUIC
8160 // wire format.
fayangd4291e42019-05-30 10:31:21 -07008161 if (!VersionHasIetfInvariantHeader(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008162 return;
8163 }
8164 set_perspective(Perspective::IS_SERVER);
nharper46833c32019-05-15 21:33:05 -07008165 QuicFrame frame;
8166 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
8167 frame = QuicFrame(&crypto_frame_);
8168 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
8169 } else {
8170 frame = QuicFrame(QuicStreamFrame(
8171 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
8172 0u, QuicStringPiece()));
8173 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
8174 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008175 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
nharper46833c32019-05-15 21:33:05 -07008176 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008177
8178 // Let connection process a Google QUIC packet.
8179 peer_framer_.set_version_for_tests(
8180 ParsedQuicVersion(PROTOCOL_QUIC_CRYPTO, QUIC_VERSION_43));
QUICHE team8c1daa22019-03-13 08:33:41 -07008181 std::unique_ptr<QuicPacket> packet(
QUICHE team6987b4a2019-03-15 16:23:04 -07008182 ConstructDataPacket(2, !kHasStopWaiting, ENCRYPTION_INITIAL));
dschinazi66dea072019-04-09 11:41:06 -07008183 char buffer[kMaxOutgoingPacketSize];
8184 size_t encrypted_length =
8185 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(2),
8186 *packet, buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008187 // Make sure no stream frame is processed.
8188 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(0);
8189 connection_.ProcessUdpPacket(
8190 kSelfAddress, kPeerAddress,
8191 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
8192
8193 EXPECT_EQ(2u, connection_.GetStats().packets_received);
8194 EXPECT_EQ(1u, connection_.GetStats().packets_processed);
8195}
8196
8197TEST_P(QuicConnectionTest, AcceptPacketNumberZero) {
fkastenholz305e1732019-06-18 05:01:22 -07008198 if (!VersionHasIetfQuicFrames(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008199 return;
8200 }
8201 // Set first_sending_packet_number to be 0 to allow successfully processing
8202 // acks which ack packet number 0.
8203 QuicFramerPeer::SetFirstSendingPacketNumber(writer_->framer()->framer(), 0);
8204 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8205
8206 ProcessPacket(0);
fayangc31c9952019-06-05 13:54:48 -07008207 EXPECT_EQ(QuicPacketNumber(0), LargestAcked(connection_.ack_frame()));
8208 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008209
8210 ProcessPacket(1);
fayangc31c9952019-06-05 13:54:48 -07008211 EXPECT_EQ(QuicPacketNumber(1), LargestAcked(connection_.ack_frame()));
8212 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008213
8214 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07008215 EXPECT_EQ(QuicPacketNumber(2), LargestAcked(connection_.ack_frame()));
8216 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008217}
8218
QUICHE teamcd098022019-03-22 18:49:55 -07008219TEST_P(QuicConnectionTest, MultiplePacketNumberSpacesBasicSending) {
8220 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8221 return;
8222 }
8223 use_tagging_decrypter();
8224 connection_.SetEncrypter(ENCRYPTION_INITIAL,
8225 QuicMakeUnique<TaggingEncrypter>(0x01));
8226
8227 connection_.SendCryptoStreamData();
8228 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8229 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
8230 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8231 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8232 QuicAckFrame frame1 = InitAckFrame(1);
8233 // Received ACK for packet 1.
8234 ProcessFramePacketAtLevel(30, QuicFrame(&frame1), ENCRYPTION_INITIAL);
8235
8236 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(4);
8237 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
8238 NO_FIN);
8239 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 4,
8240 NO_FIN);
8241 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
8242 8, NO_FIN);
8243 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
8244 12, FIN);
8245 // Received ACK for packets 2, 4, 5.
8246 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
8247 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8248 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8249 QuicAckFrame frame2 =
8250 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)},
8251 {QuicPacketNumber(4), QuicPacketNumber(6)}});
8252 // Make sure although the same packet number is used, but they are in
8253 // different packet number spaces.
8254 ProcessFramePacketAtLevel(30, QuicFrame(&frame2), ENCRYPTION_FORWARD_SECURE);
8255}
8256
8257TEST_P(QuicConnectionTest, PeerAcksPacketsInWrongPacketNumberSpace) {
8258 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8259 return;
8260 }
8261 use_tagging_decrypter();
8262 connection_.SetEncrypter(ENCRYPTION_INITIAL,
8263 QuicMakeUnique<TaggingEncrypter>(0x01));
8264
8265 connection_.SendCryptoStreamData();
8266 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8267 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
8268 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8269 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8270 QuicAckFrame frame1 = InitAckFrame(1);
8271 // Received ACK for packet 1.
8272 ProcessFramePacketAtLevel(30, QuicFrame(&frame1), ENCRYPTION_INITIAL);
8273
8274 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
8275 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
8276 NO_FIN);
8277 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 4,
8278 NO_FIN);
8279
8280 // Received ACK for packets 2 and 3 in wrong packet number space.
8281 QuicAckFrame invalid_ack =
8282 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(4)}});
8283 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, _,
8284 ConnectionCloseSource::FROM_SELF));
8285 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8286 ProcessFramePacketAtLevel(300, QuicFrame(&invalid_ack), ENCRYPTION_INITIAL);
8287}
8288
8289TEST_P(QuicConnectionTest, MultiplePacketNumberSpacesBasicReceiving) {
8290 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8291 return;
8292 }
8293 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
nharper46833c32019-05-15 21:33:05 -07008294 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
8295 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
8296 }
QUICHE teamcd098022019-03-22 18:49:55 -07008297 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
8298 use_tagging_decrypter();
8299 // Receives packet 1000 in initial data.
nharper46833c32019-05-15 21:33:05 -07008300 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
QUICHE teamcd098022019-03-22 18:49:55 -07008301 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
8302 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
8303 QuicMakeUnique<TaggingEncrypter>(0x02));
zhongyi546cc452019-04-12 15:27:49 -07008304 SetDecrypter(ENCRYPTION_ZERO_RTT,
8305 QuicMakeUnique<StrictTaggingDecrypter>(0x02));
QUICHE teamcd098022019-03-22 18:49:55 -07008306 connection_.SetEncrypter(ENCRYPTION_INITIAL,
8307 QuicMakeUnique<TaggingEncrypter>(0x02));
8308 // Receives packet 1000 in application data.
8309 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
8310 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
8311 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
8312 NO_FIN);
8313 // Verify application data ACK gets bundled with outgoing data.
8314 EXPECT_EQ(2u, writer_->frame_count());
8315 // Make sure ACK alarm is still set because initial data is not ACKed.
8316 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
8317 // Receive packet 1001 in application data.
8318 ProcessDataPacketAtLevel(1001, false, ENCRYPTION_ZERO_RTT);
8319 clock_.AdvanceTime(DefaultRetransmissionTime());
8320 // Simulates ACK alarm fires and verify two ACKs are flushed.
8321 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
8322 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
8323 QuicMakeUnique<TaggingEncrypter>(0x02));
8324 connection_.GetAckAlarm()->Fire();
8325 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
8326 // Receives more packets in application data.
8327 ProcessDataPacketAtLevel(1002, false, ENCRYPTION_ZERO_RTT);
8328 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
8329
8330 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
8331 QuicMakeUnique<TaggingEncrypter>(0x02));
zhongyi546cc452019-04-12 15:27:49 -07008332 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
8333 QuicMakeUnique<StrictTaggingDecrypter>(0x02));
QUICHE teamcd098022019-03-22 18:49:55 -07008334 // Verify zero rtt and forward secure packets get acked in the same packet.
8335 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
nharper2c9f02a2019-05-08 10:25:50 -07008336 ProcessDataPacket(1003);
QUICHE teamcd098022019-03-22 18:49:55 -07008337 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
8338}
8339
QUICHE team552f71f2019-03-23 15:37:59 -07008340TEST_P(QuicConnectionTest, CancelAckAlarmOnWriteBlocked) {
8341 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8342 return;
8343 }
8344 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
nharper46833c32019-05-15 21:33:05 -07008345 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
8346 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
8347 }
QUICHE team552f71f2019-03-23 15:37:59 -07008348 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
8349 use_tagging_decrypter();
8350 // Receives packet 1000 in initial data.
nharper46833c32019-05-15 21:33:05 -07008351 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
QUICHE team552f71f2019-03-23 15:37:59 -07008352 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
8353 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
8354 QuicMakeUnique<TaggingEncrypter>(0x02));
zhongyi546cc452019-04-12 15:27:49 -07008355 SetDecrypter(ENCRYPTION_ZERO_RTT,
8356 QuicMakeUnique<StrictTaggingDecrypter>(0x02));
QUICHE team552f71f2019-03-23 15:37:59 -07008357 connection_.SetEncrypter(ENCRYPTION_INITIAL,
8358 QuicMakeUnique<TaggingEncrypter>(0x02));
8359 // Receives packet 1000 in application data.
8360 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
8361 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
8362
8363 writer_->SetWriteBlocked();
8364 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AnyNumber());
8365 // Simulates ACK alarm fires and verify no ACK is flushed because of write
8366 // blocked.
8367 clock_.AdvanceTime(DefaultDelayedAckTime());
8368 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8369 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
8370 QuicMakeUnique<TaggingEncrypter>(0x02));
8371 connection_.GetAckAlarm()->Fire();
8372 // Verify ACK alarm is not set.
8373 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
8374
8375 writer_->SetWritable();
8376 // Verify 2 ACKs are sent when connection gets unblocked.
8377 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
8378 connection_.OnCanWrite();
8379 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
8380}
8381
dschinazi346b7ce2019-06-05 01:38:18 -07008382// Make sure a packet received with the right client connection ID is processed.
8383TEST_P(QuicConnectionTest, ValidClientConnectionId) {
8384 SetQuicRestartFlag(quic_do_not_override_connection_id, true);
8385 if (!framer_.version().SupportsClientConnectionIds()) {
8386 return;
8387 }
8388 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8389 connection_.set_client_connection_id(TestConnectionId(0x33));
8390 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_FORWARD_SECURE);
8391 header.destination_connection_id = TestConnectionId(0x33);
8392 header.destination_connection_id_included = CONNECTION_ID_PRESENT;
8393 header.source_connection_id_included = CONNECTION_ID_ABSENT;
8394 QuicFrames frames;
8395 QuicPingFrame ping_frame;
8396 QuicPaddingFrame padding_frame;
8397 frames.push_back(QuicFrame(ping_frame));
8398 frames.push_back(QuicFrame(padding_frame));
8399 std::unique_ptr<QuicPacket> packet =
8400 BuildUnsizedDataPacket(&framer_, header, frames);
8401 char buffer[kMaxOutgoingPacketSize];
8402 size_t encrypted_length = peer_framer_.EncryptPayload(
8403 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
8404 kMaxOutgoingPacketSize);
8405 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
8406 false);
8407 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
8408 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
8409 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
8410}
8411
8412// Make sure a packet received with a different client connection ID is dropped.
8413TEST_P(QuicConnectionTest, InvalidClientConnectionId) {
8414 SetQuicRestartFlag(quic_do_not_override_connection_id, true);
8415 if (!framer_.version().SupportsClientConnectionIds()) {
8416 return;
8417 }
8418 connection_.set_client_connection_id(TestConnectionId(0x33));
8419 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_FORWARD_SECURE);
8420 header.destination_connection_id = TestConnectionId(0xbad);
8421 header.destination_connection_id_included = CONNECTION_ID_PRESENT;
8422 header.source_connection_id_included = CONNECTION_ID_ABSENT;
8423 QuicFrames frames;
8424 QuicPingFrame ping_frame;
8425 QuicPaddingFrame padding_frame;
8426 frames.push_back(QuicFrame(ping_frame));
8427 frames.push_back(QuicFrame(padding_frame));
8428 std::unique_ptr<QuicPacket> packet =
8429 BuildUnsizedDataPacket(&framer_, header, frames);
8430 char buffer[kMaxOutgoingPacketSize];
8431 size_t encrypted_length = peer_framer_.EncryptPayload(
8432 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
8433 kMaxOutgoingPacketSize);
8434 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
8435 false);
8436 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
8437 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
8438 EXPECT_EQ(1u, connection_.GetStats().packets_dropped);
8439}
8440
8441// Make sure the first packet received with a different client connection ID on
8442// the server is processed and it changes the client connection ID.
8443TEST_P(QuicConnectionTest, UpdateClientConnectionIdFromFirstPacket) {
8444 SetQuicRestartFlag(quic_do_not_override_connection_id, true);
8445 if (!framer_.version().SupportsClientConnectionIds()) {
8446 return;
8447 }
8448 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8449 set_perspective(Perspective::IS_SERVER);
8450 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_INITIAL);
8451 header.source_connection_id = TestConnectionId(0x33);
8452 header.source_connection_id_included = CONNECTION_ID_PRESENT;
8453 QuicFrames frames;
8454 QuicPingFrame ping_frame;
8455 QuicPaddingFrame padding_frame;
8456 frames.push_back(QuicFrame(ping_frame));
8457 frames.push_back(QuicFrame(padding_frame));
8458 std::unique_ptr<QuicPacket> packet =
8459 BuildUnsizedDataPacket(&framer_, header, frames);
8460 char buffer[kMaxOutgoingPacketSize];
8461 size_t encrypted_length = peer_framer_.EncryptPayload(
8462 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
8463 kMaxOutgoingPacketSize);
8464 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
8465 false);
8466 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
8467 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
8468 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
8469 EXPECT_EQ(TestConnectionId(0x33), connection_.client_connection_id());
8470}
8471
fayang40ec3ac2019-06-05 09:07:54 -07008472// Regression test for b/134416344.
8473TEST_P(QuicConnectionTest, CheckConnectedBeforeFlush) {
8474 // This test mimics a scenario where a connection processes 2 packets and the
8475 // 2nd packet contains connection close frame. When the 2nd flusher goes out
8476 // of scope, a delayed ACK is pending, and ACK alarm should not be scheduled
8477 // because connection is disconnected.
8478 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8479 EXPECT_CALL(visitor_, OnConnectionClosed(_, _, _));
8480 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
8481 std::unique_ptr<QuicConnectionCloseFrame> connection_close_frame(
8482 new QuicConnectionCloseFrame(QUIC_INTERNAL_ERROR));
fkastenholz305e1732019-06-18 05:01:22 -07008483 if (VersionHasIetfQuicFrames(connection_.transport_version())) {
fayang40ec3ac2019-06-05 09:07:54 -07008484 connection_close_frame->close_type = IETF_QUIC_TRANSPORT_CONNECTION_CLOSE;
8485 }
8486 // Received 2 packets.
8487 QuicFrame frame;
8488 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
8489 frame = QuicFrame(&crypto_frame_);
8490 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
8491 } else {
8492 frame = QuicFrame(QuicStreamFrame(
8493 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
8494 0u, QuicStringPiece()));
8495 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
8496 }
8497 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
8498 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
8499 EXPECT_TRUE(ack_alarm->IsSet());
8500 ProcessFramePacketWithAddresses(QuicFrame(connection_close_frame.get()),
8501 kSelfAddress, kPeerAddress);
8502 if (GetQuicReloadableFlag(quic_check_connected_before_flush)) {
8503 // Verify ack alarm is not set.
8504 EXPECT_FALSE(ack_alarm->IsSet());
8505 } else {
8506 EXPECT_TRUE(ack_alarm->IsSet());
8507 }
8508}
8509
QUICHE teama6ef0a62019-03-07 20:34:33 -05008510} // namespace
8511} // namespace test
8512} // namespace quic