blob: 314898bc39c69971738c651fa291c2036d65a47e [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) {
95 return QuicUtils::GetHeadersStreamId(version) + n * 2;
96}
97
QUICHE team8c1daa22019-03-13 08:33:41 -070098QuicLongHeaderType EncryptionlevelToLongHeaderType(EncryptionLevel level) {
99 switch (level) {
QUICHE team6987b4a2019-03-15 16:23:04 -0700100 case ENCRYPTION_INITIAL:
QUICHE team8c1daa22019-03-13 08:33:41 -0700101 return INITIAL;
QUICHE team88ea0082019-03-15 10:05:26 -0700102 case ENCRYPTION_HANDSHAKE:
103 return HANDSHAKE;
QUICHE team8c1daa22019-03-13 08:33:41 -0700104 case ENCRYPTION_ZERO_RTT:
105 return ZERO_RTT_PROTECTED;
106 case ENCRYPTION_FORWARD_SECURE:
107 DCHECK(false);
108 return INVALID_PACKET_TYPE;
109 default:
110 DCHECK(false);
111 return INVALID_PACKET_TYPE;
112 }
113}
114
QUICHE teama6ef0a62019-03-07 20:34:33 -0500115// TaggingEncrypter appends kTagSize bytes of |tag| to the end of each message.
116class TaggingEncrypter : public QuicEncrypter {
117 public:
118 explicit TaggingEncrypter(uint8_t tag) : tag_(tag) {}
119 TaggingEncrypter(const TaggingEncrypter&) = delete;
120 TaggingEncrypter& operator=(const TaggingEncrypter&) = delete;
121
122 ~TaggingEncrypter() override {}
123
124 // QuicEncrypter interface.
125 bool SetKey(QuicStringPiece key) override { return true; }
126
127 bool SetNoncePrefix(QuicStringPiece nonce_prefix) override { return true; }
128
129 bool SetIV(QuicStringPiece iv) override { return true; }
130
QUICHE team2d187972019-03-19 16:23:47 -0700131 bool SetHeaderProtectionKey(QuicStringPiece key) override { return true; }
132
QUICHE teama6ef0a62019-03-07 20:34:33 -0500133 bool EncryptPacket(uint64_t packet_number,
134 QuicStringPiece associated_data,
135 QuicStringPiece plaintext,
136 char* output,
137 size_t* output_length,
138 size_t max_output_length) override {
139 const size_t len = plaintext.size() + kTagSize;
140 if (max_output_length < len) {
141 return false;
142 }
143 // Memmove is safe for inplace encryption.
144 memmove(output, plaintext.data(), plaintext.size());
145 output += plaintext.size();
146 memset(output, tag_, kTagSize);
147 *output_length = len;
148 return true;
149 }
150
QUICHE team2d187972019-03-19 16:23:47 -0700151 std::string GenerateHeaderProtectionMask(QuicStringPiece sample) override {
152 return std::string(5, 0);
153 }
154
QUICHE teama6ef0a62019-03-07 20:34:33 -0500155 size_t GetKeySize() const override { return 0; }
156 size_t GetNoncePrefixSize() const override { return 0; }
157 size_t GetIVSize() const override { return 0; }
158
159 size_t GetMaxPlaintextSize(size_t ciphertext_size) const override {
160 return ciphertext_size - kTagSize;
161 }
162
163 size_t GetCiphertextSize(size_t plaintext_size) const override {
164 return plaintext_size + kTagSize;
165 }
166
167 QuicStringPiece GetKey() const override { return QuicStringPiece(); }
168
169 QuicStringPiece GetNoncePrefix() const override { return QuicStringPiece(); }
170
171 private:
172 enum {
173 kTagSize = 12,
174 };
175
176 const uint8_t tag_;
177};
178
179// TaggingDecrypter ensures that the final kTagSize bytes of the message all
180// have the same value and then removes them.
181class TaggingDecrypter : public QuicDecrypter {
182 public:
183 ~TaggingDecrypter() override {}
184
185 // QuicDecrypter interface
186 bool SetKey(QuicStringPiece key) override { return true; }
187
188 bool SetNoncePrefix(QuicStringPiece nonce_prefix) override { return true; }
189
190 bool SetIV(QuicStringPiece iv) override { return true; }
191
QUICHE team2d187972019-03-19 16:23:47 -0700192 bool SetHeaderProtectionKey(QuicStringPiece key) override { return true; }
193
QUICHE teama6ef0a62019-03-07 20:34:33 -0500194 bool SetPreliminaryKey(QuicStringPiece key) override {
195 QUIC_BUG << "should not be called";
196 return false;
197 }
198
199 bool SetDiversificationNonce(const DiversificationNonce& key) override {
200 return true;
201 }
202
203 bool DecryptPacket(uint64_t packet_number,
204 QuicStringPiece associated_data,
205 QuicStringPiece ciphertext,
206 char* output,
207 size_t* output_length,
208 size_t max_output_length) override {
209 if (ciphertext.size() < kTagSize) {
210 return false;
211 }
212 if (!CheckTag(ciphertext, GetTag(ciphertext))) {
213 return false;
214 }
215 *output_length = ciphertext.size() - kTagSize;
216 memcpy(output, ciphertext.data(), *output_length);
217 return true;
218 }
219
QUICHE team2d187972019-03-19 16:23:47 -0700220 std::string GenerateHeaderProtectionMask(
221 QuicDataReader* sample_reader) override {
222 return std::string(5, 0);
223 }
224
QUICHE teama6ef0a62019-03-07 20:34:33 -0500225 size_t GetKeySize() const override { return 0; }
226 size_t GetIVSize() const override { return 0; }
227 QuicStringPiece GetKey() const override { return QuicStringPiece(); }
228 QuicStringPiece GetNoncePrefix() const override { return QuicStringPiece(); }
229 // Use a distinct value starting with 0xFFFFFF, which is never used by TLS.
230 uint32_t cipher_id() const override { return 0xFFFFFFF0; }
231
232 protected:
233 virtual uint8_t GetTag(QuicStringPiece ciphertext) {
234 return ciphertext.data()[ciphertext.size() - 1];
235 }
236
237 private:
238 enum {
239 kTagSize = 12,
240 };
241
242 bool CheckTag(QuicStringPiece ciphertext, uint8_t tag) {
243 for (size_t i = ciphertext.size() - kTagSize; i < ciphertext.size(); i++) {
244 if (ciphertext.data()[i] != tag) {
245 return false;
246 }
247 }
248
249 return true;
250 }
251};
252
253// StringTaggingDecrypter ensures that the final kTagSize bytes of the message
254// match the expected value.
255class StrictTaggingDecrypter : public TaggingDecrypter {
256 public:
257 explicit StrictTaggingDecrypter(uint8_t tag) : tag_(tag) {}
258 ~StrictTaggingDecrypter() override {}
259
260 // TaggingQuicDecrypter
261 uint8_t GetTag(QuicStringPiece ciphertext) override { return tag_; }
262
263 // Use a distinct value starting with 0xFFFFFF, which is never used by TLS.
264 uint32_t cipher_id() const override { return 0xFFFFFFF1; }
265
266 private:
267 const uint8_t tag_;
268};
269
270class TestConnectionHelper : public QuicConnectionHelperInterface {
271 public:
272 TestConnectionHelper(MockClock* clock, MockRandom* random_generator)
273 : clock_(clock), random_generator_(random_generator) {
274 clock_->AdvanceTime(QuicTime::Delta::FromSeconds(1));
275 }
276 TestConnectionHelper(const TestConnectionHelper&) = delete;
277 TestConnectionHelper& operator=(const TestConnectionHelper&) = delete;
278
279 // QuicConnectionHelperInterface
280 const QuicClock* GetClock() const override { return clock_; }
281
282 QuicRandom* GetRandomGenerator() override { return random_generator_; }
283
284 QuicBufferAllocator* GetStreamSendBufferAllocator() override {
285 return &buffer_allocator_;
286 }
287
288 private:
289 MockClock* clock_;
290 MockRandom* random_generator_;
291 SimpleBufferAllocator buffer_allocator_;
292};
293
294class TestAlarmFactory : public QuicAlarmFactory {
295 public:
296 class TestAlarm : public QuicAlarm {
297 public:
298 explicit TestAlarm(QuicArenaScopedPtr<QuicAlarm::Delegate> delegate)
299 : QuicAlarm(std::move(delegate)) {}
300
301 void SetImpl() override {}
302 void CancelImpl() override {}
303 using QuicAlarm::Fire;
304 };
305
306 TestAlarmFactory() {}
307 TestAlarmFactory(const TestAlarmFactory&) = delete;
308 TestAlarmFactory& operator=(const TestAlarmFactory&) = delete;
309
310 QuicAlarm* CreateAlarm(QuicAlarm::Delegate* delegate) override {
311 return new TestAlarm(QuicArenaScopedPtr<QuicAlarm::Delegate>(delegate));
312 }
313
314 QuicArenaScopedPtr<QuicAlarm> CreateAlarm(
315 QuicArenaScopedPtr<QuicAlarm::Delegate> delegate,
316 QuicConnectionArena* arena) override {
317 return arena->New<TestAlarm>(std::move(delegate));
318 }
319};
320
321class TestPacketWriter : public QuicPacketWriter {
322 public:
323 TestPacketWriter(ParsedQuicVersion version, MockClock* clock)
324 : version_(version),
325 framer_(SupportedVersions(version_), Perspective::IS_SERVER),
326 last_packet_size_(0),
327 write_blocked_(false),
328 write_should_fail_(false),
329 block_on_next_flush_(false),
330 block_on_next_write_(false),
331 next_packet_too_large_(false),
332 always_get_packet_too_large_(false),
333 is_write_blocked_data_buffered_(false),
334 is_batch_mode_(false),
335 final_bytes_of_last_packet_(0),
336 final_bytes_of_previous_packet_(0),
337 use_tagging_decrypter_(false),
338 packets_write_attempts_(0),
339 clock_(clock),
340 write_pause_time_delta_(QuicTime::Delta::Zero()),
dschinazi66dea072019-04-09 11:41:06 -0700341 max_packet_size_(kMaxOutgoingPacketSize),
QUICHE teama6ef0a62019-03-07 20:34:33 -0500342 supports_release_time_(false) {}
343 TestPacketWriter(const TestPacketWriter&) = delete;
344 TestPacketWriter& operator=(const TestPacketWriter&) = delete;
345
346 // QuicPacketWriter interface
347 WriteResult WritePacket(const char* buffer,
348 size_t buf_len,
349 const QuicIpAddress& self_address,
350 const QuicSocketAddress& peer_address,
351 PerPacketOptions* options) override {
352 QuicEncryptedPacket packet(buffer, buf_len);
353 ++packets_write_attempts_;
354
355 if (packet.length() >= sizeof(final_bytes_of_last_packet_)) {
356 final_bytes_of_previous_packet_ = final_bytes_of_last_packet_;
357 memcpy(&final_bytes_of_last_packet_, packet.data() + packet.length() - 4,
358 sizeof(final_bytes_of_last_packet_));
359 }
360
361 if (use_tagging_decrypter_) {
zhongyi546cc452019-04-12 15:27:49 -0700362 if (framer_.framer()->version().KnowsWhichDecrypterToUse()) {
363 framer_.framer()->InstallDecrypter(ENCRYPTION_INITIAL,
364 QuicMakeUnique<TaggingDecrypter>());
365 framer_.framer()->InstallDecrypter(ENCRYPTION_ZERO_RTT,
366 QuicMakeUnique<TaggingDecrypter>());
367 framer_.framer()->InstallDecrypter(ENCRYPTION_FORWARD_SECURE,
368 QuicMakeUnique<TaggingDecrypter>());
369 } else {
370 framer_.framer()->SetDecrypter(ENCRYPTION_INITIAL,
371 QuicMakeUnique<TaggingDecrypter>());
372 }
373 } else if (framer_.framer()->version().KnowsWhichDecrypterToUse()) {
374 framer_.framer()->InstallDecrypter(
375 ENCRYPTION_FORWARD_SECURE,
376 QuicMakeUnique<NullDecrypter>(Perspective::IS_SERVER));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500377 }
378 EXPECT_TRUE(framer_.ProcessPacket(packet));
379 if (block_on_next_write_) {
380 write_blocked_ = true;
381 block_on_next_write_ = false;
382 }
383 if (next_packet_too_large_) {
384 next_packet_too_large_ = false;
385 return WriteResult(WRITE_STATUS_ERROR, QUIC_EMSGSIZE);
386 }
387 if (always_get_packet_too_large_) {
388 return WriteResult(WRITE_STATUS_ERROR, QUIC_EMSGSIZE);
389 }
390 if (IsWriteBlocked()) {
391 return WriteResult(is_write_blocked_data_buffered_
392 ? WRITE_STATUS_BLOCKED_DATA_BUFFERED
393 : WRITE_STATUS_BLOCKED,
394 0);
395 }
396
397 if (ShouldWriteFail()) {
398 return WriteResult(WRITE_STATUS_ERROR, 0);
399 }
400
401 last_packet_size_ = packet.length();
402 last_packet_header_ = framer_.header();
403
404 if (!write_pause_time_delta_.IsZero()) {
405 clock_->AdvanceTime(write_pause_time_delta_);
406 }
407 return WriteResult(WRITE_STATUS_OK, last_packet_size_);
408 }
409
410 bool ShouldWriteFail() { return write_should_fail_; }
411
412 bool IsWriteBlocked() const override { return write_blocked_; }
413
414 void SetWriteBlocked() { write_blocked_ = true; }
415
416 void SetWritable() override { write_blocked_ = false; }
417
418 void SetShouldWriteFail() { write_should_fail_ = true; }
419
420 QuicByteCount GetMaxPacketSize(
421 const QuicSocketAddress& /*peer_address*/) const override {
422 return max_packet_size_;
423 }
424
dschinazi61eb6432019-06-14 16:27:16 -0700425 bool SupportsReleaseTime() const override { return supports_release_time_; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500426
427 bool IsBatchMode() const override { return is_batch_mode_; }
428
429 char* GetNextWriteLocation(const QuicIpAddress& self_address,
430 const QuicSocketAddress& peer_address) override {
431 return nullptr;
432 }
433
434 WriteResult Flush() override {
435 if (block_on_next_flush_) {
436 block_on_next_flush_ = false;
437 SetWriteBlocked();
438 return WriteResult(WRITE_STATUS_BLOCKED, /*errno*/ -1);
439 }
440 return WriteResult(WRITE_STATUS_OK, 0);
441 }
442
443 void BlockOnNextFlush() { block_on_next_flush_ = true; }
444
445 void BlockOnNextWrite() { block_on_next_write_ = true; }
446
447 void SimulateNextPacketTooLarge() { next_packet_too_large_ = true; }
448
449 void AlwaysGetPacketTooLarge() { always_get_packet_too_large_ = true; }
450
451 // Sets the amount of time that the writer should before the actual write.
452 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
453 write_pause_time_delta_ = delta;
454 }
455
456 void SetBatchMode(bool new_value) { is_batch_mode_ = new_value; }
457
458 const QuicPacketHeader& header() { return framer_.header(); }
459
460 size_t frame_count() const { return framer_.num_frames(); }
461
462 const std::vector<QuicAckFrame>& ack_frames() const {
463 return framer_.ack_frames();
464 }
465
466 const std::vector<QuicStopWaitingFrame>& stop_waiting_frames() const {
467 return framer_.stop_waiting_frames();
468 }
469
470 const std::vector<QuicConnectionCloseFrame>& connection_close_frames() const {
471 return framer_.connection_close_frames();
472 }
473
474 const std::vector<QuicRstStreamFrame>& rst_stream_frames() const {
475 return framer_.rst_stream_frames();
476 }
477
478 const std::vector<std::unique_ptr<QuicStreamFrame>>& stream_frames() const {
479 return framer_.stream_frames();
480 }
481
482 const std::vector<std::unique_ptr<QuicCryptoFrame>>& crypto_frames() const {
483 return framer_.crypto_frames();
484 }
485
486 const std::vector<QuicPingFrame>& ping_frames() const {
487 return framer_.ping_frames();
488 }
489
490 const std::vector<QuicMessageFrame>& message_frames() const {
491 return framer_.message_frames();
492 }
493
494 const std::vector<QuicWindowUpdateFrame>& window_update_frames() const {
495 return framer_.window_update_frames();
496 }
497
498 const std::vector<QuicPaddingFrame>& padding_frames() const {
499 return framer_.padding_frames();
500 }
501
502 const std::vector<QuicPathChallengeFrame>& path_challenge_frames() const {
503 return framer_.path_challenge_frames();
504 }
505
506 const std::vector<QuicPathResponseFrame>& path_response_frames() const {
507 return framer_.path_response_frames();
508 }
509
510 size_t last_packet_size() { return last_packet_size_; }
511
512 const QuicPacketHeader& last_packet_header() const {
513 return last_packet_header_;
514 }
515
516 const QuicVersionNegotiationPacket* version_negotiation_packet() {
517 return framer_.version_negotiation_packet();
518 }
519
520 void set_is_write_blocked_data_buffered(bool buffered) {
521 is_write_blocked_data_buffered_ = buffered;
522 }
523
524 void set_perspective(Perspective perspective) {
525 // We invert perspective here, because the framer needs to parse packets
526 // we send.
527 QuicFramerPeer::SetPerspective(framer_.framer(),
528 InvertPerspective(perspective));
529 }
530
531 // final_bytes_of_last_packet_ returns the last four bytes of the previous
532 // packet as a little-endian, uint32_t. This is intended to be used with a
533 // TaggingEncrypter so that tests can determine which encrypter was used for
534 // a given packet.
535 uint32_t final_bytes_of_last_packet() { return final_bytes_of_last_packet_; }
536
537 // Returns the final bytes of the second to last packet.
538 uint32_t final_bytes_of_previous_packet() {
539 return final_bytes_of_previous_packet_;
540 }
541
542 void use_tagging_decrypter() { use_tagging_decrypter_ = true; }
543
544 uint32_t packets_write_attempts() { return packets_write_attempts_; }
545
546 void Reset() { framer_.Reset(); }
547
548 void SetSupportedVersions(const ParsedQuicVersionVector& versions) {
549 framer_.SetSupportedVersions(versions);
550 }
551
552 void set_max_packet_size(QuicByteCount max_packet_size) {
553 max_packet_size_ = max_packet_size;
554 }
555
556 void set_supports_release_time(bool supports_release_time) {
557 supports_release_time_ = supports_release_time;
558 }
559
560 SimpleQuicFramer* framer() { return &framer_; }
561
562 private:
563 ParsedQuicVersion version_;
564 SimpleQuicFramer framer_;
565 size_t last_packet_size_;
566 QuicPacketHeader last_packet_header_;
567 bool write_blocked_;
568 bool write_should_fail_;
569 bool block_on_next_flush_;
570 bool block_on_next_write_;
571 bool next_packet_too_large_;
572 bool always_get_packet_too_large_;
573 bool is_write_blocked_data_buffered_;
574 bool is_batch_mode_;
575 uint32_t final_bytes_of_last_packet_;
576 uint32_t final_bytes_of_previous_packet_;
577 bool use_tagging_decrypter_;
578 uint32_t packets_write_attempts_;
579 MockClock* clock_;
580 // If non-zero, the clock will pause during WritePacket for this amount of
581 // time.
582 QuicTime::Delta write_pause_time_delta_;
583 QuicByteCount max_packet_size_;
584 bool supports_release_time_;
585};
586
587class TestConnection : public QuicConnection {
588 public:
589 TestConnection(QuicConnectionId connection_id,
590 QuicSocketAddress address,
591 TestConnectionHelper* helper,
592 TestAlarmFactory* alarm_factory,
593 TestPacketWriter* writer,
594 Perspective perspective,
595 ParsedQuicVersion version)
596 : QuicConnection(connection_id,
597 address,
598 helper,
599 alarm_factory,
600 writer,
601 /* owns_writer= */ false,
602 perspective,
603 SupportedVersions(version)),
604 notifier_(nullptr) {
605 writer->set_perspective(perspective);
606 SetEncrypter(ENCRYPTION_FORWARD_SECURE,
607 QuicMakeUnique<NullEncrypter>(perspective));
608 SetDataProducer(&producer_);
609 }
610 TestConnection(const TestConnection&) = delete;
611 TestConnection& operator=(const TestConnection&) = delete;
612
QUICHE teama6ef0a62019-03-07 20:34:33 -0500613 void SetSendAlgorithm(SendAlgorithmInterface* send_algorithm) {
614 QuicConnectionPeer::SetSendAlgorithm(this, send_algorithm);
615 }
616
617 void SetLossAlgorithm(LossDetectionInterface* loss_algorithm) {
618 QuicConnectionPeer::SetLossAlgorithm(this, loss_algorithm);
619 }
620
621 void SendPacket(EncryptionLevel level,
622 uint64_t packet_number,
623 std::unique_ptr<QuicPacket> packet,
624 HasRetransmittableData retransmittable,
625 bool has_ack,
626 bool has_pending_frames) {
dschinazi66dea072019-04-09 11:41:06 -0700627 char buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -0500628 size_t encrypted_length =
629 QuicConnectionPeer::GetFramer(this)->EncryptPayload(
QUICHE team6987b4a2019-03-15 16:23:04 -0700630 ENCRYPTION_INITIAL, QuicPacketNumber(packet_number), *packet,
dschinazi66dea072019-04-09 11:41:06 -0700631 buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500632 SerializedPacket serialized_packet(
633 QuicPacketNumber(packet_number), PACKET_4BYTE_PACKET_NUMBER, buffer,
634 encrypted_length, has_ack, has_pending_frames);
635 if (retransmittable == HAS_RETRANSMITTABLE_DATA) {
636 serialized_packet.retransmittable_frames.push_back(
637 QuicFrame(QuicStreamFrame()));
638 }
639 OnSerializedPacket(&serialized_packet);
640 }
641
642 QuicConsumedData SaveAndSendStreamData(QuicStreamId id,
643 const struct iovec* iov,
644 int iov_count,
645 size_t total_length,
646 QuicStreamOffset offset,
647 StreamSendingState state) {
648 ScopedPacketFlusher flusher(this, NO_ACK);
649 producer_.SaveStreamData(id, iov, iov_count, 0u, total_length);
650 if (notifier_ != nullptr) {
651 return notifier_->WriteOrBufferData(id, total_length, state);
652 }
653 return QuicConnection::SendStreamData(id, total_length, offset, state);
654 }
655
656 QuicConsumedData SendStreamDataWithString(QuicStreamId id,
657 QuicStringPiece data,
658 QuicStreamOffset offset,
659 StreamSendingState state) {
660 ScopedPacketFlusher flusher(this, NO_ACK);
nharper46833c32019-05-15 21:33:05 -0700661 if (!QuicUtils::IsCryptoStreamId(transport_version(), id) &&
QUICHE team6987b4a2019-03-15 16:23:04 -0700662 this->encryption_level() == ENCRYPTION_INITIAL) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500663 this->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
664 }
665 struct iovec iov;
666 MakeIOVector(data, &iov);
667 return SaveAndSendStreamData(id, &iov, 1, data.length(), offset, state);
668 }
669
QUICHE teamcd098022019-03-22 18:49:55 -0700670 QuicConsumedData SendApplicationDataAtLevel(EncryptionLevel encryption_level,
671 QuicStreamId id,
672 QuicStringPiece data,
673 QuicStreamOffset offset,
674 StreamSendingState state) {
675 ScopedPacketFlusher flusher(this, NO_ACK);
676 DCHECK(encryption_level >= ENCRYPTION_ZERO_RTT);
677 SetEncrypter(encryption_level, QuicMakeUnique<TaggingEncrypter>(0x01));
678 SetDefaultEncryptionLevel(encryption_level);
679 struct iovec iov;
680 MakeIOVector(data, &iov);
681 return SaveAndSendStreamData(id, &iov, 1, data.length(), offset, state);
682 }
683
QUICHE teama6ef0a62019-03-07 20:34:33 -0500684 QuicConsumedData SendStreamData3() {
685 return SendStreamDataWithString(
686 GetNthClientInitiatedStreamId(1, transport_version()), "food", 0,
687 NO_FIN);
688 }
689
690 QuicConsumedData SendStreamData5() {
691 return SendStreamDataWithString(
692 GetNthClientInitiatedStreamId(2, transport_version()), "food2", 0,
693 NO_FIN);
694 }
695
696 // Ensures the connection can write stream data before writing.
697 QuicConsumedData EnsureWritableAndSendStreamData5() {
698 EXPECT_TRUE(CanWriteStreamData());
699 return SendStreamData5();
700 }
701
702 // The crypto stream has special semantics so that it is not blocked by a
703 // congestion window limitation, and also so that it gets put into a separate
704 // packet (so that it is easier to reason about a crypto frame not being
705 // split needlessly across packet boundaries). As a result, we have separate
706 // tests for some cases for this stream.
707 QuicConsumedData SendCryptoStreamData() {
708 QuicStreamOffset offset = 0;
709 QuicStringPiece data("chlo");
nharper46833c32019-05-15 21:33:05 -0700710 return SendCryptoDataWithString(data, offset);
711 }
712
713 QuicConsumedData SendCryptoDataWithString(QuicStringPiece data,
714 QuicStreamOffset offset) {
QUICHE teamea740082019-03-11 17:58:43 -0700715 if (!QuicVersionUsesCryptoFrames(transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500716 return SendStreamDataWithString(
717 QuicUtils::GetCryptoStreamId(transport_version()), data, offset,
718 NO_FIN);
719 }
QUICHE team6987b4a2019-03-15 16:23:04 -0700720 producer_.SaveCryptoData(ENCRYPTION_INITIAL, offset, data);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500721 size_t bytes_written;
722 if (notifier_) {
723 bytes_written =
QUICHE team6987b4a2019-03-15 16:23:04 -0700724 notifier_->WriteCryptoData(ENCRYPTION_INITIAL, data.length(), offset);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500725 } else {
QUICHE team6987b4a2019-03-15 16:23:04 -0700726 bytes_written = QuicConnection::SendCryptoData(ENCRYPTION_INITIAL,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500727 data.length(), offset);
728 }
729 return QuicConsumedData(bytes_written, /*fin_consumed*/ false);
730 }
731
732 void set_version(ParsedQuicVersion version) {
733 QuicConnectionPeer::GetFramer(this)->set_version(version);
734 }
735
736 void SetSupportedVersions(const ParsedQuicVersionVector& versions) {
737 QuicConnectionPeer::GetFramer(this)->SetSupportedVersions(versions);
738 QuicConnectionPeer::SetNoVersionNegotiation(this, versions.size() == 1);
739 writer()->SetSupportedVersions(versions);
740 }
741
742 void set_perspective(Perspective perspective) {
743 writer()->set_perspective(perspective);
744 QuicConnectionPeer::SetPerspective(this, perspective);
745 }
746
747 // Enable path MTU discovery. Assumes that the test is performed from the
748 // client perspective and the higher value of MTU target is used.
749 void EnablePathMtuDiscovery(MockSendAlgorithm* send_algorithm) {
750 ASSERT_EQ(Perspective::IS_CLIENT, perspective());
751
752 QuicConfig config;
753 QuicTagVector connection_options;
754 connection_options.push_back(kMTUH);
755 config.SetConnectionOptionsToSend(connection_options);
756 EXPECT_CALL(*send_algorithm, SetFromConfig(_, _));
757 SetFromConfig(config);
758
759 // Normally, the pacing would be disabled in the test, but calling
760 // SetFromConfig enables it. Set nearly-infinite bandwidth to make the
761 // pacing algorithm work.
762 EXPECT_CALL(*send_algorithm, PacingRate(_))
763 .WillRepeatedly(Return(QuicBandwidth::Infinite()));
764 }
765
766 TestAlarmFactory::TestAlarm* GetAckAlarm() {
767 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
768 QuicConnectionPeer::GetAckAlarm(this));
769 }
770
771 TestAlarmFactory::TestAlarm* GetPingAlarm() {
772 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
773 QuicConnectionPeer::GetPingAlarm(this));
774 }
775
776 TestAlarmFactory::TestAlarm* GetRetransmissionAlarm() {
777 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
778 QuicConnectionPeer::GetRetransmissionAlarm(this));
779 }
780
781 TestAlarmFactory::TestAlarm* GetSendAlarm() {
782 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
783 QuicConnectionPeer::GetSendAlarm(this));
784 }
785
786 TestAlarmFactory::TestAlarm* GetTimeoutAlarm() {
787 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
788 QuicConnectionPeer::GetTimeoutAlarm(this));
789 }
790
791 TestAlarmFactory::TestAlarm* GetMtuDiscoveryAlarm() {
792 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
793 QuicConnectionPeer::GetMtuDiscoveryAlarm(this));
794 }
795
796 TestAlarmFactory::TestAlarm* GetPathDegradingAlarm() {
797 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
798 QuicConnectionPeer::GetPathDegradingAlarm(this));
799 }
800
801 TestAlarmFactory::TestAlarm* GetProcessUndecryptablePacketsAlarm() {
802 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
803 QuicConnectionPeer::GetProcessUndecryptablePacketsAlarm(this));
804 }
805
806 void SetMaxTailLossProbes(size_t max_tail_loss_probes) {
807 QuicSentPacketManagerPeer::SetMaxTailLossProbes(
808 QuicConnectionPeer::GetSentPacketManager(this), max_tail_loss_probes);
809 }
810
811 QuicByteCount GetBytesInFlight() {
ianswett9f459cb2019-04-21 06:39:59 -0700812 return QuicConnectionPeer::GetSentPacketManager(this)->GetBytesInFlight();
QUICHE teama6ef0a62019-03-07 20:34:33 -0500813 }
814
815 void set_notifier(SimpleSessionNotifier* notifier) { notifier_ = notifier; }
816
817 void ReturnEffectivePeerAddressForNextPacket(const QuicSocketAddress& addr) {
818 next_effective_peer_addr_ = QuicMakeUnique<QuicSocketAddress>(addr);
819 }
820
nharper46833c32019-05-15 21:33:05 -0700821 SimpleDataProducer* producer() { return &producer_; }
822
QUICHE teama6ef0a62019-03-07 20:34:33 -0500823 using QuicConnection::active_effective_peer_migration_type;
824 using QuicConnection::IsCurrentPacketConnectivityProbing;
825 using QuicConnection::SelectMutualVersion;
826 using QuicConnection::SendProbingRetransmissions;
827 using QuicConnection::set_defer_send_in_response_to_packets;
828
829 protected:
830 QuicSocketAddress GetEffectivePeerAddressFromCurrentPacket() const override {
831 if (next_effective_peer_addr_) {
832 return *std::move(next_effective_peer_addr_);
833 }
834 return QuicConnection::GetEffectivePeerAddressFromCurrentPacket();
835 }
836
837 private:
838 TestPacketWriter* writer() {
839 return static_cast<TestPacketWriter*>(QuicConnection::writer());
840 }
841
842 SimpleDataProducer producer_;
843
844 SimpleSessionNotifier* notifier_;
845
846 std::unique_ptr<QuicSocketAddress> next_effective_peer_addr_;
847};
848
849enum class AckResponse { kDefer, kImmediate };
850
851// Run tests with combinations of {ParsedQuicVersion, AckResponse}.
852struct TestParams {
853 TestParams(ParsedQuicVersion version,
854 AckResponse ack_response,
855 bool no_stop_waiting)
856 : version(version),
857 ack_response(ack_response),
858 no_stop_waiting(no_stop_waiting) {}
859
860 friend std::ostream& operator<<(std::ostream& os, const TestParams& p) {
861 os << "{ client_version: " << ParsedQuicVersionToString(p.version)
862 << " ack_response: "
863 << (p.ack_response == AckResponse::kDefer ? "defer" : "immediate")
864 << " no_stop_waiting: " << p.no_stop_waiting << " }";
865 return os;
866 }
867
868 ParsedQuicVersion version;
869 AckResponse ack_response;
870 bool no_stop_waiting;
871};
872
873// Constructs various test permutations.
874std::vector<TestParams> GetTestParams() {
875 QuicFlagSaver flags;
wub49855982019-05-01 14:16:26 -0700876 SetQuicFlag(FLAGS_quic_supports_tls_handshake, true);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500877 std::vector<TestParams> params;
878 ParsedQuicVersionVector all_supported_versions = AllSupportedVersions();
879 for (size_t i = 0; i < all_supported_versions.size(); ++i) {
880 for (AckResponse ack_response :
881 {AckResponse::kDefer, AckResponse::kImmediate}) {
882 for (bool no_stop_waiting : {true, false}) {
883 // After version 43, never use STOP_WAITING.
fayangd4291e42019-05-30 10:31:21 -0700884 params.push_back(
885 TestParams(all_supported_versions[i], ack_response,
886 !VersionHasIetfInvariantHeader(
887 all_supported_versions[i].transport_version)
888 ? no_stop_waiting
889 : true));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500890 }
891 }
892 }
893 return params;
894}
895
896class QuicConnectionTest : public QuicTestWithParam<TestParams> {
897 protected:
898 QuicConnectionTest()
899 : connection_id_(TestConnectionId()),
900 framer_(SupportedVersions(version()),
901 QuicTime::Zero(),
902 Perspective::IS_CLIENT,
903 connection_id_.length()),
904 send_algorithm_(new StrictMock<MockSendAlgorithm>),
905 loss_algorithm_(new MockLossAlgorithm()),
906 helper_(new TestConnectionHelper(&clock_, &random_generator_)),
907 alarm_factory_(new TestAlarmFactory()),
908 peer_framer_(SupportedVersions(version()),
909 QuicTime::Zero(),
910 Perspective::IS_SERVER,
911 connection_id_.length()),
912 peer_creator_(connection_id_,
913 &peer_framer_,
914 /*delegate=*/nullptr),
915 writer_(new TestPacketWriter(version(), &clock_)),
916 connection_(connection_id_,
917 kPeerAddress,
918 helper_.get(),
919 alarm_factory_.get(),
920 writer_.get(),
921 Perspective::IS_CLIENT,
922 version()),
923 creator_(QuicConnectionPeer::GetPacketCreator(&connection_)),
924 generator_(QuicConnectionPeer::GetPacketGenerator(&connection_)),
925 manager_(QuicConnectionPeer::GetSentPacketManager(&connection_)),
nharper46833c32019-05-15 21:33:05 -0700926 frame1_(0, false, 0, QuicStringPiece(data1)),
927 frame2_(0, false, 3, QuicStringPiece(data2)),
928 crypto_frame_(ENCRYPTION_INITIAL, 0, QuicStringPiece(data1)),
QUICHE teama6ef0a62019-03-07 20:34:33 -0500929 packet_number_length_(PACKET_4BYTE_PACKET_NUMBER),
930 connection_id_included_(CONNECTION_ID_PRESENT),
931 notifier_(&connection_) {
wub49855982019-05-01 14:16:26 -0700932 SetQuicFlag(FLAGS_quic_supports_tls_handshake, true);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500933 connection_.set_defer_send_in_response_to_packets(GetParam().ack_response ==
934 AckResponse::kDefer);
nharper2c9f02a2019-05-08 10:25:50 -0700935 for (EncryptionLevel level :
936 {ENCRYPTION_ZERO_RTT, ENCRYPTION_FORWARD_SECURE}) {
937 peer_creator_.SetEncrypter(
938 level, QuicMakeUnique<NullEncrypter>(peer_framer_.perspective()));
939 }
dschinazi6ece5002019-05-22 06:35:49 -0700940 if (version().handshake_protocol == PROTOCOL_TLS1_3) {
941 connection_.SetEncrypter(
942 ENCRYPTION_INITIAL,
943 QuicMakeUnique<NullEncrypter>(Perspective::IS_CLIENT));
944 connection_.InstallDecrypter(
945 ENCRYPTION_INITIAL,
946 QuicMakeUnique<NullDecrypter>(Perspective::IS_CLIENT));
947 }
dschinazi7b9278c2019-05-20 07:36:21 -0700948 QuicFramerPeer::SetLastSerializedServerConnectionId(
QUICHE teama6ef0a62019-03-07 20:34:33 -0500949 QuicConnectionPeer::GetFramer(&connection_), connection_id_);
fayangd4291e42019-05-30 10:31:21 -0700950 if (VersionHasIetfInvariantHeader(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500951 EXPECT_TRUE(QuicConnectionPeer::GetNoStopWaitingFrames(&connection_));
952 } else {
953 QuicConnectionPeer::SetNoStopWaitingFrames(&connection_,
954 GetParam().no_stop_waiting);
955 }
nharper46833c32019-05-15 21:33:05 -0700956 QuicStreamId stream_id;
957 if (QuicVersionUsesCryptoFrames(version().transport_version)) {
958 stream_id = QuicUtils::GetFirstBidirectionalStreamId(
959 version().transport_version, Perspective::IS_CLIENT);
960 } else {
961 stream_id = QuicUtils::GetCryptoStreamId(version().transport_version);
962 }
963 frame1_.stream_id = stream_id;
964 frame2_.stream_id = stream_id;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500965 connection_.set_visitor(&visitor_);
966 if (connection_.session_decides_what_to_write()) {
967 connection_.SetSessionNotifier(&notifier_);
968 connection_.set_notifier(&notifier_);
969 }
970 connection_.SetSendAlgorithm(send_algorithm_);
971 connection_.SetLossAlgorithm(loss_algorithm_.get());
972 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
973 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
974 .Times(AnyNumber());
975 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
976 .WillRepeatedly(Return(kDefaultTCPMSS));
977 EXPECT_CALL(*send_algorithm_, PacingRate(_))
978 .WillRepeatedly(Return(QuicBandwidth::Zero()));
979 EXPECT_CALL(*send_algorithm_, HasReliableBandwidthEstimate())
980 .Times(AnyNumber());
981 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
982 .Times(AnyNumber())
983 .WillRepeatedly(Return(QuicBandwidth::Zero()));
984 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
985 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
986 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
987 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).Times(AnyNumber());
988 EXPECT_CALL(visitor_, HasPendingHandshake()).Times(AnyNumber());
989 if (connection_.session_decides_what_to_write()) {
990 EXPECT_CALL(visitor_, OnCanWrite())
991 .WillRepeatedly(
992 Invoke(&notifier_, &SimpleSessionNotifier::OnCanWrite));
993 } else {
994 EXPECT_CALL(visitor_, OnCanWrite()).Times(AnyNumber());
995 }
996 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
997 .WillRepeatedly(Return(false));
998 EXPECT_CALL(visitor_, OnCongestionWindowChange(_)).Times(AnyNumber());
999 EXPECT_CALL(visitor_, OnConnectivityProbeReceived(_, _)).Times(AnyNumber());
1000 EXPECT_CALL(visitor_, OnForwardProgressConfirmed()).Times(AnyNumber());
1001
1002 EXPECT_CALL(*loss_algorithm_, GetLossTimeout())
1003 .WillRepeatedly(Return(QuicTime::Zero()));
1004 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
1005 .Times(AnyNumber());
zhongyi546cc452019-04-12 15:27:49 -07001006
1007 if (connection_.version().KnowsWhichDecrypterToUse()) {
1008 connection_.InstallDecrypter(
1009 ENCRYPTION_FORWARD_SECURE,
1010 QuicMakeUnique<NullDecrypter>(Perspective::IS_CLIENT));
1011 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001012 }
1013
1014 QuicConnectionTest(const QuicConnectionTest&) = delete;
1015 QuicConnectionTest& operator=(const QuicConnectionTest&) = delete;
1016
1017 ParsedQuicVersion version() { return GetParam().version; }
1018
QUICHE teama6ef0a62019-03-07 20:34:33 -05001019 QuicStopWaitingFrame* stop_waiting() {
1020 QuicConnectionPeer::PopulateStopWaitingFrame(&connection_, &stop_waiting_);
1021 return &stop_waiting_;
1022 }
1023
1024 QuicPacketNumber least_unacked() {
1025 if (writer_->stop_waiting_frames().empty()) {
1026 return QuicPacketNumber();
1027 }
1028 return writer_->stop_waiting_frames()[0].least_unacked;
1029 }
1030
1031 void use_tagging_decrypter() { writer_->use_tagging_decrypter(); }
1032
zhongyi546cc452019-04-12 15:27:49 -07001033 void SetDecrypter(EncryptionLevel level,
1034 std::unique_ptr<QuicDecrypter> decrypter) {
1035 if (connection_.version().KnowsWhichDecrypterToUse()) {
1036 connection_.InstallDecrypter(level, std::move(decrypter));
1037 connection_.RemoveDecrypter(ENCRYPTION_INITIAL);
1038 } else {
1039 connection_.SetDecrypter(level, std::move(decrypter));
1040 }
1041 }
1042
QUICHE teama6ef0a62019-03-07 20:34:33 -05001043 void ProcessPacket(uint64_t number) {
1044 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
1045 ProcessDataPacket(number);
1046 if (connection_.GetSendAlarm()->IsSet()) {
1047 connection_.GetSendAlarm()->Fire();
1048 }
1049 }
1050
1051 void ProcessReceivedPacket(const QuicSocketAddress& self_address,
1052 const QuicSocketAddress& peer_address,
1053 const QuicReceivedPacket& packet) {
1054 connection_.ProcessUdpPacket(self_address, peer_address, packet);
1055 if (connection_.GetSendAlarm()->IsSet()) {
1056 connection_.GetSendAlarm()->Fire();
1057 }
1058 }
1059
1060 void ProcessFramePacket(QuicFrame frame) {
1061 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
1062 }
1063
1064 void ProcessFramePacketWithAddresses(QuicFrame frame,
1065 QuicSocketAddress self_address,
1066 QuicSocketAddress peer_address) {
1067 QuicFrames frames;
1068 frames.push_back(QuicFrame(frame));
1069 QuicPacketCreatorPeer::SetSendVersionInPacket(
1070 &peer_creator_, connection_.perspective() == Perspective::IS_SERVER);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001071
dschinazi66dea072019-04-09 11:41:06 -07001072 char buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05001073 SerializedPacket serialized_packet =
dschinazi66dea072019-04-09 11:41:06 -07001074 QuicPacketCreatorPeer::SerializeAllFrames(
1075 &peer_creator_, frames, buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001076 connection_.ProcessUdpPacket(
1077 self_address, peer_address,
1078 QuicReceivedPacket(serialized_packet.encrypted_buffer,
1079 serialized_packet.encrypted_length, clock_.Now()));
1080 if (connection_.GetSendAlarm()->IsSet()) {
1081 connection_.GetSendAlarm()->Fire();
1082 }
1083 }
1084
1085 // Bypassing the packet creator is unrealistic, but allows us to process
1086 // packets the QuicPacketCreator won't allow us to create.
1087 void ForceProcessFramePacket(QuicFrame frame) {
1088 QuicFrames frames;
1089 frames.push_back(QuicFrame(frame));
zhongyi546cc452019-04-12 15:27:49 -07001090 bool send_version = connection_.perspective() == Perspective::IS_SERVER;
1091 if (connection_.version().KnowsWhichDecrypterToUse()) {
1092 send_version = true;
1093 }
1094 QuicPacketCreatorPeer::SetSendVersionInPacket(&peer_creator_, send_version);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001095 QuicPacketHeader header;
1096 QuicPacketCreatorPeer::FillPacketHeader(&peer_creator_, &header);
dschinazi66dea072019-04-09 11:41:06 -07001097 char encrypted_buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05001098 size_t length = peer_framer_.BuildDataPacket(
dschinazi66dea072019-04-09 11:41:06 -07001099 header, frames, encrypted_buffer, kMaxOutgoingPacketSize,
1100 ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001101 DCHECK_GT(length, 0u);
1102
1103 const size_t encrypted_length = peer_framer_.EncryptInPlace(
QUICHE team6987b4a2019-03-15 16:23:04 -07001104 ENCRYPTION_INITIAL, header.packet_number,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001105 GetStartOfEncryptedData(peer_framer_.version().transport_version,
1106 header),
dschinazi66dea072019-04-09 11:41:06 -07001107 length, kMaxOutgoingPacketSize, encrypted_buffer);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001108 DCHECK_GT(encrypted_length, 0u);
1109
1110 connection_.ProcessUdpPacket(
1111 kSelfAddress, kPeerAddress,
1112 QuicReceivedPacket(encrypted_buffer, encrypted_length, clock_.Now()));
1113 }
1114
1115 size_t ProcessFramePacketAtLevel(uint64_t number,
1116 QuicFrame frame,
1117 EncryptionLevel level) {
1118 QuicPacketHeader header;
1119 header.destination_connection_id = connection_id_;
1120 header.packet_number_length = packet_number_length_;
1121 header.destination_connection_id_included = connection_id_included_;
fayangd4291e42019-05-30 10:31:21 -07001122 if ((VersionHasIetfInvariantHeader(peer_framer_.transport_version()) ||
QUICHE team2252b702019-05-14 23:55:14 -04001123 GetQuicRestartFlag(quic_do_not_override_connection_id)) &&
QUICHE teama6ef0a62019-03-07 20:34:33 -05001124 peer_framer_.perspective() == Perspective::IS_SERVER) {
1125 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1126 }
zhongyi546cc452019-04-12 15:27:49 -07001127 if (level == ENCRYPTION_INITIAL &&
1128 peer_framer_.version().KnowsWhichDecrypterToUse()) {
1129 header.version_flag = true;
1130 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
1131 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
QUICHE team2252b702019-05-14 23:55:14 -04001132 }
1133 if ((GetQuicRestartFlag(quic_do_not_override_connection_id) ||
1134 (level == ENCRYPTION_INITIAL &&
1135 peer_framer_.version().KnowsWhichDecrypterToUse())) &&
1136 header.version_flag &&
1137 peer_framer_.perspective() == Perspective::IS_SERVER) {
1138 header.source_connection_id = connection_id_;
1139 header.source_connection_id_included = CONNECTION_ID_PRESENT;
zhongyi546cc452019-04-12 15:27:49 -07001140 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001141 header.packet_number = QuicPacketNumber(number);
1142 QuicFrames frames;
1143 frames.push_back(frame);
1144 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
QUICHE teamcd098022019-03-22 18:49:55 -07001145 // Set the correct encryption level and encrypter on peer_creator and
1146 // peer_framer, respectively.
1147 peer_creator_.set_encryption_level(level);
1148 if (QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_) >
1149 ENCRYPTION_INITIAL) {
1150 peer_framer_.SetEncrypter(
1151 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
1152 QuicMakeUnique<TaggingEncrypter>(0x01));
1153 // Set the corresponding decrypter.
zhongyi546cc452019-04-12 15:27:49 -07001154 if (connection_.version().KnowsWhichDecrypterToUse()) {
1155 connection_.InstallDecrypter(
1156 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
1157 QuicMakeUnique<StrictTaggingDecrypter>(0x01));
1158 connection_.RemoveDecrypter(ENCRYPTION_INITIAL);
1159 } else {
1160 connection_.SetDecrypter(
1161 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
1162 QuicMakeUnique<StrictTaggingDecrypter>(0x01));
1163 }
QUICHE teamcd098022019-03-22 18:49:55 -07001164 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001165
dschinazi66dea072019-04-09 11:41:06 -07001166 char buffer[kMaxOutgoingPacketSize];
1167 size_t encrypted_length =
1168 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
1169 buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001170 connection_.ProcessUdpPacket(
1171 kSelfAddress, kPeerAddress,
QUICHE teamcd098022019-03-22 18:49:55 -07001172 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1173 if (connection_.GetSendAlarm()->IsSet()) {
1174 connection_.GetSendAlarm()->Fire();
1175 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001176 return encrypted_length;
1177 }
1178
1179 size_t ProcessDataPacket(uint64_t number) {
nharper2c9f02a2019-05-08 10:25:50 -07001180 return ProcessDataPacketAtLevel(number, false, ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001181 }
1182
1183 size_t ProcessDataPacket(QuicPacketNumber packet_number) {
nharper2c9f02a2019-05-08 10:25:50 -07001184 return ProcessDataPacketAtLevel(packet_number, false,
1185 ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001186 }
1187
1188 size_t ProcessDataPacketAtLevel(QuicPacketNumber packet_number,
1189 bool has_stop_waiting,
1190 EncryptionLevel level) {
1191 return ProcessDataPacketAtLevel(packet_number.ToUint64(), has_stop_waiting,
1192 level);
1193 }
1194
nharper46833c32019-05-15 21:33:05 -07001195 size_t ProcessCryptoPacketAtLevel(uint64_t number, EncryptionLevel level) {
fayangc31c9952019-06-05 13:54:48 -07001196 QuicPacketHeader header = ConstructPacketHeader(number, ENCRYPTION_INITIAL);
nharper46833c32019-05-15 21:33:05 -07001197 QuicFrames frames;
1198 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1199 frames.push_back(QuicFrame(&crypto_frame_));
1200 } else {
1201 frames.push_back(QuicFrame(frame1_));
1202 }
1203 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
1204 char buffer[kMaxOutgoingPacketSize];
1205 peer_creator_.set_encryption_level(ENCRYPTION_INITIAL);
fayangc31c9952019-06-05 13:54:48 -07001206 size_t encrypted_length = peer_framer_.EncryptPayload(
1207 ENCRYPTION_INITIAL, QuicPacketNumber(number), *packet, buffer,
1208 kMaxOutgoingPacketSize);
nharper46833c32019-05-15 21:33:05 -07001209 connection_.ProcessUdpPacket(
1210 kSelfAddress, kPeerAddress,
1211 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1212 if (connection_.GetSendAlarm()->IsSet()) {
1213 connection_.GetSendAlarm()->Fire();
1214 }
1215 return encrypted_length;
1216 }
1217
QUICHE teama6ef0a62019-03-07 20:34:33 -05001218 size_t ProcessDataPacketAtLevel(uint64_t number,
1219 bool has_stop_waiting,
1220 EncryptionLevel level) {
1221 std::unique_ptr<QuicPacket> packet(
QUICHE team8c1daa22019-03-13 08:33:41 -07001222 ConstructDataPacket(number, has_stop_waiting, level));
dschinazi66dea072019-04-09 11:41:06 -07001223 char buffer[kMaxOutgoingPacketSize];
QUICHE teamcd098022019-03-22 18:49:55 -07001224 peer_creator_.set_encryption_level(level);
dschinazi66dea072019-04-09 11:41:06 -07001225 size_t encrypted_length =
1226 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
1227 buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001228 connection_.ProcessUdpPacket(
1229 kSelfAddress, kPeerAddress,
1230 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1231 if (connection_.GetSendAlarm()->IsSet()) {
1232 connection_.GetSendAlarm()->Fire();
1233 }
1234 return encrypted_length;
1235 }
1236
1237 void ProcessClosePacket(uint64_t number) {
1238 std::unique_ptr<QuicPacket> packet(ConstructClosePacket(number));
dschinazi66dea072019-04-09 11:41:06 -07001239 char buffer[kMaxOutgoingPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07001240 size_t encrypted_length = peer_framer_.EncryptPayload(
1241 ENCRYPTION_INITIAL, QuicPacketNumber(number), *packet, buffer,
dschinazi66dea072019-04-09 11:41:06 -07001242 kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001243 connection_.ProcessUdpPacket(
1244 kSelfAddress, kPeerAddress,
1245 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
1246 }
1247
1248 QuicByteCount SendStreamDataToPeer(QuicStreamId id,
1249 QuicStringPiece data,
1250 QuicStreamOffset offset,
1251 StreamSendingState state,
1252 QuicPacketNumber* last_packet) {
1253 QuicByteCount packet_size;
1254 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1255 .WillOnce(SaveArg<3>(&packet_size));
1256 connection_.SendStreamDataWithString(id, data, offset, state);
1257 if (last_packet != nullptr) {
1258 *last_packet = creator_->packet_number();
1259 }
1260 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1261 .Times(AnyNumber());
1262 return packet_size;
1263 }
1264
1265 void SendAckPacketToPeer() {
1266 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1267 {
1268 QuicConnection::ScopedPacketFlusher flusher(&connection_,
1269 QuicConnection::NO_ACK);
1270 connection_.SendAck();
1271 }
1272 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1273 .Times(AnyNumber());
1274 }
1275
1276 void SendRstStream(QuicStreamId id,
1277 QuicRstStreamErrorCode error,
1278 QuicStreamOffset bytes_written) {
1279 if (connection_.session_decides_what_to_write()) {
1280 notifier_.WriteOrBufferRstStream(id, error, bytes_written);
1281 connection_.OnStreamReset(id, error);
1282 return;
1283 }
1284 std::unique_ptr<QuicRstStreamFrame> rst_stream =
1285 QuicMakeUnique<QuicRstStreamFrame>(1, id, error, bytes_written);
1286 if (connection_.SendControlFrame(QuicFrame(rst_stream.get()))) {
1287 rst_stream.release();
1288 }
1289 connection_.OnStreamReset(id, error);
1290 }
1291
zhongyifbb25772019-04-10 16:54:08 -07001292 void SendPing() {
1293 if (connection_.session_decides_what_to_write()) {
1294 notifier_.WriteOrBufferPing();
1295 } else {
1296 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
1297 }
1298 }
1299
QUICHE teama6ef0a62019-03-07 20:34:33 -05001300 void ProcessAckPacket(uint64_t packet_number, QuicAckFrame* frame) {
1301 if (packet_number > 1) {
1302 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, packet_number - 1);
1303 } else {
1304 QuicPacketCreatorPeer::ClearPacketNumber(&peer_creator_);
1305 }
1306 ProcessFramePacket(QuicFrame(frame));
1307 }
1308
1309 void ProcessAckPacket(QuicAckFrame* frame) {
1310 ProcessFramePacket(QuicFrame(frame));
1311 }
1312
1313 void ProcessStopWaitingPacket(QuicStopWaitingFrame frame) {
1314 ProcessFramePacket(QuicFrame(frame));
1315 }
1316
1317 size_t ProcessStopWaitingPacketAtLevel(uint64_t number,
1318 QuicStopWaitingFrame frame,
1319 EncryptionLevel level) {
1320 return ProcessFramePacketAtLevel(number, QuicFrame(frame),
1321 ENCRYPTION_ZERO_RTT);
1322 }
1323
1324 void ProcessGoAwayPacket(QuicGoAwayFrame* frame) {
1325 ProcessFramePacket(QuicFrame(frame));
1326 }
1327
1328 bool IsMissing(uint64_t number) {
fayangc31c9952019-06-05 13:54:48 -07001329 return IsAwaitingPacket(connection_.ack_frame(), QuicPacketNumber(number),
QUICHE teama6ef0a62019-03-07 20:34:33 -05001330 QuicPacketNumber());
1331 }
1332
1333 std::unique_ptr<QuicPacket> ConstructPacket(const QuicPacketHeader& header,
1334 const QuicFrames& frames) {
1335 auto packet = BuildUnsizedDataPacket(&peer_framer_, header, frames);
1336 EXPECT_NE(nullptr, packet.get());
1337 return packet;
1338 }
1339
nharper46833c32019-05-15 21:33:05 -07001340 QuicPacketHeader ConstructPacketHeader(uint64_t number,
1341 EncryptionLevel level) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001342 QuicPacketHeader header;
fayangd4291e42019-05-30 10:31:21 -07001343 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version()) &&
QUICHE team8c1daa22019-03-13 08:33:41 -07001344 level < ENCRYPTION_FORWARD_SECURE) {
1345 // Set long header type accordingly.
1346 header.version_flag = true;
1347 header.long_packet_type = EncryptionlevelToLongHeaderType(level);
1348 if (QuicVersionHasLongHeaderLengths(
1349 peer_framer_.version().transport_version)) {
1350 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
1351 if (header.long_packet_type == INITIAL) {
1352 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
1353 }
1354 }
1355 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001356 // Set connection_id to peer's in memory representation as this data packet
1357 // is created by peer_framer.
QUICHE team2252b702019-05-14 23:55:14 -04001358 if (GetQuicRestartFlag(quic_do_not_override_connection_id) &&
1359 peer_framer_.perspective() == Perspective::IS_SERVER) {
1360 header.source_connection_id = connection_id_;
1361 header.source_connection_id_included = connection_id_included_;
1362 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1363 } else {
1364 header.destination_connection_id = connection_id_;
1365 header.destination_connection_id_included = connection_id_included_;
1366 }
fayangd4291e42019-05-30 10:31:21 -07001367 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version()) &&
QUICHE teama6ef0a62019-03-07 20:34:33 -05001368 peer_framer_.perspective() == Perspective::IS_SERVER) {
1369 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
QUICHE team8c1daa22019-03-13 08:33:41 -07001370 if (header.version_flag) {
1371 header.source_connection_id = connection_id_;
1372 header.source_connection_id_included = CONNECTION_ID_PRESENT;
1373 if (GetParam().version.handshake_protocol == PROTOCOL_QUIC_CRYPTO &&
1374 header.long_packet_type == ZERO_RTT_PROTECTED) {
QUICHE team548d51b2019-03-14 10:06:54 -07001375 header.nonce = &kTestDiversificationNonce;
QUICHE team8c1daa22019-03-13 08:33:41 -07001376 }
1377 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001378 }
QUICHE team2252b702019-05-14 23:55:14 -04001379 header.packet_number_length = packet_number_length_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001380 header.packet_number = QuicPacketNumber(number);
nharper46833c32019-05-15 21:33:05 -07001381 return header;
1382 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001383
nharper46833c32019-05-15 21:33:05 -07001384 std::unique_ptr<QuicPacket> ConstructDataPacket(uint64_t number,
1385 bool has_stop_waiting,
1386 EncryptionLevel level) {
1387 QuicPacketHeader header = ConstructPacketHeader(number, level);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001388 QuicFrames frames;
1389 frames.push_back(QuicFrame(frame1_));
1390 if (has_stop_waiting) {
1391 frames.push_back(QuicFrame(stop_waiting_));
1392 }
1393 return ConstructPacket(header, frames);
1394 }
1395
1396 OwningSerializedPacketPointer ConstructProbingPacket() {
1397 if (version().transport_version == QUIC_VERSION_99) {
1398 QuicPathFrameBuffer payload = {
1399 {0xde, 0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xfe}};
1400 return QuicPacketCreatorPeer::
1401 SerializePathChallengeConnectivityProbingPacket(&peer_creator_,
1402 &payload);
1403 }
1404 return QuicPacketCreatorPeer::SerializeConnectivityProbingPacket(
1405 &peer_creator_);
1406 }
1407
1408 std::unique_ptr<QuicPacket> ConstructClosePacket(uint64_t number) {
1409 QuicPacketHeader header;
1410 // Set connection_id to peer's in memory representation as this connection
1411 // close packet is created by peer_framer.
QUICHE team2252b702019-05-14 23:55:14 -04001412 if (GetQuicRestartFlag(quic_do_not_override_connection_id) &&
QUICHE teama6ef0a62019-03-07 20:34:33 -05001413 peer_framer_.perspective() == Perspective::IS_SERVER) {
QUICHE team2252b702019-05-14 23:55:14 -04001414 header.source_connection_id = connection_id_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001415 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
fayangd4291e42019-05-30 10:31:21 -07001416 if (!VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04001417 header.source_connection_id_included = CONNECTION_ID_PRESENT;
1418 }
1419 } else {
1420 header.destination_connection_id = connection_id_;
fayangd4291e42019-05-30 10:31:21 -07001421 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04001422 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1423 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001424 }
1425
QUICHE team2252b702019-05-14 23:55:14 -04001426 header.packet_number = QuicPacketNumber(number);
1427
fkastenholze9d71a82019-04-09 05:12:13 -07001428 QuicConnectionCloseFrame qccf(QUIC_PEER_GOING_AWAY);
fkastenholz72f509b2019-04-10 09:17:49 -07001429 if (peer_framer_.transport_version() == QUIC_VERSION_99) {
fkastenholz04bd4f32019-04-16 12:24:38 -07001430 // Default close-type is Google QUIC. If doing IETF/V99 then
1431 // set close type to be IETF CC/T.
fkastenholz72f509b2019-04-10 09:17:49 -07001432 qccf.close_type = IETF_QUIC_TRANSPORT_CONNECTION_CLOSE;
1433 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001434
1435 QuicFrames frames;
1436 frames.push_back(QuicFrame(&qccf));
1437 return ConstructPacket(header, frames);
1438 }
1439
1440 QuicTime::Delta DefaultRetransmissionTime() {
1441 return QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
1442 }
1443
1444 QuicTime::Delta DefaultDelayedAckTime() {
1445 return QuicTime::Delta::FromMilliseconds(kDefaultDelayedAckTimeMs);
1446 }
1447
1448 const QuicStopWaitingFrame InitStopWaitingFrame(uint64_t least_unacked) {
1449 QuicStopWaitingFrame frame;
1450 frame.least_unacked = QuicPacketNumber(least_unacked);
1451 return frame;
1452 }
1453
1454 // Construct a ack_frame that acks all packet numbers between 1 and
1455 // |largest_acked|, except |missing|.
1456 // REQUIRES: 1 <= |missing| < |largest_acked|
1457 QuicAckFrame ConstructAckFrame(uint64_t largest_acked, uint64_t missing) {
1458 return ConstructAckFrame(QuicPacketNumber(largest_acked),
1459 QuicPacketNumber(missing));
1460 }
1461
1462 QuicAckFrame ConstructAckFrame(QuicPacketNumber largest_acked,
1463 QuicPacketNumber missing) {
1464 if (missing == QuicPacketNumber(1)) {
1465 return InitAckFrame({{missing + 1, largest_acked + 1}});
1466 }
1467 return InitAckFrame(
1468 {{QuicPacketNumber(1), missing}, {missing + 1, largest_acked + 1}});
1469 }
1470
1471 // Undo nacking a packet within the frame.
1472 void AckPacket(QuicPacketNumber arrived, QuicAckFrame* frame) {
1473 EXPECT_FALSE(frame->packets.Contains(arrived));
1474 frame->packets.Add(arrived);
1475 }
1476
1477 void TriggerConnectionClose() {
1478 // Send an erroneous packet to close the connection.
QUICHE teamcd098022019-03-22 18:49:55 -07001479 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, _,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001480 ConnectionCloseSource::FROM_SELF));
QUICHE teamcd098022019-03-22 18:49:55 -07001481 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1482 // Triggers a connection by receiving ACK of unsent packet.
1483 QuicAckFrame frame = InitAckFrame(10000);
1484 ProcessAckPacket(1, &frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001485
1486 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1487 nullptr);
1488 }
1489
1490 void BlockOnNextWrite() {
1491 writer_->BlockOnNextWrite();
1492 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
1493 }
1494
1495 void SimulateNextPacketTooLarge() { writer_->SimulateNextPacketTooLarge(); }
1496
1497 void AlwaysGetPacketTooLarge() { writer_->AlwaysGetPacketTooLarge(); }
1498
1499 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
1500 writer_->SetWritePauseTimeDelta(delta);
1501 }
1502
1503 void CongestionBlockWrites() {
1504 EXPECT_CALL(*send_algorithm_, CanSend(_))
1505 .WillRepeatedly(testing::Return(false));
1506 }
1507
1508 void CongestionUnblockWrites() {
1509 EXPECT_CALL(*send_algorithm_, CanSend(_))
1510 .WillRepeatedly(testing::Return(true));
1511 }
1512
1513 void set_perspective(Perspective perspective) {
1514 connection_.set_perspective(perspective);
1515 if (perspective == Perspective::IS_SERVER) {
1516 connection_.set_can_truncate_connection_ids(true);
1517 }
1518 QuicFramerPeer::SetPerspective(&peer_framer_,
1519 InvertPerspective(perspective));
1520 }
1521
1522 void set_packets_between_probes_base(
1523 const QuicPacketCount packets_between_probes_base) {
1524 QuicConnectionPeer::SetPacketsBetweenMtuProbes(&connection_,
1525 packets_between_probes_base);
1526 QuicConnectionPeer::SetNextMtuProbeAt(
1527 &connection_, QuicPacketNumber(packets_between_probes_base));
1528 }
1529
1530 bool IsDefaultTestConfiguration() {
1531 TestParams p = GetParam();
1532 return p.ack_response == AckResponse::kImmediate &&
1533 p.version == AllSupportedVersions()[0] && p.no_stop_waiting;
1534 }
1535
1536 QuicConnectionId connection_id_;
1537 QuicFramer framer_;
1538
1539 MockSendAlgorithm* send_algorithm_;
1540 std::unique_ptr<MockLossAlgorithm> loss_algorithm_;
1541 MockClock clock_;
1542 MockRandom random_generator_;
1543 SimpleBufferAllocator buffer_allocator_;
1544 std::unique_ptr<TestConnectionHelper> helper_;
1545 std::unique_ptr<TestAlarmFactory> alarm_factory_;
1546 QuicFramer peer_framer_;
1547 QuicPacketCreator peer_creator_;
1548 std::unique_ptr<TestPacketWriter> writer_;
1549 TestConnection connection_;
1550 QuicPacketCreator* creator_;
1551 QuicPacketGenerator* generator_;
1552 QuicSentPacketManager* manager_;
1553 StrictMock<MockQuicConnectionVisitor> visitor_;
1554
1555 QuicStreamFrame frame1_;
1556 QuicStreamFrame frame2_;
nharper46833c32019-05-15 21:33:05 -07001557 QuicCryptoFrame crypto_frame_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001558 QuicAckFrame ack_;
1559 QuicStopWaitingFrame stop_waiting_;
1560 QuicPacketNumberLength packet_number_length_;
1561 QuicConnectionIdIncluded connection_id_included_;
1562
1563 SimpleSessionNotifier notifier_;
1564};
1565
1566// Run all end to end tests with all supported versions.
1567INSTANTIATE_TEST_SUITE_P(SupportedVersion,
1568 QuicConnectionTest,
1569 ::testing::ValuesIn(GetTestParams()));
1570
1571TEST_P(QuicConnectionTest, SelfAddressChangeAtClient) {
1572 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1573
1574 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
1575 EXPECT_TRUE(connection_.connected());
1576
nharper46833c32019-05-15 21:33:05 -07001577 QuicFrame frame;
1578 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1579 frame = QuicFrame(&crypto_frame_);
1580 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1581 } else {
1582 frame = QuicFrame(QuicStreamFrame(
1583 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
1584 0u, QuicStringPiece()));
1585 EXPECT_CALL(visitor_, OnStreamFrame(_));
1586 }
1587 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001588 // Cause change in self_address.
1589 QuicIpAddress host;
1590 host.FromString("1.1.1.1");
1591 QuicSocketAddress self_address(host, 123);
nharper46833c32019-05-15 21:33:05 -07001592 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1593 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1594 } else {
1595 EXPECT_CALL(visitor_, OnStreamFrame(_));
1596 }
1597 ProcessFramePacketWithAddresses(frame, self_address, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001598 EXPECT_TRUE(connection_.connected());
1599}
1600
1601TEST_P(QuicConnectionTest, SelfAddressChangeAtServer) {
1602 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1603
1604 set_perspective(Perspective::IS_SERVER);
1605 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1606
1607 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1608 EXPECT_TRUE(connection_.connected());
1609
nharper46833c32019-05-15 21:33:05 -07001610 QuicFrame frame;
1611 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1612 frame = QuicFrame(&crypto_frame_);
1613 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1614 } else {
1615 frame = QuicFrame(QuicStreamFrame(
1616 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
1617 0u, QuicStringPiece()));
1618 EXPECT_CALL(visitor_, OnStreamFrame(_));
1619 }
1620 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001621 // Cause change in self_address.
1622 QuicIpAddress host;
1623 host.FromString("1.1.1.1");
1624 QuicSocketAddress self_address(host, 123);
1625 EXPECT_CALL(visitor_, AllowSelfAddressChange()).WillOnce(Return(false));
1626 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_ERROR_MIGRATING_ADDRESS, _, _));
nharper46833c32019-05-15 21:33:05 -07001627 ProcessFramePacketWithAddresses(frame, self_address, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001628 EXPECT_FALSE(connection_.connected());
1629}
1630
1631TEST_P(QuicConnectionTest, AllowSelfAddressChangeToMappedIpv4AddressAtServer) {
1632 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1633
1634 set_perspective(Perspective::IS_SERVER);
1635 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1636
1637 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1638 EXPECT_TRUE(connection_.connected());
1639
nharper46833c32019-05-15 21:33:05 -07001640 QuicFrame frame;
1641 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1642 frame = QuicFrame(&crypto_frame_);
1643 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(3);
1644 } else {
1645 frame = QuicFrame(QuicStreamFrame(
1646 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
1647 0u, QuicStringPiece()));
1648 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(3);
1649 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001650 QuicIpAddress host;
1651 host.FromString("1.1.1.1");
1652 QuicSocketAddress self_address1(host, 443);
nharper46833c32019-05-15 21:33:05 -07001653 ProcessFramePacketWithAddresses(frame, self_address1, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001654 // Cause self_address change to mapped Ipv4 address.
1655 QuicIpAddress host2;
1656 host2.FromString(
1657 QuicStrCat("::ffff:", connection_.self_address().host().ToString()));
1658 QuicSocketAddress self_address2(host2, connection_.self_address().port());
nharper46833c32019-05-15 21:33:05 -07001659 ProcessFramePacketWithAddresses(frame, self_address2, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001660 EXPECT_TRUE(connection_.connected());
1661 // self_address change back to Ipv4 address.
nharper46833c32019-05-15 21:33:05 -07001662 ProcessFramePacketWithAddresses(frame, self_address1, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001663 EXPECT_TRUE(connection_.connected());
1664}
1665
1666TEST_P(QuicConnectionTest, ClientAddressChangeAndPacketReordered) {
1667 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1668 set_perspective(Perspective::IS_SERVER);
1669 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1670
1671 // Clear direct_peer_address.
1672 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1673 // Clear effective_peer_address, it is the same as direct_peer_address for
1674 // this test.
1675 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1676 QuicSocketAddress());
1677
nharper46833c32019-05-15 21:33:05 -07001678 QuicFrame frame;
1679 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1680 frame = QuicFrame(&crypto_frame_);
1681 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1682 } else {
1683 frame = QuicFrame(QuicStreamFrame(
1684 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
1685 0u, QuicStringPiece()));
1686 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1687 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001688 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001689 const QuicSocketAddress kNewPeerAddress =
1690 QuicSocketAddress(QuicIpAddress::Loopback6(),
1691 /*port=*/23456);
nharper46833c32019-05-15 21:33:05 -07001692 ProcessFramePacketWithAddresses(frame, kSelfAddress, kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001693 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1694 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1695
1696 // Decrease packet number to simulate out-of-order packets.
1697 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 4);
1698 // This is an old packet, do not migrate.
1699 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
nharper46833c32019-05-15 21:33:05 -07001700 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001701 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1702 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1703}
1704
1705TEST_P(QuicConnectionTest, PeerAddressChangeAtServer) {
1706 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1707 set_perspective(Perspective::IS_SERVER);
1708 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1709 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1710
1711 // Clear direct_peer_address.
1712 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1713 // Clear effective_peer_address, it is the same as direct_peer_address for
1714 // this test.
1715 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1716 QuicSocketAddress());
1717 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1718
nharper46833c32019-05-15 21:33:05 -07001719 QuicFrame frame;
1720 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1721 frame = QuicFrame(&crypto_frame_);
1722 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1723 } else {
1724 frame = QuicFrame(QuicStreamFrame(
1725 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
1726 0u, QuicStringPiece()));
1727 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1728 }
1729 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001730 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1731 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1732
1733 // Process another packet with a different peer address on server side will
1734 // start connection migration.
1735 const QuicSocketAddress kNewPeerAddress =
1736 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
1737 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
nharper46833c32019-05-15 21:33:05 -07001738 ProcessFramePacketWithAddresses(frame, kSelfAddress, kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001739 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1740 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1741}
1742
1743TEST_P(QuicConnectionTest, EffectivePeerAddressChangeAtServer) {
1744 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1745 set_perspective(Perspective::IS_SERVER);
1746 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1747 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1748
1749 // Clear direct_peer_address.
1750 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1751 // Clear effective_peer_address, it is different from direct_peer_address for
1752 // this test.
1753 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1754 QuicSocketAddress());
1755 const QuicSocketAddress kEffectivePeerAddress =
1756 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/43210);
1757 connection_.ReturnEffectivePeerAddressForNextPacket(kEffectivePeerAddress);
1758
nharper46833c32019-05-15 21:33:05 -07001759 QuicFrame frame;
1760 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1761 frame = QuicFrame(&crypto_frame_);
1762 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1763 } else {
1764 frame = QuicFrame(QuicStreamFrame(
1765 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
1766 0u, QuicStringPiece()));
1767 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1768 }
1769 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001770 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1771 EXPECT_EQ(kEffectivePeerAddress, connection_.effective_peer_address());
1772
1773 // Process another packet with the same direct peer address and different
1774 // effective peer address on server side will start connection migration.
1775 const QuicSocketAddress kNewEffectivePeerAddress =
1776 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/54321);
1777 connection_.ReturnEffectivePeerAddressForNextPacket(kNewEffectivePeerAddress);
1778 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
nharper46833c32019-05-15 21:33:05 -07001779 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001780 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1781 EXPECT_EQ(kNewEffectivePeerAddress, connection_.effective_peer_address());
1782
1783 // Process another packet with a different direct peer address and the same
1784 // effective peer address on server side will not start connection migration.
1785 const QuicSocketAddress kNewPeerAddress =
1786 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
1787 connection_.ReturnEffectivePeerAddressForNextPacket(kNewEffectivePeerAddress);
1788 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
1789 // ack_frame is used to complete the migration started by the last packet, we
1790 // need to make sure a new migration does not start after the previous one is
1791 // completed.
1792 QuicAckFrame ack_frame = InitAckFrame(1);
1793 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
1794 ProcessFramePacketWithAddresses(QuicFrame(&ack_frame), kSelfAddress,
1795 kNewPeerAddress);
1796 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1797 EXPECT_EQ(kNewEffectivePeerAddress, connection_.effective_peer_address());
1798
1799 // Process another packet with different direct peer address and different
1800 // effective peer address on server side will start connection migration.
1801 const QuicSocketAddress kNewerEffectivePeerAddress =
1802 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/65432);
1803 const QuicSocketAddress kFinalPeerAddress =
1804 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/34567);
1805 connection_.ReturnEffectivePeerAddressForNextPacket(
1806 kNewerEffectivePeerAddress);
1807 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
nharper46833c32019-05-15 21:33:05 -07001808 ProcessFramePacketWithAddresses(frame, kSelfAddress, kFinalPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001809 EXPECT_EQ(kFinalPeerAddress, connection_.peer_address());
1810 EXPECT_EQ(kNewerEffectivePeerAddress, connection_.effective_peer_address());
1811 EXPECT_EQ(PORT_CHANGE, connection_.active_effective_peer_migration_type());
1812
1813 // While the previous migration is ongoing, process another packet with the
1814 // same direct peer address and different effective peer address on server
1815 // side will start a new connection migration.
1816 const QuicSocketAddress kNewestEffectivePeerAddress =
1817 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/65430);
1818 connection_.ReturnEffectivePeerAddressForNextPacket(
1819 kNewestEffectivePeerAddress);
1820 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
1821 EXPECT_CALL(*send_algorithm_, OnConnectionMigration()).Times(1);
nharper46833c32019-05-15 21:33:05 -07001822 ProcessFramePacketWithAddresses(frame, kSelfAddress, kFinalPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001823 EXPECT_EQ(kFinalPeerAddress, connection_.peer_address());
1824 EXPECT_EQ(kNewestEffectivePeerAddress, connection_.effective_peer_address());
1825 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
1826 connection_.active_effective_peer_migration_type());
1827}
1828
1829TEST_P(QuicConnectionTest, ReceivePaddedPingAtServer) {
1830 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1831 set_perspective(Perspective::IS_SERVER);
1832 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1833 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1834
1835 // Clear direct_peer_address.
1836 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1837 // Clear effective_peer_address, it is the same as direct_peer_address for
1838 // this test.
1839 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1840 QuicSocketAddress());
1841 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1842
nharper46833c32019-05-15 21:33:05 -07001843 QuicFrame frame;
1844 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1845 frame = QuicFrame(&crypto_frame_);
1846 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1847 } else {
1848 frame = QuicFrame(QuicStreamFrame(
1849 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
1850 0u, QuicStringPiece()));
1851 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1852 }
1853 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001854 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1855 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1856
1857 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
1858 EXPECT_CALL(visitor_, OnConnectivityProbeReceived(_, _)).Times(0);
1859
1860 // Process a padded PING or PATH CHALLENGE packet with no peer address change
1861 // on server side will be ignored.
1862 OwningSerializedPacketPointer probing_packet;
1863 if (version().transport_version == QUIC_VERSION_99) {
1864 QuicPathFrameBuffer payload = {
1865 {0xde, 0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xfe}};
1866 probing_packet =
1867 QuicPacketCreatorPeer::SerializePathChallengeConnectivityProbingPacket(
1868 &peer_creator_, &payload);
1869 } else {
1870 probing_packet = QuicPacketCreatorPeer::SerializeConnectivityProbingPacket(
1871 &peer_creator_);
1872 }
1873 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
1874 QuicEncryptedPacket(probing_packet->encrypted_buffer,
1875 probing_packet->encrypted_length),
1876 clock_.Now()));
1877
1878 uint64_t num_probing_received =
1879 connection_.GetStats().num_connectivity_probing_received;
1880 ProcessReceivedPacket(kSelfAddress, kPeerAddress, *received);
1881
1882 EXPECT_EQ(num_probing_received,
1883 connection_.GetStats().num_connectivity_probing_received);
1884 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1885 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1886}
1887
1888TEST_P(QuicConnectionTest, WriteOutOfOrderQueuedPackets) {
1889 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
fayangc31c9952019-06-05 13:54:48 -07001890 if (!IsDefaultTestConfiguration()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001891 return;
1892 }
1893
1894 set_perspective(Perspective::IS_CLIENT);
1895
1896 BlockOnNextWrite();
1897
1898 QuicStreamId stream_id = 2;
1899 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
1900
1901 EXPECT_EQ(1u, connection_.NumQueuedPackets());
1902
1903 writer_->SetWritable();
1904 connection_.SendConnectivityProbingPacket(writer_.get(),
1905 connection_.peer_address());
1906
1907 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INTERNAL_ERROR,
1908 "Packet written out of order.",
1909 ConnectionCloseSource::FROM_SELF));
1910 EXPECT_QUIC_BUG(connection_.OnCanWrite(),
1911 "Attempt to write packet:1 after:2");
1912 EXPECT_FALSE(connection_.connected());
1913}
1914
1915TEST_P(QuicConnectionTest, DiscardQueuedPacketsAfterConnectionClose) {
1916 // Regression test for b/74073386.
1917 {
1918 InSequence seq;
1919 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1920 EXPECT_CALL(visitor_, OnConnectionClosed(_, _, _)).Times(1);
1921 }
1922
1923 set_perspective(Perspective::IS_CLIENT);
1924
1925 writer_->SimulateNextPacketTooLarge();
1926
1927 // This packet write should fail, which should cause the connection to close
1928 // after sending a connection close packet, then the failed packet should be
1929 // queued.
1930 connection_.SendStreamDataWithString(/*id=*/2, "foo", 0, NO_FIN);
1931
1932 EXPECT_FALSE(connection_.connected());
1933 EXPECT_EQ(1u, connection_.NumQueuedPackets());
1934
1935 EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
1936 connection_.OnCanWrite();
fayang40ec3ac2019-06-05 09:07:54 -07001937 if (GetQuicReloadableFlag(quic_check_connected_before_flush)) {
1938 EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
1939 } else {
1940 EXPECT_EQ(1u, connection_.GetStats().packets_discarded);
1941 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001942}
1943
1944TEST_P(QuicConnectionTest, ReceiveConnectivityProbingAtServer) {
1945 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1946 set_perspective(Perspective::IS_SERVER);
1947 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1948 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1949
1950 // Clear direct_peer_address.
1951 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1952 // Clear effective_peer_address, it is the same as direct_peer_address for
1953 // this test.
1954 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1955 QuicSocketAddress());
1956 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1957
nharper46833c32019-05-15 21:33:05 -07001958 QuicFrame frame;
1959 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1960 frame = QuicFrame(&crypto_frame_);
1961 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1962 } else {
1963 frame = QuicFrame(QuicStreamFrame(
1964 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
1965 0u, QuicStringPiece()));
1966 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1967 }
1968 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001969 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1970 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1971
1972 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
1973 EXPECT_CALL(visitor_, OnConnectivityProbeReceived(_, _)).Times(1);
1974
1975 // Process a padded PING packet from a new peer address on server side
1976 // is effectively receiving a connectivity probing.
1977 const QuicSocketAddress kNewPeerAddress =
1978 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
1979
1980 OwningSerializedPacketPointer probing_packet = ConstructProbingPacket();
1981 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
1982 QuicEncryptedPacket(probing_packet->encrypted_buffer,
1983 probing_packet->encrypted_length),
1984 clock_.Now()));
1985
1986 uint64_t num_probing_received =
1987 connection_.GetStats().num_connectivity_probing_received;
1988 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
1989
1990 EXPECT_EQ(num_probing_received + 1,
1991 connection_.GetStats().num_connectivity_probing_received);
1992 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1993 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1994
1995 // Process another packet with the old peer address on server side will not
1996 // start peer migration.
1997 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
nharper46833c32019-05-15 21:33:05 -07001998 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001999 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2000 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2001}
2002
2003TEST_P(QuicConnectionTest, ReceiveReorderedConnectivityProbingAtServer) {
2004 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2005 set_perspective(Perspective::IS_SERVER);
2006 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2007 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2008
2009 // Clear direct_peer_address.
2010 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2011 // Clear effective_peer_address, it is the same as direct_peer_address for
2012 // this test.
2013 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2014 QuicSocketAddress());
2015 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2016
nharper46833c32019-05-15 21:33:05 -07002017 QuicFrame frame;
2018 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2019 frame = QuicFrame(&crypto_frame_);
2020 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2021 } else {
2022 frame = QuicFrame(QuicStreamFrame(
2023 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
2024 0u, QuicStringPiece()));
2025 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2026 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002027 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
nharper46833c32019-05-15 21:33:05 -07002028 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002029 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2030 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2031
2032 // Decrease packet number to simulate out-of-order packets.
2033 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 4);
2034
2035 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2036 EXPECT_CALL(visitor_, OnConnectivityProbeReceived(_, _)).Times(1);
2037
2038 // Process a padded PING packet from a new peer address on server side
2039 // is effectively receiving a connectivity probing, even if a newer packet has
2040 // been received before this one.
2041 const QuicSocketAddress kNewPeerAddress =
2042 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2043
2044 OwningSerializedPacketPointer probing_packet = ConstructProbingPacket();
2045 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2046 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2047 probing_packet->encrypted_length),
2048 clock_.Now()));
2049
2050 uint64_t num_probing_received =
2051 connection_.GetStats().num_connectivity_probing_received;
2052 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2053
2054 EXPECT_EQ(num_probing_received + 1,
2055 connection_.GetStats().num_connectivity_probing_received);
2056 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2057 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2058}
2059
2060TEST_P(QuicConnectionTest, MigrateAfterProbingAtServer) {
2061 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2062 set_perspective(Perspective::IS_SERVER);
2063 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2064 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2065
2066 // Clear direct_peer_address.
2067 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2068 // Clear effective_peer_address, it is the same as direct_peer_address for
2069 // this test.
2070 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2071 QuicSocketAddress());
2072 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2073
nharper46833c32019-05-15 21:33:05 -07002074 QuicFrame frame;
2075 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2076 frame = QuicFrame(&crypto_frame_);
2077 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2078 } else {
2079 frame = QuicFrame(QuicStreamFrame(
2080 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
2081 0u, QuicStringPiece()));
2082 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2083 }
2084 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002085 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2086 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2087
2088 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2089 EXPECT_CALL(visitor_, OnConnectivityProbeReceived(_, _)).Times(1);
2090
2091 // Process a padded PING packet from a new peer address on server side
2092 // is effectively receiving a connectivity probing.
2093 const QuicSocketAddress kNewPeerAddress =
2094 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2095
2096 OwningSerializedPacketPointer probing_packet = ConstructProbingPacket();
2097 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2098 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2099 probing_packet->encrypted_length),
2100 clock_.Now()));
2101 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2102 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2103 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2104
2105 // Process another non-probing packet with the new peer address on server
2106 // side will start peer migration.
2107 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2108
nharper46833c32019-05-15 21:33:05 -07002109 ProcessFramePacketWithAddresses(frame, kSelfAddress, kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002110 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2111 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2112}
2113
2114TEST_P(QuicConnectionTest, ReceivePaddedPingAtClient) {
2115 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2116 set_perspective(Perspective::IS_CLIENT);
2117 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2118
2119 // Clear direct_peer_address.
2120 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2121 // Clear effective_peer_address, it is the same as direct_peer_address for
2122 // this test.
2123 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2124 QuicSocketAddress());
2125 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2126
nharper46833c32019-05-15 21:33:05 -07002127 QuicFrame frame;
2128 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2129 frame = QuicFrame(&crypto_frame_);
2130 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2131 } else {
2132 frame = QuicFrame(QuicStreamFrame(
2133 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
2134 0u, QuicStringPiece()));
2135 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2136 }
2137 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002138 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2139 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2140
2141 // Client takes all padded PING packet as speculative connectivity
2142 // probing packet, and reports to visitor.
2143 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2144 EXPECT_CALL(visitor_, OnConnectivityProbeReceived(_, _)).Times(1);
2145
2146 OwningSerializedPacketPointer probing_packet = ConstructProbingPacket();
2147 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2148 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2149 probing_packet->encrypted_length),
2150 clock_.Now()));
2151 uint64_t num_probing_received =
2152 connection_.GetStats().num_connectivity_probing_received;
2153 ProcessReceivedPacket(kSelfAddress, kPeerAddress, *received);
2154
2155 EXPECT_EQ(num_probing_received,
2156 connection_.GetStats().num_connectivity_probing_received);
2157 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2158 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2159}
2160
2161TEST_P(QuicConnectionTest, ReceiveConnectivityProbingAtClient) {
2162 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2163 set_perspective(Perspective::IS_CLIENT);
2164 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2165
2166 // Clear direct_peer_address.
2167 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2168 // Clear effective_peer_address, it is the same as direct_peer_address for
2169 // this test.
2170 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2171 QuicSocketAddress());
2172 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2173
nharper46833c32019-05-15 21:33:05 -07002174 QuicFrame frame;
2175 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2176 frame = QuicFrame(&crypto_frame_);
2177 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2178 } else {
2179 frame = QuicFrame(QuicStreamFrame(
2180 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
2181 0u, QuicStringPiece()));
2182 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2183 }
2184 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002185 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2186 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2187
2188 // Process a padded PING packet with a different self address on client side
2189 // is effectively receiving a connectivity probing.
2190 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2191 EXPECT_CALL(visitor_, OnConnectivityProbeReceived(_, _)).Times(1);
2192
2193 const QuicSocketAddress kNewSelfAddress =
2194 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2195
2196 OwningSerializedPacketPointer probing_packet = ConstructProbingPacket();
2197 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2198 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2199 probing_packet->encrypted_length),
2200 clock_.Now()));
2201 uint64_t num_probing_received =
2202 connection_.GetStats().num_connectivity_probing_received;
2203 ProcessReceivedPacket(kNewSelfAddress, kPeerAddress, *received);
2204
2205 EXPECT_EQ(num_probing_received + 1,
2206 connection_.GetStats().num_connectivity_probing_received);
2207 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2208 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2209}
2210
2211TEST_P(QuicConnectionTest, PeerAddressChangeAtClient) {
2212 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2213 set_perspective(Perspective::IS_CLIENT);
2214 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2215
2216 // Clear direct_peer_address.
2217 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2218 // Clear effective_peer_address, it is the same as direct_peer_address for
2219 // this test.
2220 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2221 QuicSocketAddress());
2222 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2223
nharper46833c32019-05-15 21:33:05 -07002224 QuicFrame frame;
2225 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2226 frame = QuicFrame(&crypto_frame_);
2227 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2228 } else {
2229 frame = QuicFrame(QuicStreamFrame(
2230 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
2231 0u, QuicStringPiece()));
2232 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2233 }
2234 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002235 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2236 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2237
2238 // Process another packet with a different peer address on client side will
2239 // only update peer address.
2240 const QuicSocketAddress kNewPeerAddress =
2241 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2242 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
nharper46833c32019-05-15 21:33:05 -07002243 ProcessFramePacketWithAddresses(frame, kSelfAddress, kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002244 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2245 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2246}
2247
2248TEST_P(QuicConnectionTest, MaxPacketSize) {
2249 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2250 EXPECT_EQ(1350u, connection_.max_packet_length());
2251}
2252
2253TEST_P(QuicConnectionTest, SmallerServerMaxPacketSize) {
2254 TestConnection connection(TestConnectionId(), kPeerAddress, helper_.get(),
2255 alarm_factory_.get(), writer_.get(),
2256 Perspective::IS_SERVER, version());
2257 EXPECT_EQ(Perspective::IS_SERVER, connection.perspective());
2258 EXPECT_EQ(1000u, connection.max_packet_length());
2259}
2260
2261TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSize) {
2262 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2263
2264 set_perspective(Perspective::IS_SERVER);
2265 connection_.SetMaxPacketLength(1000);
2266
2267 QuicPacketHeader header;
2268 header.destination_connection_id = connection_id_;
2269 header.version_flag = true;
2270 header.packet_number = QuicPacketNumber(1);
2271
2272 if (QuicVersionHasLongHeaderLengths(
2273 peer_framer_.version().transport_version)) {
2274 header.long_packet_type = INITIAL;
2275 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
2276 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
2277 }
2278
2279 QuicFrames frames;
2280 QuicPaddingFrame padding;
nharper46833c32019-05-15 21:33:05 -07002281 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2282 frames.push_back(QuicFrame(&crypto_frame_));
2283 } else {
2284 frames.push_back(QuicFrame(frame1_));
2285 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002286 frames.push_back(QuicFrame(padding));
2287 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
dschinazi66dea072019-04-09 11:41:06 -07002288 char buffer[kMaxOutgoingPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07002289 size_t encrypted_length =
2290 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12),
dschinazi66dea072019-04-09 11:41:06 -07002291 *packet, buffer, kMaxOutgoingPacketSize);
2292 EXPECT_EQ(kMaxOutgoingPacketSize, encrypted_length);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002293
2294 framer_.set_version(version());
nharper46833c32019-05-15 21:33:05 -07002295 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2296 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
2297 } else {
2298 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2299 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002300 connection_.ProcessUdpPacket(
2301 kSelfAddress, kPeerAddress,
2302 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
2303
dschinazi66dea072019-04-09 11:41:06 -07002304 EXPECT_EQ(kMaxOutgoingPacketSize, connection_.max_packet_length());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002305}
2306
2307TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSizeWhileWriterLimited) {
2308 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2309
2310 const QuicByteCount lower_max_packet_size = 1240;
2311 writer_->set_max_packet_size(lower_max_packet_size);
2312 set_perspective(Perspective::IS_SERVER);
2313 connection_.SetMaxPacketLength(1000);
2314 EXPECT_EQ(1000u, connection_.max_packet_length());
2315
2316 QuicPacketHeader header;
2317 header.destination_connection_id = connection_id_;
2318 header.version_flag = true;
2319 header.packet_number = QuicPacketNumber(1);
2320
2321 if (QuicVersionHasLongHeaderLengths(
2322 peer_framer_.version().transport_version)) {
2323 header.long_packet_type = INITIAL;
2324 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
2325 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
2326 }
2327
2328 QuicFrames frames;
2329 QuicPaddingFrame padding;
nharper46833c32019-05-15 21:33:05 -07002330 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2331 frames.push_back(QuicFrame(&crypto_frame_));
2332 } else {
2333 frames.push_back(QuicFrame(frame1_));
2334 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002335 frames.push_back(QuicFrame(padding));
2336 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
dschinazi66dea072019-04-09 11:41:06 -07002337 char buffer[kMaxOutgoingPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07002338 size_t encrypted_length =
2339 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12),
dschinazi66dea072019-04-09 11:41:06 -07002340 *packet, buffer, kMaxOutgoingPacketSize);
2341 EXPECT_EQ(kMaxOutgoingPacketSize, encrypted_length);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002342
2343 framer_.set_version(version());
nharper46833c32019-05-15 21:33:05 -07002344 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2345 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
2346 } else {
2347 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2348 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002349 connection_.ProcessUdpPacket(
2350 kSelfAddress, kPeerAddress,
2351 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
2352
2353 // Here, the limit imposed by the writer is lower than the size of the packet
2354 // received, so the writer max packet size is used.
2355 EXPECT_EQ(lower_max_packet_size, connection_.max_packet_length());
2356}
2357
2358TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriter) {
2359 const QuicByteCount lower_max_packet_size = 1240;
2360 writer_->set_max_packet_size(lower_max_packet_size);
2361
2362 static_assert(lower_max_packet_size < kDefaultMaxPacketSize,
2363 "Default maximum packet size is too low");
2364 connection_.SetMaxPacketLength(kDefaultMaxPacketSize);
2365
2366 EXPECT_EQ(lower_max_packet_size, connection_.max_packet_length());
2367}
2368
2369TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriterForNewConnection) {
2370 const QuicConnectionId connection_id = TestConnectionId(17);
2371 const QuicByteCount lower_max_packet_size = 1240;
2372 writer_->set_max_packet_size(lower_max_packet_size);
2373 TestConnection connection(connection_id, kPeerAddress, helper_.get(),
2374 alarm_factory_.get(), writer_.get(),
2375 Perspective::IS_CLIENT, version());
2376 EXPECT_EQ(Perspective::IS_CLIENT, connection.perspective());
2377 EXPECT_EQ(lower_max_packet_size, connection.max_packet_length());
2378}
2379
2380TEST_P(QuicConnectionTest, PacketsInOrder) {
2381 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2382
2383 ProcessPacket(1);
fayangc31c9952019-06-05 13:54:48 -07002384 EXPECT_EQ(QuicPacketNumber(1u), LargestAcked(connection_.ack_frame()));
2385 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002386
2387 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07002388 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(connection_.ack_frame()));
2389 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002390
2391 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002392 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
2393 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002394}
2395
2396TEST_P(QuicConnectionTest, PacketsOutOfOrder) {
2397 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2398
2399 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002400 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002401 EXPECT_TRUE(IsMissing(2));
2402 EXPECT_TRUE(IsMissing(1));
2403
2404 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07002405 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002406 EXPECT_FALSE(IsMissing(2));
2407 EXPECT_TRUE(IsMissing(1));
2408
2409 ProcessPacket(1);
fayangc31c9952019-06-05 13:54:48 -07002410 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002411 EXPECT_FALSE(IsMissing(2));
2412 EXPECT_FALSE(IsMissing(1));
2413}
2414
2415TEST_P(QuicConnectionTest, DuplicatePacket) {
2416 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2417
2418 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002419 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002420 EXPECT_TRUE(IsMissing(2));
2421 EXPECT_TRUE(IsMissing(1));
2422
2423 // Send packet 3 again, but do not set the expectation that
2424 // the visitor OnStreamFrame() will be called.
2425 ProcessDataPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002426 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002427 EXPECT_TRUE(IsMissing(2));
2428 EXPECT_TRUE(IsMissing(1));
2429}
2430
2431TEST_P(QuicConnectionTest, PacketsOutOfOrderWithAdditionsAndLeastAwaiting) {
QUICHE teamcd098022019-03-22 18:49:55 -07002432 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2433 return;
2434 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002435 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2436
2437 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002438 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002439 EXPECT_TRUE(IsMissing(2));
2440 EXPECT_TRUE(IsMissing(1));
2441
2442 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07002443 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002444 EXPECT_TRUE(IsMissing(1));
2445
2446 ProcessPacket(5);
fayangc31c9952019-06-05 13:54:48 -07002447 EXPECT_EQ(QuicPacketNumber(5u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002448 EXPECT_TRUE(IsMissing(1));
2449 EXPECT_TRUE(IsMissing(4));
2450
2451 // Pretend at this point the client has gotten acks for 2 and 3 and 1 is a
2452 // packet the peer will not retransmit. It indicates this by sending 'least
2453 // awaiting' is 4. The connection should then realize 1 will not be
2454 // retransmitted, and will remove it from the missing list.
2455 QuicAckFrame frame = InitAckFrame(1);
2456 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
2457 ProcessAckPacket(6, &frame);
2458
2459 // Force an ack to be sent.
2460 SendAckPacketToPeer();
2461 EXPECT_TRUE(IsMissing(4));
2462}
2463
2464TEST_P(QuicConnectionTest, RejectPacketTooFarOut) {
QUICHE teamcd098022019-03-22 18:49:55 -07002465 if (GetQuicReloadableFlag(quic_use_uber_received_packet_manager)) {
2466 return;
2467 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002468 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_PACKET_HEADER, _,
2469 ConnectionCloseSource::FROM_SELF));
2470
2471 // Call ProcessDataPacket rather than ProcessPacket, as we should not get a
2472 // packet call to the visitor.
2473 if (GetQuicRestartFlag(quic_enable_accept_random_ipn)) {
2474 ProcessDataPacket(MaxRandomInitialPacketNumber() + 6000);
2475 } else {
2476 ProcessDataPacket(6000);
2477 }
2478 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
2479 nullptr);
2480}
2481
2482TEST_P(QuicConnectionTest, RejectUnencryptedStreamData) {
2483 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
2484 if (!IsDefaultTestConfiguration()) {
2485 return;
2486 }
2487
2488 // Process an unencrypted packet from the non-crypto stream.
2489 frame1_.stream_id = 3;
2490 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2491 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_UNENCRYPTED_STREAM_DATA, _,
2492 ConnectionCloseSource::FROM_SELF));
nharper2c9f02a2019-05-08 10:25:50 -07002493 EXPECT_QUIC_PEER_BUG(ProcessDataPacketAtLevel(1, false, ENCRYPTION_INITIAL),
2494 "");
QUICHE teama6ef0a62019-03-07 20:34:33 -05002495 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
2496 nullptr);
2497 const std::vector<QuicConnectionCloseFrame>& connection_close_frames =
2498 writer_->connection_close_frames();
nharper2c9f02a2019-05-08 10:25:50 -07002499 ASSERT_EQ(1u, connection_close_frames.size());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002500 EXPECT_EQ(QUIC_UNENCRYPTED_STREAM_DATA,
fkastenholze9d71a82019-04-09 05:12:13 -07002501 connection_close_frames[0].quic_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002502}
2503
2504TEST_P(QuicConnectionTest, OutOfOrderReceiptCausesAckSend) {
2505 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2506
2507 ProcessPacket(3);
2508 if (GetQuicRestartFlag(quic_enable_accept_random_ipn)) {
2509 // Should not cause an ack.
2510 EXPECT_EQ(0u, writer_->packets_write_attempts());
2511 } else {
2512 // Should ack immediately since we have missing packets.
2513 EXPECT_EQ(1u, writer_->packets_write_attempts());
2514 }
2515
2516 ProcessPacket(2);
2517 if (GetQuicRestartFlag(quic_enable_accept_random_ipn)) {
2518 // Should ack immediately, since this fills the last hole.
2519 EXPECT_EQ(1u, writer_->packets_write_attempts());
2520 } else {
2521 // Should ack immediately since we have missing packets.
2522 EXPECT_EQ(2u, writer_->packets_write_attempts());
2523 }
2524
2525 ProcessPacket(1);
2526 // Should ack immediately, since this fills the last hole.
2527 if (GetQuicRestartFlag(quic_enable_accept_random_ipn)) {
2528 EXPECT_EQ(2u, writer_->packets_write_attempts());
2529 } else {
2530 EXPECT_EQ(3u, writer_->packets_write_attempts());
2531 }
2532
2533 ProcessPacket(4);
2534 // Should not cause an ack.
2535 if (GetQuicRestartFlag(quic_enable_accept_random_ipn)) {
2536 EXPECT_EQ(2u, writer_->packets_write_attempts());
2537 } else {
2538 EXPECT_EQ(3u, writer_->packets_write_attempts());
2539 }
2540}
2541
2542TEST_P(QuicConnectionTest, OutOfOrderAckReceiptCausesNoAck) {
2543 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2544
2545 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
2546 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
2547 EXPECT_EQ(2u, writer_->packets_write_attempts());
2548
2549 QuicAckFrame ack1 = InitAckFrame(1);
2550 QuicAckFrame ack2 = InitAckFrame(2);
2551 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2552 ProcessAckPacket(2, &ack2);
2553 // Should ack immediately since we have missing packets.
2554 EXPECT_EQ(2u, writer_->packets_write_attempts());
2555
2556 ProcessAckPacket(1, &ack1);
2557 // Should not ack an ack filling a missing packet.
2558 EXPECT_EQ(2u, writer_->packets_write_attempts());
2559}
2560
2561TEST_P(QuicConnectionTest, AckReceiptCausesAckSend) {
2562 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2563 QuicPacketNumber original, second;
2564
2565 QuicByteCount packet_size =
2566 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &original); // 1st packet.
2567 SendStreamDataToPeer(3, "bar", 3, NO_FIN, &second); // 2nd packet.
2568
2569 QuicAckFrame frame = InitAckFrame({{second, second + 1}});
2570 // First nack triggers early retransmit.
2571 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07002572 lost_packets.push_back(LostPacket(original, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002573 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
2574 .WillOnce(SetArgPointee<5>(lost_packets));
2575 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2576 QuicPacketNumber retransmission;
2577 // Packet 1 is short header for IETF QUIC because the encryption level
2578 // switched to ENCRYPTION_FORWARD_SECURE in SendStreamDataToPeer.
fayangd4291e42019-05-30 10:31:21 -07002579 EXPECT_CALL(*send_algorithm_,
2580 OnPacketSent(_, _, _,
2581 VersionHasIetfInvariantHeader(
2582 GetParam().version.transport_version)
2583 ? packet_size
2584 : packet_size - kQuicVersionSize,
2585 _))
QUICHE teama6ef0a62019-03-07 20:34:33 -05002586 .WillOnce(SaveArg<2>(&retransmission));
2587
2588 ProcessAckPacket(&frame);
2589
2590 QuicAckFrame frame2 = ConstructAckFrame(retransmission, original);
2591 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2592 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
2593 ProcessAckPacket(&frame2);
2594
2595 // Now if the peer sends an ack which still reports the retransmitted packet
2596 // as missing, that will bundle an ack with data after two acks in a row
2597 // indicate the high water mark needs to be raised.
2598 EXPECT_CALL(*send_algorithm_,
2599 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA));
2600 connection_.SendStreamDataWithString(3, "foo", 6, NO_FIN);
2601 // No ack sent.
nharper55fa6132019-05-07 19:37:21 -07002602 size_t padding_frame_count = writer_->padding_frames().size();
2603 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002604 EXPECT_EQ(1u, writer_->stream_frames().size());
2605
2606 // No more packet loss for the rest of the test.
2607 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
2608 .Times(AnyNumber());
2609 ProcessAckPacket(&frame2);
2610 EXPECT_CALL(*send_algorithm_,
2611 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA));
fayang03916692019-05-22 17:57:18 -07002612 connection_.SendStreamDataWithString(3, "foofoofoo", 9, NO_FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002613 // Ack bundled.
2614 if (GetParam().no_stop_waiting) {
fayang03916692019-05-22 17:57:18 -07002615 if (GetQuicReloadableFlag(quic_simplify_stop_waiting)) {
2616 // Do not ACK acks.
2617 EXPECT_EQ(1u, writer_->frame_count());
2618 } else {
2619 EXPECT_EQ(2u, writer_->frame_count());
2620 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002621 } else {
2622 EXPECT_EQ(3u, writer_->frame_count());
2623 }
2624 EXPECT_EQ(1u, writer_->stream_frames().size());
fayang03916692019-05-22 17:57:18 -07002625 if (GetParam().no_stop_waiting &&
2626 GetQuicReloadableFlag(quic_simplify_stop_waiting)) {
2627 EXPECT_TRUE(writer_->ack_frames().empty());
2628 } else {
2629 EXPECT_FALSE(writer_->ack_frames().empty());
2630 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002631
2632 // But an ack with no missing packets will not send an ack.
2633 AckPacket(original, &frame2);
2634 ProcessAckPacket(&frame2);
2635 ProcessAckPacket(&frame2);
2636}
2637
2638TEST_P(QuicConnectionTest, AckSentEveryNthPacket) {
2639 connection_.set_ack_frequency_before_ack_decimation(3);
2640
2641 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2642 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(39);
2643
2644 // Expect 13 acks, every 3rd packet.
2645 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(13);
2646 // Receives packets 1 - 39.
2647 for (size_t i = 1; i <= 39; ++i) {
2648 ProcessDataPacket(i);
2649 }
2650}
2651
2652TEST_P(QuicConnectionTest, AckDecimationReducesAcks) {
2653 const size_t kMinRttMs = 40;
2654 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
2655 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
2656 QuicTime::Delta::Zero(), QuicTime::Zero());
2657 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
2658
2659 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
2660
2661 // Start ack decimation from 10th packet.
2662 connection_.set_min_received_before_ack_decimation(10);
2663
2664 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2665 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(30);
2666
2667 // Expect 6 acks: 5 acks between packets 1-10, and ack at 20.
2668 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(6);
2669 // Receives packets 1 - 29.
2670 for (size_t i = 1; i <= 29; ++i) {
2671 ProcessDataPacket(i);
2672 }
2673
2674 // We now receive the 30th packet, and so we send an ack.
2675 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2676 ProcessDataPacket(30);
2677}
2678
2679TEST_P(QuicConnectionTest, AckNeedsRetransmittableFrames) {
ianswett68cf0042019-05-09 08:37:58 -07002680 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002681 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2682 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(99);
2683
2684 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(19);
2685 // Receives packets 1 - 39.
2686 for (size_t i = 1; i <= 39; ++i) {
2687 ProcessDataPacket(i);
2688 }
2689 // Receiving Packet 40 causes 20th ack to send. Session is informed and adds
2690 // WINDOW_UPDATE.
2691 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
2692 .WillOnce(Invoke([this]() {
2693 connection_.SendControlFrame(
2694 QuicFrame(new QuicWindowUpdateFrame(1, 0, 0)));
2695 }));
2696 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2697 EXPECT_EQ(0u, writer_->window_update_frames().size());
2698 ProcessDataPacket(40);
2699 EXPECT_EQ(1u, writer_->window_update_frames().size());
2700
2701 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(9);
2702 // Receives packets 41 - 59.
2703 for (size_t i = 41; i <= 59; ++i) {
2704 ProcessDataPacket(i);
2705 }
2706 // Send a packet containing stream frame.
QUICHE team8c1daa22019-03-13 08:33:41 -07002707 SendStreamDataToPeer(
nharper46833c32019-05-15 21:33:05 -07002708 QuicUtils::GetFirstBidirectionalStreamId(
2709 connection_.version().transport_version, Perspective::IS_CLIENT),
QUICHE team8c1daa22019-03-13 08:33:41 -07002710 "bar", 0, NO_FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002711
2712 // Session will not be informed until receiving another 20 packets.
2713 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(19);
2714 for (size_t i = 60; i <= 98; ++i) {
2715 ProcessDataPacket(i);
2716 EXPECT_EQ(0u, writer_->window_update_frames().size());
2717 }
2718 // Session does not add a retransmittable frame.
2719 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
2720 .WillOnce(Invoke([this]() {
2721 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
2722 }));
2723 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2724 EXPECT_EQ(0u, writer_->ping_frames().size());
2725 ProcessDataPacket(99);
2726 EXPECT_EQ(0u, writer_->window_update_frames().size());
2727 // A ping frame will be added.
2728 EXPECT_EQ(1u, writer_->ping_frames().size());
2729}
2730
2731TEST_P(QuicConnectionTest, LeastUnackedLower) {
fayangc31c9952019-06-05 13:54:48 -07002732 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002733 return;
2734 }
2735 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2736
2737 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
2738 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
2739 SendStreamDataToPeer(1, "eep", 6, NO_FIN, nullptr);
2740
2741 // Start out saying the least unacked is 2.
2742 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
2743 ProcessStopWaitingPacket(InitStopWaitingFrame(2));
2744
2745 // Change it to 1, but lower the packet number to fake out-of-order packets.
2746 // This should be fine.
2747 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 1);
2748 // The scheduler will not process out of order acks, but all packet processing
2749 // causes the connection to try to write.
2750 if (!GetParam().no_stop_waiting) {
2751 EXPECT_CALL(visitor_, OnCanWrite());
2752 }
2753 ProcessStopWaitingPacket(InitStopWaitingFrame(1));
2754
2755 // Now claim it's one, but set the ordering so it was sent "after" the first
2756 // one. This should cause a connection error.
2757 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 7);
2758 if (!GetParam().no_stop_waiting) {
2759 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2760 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_STOP_WAITING_DATA, _,
2761 ConnectionCloseSource::FROM_SELF));
2762 }
2763 ProcessStopWaitingPacket(InitStopWaitingFrame(1));
2764}
2765
2766TEST_P(QuicConnectionTest, TooManySentPackets) {
2767 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2768
2769 QuicPacketCount max_tracked_packets = 50;
2770 QuicConnectionPeer::SetMaxTrackedPackets(&connection_, max_tracked_packets);
2771
2772 const int num_packets = max_tracked_packets + 5;
2773
2774 for (int i = 0; i < num_packets; ++i) {
2775 SendStreamDataToPeer(1, "foo", 3 * i, NO_FIN, nullptr);
2776 }
2777
2778 // Ack packet 1, which leaves more than the limit outstanding.
2779 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2780 EXPECT_CALL(visitor_,
2781 OnConnectionClosed(QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS, _,
2782 ConnectionCloseSource::FROM_SELF));
2783
2784 // Nack the first packet and ack the rest, leaving a huge gap.
2785 QuicAckFrame frame1 = ConstructAckFrame(num_packets, 1);
2786 ProcessAckPacket(&frame1);
2787}
2788
2789TEST_P(QuicConnectionTest, LargestObservedLower) {
2790 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2791
2792 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
2793 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
2794 SendStreamDataToPeer(1, "eep", 6, NO_FIN, nullptr);
2795 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2796
2797 // Start out saying the largest observed is 2.
2798 QuicAckFrame frame1 = InitAckFrame(1);
2799 QuicAckFrame frame2 = InitAckFrame(2);
2800 ProcessAckPacket(&frame2);
2801
QUICHE team9929cc42019-03-13 08:17:43 -07002802 if (GetQuicReloadableFlag(quic_tolerate_reneging)) {
2803 EXPECT_CALL(visitor_, OnCanWrite());
2804 } else {
2805 // Now change it to 1, and it should cause a connection error.
2806 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, _,
2807 ConnectionCloseSource::FROM_SELF));
2808 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
2809 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002810 ProcessAckPacket(&frame1);
2811}
2812
2813TEST_P(QuicConnectionTest, AckUnsentData) {
2814 // Ack a packet which has not been sent.
2815 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, _,
2816 ConnectionCloseSource::FROM_SELF));
2817 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2818 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2819 QuicAckFrame frame = InitAckFrame(1);
2820 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
2821 ProcessAckPacket(&frame);
2822}
2823
2824TEST_P(QuicConnectionTest, BasicSending) {
QUICHE teamcd098022019-03-22 18:49:55 -07002825 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2826 return;
2827 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002828 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2829 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2830 ProcessDataPacket(1);
2831 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
2832 QuicPacketNumber last_packet;
2833 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
2834 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
2835 SendAckPacketToPeer(); // Packet 2
2836
2837 if (GetParam().no_stop_waiting) {
2838 // Expect no stop waiting frame is sent.
2839 EXPECT_FALSE(least_unacked().IsInitialized());
2840 } else {
2841 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
2842 }
2843
2844 SendAckPacketToPeer(); // Packet 3
2845 if (GetParam().no_stop_waiting) {
2846 // Expect no stop waiting frame is sent.
2847 EXPECT_FALSE(least_unacked().IsInitialized());
2848 } else {
2849 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
2850 }
2851
2852 SendStreamDataToPeer(1, "bar", 3, NO_FIN, &last_packet); // Packet 4
2853 EXPECT_EQ(QuicPacketNumber(4u), last_packet);
2854 SendAckPacketToPeer(); // Packet 5
2855 if (GetParam().no_stop_waiting) {
2856 // Expect no stop waiting frame is sent.
2857 EXPECT_FALSE(least_unacked().IsInitialized());
2858 } else {
2859 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
2860 }
2861
2862 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2863
2864 // Peer acks up to packet 3.
2865 QuicAckFrame frame = InitAckFrame(3);
2866 ProcessAckPacket(&frame);
2867 SendAckPacketToPeer(); // Packet 6
2868
2869 // As soon as we've acked one, we skip ack packets 2 and 3 and note lack of
2870 // ack for 4.
2871 if (GetParam().no_stop_waiting) {
2872 // Expect no stop waiting frame is sent.
2873 EXPECT_FALSE(least_unacked().IsInitialized());
2874 } else {
2875 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
2876 }
2877
2878 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2879
2880 // Peer acks up to packet 4, the last packet.
2881 QuicAckFrame frame2 = InitAckFrame(6);
2882 ProcessAckPacket(&frame2); // Acks don't instigate acks.
2883
2884 // Verify that we did not send an ack.
2885 EXPECT_EQ(QuicPacketNumber(6u), writer_->header().packet_number);
2886
2887 // So the last ack has not changed.
2888 if (GetParam().no_stop_waiting) {
2889 // Expect no stop waiting frame is sent.
2890 EXPECT_FALSE(least_unacked().IsInitialized());
2891 } else {
2892 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
2893 }
2894
2895 // If we force an ack, we shouldn't change our retransmit state.
2896 SendAckPacketToPeer(); // Packet 7
2897 if (GetParam().no_stop_waiting) {
2898 // Expect no stop waiting frame is sent.
2899 EXPECT_FALSE(least_unacked().IsInitialized());
2900 } else {
2901 EXPECT_EQ(QuicPacketNumber(7u), least_unacked());
2902 }
2903
2904 // But if we send more data it should.
2905 SendStreamDataToPeer(1, "eep", 6, NO_FIN, &last_packet); // Packet 8
2906 EXPECT_EQ(QuicPacketNumber(8u), last_packet);
2907 SendAckPacketToPeer(); // Packet 9
2908 if (GetParam().no_stop_waiting) {
2909 // Expect no stop waiting frame is sent.
2910 EXPECT_FALSE(least_unacked().IsInitialized());
2911 } else {
2912 EXPECT_EQ(QuicPacketNumber(7u), least_unacked());
2913 }
2914}
2915
2916// QuicConnection should record the packet sent-time prior to sending the
2917// packet.
2918TEST_P(QuicConnectionTest, RecordSentTimeBeforePacketSent) {
2919 // We're using a MockClock for the tests, so we have complete control over the
2920 // time.
2921 // Our recorded timestamp for the last packet sent time will be passed in to
2922 // the send_algorithm. Make sure that it is set to the correct value.
2923 QuicTime actual_recorded_send_time = QuicTime::Zero();
2924 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2925 .WillOnce(SaveArg<0>(&actual_recorded_send_time));
2926
2927 // First send without any pause and check the result.
2928 QuicTime expected_recorded_send_time = clock_.Now();
2929 connection_.SendStreamDataWithString(1, "foo", 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 // Now pause during the write, and check the results.
2935 actual_recorded_send_time = QuicTime::Zero();
2936 const QuicTime::Delta write_pause_time_delta =
2937 QuicTime::Delta::FromMilliseconds(5000);
2938 SetWritePauseTimeDelta(write_pause_time_delta);
2939 expected_recorded_send_time = clock_.Now();
2940
2941 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2942 .WillOnce(SaveArg<0>(&actual_recorded_send_time));
2943 connection_.SendStreamDataWithString(2, "baz", 0, NO_FIN);
2944 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
2945 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
2946 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
2947}
2948
2949TEST_P(QuicConnectionTest, FramePacking) {
2950 // Send two stream frames in 1 packet by queueing them.
2951 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2952 {
2953 QuicConnection::ScopedPacketFlusher flusher(&connection_,
2954 QuicConnection::SEND_ACK);
2955 connection_.SendStreamData3();
2956 connection_.SendStreamData5();
2957 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2958 }
2959 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2960 EXPECT_FALSE(connection_.HasQueuedData());
2961
2962 // Parse the last packet and ensure it's an ack and two stream frames from
2963 // two different streams.
2964 if (GetParam().no_stop_waiting) {
2965 EXPECT_EQ(2u, writer_->frame_count());
2966 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
2967 } else {
2968 EXPECT_EQ(2u, writer_->frame_count());
2969 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
2970 }
2971
2972 EXPECT_TRUE(writer_->ack_frames().empty());
2973
2974 ASSERT_EQ(2u, writer_->stream_frames().size());
2975 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
2976 writer_->stream_frames()[0]->stream_id);
2977 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
2978 writer_->stream_frames()[1]->stream_id);
2979}
2980
2981TEST_P(QuicConnectionTest, FramePackingNonCryptoThenCrypto) {
2982 // Send two stream frames (one non-crypto, then one crypto) in 2 packets by
2983 // queueing them.
2984 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2985 {
2986 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
2987 QuicConnection::ScopedPacketFlusher flusher(&connection_,
2988 QuicConnection::SEND_ACK);
2989 connection_.SendStreamData3();
2990 connection_.SendCryptoStreamData();
2991 }
2992 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2993 EXPECT_FALSE(connection_.HasQueuedData());
2994
2995 // Parse the last packet and ensure it's the crypto stream frame.
2996 EXPECT_EQ(2u, writer_->frame_count());
2997 ASSERT_EQ(1u, writer_->padding_frames().size());
QUICHE teamea740082019-03-11 17:58:43 -07002998 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002999 ASSERT_EQ(1u, writer_->stream_frames().size());
3000 EXPECT_EQ(QuicUtils::GetCryptoStreamId(connection_.transport_version()),
3001 writer_->stream_frames()[0]->stream_id);
3002 } else {
3003 EXPECT_EQ(1u, writer_->crypto_frames().size());
3004 }
3005}
3006
3007TEST_P(QuicConnectionTest, FramePackingCryptoThenNonCrypto) {
3008 // Send two stream frames (one crypto, then one non-crypto) in 2 packets by
3009 // queueing them.
3010 {
3011 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3012 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3013 QuicConnection::ScopedPacketFlusher flusher(&connection_,
3014 QuicConnection::SEND_ACK);
3015 connection_.SendCryptoStreamData();
3016 connection_.SendStreamData3();
3017 }
3018 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3019 EXPECT_FALSE(connection_.HasQueuedData());
3020
3021 // Parse the last packet and ensure it's the stream frame from stream 3.
nharper55fa6132019-05-07 19:37:21 -07003022 size_t padding_frame_count = writer_->padding_frames().size();
3023 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003024 ASSERT_EQ(1u, writer_->stream_frames().size());
3025 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3026 writer_->stream_frames()[0]->stream_id);
3027}
3028
3029TEST_P(QuicConnectionTest, FramePackingAckResponse) {
3030 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3031 // Process a data packet to queue up a pending ack.
fayang3451f6e2019-06-11 08:18:12 -07003032 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3033 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
3034 } else {
3035 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3036 }
3037 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
3038
QUICHE teama6ef0a62019-03-07 20:34:33 -05003039 QuicPacketNumber last_packet;
nharper46833c32019-05-15 21:33:05 -07003040 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3041 connection_.SendCryptoDataWithString("foo", 0);
3042 } else {
3043 SendStreamDataToPeer(
3044 QuicUtils::GetCryptoStreamId(connection_.transport_version()), "foo", 0,
3045 NO_FIN, &last_packet);
3046 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003047 // Verify ack is bundled with outging packet.
3048 EXPECT_FALSE(writer_->ack_frames().empty());
3049
3050 EXPECT_CALL(visitor_, OnCanWrite())
3051 .WillOnce(DoAll(IgnoreResult(InvokeWithoutArgs(
3052 &connection_, &TestConnection::SendStreamData3)),
3053 IgnoreResult(InvokeWithoutArgs(
3054 &connection_, &TestConnection::SendStreamData5))));
3055
3056 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3057
3058 // Process a data packet to cause the visitor's OnCanWrite to be invoked.
3059 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
QUICHE team8c1daa22019-03-13 08:33:41 -07003060 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
3061 QuicMakeUnique<TaggingEncrypter>(0x01));
zhongyi546cc452019-04-12 15:27:49 -07003062 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
3063 QuicMakeUnique<StrictTaggingDecrypter>(0x01));
nharper2c9f02a2019-05-08 10:25:50 -07003064 ProcessDataPacket(2);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003065
3066 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3067 EXPECT_FALSE(connection_.HasQueuedData());
3068
3069 // Parse the last packet and ensure it's an ack and two stream frames from
3070 // two different streams.
3071 if (GetParam().no_stop_waiting) {
3072 EXPECT_EQ(3u, writer_->frame_count());
3073 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
3074 } else {
3075 EXPECT_EQ(4u, writer_->frame_count());
3076 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3077 }
3078 EXPECT_FALSE(writer_->ack_frames().empty());
3079 ASSERT_EQ(2u, writer_->stream_frames().size());
3080 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3081 writer_->stream_frames()[0]->stream_id);
3082 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3083 writer_->stream_frames()[1]->stream_id);
3084}
3085
3086TEST_P(QuicConnectionTest, FramePackingSendv) {
nharper46833c32019-05-15 21:33:05 -07003087 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003088 // Send data in 1 packet by writing multiple blocks in a single iovector
3089 // using writev.
3090 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3091
3092 char data[] = "ABCDEF";
3093 struct iovec iov[2];
3094 iov[0].iov_base = data;
3095 iov[0].iov_len = 4;
3096 iov[1].iov_base = data + 4;
3097 iov[1].iov_len = 2;
nharper46833c32019-05-15 21:33:05 -07003098 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
3099 connection_.transport_version(), Perspective::IS_CLIENT);
3100 connection_.SaveAndSendStreamData(stream_id, iov, 2, 6, 0, NO_FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003101
3102 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3103 EXPECT_FALSE(connection_.HasQueuedData());
3104
3105 // Parse the last packet and ensure multiple iovector blocks have
3106 // been packed into a single stream frame from one stream.
nharper46833c32019-05-15 21:33:05 -07003107 EXPECT_EQ(1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003108 EXPECT_EQ(1u, writer_->stream_frames().size());
nharper46833c32019-05-15 21:33:05 -07003109 EXPECT_EQ(0u, writer_->padding_frames().size());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003110 QuicStreamFrame* frame = writer_->stream_frames()[0].get();
nharper46833c32019-05-15 21:33:05 -07003111 EXPECT_EQ(stream_id, frame->stream_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003112 EXPECT_EQ("ABCDEF", QuicStringPiece(frame->data_buffer, frame->data_length));
3113}
3114
3115TEST_P(QuicConnectionTest, FramePackingSendvQueued) {
nharper46833c32019-05-15 21:33:05 -07003116 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003117 // Try to send two stream frames in 1 packet by using writev.
3118 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3119
3120 BlockOnNextWrite();
3121 char data[] = "ABCDEF";
3122 struct iovec iov[2];
3123 iov[0].iov_base = data;
3124 iov[0].iov_len = 4;
3125 iov[1].iov_base = data + 4;
3126 iov[1].iov_len = 2;
nharper46833c32019-05-15 21:33:05 -07003127 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
3128 connection_.transport_version(), Perspective::IS_CLIENT);
3129 connection_.SaveAndSendStreamData(stream_id, iov, 2, 6, 0, NO_FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003130
3131 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3132 EXPECT_TRUE(connection_.HasQueuedData());
3133
3134 // Unblock the writes and actually send.
3135 writer_->SetWritable();
3136 connection_.OnCanWrite();
3137 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3138
3139 // Parse the last packet and ensure it's one stream frame from one stream.
nharper46833c32019-05-15 21:33:05 -07003140 EXPECT_EQ(1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003141 EXPECT_EQ(1u, writer_->stream_frames().size());
nharper46833c32019-05-15 21:33:05 -07003142 EXPECT_EQ(0u, writer_->padding_frames().size());
3143 EXPECT_EQ(stream_id, writer_->stream_frames()[0]->stream_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003144}
3145
3146TEST_P(QuicConnectionTest, SendingZeroBytes) {
3147 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3148 // Send a zero byte write with a fin using writev.
3149 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
nharper46833c32019-05-15 21:33:05 -07003150 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
3151 connection_.transport_version(), Perspective::IS_CLIENT);
3152 connection_.SaveAndSendStreamData(stream_id, nullptr, 0, 0, 0, FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003153
3154 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3155 EXPECT_FALSE(connection_.HasQueuedData());
3156
nharper55fa6132019-05-07 19:37:21 -07003157 // Padding frames are added by v99 to ensure a minimum packet size.
3158 size_t extra_padding_frames = 0;
3159 if (GetParam().version.HasHeaderProtection()) {
3160 extra_padding_frames = 1;
3161 }
3162
QUICHE teama6ef0a62019-03-07 20:34:33 -05003163 // Parse the last packet and ensure it's one stream frame from one stream.
nharper55fa6132019-05-07 19:37:21 -07003164 EXPECT_EQ(1u + extra_padding_frames, writer_->frame_count());
3165 EXPECT_EQ(extra_padding_frames, writer_->padding_frames().size());
3166 ASSERT_EQ(1u, writer_->stream_frames().size());
nharper46833c32019-05-15 21:33:05 -07003167 EXPECT_EQ(stream_id, writer_->stream_frames()[0]->stream_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003168 EXPECT_TRUE(writer_->stream_frames()[0]->fin);
3169}
3170
3171TEST_P(QuicConnectionTest, LargeSendWithPendingAck) {
3172 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3173 // Set the ack alarm by processing a ping frame.
3174 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3175
3176 // Processs a PING frame.
3177 ProcessFramePacket(QuicFrame(QuicPingFrame()));
3178 // Ensure that this has caused the ACK alarm to be set.
3179 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
3180 EXPECT_TRUE(ack_alarm->IsSet());
3181
3182 // Send data and ensure the ack is bundled.
3183 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(8);
3184 size_t len = 10000;
3185 std::unique_ptr<char[]> data_array(new char[len]);
3186 memset(data_array.get(), '?', len);
3187 struct iovec iov;
3188 iov.iov_base = data_array.get();
3189 iov.iov_len = len;
3190 QuicConsumedData consumed = connection_.SaveAndSendStreamData(
3191 QuicUtils::GetHeadersStreamId(connection_.transport_version()), &iov, 1,
3192 len, 0, FIN);
3193 EXPECT_EQ(len, consumed.bytes_consumed);
3194 EXPECT_TRUE(consumed.fin_consumed);
3195 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3196 EXPECT_FALSE(connection_.HasQueuedData());
3197
3198 // Parse the last packet and ensure it's one stream frame with a fin.
3199 EXPECT_EQ(1u, writer_->frame_count());
nharper55fa6132019-05-07 19:37:21 -07003200 ASSERT_EQ(1u, writer_->stream_frames().size());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003201 EXPECT_EQ(QuicUtils::GetHeadersStreamId(connection_.transport_version()),
3202 writer_->stream_frames()[0]->stream_id);
3203 EXPECT_TRUE(writer_->stream_frames()[0]->fin);
3204 // Ensure the ack alarm was cancelled when the ack was sent.
3205 EXPECT_FALSE(ack_alarm->IsSet());
3206}
3207
3208TEST_P(QuicConnectionTest, OnCanWrite) {
3209 // Visitor's OnCanWrite will send data, but will have more pending writes.
3210 EXPECT_CALL(visitor_, OnCanWrite())
3211 .WillOnce(DoAll(IgnoreResult(InvokeWithoutArgs(
3212 &connection_, &TestConnection::SendStreamData3)),
3213 IgnoreResult(InvokeWithoutArgs(
3214 &connection_, &TestConnection::SendStreamData5))));
3215 {
3216 InSequence seq;
3217 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillOnce(Return(true));
3218 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
3219 .WillRepeatedly(Return(false));
3220 }
3221
3222 EXPECT_CALL(*send_algorithm_, CanSend(_))
3223 .WillRepeatedly(testing::Return(true));
3224
3225 connection_.OnCanWrite();
3226
3227 // Parse the last packet and ensure it's the two stream frames from
3228 // two different streams.
3229 EXPECT_EQ(2u, writer_->frame_count());
3230 EXPECT_EQ(2u, writer_->stream_frames().size());
3231 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3232 writer_->stream_frames()[0]->stream_id);
3233 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3234 writer_->stream_frames()[1]->stream_id);
3235}
3236
3237TEST_P(QuicConnectionTest, RetransmitOnNack) {
3238 QuicPacketNumber last_packet;
3239 QuicByteCount second_packet_size;
3240 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet); // Packet 1
3241 second_packet_size =
3242 SendStreamDataToPeer(3, "foos", 3, NO_FIN, &last_packet); // Packet 2
3243 SendStreamDataToPeer(3, "fooos", 7, NO_FIN, &last_packet); // Packet 3
3244
3245 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3246
3247 // Don't lose a packet on an ack, and nothing is retransmitted.
3248 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3249 QuicAckFrame ack_one = InitAckFrame(1);
3250 ProcessAckPacket(&ack_one);
3251
3252 // Lose a packet and ensure it triggers retransmission.
3253 QuicAckFrame nack_two = ConstructAckFrame(3, 2);
3254 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003255 lost_packets.push_back(
3256 LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003257 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3258 .WillOnce(SetArgPointee<5>(lost_packets));
3259 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3260 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3261 EXPECT_FALSE(QuicPacketCreatorPeer::SendVersionInPacket(creator_));
3262 ProcessAckPacket(&nack_two);
3263}
3264
3265TEST_P(QuicConnectionTest, DoNotSendQueuedPacketForResetStream) {
3266 // Block the connection to queue the packet.
3267 BlockOnNextWrite();
3268
3269 QuicStreamId stream_id = 2;
3270 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
3271
3272 // Now that there is a queued packet, reset the stream.
3273 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
3274
3275 // Unblock the connection and verify that only the RST_STREAM is sent.
3276 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3277 writer_->SetWritable();
3278 connection_.OnCanWrite();
3279 if (!connection_.session_decides_what_to_write()) {
3280 // OnCanWrite will cause RST_STREAM be sent again.
3281 connection_.SendControlFrame(QuicFrame(new QuicRstStreamFrame(
3282 1, stream_id, QUIC_ERROR_PROCESSING_STREAM, 14)));
3283 }
nharper55fa6132019-05-07 19:37:21 -07003284 size_t padding_frame_count = writer_->padding_frames().size();
3285 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003286 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3287}
3288
3289TEST_P(QuicConnectionTest, SendQueuedPacketForQuicRstStreamNoError) {
3290 // Block the connection to queue the packet.
3291 BlockOnNextWrite();
3292
3293 QuicStreamId stream_id = 2;
3294 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
3295
3296 // Now that there is a queued packet, reset the stream.
3297 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 3);
3298
3299 // Unblock the connection and verify that the RST_STREAM is sent and the data
3300 // packet is sent.
3301 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(2));
3302 writer_->SetWritable();
3303 connection_.OnCanWrite();
3304 if (!connection_.session_decides_what_to_write()) {
3305 // OnCanWrite will cause RST_STREAM be sent again.
3306 connection_.SendControlFrame(QuicFrame(
3307 new QuicRstStreamFrame(1, stream_id, QUIC_STREAM_NO_ERROR, 14)));
3308 }
nharper55fa6132019-05-07 19:37:21 -07003309 size_t padding_frame_count = writer_->padding_frames().size();
3310 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003311 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3312}
3313
3314TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnNack) {
3315 QuicStreamId stream_id = 2;
3316 QuicPacketNumber last_packet;
3317 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3318 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3319 SendStreamDataToPeer(stream_id, "fooos", 7, NO_FIN, &last_packet);
3320
3321 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3322 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 12);
3323
3324 // Lose a packet and ensure it does not trigger retransmission.
3325 QuicAckFrame nack_two = ConstructAckFrame(last_packet, last_packet - 1);
3326 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3327 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3328 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3329 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3330 ProcessAckPacket(&nack_two);
3331}
3332
3333TEST_P(QuicConnectionTest, RetransmitForQuicRstStreamNoErrorOnNack) {
3334 QuicStreamId stream_id = 2;
3335 QuicPacketNumber last_packet;
3336 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3337 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3338 SendStreamDataToPeer(stream_id, "fooos", 7, NO_FIN, &last_packet);
3339
3340 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3341 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 12);
3342
3343 // Lose a packet, ensure it triggers retransmission.
3344 QuicAckFrame nack_two = ConstructAckFrame(last_packet, last_packet - 1);
3345 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3346 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003347 lost_packets.push_back(LostPacket(last_packet - 1, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003348 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3349 .WillOnce(SetArgPointee<5>(lost_packets));
3350 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3351 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
3352 ProcessAckPacket(&nack_two);
3353}
3354
3355TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnRTO) {
3356 QuicStreamId stream_id = 2;
3357 QuicPacketNumber last_packet;
3358 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3359
3360 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3361 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
3362
3363 // Fire the RTO and verify that the RST_STREAM is resent, not stream data.
3364 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3365 clock_.AdvanceTime(DefaultRetransmissionTime());
3366 connection_.GetRetransmissionAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07003367 size_t padding_frame_count = writer_->padding_frames().size();
3368 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003369 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3370 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
3371}
3372
3373// Ensure that if the only data in flight is non-retransmittable, the
3374// retransmission alarm is not set.
3375TEST_P(QuicConnectionTest, CancelRetransmissionAlarmAfterResetStream) {
3376 QuicStreamId stream_id = 2;
3377 QuicPacketNumber last_data_packet;
3378 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
3379
3380 // Cancel the stream.
3381 const QuicPacketNumber rst_packet = last_data_packet + 1;
3382 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, rst_packet, _, _)).Times(1);
3383 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
3384
3385 // Ack the RST_STREAM frame (since it's retransmittable), but not the data
3386 // packet, which is no longer retransmittable since the stream was cancelled.
3387 QuicAckFrame nack_stream_data =
3388 ConstructAckFrame(rst_packet, last_data_packet);
3389 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3390 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3391 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3392 ProcessAckPacket(&nack_stream_data);
3393
3394 // Ensure that the data is still in flight, but the retransmission alarm is no
3395 // longer set.
ianswett9f459cb2019-04-21 06:39:59 -07003396 EXPECT_GT(manager_->GetBytesInFlight(), 0u);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003397 if (GetQuicReloadableFlag(quic_optimize_inflight_check)) {
3398 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3399 // Firing the alarm should remove all bytes_in_flight.
3400 connection_.GetRetransmissionAlarm()->Fire();
ianswett9f459cb2019-04-21 06:39:59 -07003401 EXPECT_EQ(0u, manager_->GetBytesInFlight());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003402 }
3403 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3404}
3405
3406TEST_P(QuicConnectionTest, RetransmitForQuicRstStreamNoErrorOnRTO) {
3407 connection_.SetMaxTailLossProbes(0);
3408
3409 QuicStreamId stream_id = 2;
3410 QuicPacketNumber last_packet;
3411 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3412
3413 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3414 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 3);
3415
3416 // Fire the RTO and verify that the RST_STREAM is resent, the stream data
3417 // is sent.
3418 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(2));
3419 clock_.AdvanceTime(DefaultRetransmissionTime());
3420 connection_.GetRetransmissionAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07003421 size_t padding_frame_count = writer_->padding_frames().size();
3422 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003423 ASSERT_EQ(1u, writer_->rst_stream_frames().size());
3424 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
3425}
3426
3427TEST_P(QuicConnectionTest, DoNotSendPendingRetransmissionForResetStream) {
3428 QuicStreamId stream_id = 2;
3429 QuicPacketNumber last_packet;
3430 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3431 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3432 BlockOnNextWrite();
3433 connection_.SendStreamDataWithString(stream_id, "fooos", 7, NO_FIN);
3434
3435 // Lose a packet which will trigger a pending retransmission.
3436 QuicAckFrame ack = ConstructAckFrame(last_packet, last_packet - 1);
3437 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3438 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3439 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3440 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3441 ProcessAckPacket(&ack);
3442
3443 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 12);
3444
3445 // Unblock the connection and verify that the RST_STREAM is sent but not the
3446 // second data packet nor a retransmit.
3447 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3448 writer_->SetWritable();
3449 connection_.OnCanWrite();
3450 if (!connection_.session_decides_what_to_write()) {
3451 // OnCanWrite will cause this RST_STREAM_FRAME be sent again.
3452 connection_.SendControlFrame(QuicFrame(new QuicRstStreamFrame(
3453 1, stream_id, QUIC_ERROR_PROCESSING_STREAM, 14)));
3454 }
nharper55fa6132019-05-07 19:37:21 -07003455 size_t padding_frame_count = writer_->padding_frames().size();
3456 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
zhongyi546cc452019-04-12 15:27:49 -07003457 ASSERT_EQ(1u, writer_->rst_stream_frames().size());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003458 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
3459}
3460
3461TEST_P(QuicConnectionTest, SendPendingRetransmissionForQuicRstStreamNoError) {
3462 QuicStreamId stream_id = 2;
3463 QuicPacketNumber last_packet;
3464 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3465 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3466 BlockOnNextWrite();
3467 connection_.SendStreamDataWithString(stream_id, "fooos", 7, NO_FIN);
3468
3469 // Lose a packet which will trigger a pending retransmission.
3470 QuicAckFrame ack = ConstructAckFrame(last_packet, last_packet - 1);
3471 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3472 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003473 lost_packets.push_back(LostPacket(last_packet - 1, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003474 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3475 .WillOnce(SetArgPointee<5>(lost_packets));
3476 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3477 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3478 ProcessAckPacket(&ack);
3479
3480 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 12);
3481
3482 // Unblock the connection and verify that the RST_STREAM is sent and the
3483 // second data packet or a retransmit is sent.
3484 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(2));
3485 writer_->SetWritable();
3486 connection_.OnCanWrite();
3487 // The RST_STREAM_FRAME is sent after queued packets and pending
3488 // retransmission.
3489 connection_.SendControlFrame(QuicFrame(
3490 new QuicRstStreamFrame(1, stream_id, QUIC_STREAM_NO_ERROR, 14)));
nharper55fa6132019-05-07 19:37:21 -07003491 size_t padding_frame_count = writer_->padding_frames().size();
3492 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003493 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3494}
3495
3496TEST_P(QuicConnectionTest, RetransmitAckedPacket) {
3497 QuicPacketNumber last_packet;
3498 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
3499 SendStreamDataToPeer(1, "foos", 3, NO_FIN, &last_packet); // Packet 2
3500 SendStreamDataToPeer(1, "fooos", 7, NO_FIN, &last_packet); // Packet 3
3501
3502 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3503
3504 // Instigate a loss with an ack.
3505 QuicAckFrame nack_two = ConstructAckFrame(3, 2);
3506 // The first nack should trigger a fast retransmission, but we'll be
3507 // write blocked, so the packet will be queued.
3508 BlockOnNextWrite();
3509
3510 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003511 lost_packets.push_back(
3512 LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003513 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3514 .WillOnce(SetArgPointee<5>(lost_packets));
3515 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3516 ProcessAckPacket(&nack_two);
3517 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3518
3519 // Now, ack the previous transmission.
3520 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3521 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(false, _, _, _, _));
3522 QuicAckFrame ack_all = InitAckFrame(3);
3523 ProcessAckPacket(&ack_all);
3524
3525 // Unblock the socket and attempt to send the queued packets. We will always
3526 // send the retransmission.
3527 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _))
3528 .Times(1);
3529
3530 writer_->SetWritable();
3531 connection_.OnCanWrite();
3532
3533 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3534 // We do not store retransmittable frames of this retransmission.
3535 EXPECT_FALSE(QuicConnectionPeer::HasRetransmittableFrames(&connection_, 4));
3536}
3537
3538TEST_P(QuicConnectionTest, RetransmitNackedLargestObserved) {
3539 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3540 QuicPacketNumber original, second;
3541
3542 QuicByteCount packet_size =
3543 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &original); // 1st packet.
3544 SendStreamDataToPeer(3, "bar", 3, NO_FIN, &second); // 2nd packet.
3545
3546 QuicAckFrame frame = InitAckFrame({{second, second + 1}});
3547 // The first nack should retransmit the largest observed packet.
3548 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003549 lost_packets.push_back(LostPacket(original, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003550 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3551 .WillOnce(SetArgPointee<5>(lost_packets));
3552 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3553 // Packet 1 is short header for IETF QUIC because the encryption level
3554 // switched to ENCRYPTION_FORWARD_SECURE in SendStreamDataToPeer.
fayangd4291e42019-05-30 10:31:21 -07003555 EXPECT_CALL(*send_algorithm_,
3556 OnPacketSent(_, _, _,
3557 VersionHasIetfInvariantHeader(
3558 GetParam().version.transport_version)
3559 ? packet_size
3560 : packet_size - kQuicVersionSize,
3561 _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003562 ProcessAckPacket(&frame);
3563}
3564
3565TEST_P(QuicConnectionTest, QueueAfterTwoRTOs) {
3566 connection_.SetMaxTailLossProbes(0);
3567
3568 for (int i = 0; i < 10; ++i) {
3569 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3570 connection_.SendStreamDataWithString(3, "foo", i * 3, NO_FIN);
3571 }
3572
3573 // Block the writer and ensure they're queued.
3574 BlockOnNextWrite();
3575 clock_.AdvanceTime(DefaultRetransmissionTime());
3576 // Only one packet should be retransmitted.
3577 connection_.GetRetransmissionAlarm()->Fire();
3578 EXPECT_TRUE(connection_.HasQueuedData());
3579
3580 // Unblock the writer.
3581 writer_->SetWritable();
3582 clock_.AdvanceTime(QuicTime::Delta::FromMicroseconds(
3583 2 * DefaultRetransmissionTime().ToMicroseconds()));
3584 // Retransmit already retransmitted packets event though the packet number
3585 // greater than the largest observed.
3586 if (connection_.session_decides_what_to_write()) {
3587 // 2 RTOs + 1 TLP.
3588 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
3589 } else {
3590 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3591 }
3592 connection_.GetRetransmissionAlarm()->Fire();
3593 connection_.OnCanWrite();
3594}
3595
3596TEST_P(QuicConnectionTest, WriteBlockedBufferedThenSent) {
3597 BlockOnNextWrite();
3598 writer_->set_is_write_blocked_data_buffered(true);
3599 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3600 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3601 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3602
3603 writer_->SetWritable();
3604 connection_.OnCanWrite();
3605 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3606}
3607
3608TEST_P(QuicConnectionTest, WriteBlockedThenSent) {
3609 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3610 BlockOnNextWrite();
3611 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3612 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3613 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3614
3615 // The second packet should also be queued, in order to ensure packets are
3616 // never sent out of order.
3617 writer_->SetWritable();
3618 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3619 EXPECT_EQ(2u, connection_.NumQueuedPackets());
3620
3621 // Now both are sent in order when we unblock.
3622 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3623 connection_.OnCanWrite();
3624 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3625}
3626
3627TEST_P(QuicConnectionTest, RetransmitWriteBlockedAckedOriginalThenSent) {
3628 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3629 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
3630 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3631
3632 BlockOnNextWrite();
3633 writer_->set_is_write_blocked_data_buffered(true);
3634 // Simulate the retransmission alarm firing.
3635 clock_.AdvanceTime(DefaultRetransmissionTime());
3636 connection_.GetRetransmissionAlarm()->Fire();
3637
3638 // Ack the sent packet before the callback returns, which happens in
3639 // rare circumstances with write blocked sockets.
3640 QuicAckFrame ack = InitAckFrame(1);
3641 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3642 ProcessAckPacket(&ack);
3643
3644 writer_->SetWritable();
3645 connection_.OnCanWrite();
3646 // There is now a pending packet, but with no retransmittable frames.
3647 if (GetQuicReloadableFlag(quic_optimize_inflight_check)) {
3648 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3649 // Firing the alarm should remove all bytes_in_flight.
3650 connection_.GetRetransmissionAlarm()->Fire();
ianswett9f459cb2019-04-21 06:39:59 -07003651 EXPECT_EQ(0u, manager_->GetBytesInFlight());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003652 }
3653 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3654 EXPECT_FALSE(QuicConnectionPeer::HasRetransmittableFrames(&connection_, 2));
3655}
3656
3657TEST_P(QuicConnectionTest, AlarmsWhenWriteBlocked) {
3658 // Block the connection.
3659 BlockOnNextWrite();
3660 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
3661 EXPECT_EQ(1u, writer_->packets_write_attempts());
3662 EXPECT_TRUE(writer_->IsWriteBlocked());
3663
3664 // Set the send alarm. Fire the alarm and ensure it doesn't attempt to write.
3665 connection_.GetSendAlarm()->Set(clock_.ApproximateNow());
3666 connection_.GetSendAlarm()->Fire();
3667 EXPECT_TRUE(writer_->IsWriteBlocked());
3668 EXPECT_EQ(1u, writer_->packets_write_attempts());
3669}
3670
3671TEST_P(QuicConnectionTest, NoSendAlarmAfterProcessPacketWhenWriteBlocked) {
3672 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3673
3674 // Block the connection.
3675 BlockOnNextWrite();
3676 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
3677 EXPECT_TRUE(writer_->IsWriteBlocked());
3678 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3679 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
3680
3681 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3682 // Process packet number 1. Can not call ProcessPacket or ProcessDataPacket
3683 // here, because they will fire the alarm after QuicConnection::ProcessPacket
3684 // is returned.
3685 const uint64_t received_packet_num = 1;
3686 const bool has_stop_waiting = false;
QUICHE team6987b4a2019-03-15 16:23:04 -07003687 const EncryptionLevel level = ENCRYPTION_INITIAL;
QUICHE team8c1daa22019-03-13 08:33:41 -07003688 std::unique_ptr<QuicPacket> packet(ConstructDataPacket(
nharper46833c32019-05-15 21:33:05 -07003689 received_packet_num, has_stop_waiting, ENCRYPTION_FORWARD_SECURE));
dschinazi66dea072019-04-09 11:41:06 -07003690 char buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05003691 size_t encrypted_length =
3692 peer_framer_.EncryptPayload(level, QuicPacketNumber(received_packet_num),
dschinazi66dea072019-04-09 11:41:06 -07003693 *packet, buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003694 connection_.ProcessUdpPacket(
3695 kSelfAddress, kPeerAddress,
3696 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
3697
3698 EXPECT_TRUE(writer_->IsWriteBlocked());
3699 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
3700}
3701
3702TEST_P(QuicConnectionTest, AddToWriteBlockedListIfWriterBlockedWhenProcessing) {
3703 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3704 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
3705
3706 // Simulate the case where a shared writer gets blocked by another connection.
3707 writer_->SetWriteBlocked();
3708
3709 // Process an ACK, make sure the connection calls visitor_->OnWriteBlocked().
3710 QuicAckFrame ack1 = InitAckFrame(1);
3711 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
3712 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
3713 ProcessAckPacket(1, &ack1);
3714}
3715
3716TEST_P(QuicConnectionTest, DoNotAddToWriteBlockedListAfterDisconnect) {
3717 writer_->SetBatchMode(true);
3718 EXPECT_TRUE(connection_.connected());
3719 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, _,
3720 ConnectionCloseSource::FROM_SELF));
3721
3722 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
3723
3724 {
3725 QuicConnection::ScopedPacketFlusher flusher(&connection_,
3726 QuicConnection::NO_ACK);
3727 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
3728 ConnectionCloseBehavior::SILENT_CLOSE);
3729
3730 EXPECT_FALSE(connection_.connected());
3731 writer_->SetWriteBlocked();
3732 }
3733}
3734
3735TEST_P(QuicConnectionTest, AddToWriteBlockedListIfBlockedOnFlushPackets) {
3736 writer_->SetBatchMode(true);
3737 writer_->BlockOnNextFlush();
3738
3739 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
3740 {
3741 QuicConnection::ScopedPacketFlusher flusher(&connection_,
3742 QuicConnection::NO_ACK);
3743 // flusher's destructor will call connection_.FlushPackets, which should add
3744 // the connection to the write blocked list.
3745 }
3746}
3747
3748TEST_P(QuicConnectionTest, NoLimitPacketsPerNack) {
3749 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3750 int offset = 0;
3751 // Send packets 1 to 15.
3752 for (int i = 0; i < 15; ++i) {
3753 SendStreamDataToPeer(1, "foo", offset, NO_FIN, nullptr);
3754 offset += 3;
3755 }
3756
3757 // Ack 15, nack 1-14.
3758
3759 QuicAckFrame nack =
3760 InitAckFrame({{QuicPacketNumber(15), QuicPacketNumber(16)}});
3761
3762 // 14 packets have been NACK'd and lost.
3763 LostPacketVector lost_packets;
3764 for (int i = 1; i < 15; ++i) {
dschinazi66dea072019-04-09 11:41:06 -07003765 lost_packets.push_back(
3766 LostPacket(QuicPacketNumber(i), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003767 }
3768 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3769 .WillOnce(SetArgPointee<5>(lost_packets));
3770 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3771 if (connection_.session_decides_what_to_write()) {
3772 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3773 } else {
3774 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(14);
3775 }
3776 ProcessAckPacket(&nack);
3777}
3778
3779// Test sending multiple acks from the connection to the session.
3780TEST_P(QuicConnectionTest, MultipleAcks) {
QUICHE teamcd098022019-03-22 18:49:55 -07003781 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3782 return;
3783 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003784 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3785 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3786 ProcessDataPacket(1);
3787 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
3788 QuicPacketNumber last_packet;
3789 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
3790 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
3791 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet); // Packet 2
3792 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
3793 SendAckPacketToPeer(); // Packet 3
3794 SendStreamDataToPeer(5, "foo", 0, NO_FIN, &last_packet); // Packet 4
3795 EXPECT_EQ(QuicPacketNumber(4u), last_packet);
3796 SendStreamDataToPeer(1, "foo", 3, NO_FIN, &last_packet); // Packet 5
3797 EXPECT_EQ(QuicPacketNumber(5u), last_packet);
3798 SendStreamDataToPeer(3, "foo", 3, NO_FIN, &last_packet); // Packet 6
3799 EXPECT_EQ(QuicPacketNumber(6u), last_packet);
3800
3801 // Client will ack packets 1, 2, [!3], 4, 5.
3802 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3803 QuicAckFrame frame1 = ConstructAckFrame(5, 3);
3804 ProcessAckPacket(&frame1);
3805
3806 // Now the client implicitly acks 3, and explicitly acks 6.
3807 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3808 QuicAckFrame frame2 = InitAckFrame(6);
3809 ProcessAckPacket(&frame2);
3810}
3811
3812TEST_P(QuicConnectionTest, DontLatchUnackedPacket) {
QUICHE teamcd098022019-03-22 18:49:55 -07003813 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3814 return;
3815 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003816 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3817 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3818 ProcessDataPacket(1);
3819 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
3820 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr); // Packet 1;
3821 // From now on, we send acks, so the send algorithm won't mark them pending.
3822 SendAckPacketToPeer(); // Packet 2
3823
3824 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3825 QuicAckFrame frame = InitAckFrame(1);
3826 ProcessAckPacket(&frame);
3827
3828 // Verify that our internal state has least-unacked as 2, because we're still
3829 // waiting for a potential ack for 2.
3830
3831 EXPECT_EQ(QuicPacketNumber(2u), stop_waiting()->least_unacked);
3832
3833 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3834 frame = InitAckFrame(2);
3835 ProcessAckPacket(&frame);
3836 EXPECT_EQ(QuicPacketNumber(3u), stop_waiting()->least_unacked);
3837
3838 // When we send an ack, we make sure our least-unacked makes sense. In this
3839 // case since we're not waiting on an ack for 2 and all packets are acked, we
3840 // set it to 3.
3841 SendAckPacketToPeer(); // Packet 3
3842 // Least_unacked remains at 3 until another ack is received.
3843 EXPECT_EQ(QuicPacketNumber(3u), stop_waiting()->least_unacked);
3844 if (GetParam().no_stop_waiting) {
3845 // Expect no stop waiting frame is sent.
3846 EXPECT_FALSE(least_unacked().IsInitialized());
3847 } else {
3848 // Check that the outgoing ack had its packet number as least_unacked.
3849 EXPECT_EQ(QuicPacketNumber(3u), least_unacked());
3850 }
3851
3852 // Ack the ack, which updates the rtt and raises the least unacked.
3853 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3854 frame = InitAckFrame(3);
3855 ProcessAckPacket(&frame);
3856
3857 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr); // Packet 4
3858 EXPECT_EQ(QuicPacketNumber(4u), stop_waiting()->least_unacked);
3859 SendAckPacketToPeer(); // Packet 5
3860 if (GetParam().no_stop_waiting) {
3861 // Expect no stop waiting frame is sent.
3862 EXPECT_FALSE(least_unacked().IsInitialized());
3863 } else {
3864 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
3865 }
3866
3867 // Send two data packets at the end, and ensure if the last one is acked,
3868 // the least unacked is raised above the ack packets.
3869 SendStreamDataToPeer(1, "bar", 6, NO_FIN, nullptr); // Packet 6
3870 SendStreamDataToPeer(1, "bar", 9, NO_FIN, nullptr); // Packet 7
3871
3872 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3873 frame = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(5)},
3874 {QuicPacketNumber(7), QuicPacketNumber(8)}});
3875 ProcessAckPacket(&frame);
3876
3877 EXPECT_EQ(QuicPacketNumber(6u), stop_waiting()->least_unacked);
3878}
3879
3880TEST_P(QuicConnectionTest, TLP) {
3881 connection_.SetMaxTailLossProbes(1);
3882
3883 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
3884 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
3885 QuicTime retransmission_time =
3886 connection_.GetRetransmissionAlarm()->deadline();
3887 EXPECT_NE(QuicTime::Zero(), retransmission_time);
3888
3889 EXPECT_EQ(QuicPacketNumber(1u), writer_->header().packet_number);
3890 // Simulate the retransmission alarm firing and sending a tlp,
3891 // so send algorithm's OnRetransmissionTimeout is not called.
3892 clock_.AdvanceTime(retransmission_time - clock_.Now());
3893 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
3894 connection_.GetRetransmissionAlarm()->Fire();
3895 EXPECT_EQ(QuicPacketNumber(2u), writer_->header().packet_number);
3896 // We do not raise the high water mark yet.
3897 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
3898}
3899
zhongyifbb25772019-04-10 16:54:08 -07003900TEST_P(QuicConnectionTest, TailLossProbeDelayForStreamDataInTLPR) {
zhongyi1b2f7832019-06-14 13:31:34 -07003901 if (!connection_.session_decides_what_to_write()) {
3902 return;
3903 }
3904
zhongyifbb25772019-04-10 16:54:08 -07003905 // Set TLPR from QuicConfig.
3906 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3907 QuicConfig config;
3908 QuicTagVector options;
3909 options.push_back(kTLPR);
3910 config.SetConnectionOptionsToSend(options);
3911 connection_.SetFromConfig(config);
3912 connection_.SetMaxTailLossProbes(1);
3913
3914 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
3915 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
3916
3917 QuicTime retransmission_time =
3918 connection_.GetRetransmissionAlarm()->deadline();
3919 EXPECT_NE(QuicTime::Zero(), retransmission_time);
3920 QuicTime::Delta expected_tlp_delay =
3921 0.5 * manager_->GetRttStats()->SmoothedOrInitialRtt();
3922 EXPECT_EQ(expected_tlp_delay, retransmission_time - clock_.Now());
3923
3924 EXPECT_EQ(QuicPacketNumber(1u), writer_->header().packet_number);
3925 // Simulate firing of the retransmission alarm and retransmit the packet.
3926 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
3927 clock_.AdvanceTime(retransmission_time - clock_.Now());
3928 connection_.GetRetransmissionAlarm()->Fire();
3929 EXPECT_EQ(QuicPacketNumber(2u), writer_->header().packet_number);
3930
3931 // We do not raise the high water mark yet.
3932 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
3933}
3934
3935TEST_P(QuicConnectionTest, TailLossProbeDelayForNonStreamDataInTLPR) {
zhongyi1b2f7832019-06-14 13:31:34 -07003936 if (!connection_.session_decides_what_to_write()) {
3937 return;
3938 }
3939
zhongyifbb25772019-04-10 16:54:08 -07003940 // Set TLPR from QuicConfig.
3941 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3942 QuicConfig config;
3943 QuicTagVector options;
3944 options.push_back(kTLPR);
3945 config.SetConnectionOptionsToSend(options);
3946 connection_.SetFromConfig(config);
3947 connection_.SetMaxTailLossProbes(1);
3948
3949 // Sets retransmittable on wire.
3950 const QuicTime::Delta retransmittable_on_wire_timeout =
3951 QuicTime::Delta::FromMilliseconds(50);
3952 connection_.set_retransmittable_on_wire_timeout(
3953 retransmittable_on_wire_timeout);
3954
3955 EXPECT_TRUE(connection_.connected());
3956 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
3957 .WillRepeatedly(Return(true));
3958 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
3959 EXPECT_FALSE(connection_.IsPathDegrading());
3960 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
3961
3962 const char data[] = "data";
3963 size_t data_size = strlen(data);
3964 QuicStreamOffset offset = 0;
3965
3966 // Send a data packet.
3967 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
3968 offset += data_size;
3969
3970 // Path degrading alarm should be set when there is a retransmittable packet
3971 // on the wire.
3972 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
3973
3974 // Verify the path degrading delay.
3975 // First TLP with stream data.
3976 QuicTime::Delta srtt = manager_->GetRttStats()->SmoothedOrInitialRtt();
3977 QuicTime::Delta expected_delay = 0.5 * srtt;
3978 // Add 1st RTO.
3979 QuicTime::Delta retransmission_delay =
3980 QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
3981 expected_delay = expected_delay + retransmission_delay;
3982 // Add 2nd RTO.
3983 expected_delay = expected_delay + retransmission_delay * 2;
3984 EXPECT_EQ(expected_delay,
3985 QuicConnectionPeer::GetSentPacketManager(&connection_)
3986 ->GetPathDegradingDelay());
3987 ASSERT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
3988
3989 // The ping alarm is set for the ping timeout, not the shorter
3990 // retransmittable_on_wire_timeout.
3991 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
3992 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
3993 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
3994
3995 // Receive an ACK for the data packet.
3996 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
3997 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3998 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3999 QuicAckFrame frame =
4000 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
4001 ProcessAckPacket(&frame);
4002
4003 // Path degrading alarm should be cancelled as there is no more
4004 // reretransmittable packets on the wire.
4005 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
4006 // The ping alarm should be set to the retransmittable_on_wire_timeout.
4007 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4008 EXPECT_EQ(retransmittable_on_wire_timeout,
4009 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
4010
4011 // Simulate firing of the retransmittable on wire and send a PING.
4012 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
4013 clock_.AdvanceTime(retransmittable_on_wire_timeout);
4014 connection_.GetPingAlarm()->Fire();
4015
4016 // The retransmission alarm and the path degrading alarm should be set as
4017 // there is a retransmittable packet (PING) on the wire,
4018 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4019 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
4020
4021 // Verify the retransmission delay.
4022 QuicTime::Delta min_rto_timeout =
4023 QuicTime::Delta::FromMilliseconds(kMinRetransmissionTimeMs);
4024 srtt = manager_->GetRttStats()->SmoothedOrInitialRtt();
zhongyi1b2f7832019-06-14 13:31:34 -07004025 if (GetQuicReloadableFlag(quic_ignore_tlpr_if_no_pending_stream_data)) {
zhongyifbb25772019-04-10 16:54:08 -07004026 // First TLP without unacked stream data will no longer use TLPR.
4027 expected_delay = std::max(2 * srtt, 1.5 * srtt + 0.5 * min_rto_timeout);
4028 } else {
4029 expected_delay =
4030 std::max(QuicTime::Delta::FromMilliseconds(kMinTailLossProbeTimeoutMs),
4031 srtt * 0.5);
4032 }
4033 EXPECT_EQ(expected_delay,
4034 connection_.GetRetransmissionAlarm()->deadline() - clock_.Now());
4035
zhongyi1b2f7832019-06-14 13:31:34 -07004036 // Verify the path degrading delay = TLP delay + 1st RTO + 2nd RTO.
zhongyifbb25772019-04-10 16:54:08 -07004037 // Add 1st RTO.
4038 retransmission_delay =
4039 std::max(manager_->GetRttStats()->smoothed_rtt() +
4040 4 * manager_->GetRttStats()->mean_deviation(),
4041 min_rto_timeout);
4042 expected_delay = expected_delay + retransmission_delay;
4043 // Add 2nd RTO.
4044 expected_delay = expected_delay + retransmission_delay * 2;
4045 EXPECT_EQ(expected_delay,
4046 QuicConnectionPeer::GetSentPacketManager(&connection_)
4047 ->GetPathDegradingDelay());
4048
4049 // The ping alarm is set for the ping timeout, not the shorter
4050 // retransmittable_on_wire_timeout.
4051 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4052 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
4053 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
zhongyi1b2f7832019-06-14 13:31:34 -07004054
4055 // Advance a small period of time: 5ms. And receive a retransmitted ACK.
4056 // This will update the retransmission alarm, verify the retransmission delay
4057 // is correct.
4058 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4059 QuicAckFrame ack = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
4060 ProcessAckPacket(&ack);
4061
4062 // Verify the retransmission delay.
4063 if (GetQuicReloadableFlag(quic_ignore_tlpr_if_no_pending_stream_data)) {
4064 // First TLP without unacked stream data will no longer use TLPR.
4065 expected_delay = std::max(2 * srtt, 1.5 * srtt + 0.5 * min_rto_timeout);
4066 } else {
4067 expected_delay =
4068 std::max(QuicTime::Delta::FromMilliseconds(kMinTailLossProbeTimeoutMs),
4069 srtt * 0.5);
4070 }
4071 expected_delay = expected_delay - QuicTime::Delta::FromMilliseconds(5);
4072 EXPECT_EQ(expected_delay,
4073 connection_.GetRetransmissionAlarm()->deadline() - clock_.Now());
zhongyifbb25772019-04-10 16:54:08 -07004074}
4075
QUICHE teama6ef0a62019-03-07 20:34:33 -05004076TEST_P(QuicConnectionTest, RTO) {
4077 connection_.SetMaxTailLossProbes(0);
4078
4079 QuicTime default_retransmission_time =
4080 clock_.ApproximateNow() + DefaultRetransmissionTime();
4081 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
4082 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4083
4084 EXPECT_EQ(QuicPacketNumber(1u), writer_->header().packet_number);
4085 EXPECT_EQ(default_retransmission_time,
4086 connection_.GetRetransmissionAlarm()->deadline());
4087 // Simulate the retransmission alarm firing.
4088 clock_.AdvanceTime(DefaultRetransmissionTime());
4089 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
4090 connection_.GetRetransmissionAlarm()->Fire();
4091 EXPECT_EQ(QuicPacketNumber(2u), writer_->header().packet_number);
4092 // We do not raise the high water mark yet.
4093 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4094}
4095
4096TEST_P(QuicConnectionTest, RetransmitWithSameEncryptionLevel) {
4097 use_tagging_decrypter();
4098
4099 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
4100 // the end of the packet. We can test this to check which encrypter was used.
QUICHE team6987b4a2019-03-15 16:23:04 -07004101 connection_.SetEncrypter(ENCRYPTION_INITIAL,
QUICHE teama6ef0a62019-03-07 20:34:33 -05004102 QuicMakeUnique<TaggingEncrypter>(0x01));
nharper46833c32019-05-15 21:33:05 -07004103 QuicByteCount packet_size;
4104 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4105 .WillOnce(SaveArg<3>(&packet_size));
4106 connection_.SendCryptoDataWithString("foo", 0);
4107 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004108 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
4109
4110 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
4111 QuicMakeUnique<TaggingEncrypter>(0x02));
4112 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4113 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
4114 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
4115
4116 {
4117 InSequence s;
4118 EXPECT_CALL(*send_algorithm_,
4119 OnPacketSent(_, _, QuicPacketNumber(3), _, _));
4120 EXPECT_CALL(*send_algorithm_,
4121 OnPacketSent(_, _, QuicPacketNumber(4), _, _));
4122 }
4123
4124 // Manually mark both packets for retransmission.
4125 connection_.RetransmitUnackedPackets(ALL_UNACKED_RETRANSMISSION);
4126
QUICHE team6987b4a2019-03-15 16:23:04 -07004127 // Packet should have been sent with ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05004128 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_previous_packet());
4129
4130 // Packet should have been sent with ENCRYPTION_ZERO_RTT.
4131 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
4132}
4133
4134TEST_P(QuicConnectionTest, SendHandshakeMessages) {
4135 use_tagging_decrypter();
4136 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
4137 // the end of the packet. We can test this to check which encrypter was used.
QUICHE team6987b4a2019-03-15 16:23:04 -07004138 connection_.SetEncrypter(ENCRYPTION_INITIAL,
QUICHE teama6ef0a62019-03-07 20:34:33 -05004139 QuicMakeUnique<TaggingEncrypter>(0x01));
4140
4141 // Attempt to send a handshake message and have the socket block.
4142 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
4143 BlockOnNextWrite();
nharper46833c32019-05-15 21:33:05 -07004144 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004145 // The packet should be serialized, but not queued.
4146 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4147
4148 // Switch to the new encrypter.
4149 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
4150 QuicMakeUnique<TaggingEncrypter>(0x02));
4151 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4152
4153 // Now become writeable and flush the packets.
4154 writer_->SetWritable();
4155 EXPECT_CALL(visitor_, OnCanWrite());
4156 connection_.OnCanWrite();
4157 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4158
4159 // Verify that the handshake packet went out at the null encryption.
4160 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
4161}
4162
4163TEST_P(QuicConnectionTest,
4164 DropRetransmitsForNullEncryptedPacketAfterForwardSecure) {
4165 use_tagging_decrypter();
QUICHE team6987b4a2019-03-15 16:23:04 -07004166 connection_.SetEncrypter(ENCRYPTION_INITIAL,
QUICHE teama6ef0a62019-03-07 20:34:33 -05004167 QuicMakeUnique<TaggingEncrypter>(0x01));
4168 QuicPacketNumber packet_number;
4169 connection_.SendCryptoStreamData();
4170
4171 // Simulate the retransmission alarm firing and the socket blocking.
4172 BlockOnNextWrite();
4173 clock_.AdvanceTime(DefaultRetransmissionTime());
4174 connection_.GetRetransmissionAlarm()->Fire();
4175
4176 // Go forward secure.
4177 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
4178 QuicMakeUnique<TaggingEncrypter>(0x02));
4179 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4180 notifier_.NeuterUnencryptedData();
4181 connection_.NeuterUnencryptedPackets();
4182
4183 EXPECT_EQ(QuicTime::Zero(), connection_.GetRetransmissionAlarm()->deadline());
4184 // Unblock the socket and ensure that no packets are sent.
4185 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4186 writer_->SetWritable();
4187 connection_.OnCanWrite();
4188}
4189
4190TEST_P(QuicConnectionTest, RetransmitPacketsWithInitialEncryption) {
4191 use_tagging_decrypter();
QUICHE team6987b4a2019-03-15 16:23:04 -07004192 connection_.SetEncrypter(ENCRYPTION_INITIAL,
QUICHE teama6ef0a62019-03-07 20:34:33 -05004193 QuicMakeUnique<TaggingEncrypter>(0x01));
QUICHE team6987b4a2019-03-15 16:23:04 -07004194 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004195
nharper46833c32019-05-15 21:33:05 -07004196 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004197
4198 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
4199 QuicMakeUnique<TaggingEncrypter>(0x02));
4200 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4201
4202 SendStreamDataToPeer(2, "bar", 0, NO_FIN, nullptr);
4203 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4204
4205 connection_.RetransmitUnackedPackets(ALL_INITIAL_RETRANSMISSION);
4206}
4207
4208TEST_P(QuicConnectionTest, BufferNonDecryptablePackets) {
QUICHE teamcd098022019-03-22 18:49:55 -07004209 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4210 return;
4211 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004212 // SetFromConfig is always called after construction from InitializeSession.
4213 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4214 QuicConfig config;
4215 connection_.SetFromConfig(config);
4216 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4217 use_tagging_decrypter();
4218
4219 const uint8_t tag = 0x07;
4220 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
4221 QuicMakeUnique<TaggingEncrypter>(tag));
4222
4223 // Process an encrypted packet which can not yet be decrypted which should
4224 // result in the packet being buffered.
4225 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4226
4227 // Transition to the new encryption state and process another encrypted packet
4228 // which should result in the original packet being processed.
zhongyi546cc452019-04-12 15:27:49 -07004229 SetDecrypter(ENCRYPTION_ZERO_RTT,
4230 QuicMakeUnique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004231 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4232 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
4233 QuicMakeUnique<TaggingEncrypter>(tag));
4234 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(2);
4235 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4236
4237 // Finally, process a third packet and note that we do not reprocess the
4238 // buffered packet.
4239 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4240 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4241}
4242
4243TEST_P(QuicConnectionTest, TestRetransmitOrder) {
4244 connection_.SetMaxTailLossProbes(0);
4245
4246 QuicByteCount first_packet_size;
4247 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4248 .WillOnce(SaveArg<3>(&first_packet_size));
4249
4250 connection_.SendStreamDataWithString(3, "first_packet", 0, NO_FIN);
4251 QuicByteCount second_packet_size;
4252 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4253 .WillOnce(SaveArg<3>(&second_packet_size));
4254 connection_.SendStreamDataWithString(3, "second_packet", 12, NO_FIN);
4255 EXPECT_NE(first_packet_size, second_packet_size);
4256 // Advance the clock by huge time to make sure packets will be retransmitted.
4257 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
4258 {
4259 InSequence s;
4260 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, first_packet_size, _));
4261 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, second_packet_size, _));
4262 }
4263 connection_.GetRetransmissionAlarm()->Fire();
4264
4265 // Advance again and expect the packets to be sent again in the same order.
4266 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(20));
4267 {
4268 InSequence s;
4269 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, first_packet_size, _));
4270 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, second_packet_size, _));
4271 }
4272 connection_.GetRetransmissionAlarm()->Fire();
4273}
4274
4275TEST_P(QuicConnectionTest, Buffer100NonDecryptablePacketsThenKeyChange) {
QUICHE teamcd098022019-03-22 18:49:55 -07004276 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4277 return;
4278 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004279 // SetFromConfig is always called after construction from InitializeSession.
4280 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4281 QuicConfig config;
4282 config.set_max_undecryptable_packets(100);
4283 connection_.SetFromConfig(config);
4284 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4285 use_tagging_decrypter();
4286
4287 const uint8_t tag = 0x07;
4288 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
4289 QuicMakeUnique<TaggingEncrypter>(tag));
4290
4291 // Process an encrypted packet which can not yet be decrypted which should
4292 // result in the packet being buffered.
4293 for (uint64_t i = 1; i <= 100; ++i) {
4294 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4295 }
4296
4297 // Transition to the new encryption state and process another encrypted packet
4298 // which should result in the original packets being processed.
4299 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
zhongyi546cc452019-04-12 15:27:49 -07004300 SetDecrypter(ENCRYPTION_ZERO_RTT,
4301 QuicMakeUnique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004302 EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
4303 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4304 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
4305 QuicMakeUnique<TaggingEncrypter>(tag));
4306
4307 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(100);
4308 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
4309
4310 // Finally, process a third packet and note that we do not reprocess the
4311 // buffered packet.
4312 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4313 ProcessDataPacketAtLevel(102, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4314}
4315
4316TEST_P(QuicConnectionTest, SetRTOAfterWritingToSocket) {
4317 BlockOnNextWrite();
4318 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4319 // Make sure that RTO is not started when the packet is queued.
4320 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4321
4322 // Test that RTO is started once we write to the socket.
4323 writer_->SetWritable();
4324 connection_.OnCanWrite();
4325 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4326}
4327
4328TEST_P(QuicConnectionTest, DelayRTOWithAckReceipt) {
4329 connection_.SetMaxTailLossProbes(0);
4330
4331 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4332 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
4333 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
4334 connection_.SendStreamDataWithString(3, "bar", 0, NO_FIN);
4335 QuicAlarm* retransmission_alarm = connection_.GetRetransmissionAlarm();
4336 EXPECT_TRUE(retransmission_alarm->IsSet());
4337 EXPECT_EQ(clock_.Now() + DefaultRetransmissionTime(),
4338 retransmission_alarm->deadline());
4339
4340 // Advance the time right before the RTO, then receive an ack for the first
4341 // packet to delay the RTO.
4342 clock_.AdvanceTime(DefaultRetransmissionTime());
4343 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4344 QuicAckFrame ack = InitAckFrame(1);
4345 ProcessAckPacket(&ack);
4346 // Now we have an RTT sample of DefaultRetransmissionTime(500ms),
4347 // so the RTO has increased to 2 * SRTT.
4348 EXPECT_TRUE(retransmission_alarm->IsSet());
4349 EXPECT_EQ(retransmission_alarm->deadline(),
4350 clock_.Now() + 2 * DefaultRetransmissionTime());
4351
4352 // Move forward past the original RTO and ensure the RTO is still pending.
4353 clock_.AdvanceTime(2 * DefaultRetransmissionTime());
4354
4355 // Ensure the second packet gets retransmitted when it finally fires.
4356 EXPECT_TRUE(retransmission_alarm->IsSet());
4357 EXPECT_EQ(retransmission_alarm->deadline(), clock_.ApproximateNow());
4358 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4359 // Manually cancel the alarm to simulate a real test.
4360 connection_.GetRetransmissionAlarm()->Fire();
4361
4362 // The new retransmitted packet number should set the RTO to a larger value
4363 // than previously.
4364 EXPECT_TRUE(retransmission_alarm->IsSet());
4365 QuicTime next_rto_time = retransmission_alarm->deadline();
4366 QuicTime expected_rto_time =
4367 connection_.sent_packet_manager().GetRetransmissionTime();
4368 EXPECT_EQ(next_rto_time, expected_rto_time);
4369}
4370
4371TEST_P(QuicConnectionTest, TestQueued) {
4372 connection_.SetMaxTailLossProbes(0);
4373
4374 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4375 BlockOnNextWrite();
4376 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4377 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4378
4379 // Unblock the writes and actually send.
4380 writer_->SetWritable();
4381 connection_.OnCanWrite();
4382 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4383}
4384
4385TEST_P(QuicConnectionTest, InitialTimeout) {
4386 EXPECT_TRUE(connection_.connected());
4387 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4388 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4389
4390 // SetFromConfig sets the initial timeouts before negotiation.
4391 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4392 QuicConfig config;
4393 connection_.SetFromConfig(config);
4394 // Subtract a second from the idle timeout on the client side.
4395 QuicTime default_timeout =
4396 clock_.ApproximateNow() +
4397 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4398 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
4399
4400 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NETWORK_IDLE_TIMEOUT, _,
4401 ConnectionCloseSource::FROM_SELF));
4402 // Simulate the timeout alarm firing.
4403 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1));
4404 connection_.GetTimeoutAlarm()->Fire();
4405
4406 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4407 EXPECT_FALSE(connection_.connected());
4408
4409 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
4410 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4411 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4412 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4413 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
renjietang11e4a3d2019-05-03 11:27:26 -07004414 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004415}
4416
4417TEST_P(QuicConnectionTest, IdleTimeoutAfterFirstSentPacket) {
4418 EXPECT_TRUE(connection_.connected());
4419 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4420 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4421
4422 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4423 QuicConfig config;
4424 connection_.SetFromConfig(config);
4425 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4426 QuicTime initial_ddl =
4427 clock_.ApproximateNow() +
4428 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4429 EXPECT_EQ(initial_ddl, connection_.GetTimeoutAlarm()->deadline());
4430 EXPECT_TRUE(connection_.connected());
4431
4432 // Advance the time and send the first packet to the peer.
4433 clock_.AdvanceTime(QuicTime::Delta::FromMicroseconds(20));
4434 QuicPacketNumber last_packet;
4435 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4436 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4437 // This will be the updated deadline for the connection to idle time out.
4438 QuicTime new_ddl = clock_.ApproximateNow() +
4439 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4440
4441 // Simulate the timeout alarm firing, the connection should not be closed as
4442 // a new packet has been sent.
4443 EXPECT_CALL(visitor_, OnConnectionClosed(_, _, _)).Times(0);
4444 QuicTime::Delta delay = initial_ddl - clock_.ApproximateNow();
4445 clock_.AdvanceTime(delay);
4446 connection_.GetTimeoutAlarm()->Fire();
4447 // Verify the timeout alarm deadline is updated.
4448 EXPECT_TRUE(connection_.connected());
4449 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4450 EXPECT_EQ(new_ddl, connection_.GetTimeoutAlarm()->deadline());
4451
4452 // Simulate the timeout alarm firing again, the connection now should be
4453 // closed.
4454 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NETWORK_IDLE_TIMEOUT, _,
4455 ConnectionCloseSource::FROM_SELF));
4456 clock_.AdvanceTime(new_ddl - clock_.ApproximateNow());
4457 connection_.GetTimeoutAlarm()->Fire();
4458 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4459 EXPECT_FALSE(connection_.connected());
4460
4461 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
4462 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4463 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4464 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4465 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4466}
4467
4468TEST_P(QuicConnectionTest, IdleTimeoutAfterSendTwoPackets) {
4469 EXPECT_TRUE(connection_.connected());
4470 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4471 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4472
4473 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4474 QuicConfig config;
4475 connection_.SetFromConfig(config);
4476 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4477 QuicTime initial_ddl =
4478 clock_.ApproximateNow() +
4479 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4480 EXPECT_EQ(initial_ddl, connection_.GetTimeoutAlarm()->deadline());
4481 EXPECT_TRUE(connection_.connected());
4482
4483 // Immediately send the first packet, this is a rare case but test code will
4484 // hit this issue often as MockClock used for tests doesn't move with code
4485 // execution until manually adjusted.
4486 QuicPacketNumber last_packet;
4487 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4488 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4489
4490 // Advance the time and send the second packet to the peer.
4491 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
4492 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4493 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
4494
4495 if (GetQuicReloadableFlag(
4496 quic_fix_time_of_first_packet_sent_after_receiving)) {
4497 // Simulate the timeout alarm firing, the connection will be closed.
4498 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NETWORK_IDLE_TIMEOUT, _,
4499 ConnectionCloseSource::FROM_SELF));
4500 clock_.AdvanceTime(initial_ddl - clock_.ApproximateNow());
4501 connection_.GetTimeoutAlarm()->Fire();
4502 } else {
4503 // Simulate the timeout alarm firing, the connection will not be closed.
4504 EXPECT_CALL(visitor_, OnConnectionClosed(_, _, _)).Times(0);
4505 clock_.AdvanceTime(initial_ddl - clock_.ApproximateNow());
4506 connection_.GetTimeoutAlarm()->Fire();
4507 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4508 EXPECT_TRUE(connection_.connected());
4509
4510 // Advance another 20ms, and fire the alarm again. The connection will be
4511 // closed.
4512 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NETWORK_IDLE_TIMEOUT, _,
4513 ConnectionCloseSource::FROM_SELF));
4514 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
4515 connection_.GetTimeoutAlarm()->Fire();
4516 }
4517
4518 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4519 EXPECT_FALSE(connection_.connected());
4520
4521 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
4522 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4523 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4524 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4525 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4526}
4527
4528TEST_P(QuicConnectionTest, HandshakeTimeout) {
4529 // Use a shorter handshake timeout than idle timeout for this test.
4530 const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(5);
4531 connection_.SetNetworkTimeouts(timeout, timeout);
4532 EXPECT_TRUE(connection_.connected());
4533 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4534
4535 QuicTime handshake_timeout =
4536 clock_.ApproximateNow() + timeout - QuicTime::Delta::FromSeconds(1);
4537 EXPECT_EQ(handshake_timeout, connection_.GetTimeoutAlarm()->deadline());
4538 EXPECT_TRUE(connection_.connected());
4539
4540 // Send and ack new data 3 seconds later to lengthen the idle timeout.
4541 SendStreamDataToPeer(
4542 QuicUtils::GetHeadersStreamId(connection_.transport_version()), "GET /",
4543 0, FIN, nullptr);
4544 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(3));
4545 QuicAckFrame frame = InitAckFrame(1);
4546 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4547 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4548 ProcessAckPacket(&frame);
4549
4550 // Fire early to verify it wouldn't timeout yet.
4551 connection_.GetTimeoutAlarm()->Fire();
4552 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4553 EXPECT_TRUE(connection_.connected());
4554
4555 clock_.AdvanceTime(timeout - QuicTime::Delta::FromSeconds(2));
4556
4557 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_HANDSHAKE_TIMEOUT, _,
4558 ConnectionCloseSource::FROM_SELF));
4559 // Simulate the timeout alarm firing.
4560 connection_.GetTimeoutAlarm()->Fire();
4561
4562 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4563 EXPECT_FALSE(connection_.connected());
4564
4565 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
4566 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4567 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4568 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4569}
4570
4571TEST_P(QuicConnectionTest, PingAfterSend) {
QUICHE teamcd098022019-03-22 18:49:55 -07004572 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4573 return;
4574 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004575 EXPECT_TRUE(connection_.connected());
4576 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4577 .WillRepeatedly(Return(true));
4578 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4579
4580 // Advance to 5ms, and send a packet to the peer, which will set
4581 // the ping alarm.
4582 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4583 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4584 SendStreamDataToPeer(
4585 QuicUtils::GetHeadersStreamId(connection_.transport_version()), "GET /",
4586 0, FIN, nullptr);
4587 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4588 EXPECT_EQ(clock_.ApproximateNow() + QuicTime::Delta::FromSeconds(15),
4589 connection_.GetPingAlarm()->deadline());
4590
4591 // Now recevie an ACK of the previous packet, which will move the
4592 // ping alarm forward.
4593 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4594 QuicAckFrame frame = InitAckFrame(1);
4595 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4596 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4597 ProcessAckPacket(&frame);
4598 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4599 // The ping timer is set slightly less than 15 seconds in the future, because
4600 // of the 1s ping timer alarm granularity.
4601 EXPECT_EQ(clock_.ApproximateNow() + QuicTime::Delta::FromSeconds(15) -
4602 QuicTime::Delta::FromMilliseconds(5),
4603 connection_.GetPingAlarm()->deadline());
4604
4605 writer_->Reset();
4606 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15));
zhongyifbb25772019-04-10 16:54:08 -07004607 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004608 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07004609 size_t padding_frame_count = writer_->padding_frames().size();
4610 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004611 ASSERT_EQ(1u, writer_->ping_frames().size());
4612 writer_->Reset();
4613
4614 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4615 .WillRepeatedly(Return(false));
4616 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4617 SendAckPacketToPeer();
4618
4619 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4620}
4621
4622TEST_P(QuicConnectionTest, ReducedPingTimeout) {
QUICHE teamcd098022019-03-22 18:49:55 -07004623 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4624 return;
4625 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004626 EXPECT_TRUE(connection_.connected());
4627 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4628 .WillRepeatedly(Return(true));
4629 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4630
4631 // Use a reduced ping timeout for this connection.
4632 connection_.set_ping_timeout(QuicTime::Delta::FromSeconds(10));
4633
4634 // Advance to 5ms, and send a packet to the peer, which will set
4635 // the ping alarm.
4636 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4637 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4638 SendStreamDataToPeer(
4639 QuicUtils::GetHeadersStreamId(connection_.transport_version()), "GET /",
4640 0, FIN, nullptr);
4641 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4642 EXPECT_EQ(clock_.ApproximateNow() + QuicTime::Delta::FromSeconds(10),
4643 connection_.GetPingAlarm()->deadline());
4644
4645 // Now recevie an ACK of the previous packet, which will move the
4646 // ping alarm forward.
4647 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4648 QuicAckFrame frame = InitAckFrame(1);
4649 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4650 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4651 ProcessAckPacket(&frame);
4652 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4653 // The ping timer is set slightly less than 10 seconds in the future, because
4654 // of the 1s ping timer alarm granularity.
4655 EXPECT_EQ(clock_.ApproximateNow() + QuicTime::Delta::FromSeconds(10) -
4656 QuicTime::Delta::FromMilliseconds(5),
4657 connection_.GetPingAlarm()->deadline());
4658
4659 writer_->Reset();
4660 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
4661 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
4662 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
4663 }));
4664 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07004665 size_t padding_frame_count = writer_->padding_frames().size();
4666 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004667 ASSERT_EQ(1u, writer_->ping_frames().size());
4668 writer_->Reset();
4669
4670 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4671 .WillRepeatedly(Return(false));
4672 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4673 SendAckPacketToPeer();
4674
4675 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4676}
4677
4678// Tests whether sending an MTU discovery packet to peer successfully causes the
4679// maximum packet size to increase.
4680TEST_P(QuicConnectionTest, SendMtuDiscoveryPacket) {
QUICHE teamcd098022019-03-22 18:49:55 -07004681 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4682 return;
4683 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004684 EXPECT_TRUE(connection_.connected());
4685
4686 // Send an MTU probe.
4687 const size_t new_mtu = kDefaultMaxPacketSize + 100;
4688 QuicByteCount mtu_probe_size;
4689 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4690 .WillOnce(SaveArg<3>(&mtu_probe_size));
4691 connection_.SendMtuDiscoveryPacket(new_mtu);
4692 EXPECT_EQ(new_mtu, mtu_probe_size);
4693 EXPECT_EQ(QuicPacketNumber(1u), creator_->packet_number());
4694
4695 // Send more than MTU worth of data. No acknowledgement was received so far,
4696 // so the MTU should be at its old value.
vasilvvc48c8712019-03-11 13:38:16 -07004697 const std::string data(kDefaultMaxPacketSize + 1, '.');
QUICHE teama6ef0a62019-03-07 20:34:33 -05004698 QuicByteCount size_before_mtu_change;
4699 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4700 .Times(2)
4701 .WillOnce(SaveArg<3>(&size_before_mtu_change))
4702 .WillOnce(Return());
4703 connection_.SendStreamDataWithString(3, data, 0, FIN);
4704 EXPECT_EQ(QuicPacketNumber(3u), creator_->packet_number());
4705 EXPECT_EQ(kDefaultMaxPacketSize, size_before_mtu_change);
4706
4707 // Acknowledge all packets so far.
4708 QuicAckFrame probe_ack = InitAckFrame(3);
4709 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4710 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4711 ProcessAckPacket(&probe_ack);
4712 EXPECT_EQ(new_mtu, connection_.max_packet_length());
4713
4714 // Send the same data again. Check that it fits into a single packet now.
4715 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4716 connection_.SendStreamDataWithString(3, data, 0, FIN);
4717 EXPECT_EQ(QuicPacketNumber(4u), creator_->packet_number());
4718}
4719
4720// Tests whether MTU discovery does not happen when it is not explicitly enabled
4721// by the connection options.
4722TEST_P(QuicConnectionTest, MtuDiscoveryDisabled) {
4723 EXPECT_TRUE(connection_.connected());
4724
4725 const QuicPacketCount packets_between_probes_base = 10;
4726 set_packets_between_probes_base(packets_between_probes_base);
4727
4728 const QuicPacketCount number_of_packets = packets_between_probes_base * 2;
4729 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
4730 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
4731 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4732 EXPECT_EQ(0u, connection_.mtu_probe_count());
4733 }
4734}
4735
4736// Tests whether MTU discovery works when the probe gets acknowledged on the
4737// first try.
4738TEST_P(QuicConnectionTest, MtuDiscoveryEnabled) {
4739 EXPECT_TRUE(connection_.connected());
4740
4741 connection_.EnablePathMtuDiscovery(send_algorithm_);
4742
4743 const QuicPacketCount packets_between_probes_base = 5;
4744 set_packets_between_probes_base(packets_between_probes_base);
4745
4746 // Send enough packets so that the next one triggers path MTU discovery.
4747 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
4748 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
4749 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4750 }
4751
4752 // Trigger the probe.
4753 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
4754 nullptr);
4755 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4756 QuicByteCount probe_size;
4757 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4758 .WillOnce(SaveArg<3>(&probe_size));
4759 connection_.GetMtuDiscoveryAlarm()->Fire();
4760 EXPECT_EQ(kMtuDiscoveryTargetPacketSizeHigh, probe_size);
4761
4762 const QuicPacketNumber probe_packet_number =
4763 FirstSendingPacketNumber() + packets_between_probes_base;
4764 ASSERT_EQ(probe_packet_number, creator_->packet_number());
4765
4766 // Acknowledge all packets sent so far.
4767 QuicAckFrame probe_ack = InitAckFrame(probe_packet_number);
4768 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4769 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4770 ProcessAckPacket(&probe_ack);
4771 EXPECT_EQ(kMtuDiscoveryTargetPacketSizeHigh, connection_.max_packet_length());
4772 EXPECT_EQ(0u, connection_.GetBytesInFlight());
4773
4774 // Send more packets, and ensure that none of them sets the alarm.
4775 for (QuicPacketCount i = 0; i < 4 * packets_between_probes_base; i++) {
4776 SendStreamDataToPeer(3, ".", packets_between_probes_base + i, NO_FIN,
4777 nullptr);
4778 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4779 }
4780
4781 EXPECT_EQ(1u, connection_.mtu_probe_count());
4782}
4783
4784// Tests whether MTU discovery works correctly when the probes never get
4785// acknowledged.
4786TEST_P(QuicConnectionTest, MtuDiscoveryFailed) {
4787 EXPECT_TRUE(connection_.connected());
4788
4789 connection_.EnablePathMtuDiscovery(send_algorithm_);
4790
4791 const QuicTime::Delta rtt = QuicTime::Delta::FromMilliseconds(100);
4792
4793 EXPECT_EQ(kPacketsBetweenMtuProbesBase,
4794 QuicConnectionPeer::GetPacketsBetweenMtuProbes(&connection_));
4795 // Lower the number of probes between packets in order to make the test go
4796 // much faster.
4797 const QuicPacketCount packets_between_probes_base = 5;
4798 set_packets_between_probes_base(packets_between_probes_base);
4799
4800 // This tests sends more packets than strictly necessary to make sure that if
4801 // the connection was to send more discovery packets than needed, those would
4802 // get caught as well.
4803 const QuicPacketCount number_of_packets =
4804 packets_between_probes_base * (1 << (kMtuDiscoveryAttempts + 1));
4805 std::vector<QuicPacketNumber> mtu_discovery_packets;
4806 // Called by the first ack.
4807 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4808 // Called on many acks.
4809 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
4810 .Times(AnyNumber());
4811 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
4812 SendStreamDataToPeer(3, "!", i, NO_FIN, nullptr);
4813 clock_.AdvanceTime(rtt);
4814
4815 // Receive an ACK, which marks all data packets as received, and all MTU
4816 // discovery packets as missing.
4817
4818 QuicAckFrame ack;
4819
4820 if (!mtu_discovery_packets.empty()) {
4821 QuicPacketNumber min_packet = *min_element(mtu_discovery_packets.begin(),
4822 mtu_discovery_packets.end());
4823 QuicPacketNumber max_packet = *max_element(mtu_discovery_packets.begin(),
4824 mtu_discovery_packets.end());
4825 ack.packets.AddRange(QuicPacketNumber(1), min_packet);
4826 ack.packets.AddRange(QuicPacketNumber(max_packet + 1),
4827 creator_->packet_number() + 1);
4828 ack.largest_acked = creator_->packet_number();
4829
4830 } else {
4831 ack.packets.AddRange(QuicPacketNumber(1), creator_->packet_number() + 1);
4832 ack.largest_acked = creator_->packet_number();
4833 }
4834
4835 ProcessAckPacket(&ack);
4836
4837 // Trigger MTU probe if it would be scheduled now.
4838 if (!connection_.GetMtuDiscoveryAlarm()->IsSet()) {
4839 continue;
4840 }
4841
4842 // Fire the alarm. The alarm should cause a packet to be sent.
4843 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4844 connection_.GetMtuDiscoveryAlarm()->Fire();
4845 // Record the packet number of the MTU discovery packet in order to
4846 // mark it as NACK'd.
4847 mtu_discovery_packets.push_back(creator_->packet_number());
4848 }
4849
4850 // Ensure the number of packets between probes grows exponentially by checking
4851 // it against the closed-form expression for the packet number.
4852 ASSERT_EQ(kMtuDiscoveryAttempts, mtu_discovery_packets.size());
4853 for (uint64_t i = 0; i < kMtuDiscoveryAttempts; i++) {
4854 // 2^0 + 2^1 + 2^2 + ... + 2^n = 2^(n + 1) - 1
4855 const QuicPacketCount packets_between_probes =
4856 packets_between_probes_base * ((1 << (i + 1)) - 1);
4857 EXPECT_EQ(QuicPacketNumber(packets_between_probes + (i + 1)),
4858 mtu_discovery_packets[i]);
4859 }
4860
4861 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4862 EXPECT_EQ(kDefaultMaxPacketSize, connection_.max_packet_length());
4863 EXPECT_EQ(kMtuDiscoveryAttempts, connection_.mtu_probe_count());
4864}
4865
4866// Tests whether MTU discovery works when the writer has a limit on how large a
4867// packet can be.
4868TEST_P(QuicConnectionTest, MtuDiscoveryWriterLimited) {
4869 EXPECT_TRUE(connection_.connected());
4870
4871 const QuicByteCount mtu_limit = kMtuDiscoveryTargetPacketSizeHigh - 1;
4872 writer_->set_max_packet_size(mtu_limit);
4873 connection_.EnablePathMtuDiscovery(send_algorithm_);
4874
4875 const QuicPacketCount packets_between_probes_base = 5;
4876 set_packets_between_probes_base(packets_between_probes_base);
4877
4878 // Send enough packets so that the next one triggers path MTU discovery.
4879 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
4880 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
4881 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4882 }
4883
4884 // Trigger the probe.
4885 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
4886 nullptr);
4887 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4888 QuicByteCount probe_size;
4889 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4890 .WillOnce(SaveArg<3>(&probe_size));
4891 connection_.GetMtuDiscoveryAlarm()->Fire();
4892 EXPECT_EQ(mtu_limit, probe_size);
4893
4894 const QuicPacketNumber probe_sequence_number =
4895 FirstSendingPacketNumber() + packets_between_probes_base;
4896 ASSERT_EQ(probe_sequence_number, creator_->packet_number());
4897
4898 // Acknowledge all packets sent so far.
4899 QuicAckFrame probe_ack = InitAckFrame(probe_sequence_number);
4900 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4901 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4902 ProcessAckPacket(&probe_ack);
4903 EXPECT_EQ(mtu_limit, connection_.max_packet_length());
4904 EXPECT_EQ(0u, connection_.GetBytesInFlight());
4905
4906 // Send more packets, and ensure that none of them sets the alarm.
4907 for (QuicPacketCount i = 0; i < 4 * packets_between_probes_base; i++) {
4908 SendStreamDataToPeer(3, ".", packets_between_probes_base + i, NO_FIN,
4909 nullptr);
4910 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4911 }
4912
4913 EXPECT_EQ(1u, connection_.mtu_probe_count());
4914}
4915
4916// Tests whether MTU discovery works when the writer returns an error despite
4917// advertising higher packet length.
4918TEST_P(QuicConnectionTest, MtuDiscoveryWriterFailed) {
4919 EXPECT_TRUE(connection_.connected());
4920
4921 const QuicByteCount mtu_limit = kMtuDiscoveryTargetPacketSizeHigh - 1;
4922 const QuicByteCount initial_mtu = connection_.max_packet_length();
4923 EXPECT_LT(initial_mtu, mtu_limit);
4924 writer_->set_max_packet_size(mtu_limit);
4925 connection_.EnablePathMtuDiscovery(send_algorithm_);
4926
4927 const QuicPacketCount packets_between_probes_base = 5;
4928 set_packets_between_probes_base(packets_between_probes_base);
4929
4930 // Send enough packets so that the next one triggers path MTU discovery.
4931 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
4932 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
4933 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4934 }
4935
4936 // Trigger the probe.
4937 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
4938 nullptr);
4939 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4940 writer_->SimulateNextPacketTooLarge();
4941 connection_.GetMtuDiscoveryAlarm()->Fire();
4942 ASSERT_TRUE(connection_.connected());
4943
4944 // Send more data.
4945 QuicPacketNumber probe_number = creator_->packet_number();
4946 QuicPacketCount extra_packets = packets_between_probes_base * 3;
4947 for (QuicPacketCount i = 0; i < extra_packets; i++) {
4948 connection_.EnsureWritableAndSendStreamData5();
4949 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4950 }
4951
4952 // Acknowledge all packets sent so far, except for the lost probe.
4953 QuicAckFrame probe_ack =
4954 ConstructAckFrame(creator_->packet_number(), probe_number);
4955 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4956 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4957 ProcessAckPacket(&probe_ack);
4958 EXPECT_EQ(initial_mtu, connection_.max_packet_length());
4959
4960 // Send more packets, and ensure that none of them sets the alarm.
4961 for (QuicPacketCount i = 0; i < 4 * packets_between_probes_base; i++) {
4962 connection_.EnsureWritableAndSendStreamData5();
4963 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4964 }
4965
4966 EXPECT_EQ(initial_mtu, connection_.max_packet_length());
4967 EXPECT_EQ(1u, connection_.mtu_probe_count());
4968}
4969
4970TEST_P(QuicConnectionTest, NoMtuDiscoveryAfterConnectionClosed) {
4971 EXPECT_TRUE(connection_.connected());
4972
4973 connection_.EnablePathMtuDiscovery(send_algorithm_);
4974
4975 const QuicPacketCount packets_between_probes_base = 10;
4976 set_packets_between_probes_base(packets_between_probes_base);
4977
4978 // Send enough packets so that the next one triggers path MTU discovery.
4979 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
4980 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
4981 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4982 }
4983
4984 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
4985 nullptr);
4986 EXPECT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4987
4988 EXPECT_CALL(visitor_, OnConnectionClosed(_, _, _));
4989 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
4990 ConnectionCloseBehavior::SILENT_CLOSE);
4991 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4992}
4993
4994TEST_P(QuicConnectionTest, TimeoutAfterSend) {
4995 EXPECT_TRUE(connection_.connected());
4996 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4997 QuicConfig config;
4998 connection_.SetFromConfig(config);
4999 EXPECT_FALSE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
5000
5001 const QuicTime::Delta initial_idle_timeout =
5002 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5003 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5004 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
5005
5006 // When we send a packet, the timeout will change to 5ms +
5007 // kInitialIdleTimeoutSecs.
5008 clock_.AdvanceTime(five_ms);
5009 SendStreamDataToPeer(
5010 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5011 0, FIN, nullptr);
5012 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5013
5014 // Now send more data. This will not move the timeout because
5015 // no data has been received since the previous write.
5016 clock_.AdvanceTime(five_ms);
5017 SendStreamDataToPeer(
5018 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5019 3, FIN, nullptr);
5020 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5021
5022 // The original alarm will fire. We should not time out because we had a
5023 // network event at t=5ms. The alarm will reregister.
5024 clock_.AdvanceTime(initial_idle_timeout - five_ms - five_ms);
5025 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
5026 connection_.GetTimeoutAlarm()->Fire();
5027 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5028 EXPECT_TRUE(connection_.connected());
5029 EXPECT_EQ(default_timeout + five_ms,
5030 connection_.GetTimeoutAlarm()->deadline());
5031
5032 // This time, we should time out.
5033 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NETWORK_IDLE_TIMEOUT, _,
5034 ConnectionCloseSource::FROM_SELF));
5035 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5036 clock_.AdvanceTime(five_ms);
5037 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5038 connection_.GetTimeoutAlarm()->Fire();
5039 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5040 EXPECT_FALSE(connection_.connected());
5041}
5042
5043TEST_P(QuicConnectionTest, TimeoutAfterRetransmission) {
5044 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5045 EXPECT_TRUE(connection_.connected());
5046 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5047 QuicConfig config;
5048 connection_.SetFromConfig(config);
5049 EXPECT_FALSE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
5050
5051 const QuicTime start_time = clock_.Now();
5052 const QuicTime::Delta initial_idle_timeout =
5053 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5054 QuicTime default_timeout = clock_.Now() + initial_idle_timeout;
5055
5056 connection_.SetMaxTailLossProbes(0);
5057 const QuicTime default_retransmission_time =
5058 start_time + DefaultRetransmissionTime();
5059
5060 ASSERT_LT(default_retransmission_time, default_timeout);
5061
5062 // When we send a packet, the timeout will change to 5 ms +
5063 // kInitialIdleTimeoutSecs (but it will not reschedule the alarm).
5064 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5065 const QuicTime send_time = start_time + five_ms;
5066 clock_.AdvanceTime(five_ms);
5067 ASSERT_EQ(send_time, clock_.Now());
5068 SendStreamDataToPeer(
5069 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5070 0, FIN, nullptr);
5071 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5072
5073 // Move forward 5 ms and receive a packet, which will move the timeout
5074 // forward 5 ms more (but will not reschedule the alarm).
5075 const QuicTime receive_time = send_time + five_ms;
5076 clock_.AdvanceTime(receive_time - clock_.Now());
5077 ASSERT_EQ(receive_time, clock_.Now());
5078 ProcessPacket(1);
5079
5080 // Now move forward to the retransmission time and retransmit the
5081 // packet, which should move the timeout forward again (but will not
5082 // reschedule the alarm).
5083 EXPECT_EQ(default_retransmission_time + five_ms,
5084 connection_.GetRetransmissionAlarm()->deadline());
5085 // Simulate the retransmission alarm firing.
5086 const QuicTime rto_time = send_time + DefaultRetransmissionTime();
5087 const QuicTime final_timeout = rto_time + initial_idle_timeout;
5088 clock_.AdvanceTime(rto_time - clock_.Now());
5089 ASSERT_EQ(rto_time, clock_.Now());
5090 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _));
5091 connection_.GetRetransmissionAlarm()->Fire();
5092
5093 // Advance to the original timeout and fire the alarm. The connection should
5094 // timeout, and the alarm should be registered based on the time of the
5095 // retransmission.
5096 clock_.AdvanceTime(default_timeout - clock_.Now());
5097 ASSERT_EQ(default_timeout.ToDebuggingValue(),
5098 clock_.Now().ToDebuggingValue());
5099 EXPECT_EQ(default_timeout, clock_.Now());
5100 connection_.GetTimeoutAlarm()->Fire();
5101 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5102 EXPECT_TRUE(connection_.connected());
5103 ASSERT_EQ(final_timeout.ToDebuggingValue(),
5104 connection_.GetTimeoutAlarm()->deadline().ToDebuggingValue());
5105
5106 // This time, we should time out.
5107 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NETWORK_IDLE_TIMEOUT, _,
5108 ConnectionCloseSource::FROM_SELF));
5109 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5110 clock_.AdvanceTime(final_timeout - clock_.Now());
5111 EXPECT_EQ(connection_.GetTimeoutAlarm()->deadline(), clock_.Now());
5112 EXPECT_EQ(final_timeout, clock_.Now());
5113 connection_.GetTimeoutAlarm()->Fire();
5114 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5115 EXPECT_FALSE(connection_.connected());
5116}
5117
5118TEST_P(QuicConnectionTest, NewTimeoutAfterSendSilentClose) {
5119 // Same test as above, but complete a handshake which enables silent close,
5120 // causing no connection close packet to be sent.
5121 EXPECT_TRUE(connection_.connected());
5122 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5123 QuicConfig config;
5124
5125 // Create a handshake message that also enables silent close.
5126 CryptoHandshakeMessage msg;
vasilvvc48c8712019-03-11 13:38:16 -07005127 std::string error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005128 QuicConfig client_config;
5129 client_config.SetInitialStreamFlowControlWindowToSend(
5130 kInitialStreamFlowControlWindowForTest);
5131 client_config.SetInitialSessionFlowControlWindowToSend(
5132 kInitialSessionFlowControlWindowForTest);
5133 client_config.SetIdleNetworkTimeout(
5134 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs),
5135 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs));
fkastenholzd3a1de92019-05-15 07:00:07 -07005136 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005137 const QuicErrorCode error =
5138 config.ProcessPeerHello(msg, CLIENT, &error_details);
5139 EXPECT_EQ(QUIC_NO_ERROR, error);
5140
5141 connection_.SetFromConfig(config);
5142 EXPECT_TRUE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
5143
5144 const QuicTime::Delta default_idle_timeout =
5145 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs - 1);
5146 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5147 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5148
5149 // When we send a packet, the timeout will change to 5ms +
5150 // kInitialIdleTimeoutSecs.
5151 clock_.AdvanceTime(five_ms);
5152 SendStreamDataToPeer(
5153 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5154 0, FIN, nullptr);
5155 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5156
5157 // Now send more data. This will not move the timeout because
5158 // no data has been received since the previous write.
5159 clock_.AdvanceTime(five_ms);
5160 SendStreamDataToPeer(
5161 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5162 3, FIN, nullptr);
5163 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5164
5165 // The original alarm will fire. We should not time out because we had a
5166 // network event at t=5ms. The alarm will reregister.
5167 clock_.AdvanceTime(default_idle_timeout - five_ms - five_ms);
5168 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
5169 connection_.GetTimeoutAlarm()->Fire();
5170 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5171 EXPECT_TRUE(connection_.connected());
5172 EXPECT_EQ(default_timeout + five_ms,
5173 connection_.GetTimeoutAlarm()->deadline());
5174
5175 // This time, we should time out.
5176 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NETWORK_IDLE_TIMEOUT, _,
5177 ConnectionCloseSource::FROM_SELF));
5178 clock_.AdvanceTime(five_ms);
5179 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5180 connection_.GetTimeoutAlarm()->Fire();
5181 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5182 EXPECT_FALSE(connection_.connected());
5183}
5184
5185TEST_P(QuicConnectionTest, TimeoutAfterSendSilentCloseAndTLP) {
5186 // Same test as above, but complete a handshake which enables silent close,
5187 // but sending TLPs causes the connection close to be sent.
5188 EXPECT_TRUE(connection_.connected());
5189 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5190 QuicConfig config;
5191
5192 // Create a handshake message that also enables silent close.
5193 CryptoHandshakeMessage msg;
vasilvvc48c8712019-03-11 13:38:16 -07005194 std::string error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005195 QuicConfig client_config;
5196 client_config.SetInitialStreamFlowControlWindowToSend(
5197 kInitialStreamFlowControlWindowForTest);
5198 client_config.SetInitialSessionFlowControlWindowToSend(
5199 kInitialSessionFlowControlWindowForTest);
5200 client_config.SetIdleNetworkTimeout(
5201 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs),
5202 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs));
fkastenholzd3a1de92019-05-15 07:00:07 -07005203 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005204 const QuicErrorCode error =
5205 config.ProcessPeerHello(msg, CLIENT, &error_details);
5206 EXPECT_EQ(QUIC_NO_ERROR, error);
5207
5208 connection_.SetFromConfig(config);
5209 EXPECT_TRUE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
5210
5211 const QuicTime::Delta default_idle_timeout =
5212 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs - 1);
5213 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5214 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5215
5216 // When we send a packet, the timeout will change to 5ms +
5217 // kInitialIdleTimeoutSecs.
5218 clock_.AdvanceTime(five_ms);
5219 SendStreamDataToPeer(
5220 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5221 0, FIN, nullptr);
5222 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5223
5224 // Retransmit the packet via tail loss probe.
5225 clock_.AdvanceTime(connection_.GetRetransmissionAlarm()->deadline() -
5226 clock_.Now());
5227 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _));
5228 connection_.GetRetransmissionAlarm()->Fire();
5229
5230 // This time, we should time out and send a connection close due to the TLP.
5231 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NETWORK_IDLE_TIMEOUT, _,
5232 ConnectionCloseSource::FROM_SELF));
5233 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5234 clock_.AdvanceTime(connection_.GetTimeoutAlarm()->deadline() -
5235 clock_.ApproximateNow() + five_ms);
5236 connection_.GetTimeoutAlarm()->Fire();
5237 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5238 EXPECT_FALSE(connection_.connected());
5239}
5240
5241TEST_P(QuicConnectionTest, TimeoutAfterSendSilentCloseWithOpenStreams) {
5242 // Same test as above, but complete a handshake which enables silent close,
5243 // but having open streams causes the connection close to be sent.
5244 EXPECT_TRUE(connection_.connected());
5245 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5246 QuicConfig config;
5247
5248 // Create a handshake message that also enables silent close.
5249 CryptoHandshakeMessage msg;
vasilvvc48c8712019-03-11 13:38:16 -07005250 std::string error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005251 QuicConfig client_config;
5252 client_config.SetInitialStreamFlowControlWindowToSend(
5253 kInitialStreamFlowControlWindowForTest);
5254 client_config.SetInitialSessionFlowControlWindowToSend(
5255 kInitialSessionFlowControlWindowForTest);
5256 client_config.SetIdleNetworkTimeout(
5257 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs),
5258 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs));
fkastenholzd3a1de92019-05-15 07:00:07 -07005259 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005260 const QuicErrorCode error =
5261 config.ProcessPeerHello(msg, CLIENT, &error_details);
5262 EXPECT_EQ(QUIC_NO_ERROR, error);
5263
5264 connection_.SetFromConfig(config);
5265 EXPECT_TRUE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
5266
5267 const QuicTime::Delta default_idle_timeout =
5268 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs - 1);
5269 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5270 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5271
5272 // When we send a packet, the timeout will change to 5ms +
5273 // kInitialIdleTimeoutSecs.
5274 clock_.AdvanceTime(five_ms);
5275 SendStreamDataToPeer(
5276 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5277 0, FIN, nullptr);
5278 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5279
5280 // Indicate streams are still open.
5281 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
5282 .WillRepeatedly(Return(true));
5283
5284 // This time, we should time out and send a connection close due to the TLP.
5285 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NETWORK_IDLE_TIMEOUT, _,
5286 ConnectionCloseSource::FROM_SELF));
5287 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5288 clock_.AdvanceTime(connection_.GetTimeoutAlarm()->deadline() -
5289 clock_.ApproximateNow() + five_ms);
5290 connection_.GetTimeoutAlarm()->Fire();
5291 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5292 EXPECT_FALSE(connection_.connected());
5293}
5294
5295TEST_P(QuicConnectionTest, TimeoutAfterReceive) {
5296 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5297 EXPECT_TRUE(connection_.connected());
5298 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5299 QuicConfig config;
5300 connection_.SetFromConfig(config);
5301 EXPECT_FALSE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
5302
5303 const QuicTime::Delta initial_idle_timeout =
5304 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5305 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5306 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
5307
5308 connection_.SendStreamDataWithString(
5309 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5310 0, NO_FIN);
5311 connection_.SendStreamDataWithString(
5312 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5313 3, NO_FIN);
5314
5315 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5316 clock_.AdvanceTime(five_ms);
5317
5318 // When we receive a packet, the timeout will change to 5ms +
5319 // kInitialIdleTimeoutSecs.
5320 QuicAckFrame ack = InitAckFrame(2);
5321 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5322 ProcessAckPacket(&ack);
5323
5324 // The original alarm will fire. We should not time out because we had a
5325 // network event at t=5ms. The alarm will reregister.
5326 clock_.AdvanceTime(initial_idle_timeout - five_ms);
5327 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
5328 connection_.GetTimeoutAlarm()->Fire();
5329 EXPECT_TRUE(connection_.connected());
5330 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5331 EXPECT_EQ(default_timeout + five_ms,
5332 connection_.GetTimeoutAlarm()->deadline());
5333
5334 // This time, we should time out.
5335 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NETWORK_IDLE_TIMEOUT, _,
5336 ConnectionCloseSource::FROM_SELF));
5337 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5338 clock_.AdvanceTime(five_ms);
5339 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5340 connection_.GetTimeoutAlarm()->Fire();
5341 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5342 EXPECT_FALSE(connection_.connected());
5343}
5344
5345TEST_P(QuicConnectionTest, TimeoutAfterReceiveNotSendWhenUnacked) {
5346 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5347 EXPECT_TRUE(connection_.connected());
5348 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5349 QuicConfig config;
5350 connection_.SetFromConfig(config);
5351 EXPECT_FALSE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
5352
5353 const QuicTime::Delta initial_idle_timeout =
5354 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5355 connection_.SetNetworkTimeouts(
5356 QuicTime::Delta::Infinite(),
5357 initial_idle_timeout + QuicTime::Delta::FromSeconds(1));
5358 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5359 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
5360
5361 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5362 connection_.SendStreamDataWithString(
5363 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5364 0, NO_FIN);
5365 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5366 connection_.SendStreamDataWithString(
5367 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5368 3, NO_FIN);
5369
5370 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5371
5372 clock_.AdvanceTime(five_ms);
5373
5374 // When we receive a packet, the timeout will change to 5ms +
5375 // kInitialIdleTimeoutSecs.
5376 QuicAckFrame ack = InitAckFrame(2);
5377 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5378 ProcessAckPacket(&ack);
5379
5380 // The original alarm will fire. We should not time out because we had a
5381 // network event at t=5ms. The alarm will reregister.
5382 clock_.AdvanceTime(initial_idle_timeout - five_ms);
5383 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
5384 connection_.GetTimeoutAlarm()->Fire();
5385 EXPECT_TRUE(connection_.connected());
5386 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5387 EXPECT_EQ(default_timeout + five_ms,
5388 connection_.GetTimeoutAlarm()->deadline());
5389
5390 // Now, send packets while advancing the time and verify that the connection
5391 // eventually times out.
5392 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NETWORK_IDLE_TIMEOUT, _,
5393 ConnectionCloseSource::FROM_SELF));
5394 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
5395 for (int i = 0; i < 100 && connection_.connected(); ++i) {
5396 QUIC_LOG(INFO) << "sending data packet";
5397 connection_.SendStreamDataWithString(
5398 GetNthClientInitiatedStreamId(1, connection_.transport_version()),
5399 "foo", 0, NO_FIN);
5400 connection_.GetTimeoutAlarm()->Fire();
5401 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
5402 }
5403 EXPECT_FALSE(connection_.connected());
5404 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5405}
5406
5407TEST_P(QuicConnectionTest, TimeoutAfter5ClientRTOs) {
5408 connection_.SetMaxTailLossProbes(2);
5409 EXPECT_TRUE(connection_.connected());
5410 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5411 QuicConfig config;
5412 QuicTagVector connection_options;
5413 connection_options.push_back(k5RTO);
5414 config.SetConnectionOptionsToSend(connection_options);
5415 connection_.SetFromConfig(config);
5416
5417 // Send stream data.
5418 SendStreamDataToPeer(
5419 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5420 0, FIN, nullptr);
5421
5422 // Fire the retransmission alarm 6 times, twice for TLP and 4 times for RTO.
5423 for (int i = 0; i < 6; ++i) {
5424 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5425 connection_.GetRetransmissionAlarm()->Fire();
5426 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5427 EXPECT_TRUE(connection_.connected());
5428 }
5429
5430 EXPECT_EQ(2u, connection_.sent_packet_manager().GetConsecutiveTlpCount());
5431 EXPECT_EQ(4u, connection_.sent_packet_manager().GetConsecutiveRtoCount());
5432 // This time, we should time out.
5433 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_TOO_MANY_RTOS, _,
5434 ConnectionCloseSource::FROM_SELF));
5435 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5436 connection_.GetRetransmissionAlarm()->Fire();
5437 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5438 EXPECT_FALSE(connection_.connected());
5439}
5440
5441TEST_P(QuicConnectionTest, SendScheduler) {
5442 // Test that if we send a packet without delay, it is not queued.
5443 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
QUICHE team8c1daa22019-03-13 08:33:41 -07005444 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07005445 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005446 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
5447 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
QUICHE team6987b4a2019-03-15 16:23:04 -07005448 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05005449 HAS_RETRANSMITTABLE_DATA, false, false);
5450 EXPECT_EQ(0u, connection_.NumQueuedPackets());
5451}
5452
5453TEST_P(QuicConnectionTest, FailToSendFirstPacket) {
5454 // Test that the connection does not crash when it fails to send the first
5455 // packet at which point self_address_ might be uninitialized.
5456 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
5457 EXPECT_CALL(visitor_, OnConnectionClosed(_, _, _)).Times(1);
QUICHE team8c1daa22019-03-13 08:33:41 -07005458 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07005459 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005460 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
5461 writer_->SetShouldWriteFail();
QUICHE team6987b4a2019-03-15 16:23:04 -07005462 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05005463 HAS_RETRANSMITTABLE_DATA, false, false);
5464}
5465
5466TEST_P(QuicConnectionTest, SendSchedulerEAGAIN) {
5467 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
QUICHE team8c1daa22019-03-13 08:33:41 -07005468 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07005469 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005470 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
5471 BlockOnNextWrite();
5472 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _))
5473 .Times(0);
QUICHE team6987b4a2019-03-15 16:23:04 -07005474 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05005475 HAS_RETRANSMITTABLE_DATA, false, false);
5476 EXPECT_EQ(1u, connection_.NumQueuedPackets());
5477}
5478
5479TEST_P(QuicConnectionTest, TestQueueLimitsOnSendStreamData) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005480 // Queue the first packet.
ianswett3085da82019-04-04 07:24:24 -07005481 size_t payload_length = connection_.max_packet_length();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005482 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(testing::Return(false));
vasilvvc48c8712019-03-11 13:38:16 -07005483 const std::string payload(payload_length, 'a');
ianswett3085da82019-04-04 07:24:24 -07005484 QuicStreamId first_bidi_stream_id(QuicUtils::GetFirstBidirectionalStreamId(
5485 connection_.version().transport_version, Perspective::IS_CLIENT));
5486 EXPECT_EQ(0u, connection_
5487 .SendStreamDataWithString(first_bidi_stream_id, payload, 0,
5488 NO_FIN)
QUICHE teama6ef0a62019-03-07 20:34:33 -05005489 .bytes_consumed);
5490 EXPECT_EQ(0u, connection_.NumQueuedPackets());
5491}
5492
ianswett3085da82019-04-04 07:24:24 -07005493TEST_P(QuicConnectionTest, SendingThreePackets) {
ianswett3085da82019-04-04 07:24:24 -07005494 // Make the payload twice the size of the packet, so 3 packets are written.
5495 size_t total_payload_length = 2 * connection_.max_packet_length();
vasilvvc48c8712019-03-11 13:38:16 -07005496 const std::string payload(total_payload_length, 'a');
ianswett3085da82019-04-04 07:24:24 -07005497 QuicStreamId first_bidi_stream_id(QuicUtils::GetFirstBidirectionalStreamId(
5498 connection_.version().transport_version, Perspective::IS_CLIENT));
5499 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
5500 EXPECT_EQ(payload.size(), connection_
5501 .SendStreamDataWithString(first_bidi_stream_id,
5502 payload, 0, NO_FIN)
5503 .bytes_consumed);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005504}
5505
5506TEST_P(QuicConnectionTest, LoopThroughSendingPacketsWithTruncation) {
5507 set_perspective(Perspective::IS_SERVER);
fayangd4291e42019-05-30 10:31:21 -07005508 if (!VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005509 // For IETF QUIC, encryption level will be switched to FORWARD_SECURE in
5510 // SendStreamDataWithString.
5511 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
5512 }
5513 // Set up a larger payload than will fit in one packet.
vasilvvc48c8712019-03-11 13:38:16 -07005514 const std::string payload(connection_.max_packet_length(), 'a');
QUICHE teama6ef0a62019-03-07 20:34:33 -05005515 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
5516
5517 // Now send some packets with no truncation.
5518 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
5519 EXPECT_EQ(payload.size(),
5520 connection_.SendStreamDataWithString(3, payload, 0, NO_FIN)
5521 .bytes_consumed);
5522 // Track the size of the second packet here. The overhead will be the largest
5523 // we see in this test, due to the non-truncated connection id.
5524 size_t non_truncated_packet_size = writer_->last_packet_size();
5525
5526 // Change to a 0 byte connection id.
5527 QuicConfig config;
5528 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
5529 connection_.SetFromConfig(config);
5530 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
5531 EXPECT_EQ(payload.size(),
5532 connection_.SendStreamDataWithString(3, payload, 1350, NO_FIN)
5533 .bytes_consumed);
fayangd4291e42019-05-30 10:31:21 -07005534 if (VersionHasIetfInvariantHeader(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005535 // Short header packets sent from server omit connection ID already, and
5536 // stream offset size increases from 0 to 2.
5537 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() - 2);
5538 } else {
5539 // Just like above, we save 8 bytes on payload, and 8 on truncation. -2
5540 // because stream offset size is 2 instead of 0.
5541 EXPECT_EQ(non_truncated_packet_size,
5542 writer_->last_packet_size() + 8 * 2 - 2);
5543 }
5544}
5545
5546TEST_P(QuicConnectionTest, SendDelayedAck) {
5547 QuicTime ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
5548 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5549 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5550 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07005551 SetDecrypter(ENCRYPTION_ZERO_RTT,
5552 QuicMakeUnique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005553 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
5554 QuicMakeUnique<TaggingEncrypter>(tag));
5555 // Process a packet from the non-crypto stream.
5556 frame1_.stream_id = 3;
5557
5558 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07005559 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005560 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5561 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5562
5563 // Check if delayed ack timer is running for the expected interval.
5564 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5565 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5566 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07005567 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005568 connection_.GetAckAlarm()->Fire();
5569 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07005570 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005571 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07005572 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005573 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
5574 } else {
nharper55fa6132019-05-07 19:37:21 -07005575 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005576 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
5577 }
5578 EXPECT_FALSE(writer_->ack_frames().empty());
5579 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5580}
5581
5582TEST_P(QuicConnectionTest, SendDelayedAfterQuiescence) {
5583 QuicConnectionPeer::SetFastAckAfterQuiescence(&connection_, true);
5584
5585 // The beginning of the connection counts as quiescence.
5586 QuicTime ack_time =
5587 clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
5588 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5589 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5590 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07005591 SetDecrypter(ENCRYPTION_ZERO_RTT,
5592 QuicMakeUnique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005593 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
5594 QuicMakeUnique<TaggingEncrypter>(tag));
5595 // Process a packet from the non-crypto stream.
5596 frame1_.stream_id = 3;
5597
5598 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07005599 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005600 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5601 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5602
5603 // Check if delayed ack timer is running for the expected interval.
5604 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5605 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5606 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07005607 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005608 connection_.GetAckAlarm()->Fire();
5609 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07005610 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005611 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07005612 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005613 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
5614 } else {
nharper55fa6132019-05-07 19:37:21 -07005615 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005616 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
5617 }
5618 EXPECT_FALSE(writer_->ack_frames().empty());
5619 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5620
5621 // Process another packet immedately after sending the ack and expect the
5622 // ack alarm to be set delayed ack time in the future.
5623 ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
5624 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5625 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5626
5627 // Check if delayed ack timer is running for the expected interval.
5628 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5629 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5630 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07005631 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005632 connection_.GetAckAlarm()->Fire();
5633 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07005634 padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005635 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07005636 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005637 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
5638 } else {
nharper55fa6132019-05-07 19:37:21 -07005639 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005640 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
5641 }
5642 EXPECT_FALSE(writer_->ack_frames().empty());
5643 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5644
5645 // Wait 1 second and enesure the ack alarm is set to 1ms in the future.
5646 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
5647 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
5648 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5649 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5650
5651 // Check if delayed ack timer is running for the expected interval.
5652 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5653 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5654}
5655
5656TEST_P(QuicConnectionTest, SendDelayedAckDecimation) {
5657 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
5658 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION);
5659
5660 const size_t kMinRttMs = 40;
5661 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
5662 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
5663 QuicTime::Delta::Zero(), QuicTime::Zero());
5664 // The ack time should be based on min_rtt/4, since it's less than the
5665 // default delayed ack time.
5666 QuicTime ack_time = clock_.ApproximateNow() +
5667 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
5668 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5669 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5670 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07005671 SetDecrypter(ENCRYPTION_ZERO_RTT,
5672 QuicMakeUnique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005673 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
5674 QuicMakeUnique<TaggingEncrypter>(tag));
5675 // Process a packet from the non-crypto stream.
5676 frame1_.stream_id = 3;
5677
5678 // Process all the initial packets in order so there aren't missing packets.
5679 uint64_t kFirstDecimatedPacket = 101;
5680 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
5681 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5682 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5683 }
5684 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5685 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07005686 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005687 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5688 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
5689 ENCRYPTION_ZERO_RTT);
5690
5691 // Check if delayed ack timer is running for the expected interval.
5692 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5693 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5694
5695 // The 10th received packet causes an ack to be sent.
5696 for (int i = 0; i < 9; ++i) {
5697 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5698 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5699 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
5700 ENCRYPTION_ZERO_RTT);
5701 }
5702 // Check that ack is sent and that delayed ack alarm is reset.
5703 if (GetParam().no_stop_waiting) {
5704 EXPECT_EQ(1u, writer_->frame_count());
5705 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
5706 } else {
5707 EXPECT_EQ(2u, writer_->frame_count());
5708 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
5709 }
5710 EXPECT_FALSE(writer_->ack_frames().empty());
5711 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5712}
5713
5714TEST_P(QuicConnectionTest, SendDelayedAckAckDecimationAfterQuiescence) {
5715 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
5716 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION);
5717 QuicConnectionPeer::SetFastAckAfterQuiescence(&connection_, true);
5718
5719 const size_t kMinRttMs = 40;
5720 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
5721 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
5722 QuicTime::Delta::Zero(), QuicTime::Zero());
5723
5724 // The beginning of the connection counts as quiescence.
5725 QuicTime ack_time =
5726 clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
5727 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5728 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5729 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07005730 SetDecrypter(ENCRYPTION_ZERO_RTT,
5731 QuicMakeUnique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005732 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
5733 QuicMakeUnique<TaggingEncrypter>(tag));
5734 // Process a packet from the non-crypto stream.
5735 frame1_.stream_id = 3;
5736
5737 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07005738 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005739 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5740 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5741
5742 // Check if delayed ack timer is running for the expected interval.
5743 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5744 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5745 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07005746 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005747 connection_.GetAckAlarm()->Fire();
5748 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07005749 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005750 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07005751 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005752 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
5753 } else {
nharper55fa6132019-05-07 19:37:21 -07005754 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005755 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
5756 }
5757 EXPECT_FALSE(writer_->ack_frames().empty());
5758 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5759
5760 // Process another packet immedately after sending the ack and expect the
5761 // ack alarm to be set delayed ack time in the future.
5762 ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
5763 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5764 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5765
5766 // Check if delayed ack timer is running for the expected interval.
5767 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5768 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5769 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07005770 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005771 connection_.GetAckAlarm()->Fire();
5772 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07005773 padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005774 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07005775 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005776 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
5777 } else {
nharper55fa6132019-05-07 19:37:21 -07005778 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005779 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
5780 }
5781 EXPECT_FALSE(writer_->ack_frames().empty());
5782 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5783
5784 // Wait 1 second and enesure the ack alarm is set to 1ms in the future.
5785 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
5786 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
5787 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5788 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5789
5790 // Check if delayed ack timer is running for the expected interval.
5791 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5792 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5793
5794 // Process enough packets to get into ack decimation behavior.
5795 // The ack time should be based on min_rtt/4, since it's less than the
5796 // default delayed ack time.
5797 ack_time = clock_.ApproximateNow() +
5798 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
5799 uint64_t kFirstDecimatedPacket = 101;
5800 for (unsigned int i = 0; i < kFirstDecimatedPacket - 4; ++i) {
5801 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5802 ProcessDataPacketAtLevel(4 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5803 }
5804 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5805 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07005806 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005807 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5808 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
5809 ENCRYPTION_ZERO_RTT);
5810
5811 // Check if delayed ack timer is running for the expected interval.
5812 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5813 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5814
5815 // The 10th received packet causes an ack to be sent.
5816 for (int i = 0; i < 9; ++i) {
5817 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5818 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5819 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
5820 ENCRYPTION_ZERO_RTT);
5821 }
5822 // Check that ack is sent and that delayed ack alarm is reset.
5823 if (GetParam().no_stop_waiting) {
5824 EXPECT_EQ(1u, writer_->frame_count());
5825 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
5826 } else {
5827 EXPECT_EQ(2u, writer_->frame_count());
5828 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
5829 }
5830 EXPECT_FALSE(writer_->ack_frames().empty());
5831 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5832
5833 // Wait 1 second and enesure the ack alarm is set to 1ms in the future.
5834 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
5835 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
5836 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5837 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 10, !kHasStopWaiting,
5838 ENCRYPTION_ZERO_RTT);
5839
5840 // Check if delayed ack timer is running for the expected interval.
5841 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5842 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5843}
5844
5845TEST_P(QuicConnectionTest, SendDelayedAckDecimationUnlimitedAggregation) {
5846 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
5847 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5848 QuicConfig config;
5849 QuicTagVector connection_options;
5850 connection_options.push_back(kACKD);
5851 // No limit on the number of packets received before sending an ack.
5852 connection_options.push_back(kAKDU);
5853 config.SetConnectionOptionsToSend(connection_options);
5854 connection_.SetFromConfig(config);
5855
5856 const size_t kMinRttMs = 40;
5857 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
5858 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
5859 QuicTime::Delta::Zero(), QuicTime::Zero());
5860 // The ack time should be based on min_rtt/4, since it's less than the
5861 // default delayed ack time.
5862 QuicTime ack_time = clock_.ApproximateNow() +
5863 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
5864 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5865 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5866 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07005867 SetDecrypter(ENCRYPTION_ZERO_RTT,
5868 QuicMakeUnique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005869 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
5870 QuicMakeUnique<TaggingEncrypter>(tag));
5871 // Process a packet from the non-crypto stream.
5872 frame1_.stream_id = 3;
5873
5874 // Process all the initial packets in order so there aren't missing packets.
5875 uint64_t kFirstDecimatedPacket = 101;
5876 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
5877 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5878 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5879 }
5880 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5881 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07005882 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005883 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5884 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
5885 ENCRYPTION_ZERO_RTT);
5886
5887 // Check if delayed ack timer is running for the expected interval.
5888 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5889 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5890
5891 // 18 packets will not cause an ack to be sent. 19 will because when
5892 // stop waiting frames are in use, we ack every 20 packets no matter what.
5893 for (int i = 0; i < 18; ++i) {
5894 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5895 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5896 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
5897 ENCRYPTION_ZERO_RTT);
5898 }
5899 // The delayed ack timer should still be set to the expected deadline.
5900 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5901 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5902}
5903
5904TEST_P(QuicConnectionTest, SendDelayedAckDecimationEighthRtt) {
5905 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
5906 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION);
5907 QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
5908
5909 const size_t kMinRttMs = 40;
5910 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
5911 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
5912 QuicTime::Delta::Zero(), QuicTime::Zero());
5913 // The ack time should be based on min_rtt/8, since it's less than the
5914 // default delayed ack time.
5915 QuicTime ack_time = clock_.ApproximateNow() +
5916 QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
5917 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5918 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5919 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07005920 SetDecrypter(ENCRYPTION_ZERO_RTT,
5921 QuicMakeUnique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005922 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
5923 QuicMakeUnique<TaggingEncrypter>(tag));
5924 // Process a packet from the non-crypto stream.
5925 frame1_.stream_id = 3;
5926
5927 // Process all the initial packets in order so there aren't missing packets.
5928 uint64_t kFirstDecimatedPacket = 101;
5929 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
5930 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5931 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5932 }
5933 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5934 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07005935 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005936 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5937 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
5938 ENCRYPTION_ZERO_RTT);
5939
5940 // Check if delayed ack timer is running for the expected interval.
5941 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5942 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5943
5944 // The 10th received packet causes an ack to be sent.
5945 for (int i = 0; i < 9; ++i) {
5946 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5947 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5948 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
5949 ENCRYPTION_ZERO_RTT);
5950 }
5951 // Check that ack is sent and that delayed ack alarm is reset.
5952 if (GetParam().no_stop_waiting) {
5953 EXPECT_EQ(1u, writer_->frame_count());
5954 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
5955 } else {
5956 EXPECT_EQ(2u, writer_->frame_count());
5957 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
5958 }
5959 EXPECT_FALSE(writer_->ack_frames().empty());
5960 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5961}
5962
5963TEST_P(QuicConnectionTest, SendDelayedAckDecimationWithReordering) {
5964 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
5965 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
5966
5967 const size_t kMinRttMs = 40;
5968 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
5969 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
5970 QuicTime::Delta::Zero(), QuicTime::Zero());
5971 // The ack time should be based on min_rtt/4, since it's less than the
5972 // default delayed ack time.
5973 QuicTime ack_time = clock_.ApproximateNow() +
5974 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
5975 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5976 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5977 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07005978 SetDecrypter(ENCRYPTION_ZERO_RTT,
5979 QuicMakeUnique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005980 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
5981 QuicMakeUnique<TaggingEncrypter>(tag));
5982 // Process a packet from the non-crypto stream.
5983 frame1_.stream_id = 3;
5984
5985 // Process all the initial packets in order so there aren't missing packets.
5986 uint64_t kFirstDecimatedPacket = 101;
5987 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
5988 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5989 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5990 }
5991 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5992
5993 // Receive one packet out of order and then the rest in order.
5994 // The loop leaves a one packet gap between acks sent to simulate some loss.
5995 for (int j = 0; j < 3; ++j) {
5996 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
5997 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5998 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 9 + (j * 11),
5999 !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6000 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
6001 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6002 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6003
6004 // The 10th received packet causes an ack to be sent.
6005 writer_->Reset();
6006 for (int i = 0; i < 9; ++i) {
6007 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6008 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6009 // The ACK shouldn't be sent until the 10th packet is processed.
6010 EXPECT_TRUE(writer_->ack_frames().empty());
6011 ProcessDataPacketAtLevel(kFirstDecimatedPacket + i + (j * 11),
6012 !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6013 }
6014 // Check that ack is sent and that delayed ack alarm is reset.
6015 if (GetParam().no_stop_waiting) {
6016 EXPECT_EQ(1u, writer_->frame_count());
6017 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6018 } else {
6019 EXPECT_EQ(2u, writer_->frame_count());
6020 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6021 }
6022 EXPECT_FALSE(writer_->ack_frames().empty());
6023 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6024 }
6025}
6026
6027TEST_P(QuicConnectionTest, SendDelayedAckDecimationWithLargeReordering) {
6028 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6029 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6030
6031 const size_t kMinRttMs = 40;
6032 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6033 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6034 QuicTime::Delta::Zero(), QuicTime::Zero());
6035 // The ack time should be based on min_rtt/4, since it's less than the
6036 // default delayed ack time.
6037 QuicTime ack_time = clock_.ApproximateNow() +
6038 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6039 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6040 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6041 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006042 SetDecrypter(ENCRYPTION_ZERO_RTT,
6043 QuicMakeUnique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006044 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
6045 QuicMakeUnique<TaggingEncrypter>(tag));
6046 // Process a packet from the non-crypto stream.
6047 frame1_.stream_id = 3;
6048
6049 // Process all the initial packets in order so there aren't missing packets.
6050 uint64_t kFirstDecimatedPacket = 101;
6051 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6052 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6053 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6054 }
6055 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6056 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006057 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006058 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6059 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6060 ENCRYPTION_ZERO_RTT);
6061
6062 // Check if delayed ack timer is running for the expected interval.
6063 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6064 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6065
6066 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6067 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6068 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 19, !kHasStopWaiting,
6069 ENCRYPTION_ZERO_RTT);
6070 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
6071 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6072 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6073
6074 // The 10th received packet causes an ack to be sent.
6075 for (int i = 0; i < 8; ++i) {
6076 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6077 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6078 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6079 ENCRYPTION_ZERO_RTT);
6080 }
6081 // Check that ack is sent and that delayed ack alarm is reset.
6082 if (GetParam().no_stop_waiting) {
6083 EXPECT_EQ(1u, writer_->frame_count());
6084 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6085 } else {
6086 EXPECT_EQ(2u, writer_->frame_count());
6087 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6088 }
6089 EXPECT_FALSE(writer_->ack_frames().empty());
6090 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6091
6092 // The next packet received in order will cause an immediate ack,
6093 // because it fills a hole.
6094 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6095 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6096 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 10, !kHasStopWaiting,
6097 ENCRYPTION_ZERO_RTT);
6098 // Check that ack is sent and that delayed ack alarm is reset.
6099 if (GetParam().no_stop_waiting) {
6100 EXPECT_EQ(1u, writer_->frame_count());
6101 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6102 } else {
6103 EXPECT_EQ(2u, writer_->frame_count());
6104 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6105 }
6106 EXPECT_FALSE(writer_->ack_frames().empty());
6107 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6108}
6109
6110TEST_P(QuicConnectionTest, SendDelayedAckDecimationWithReorderingEighthRtt) {
6111 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6112 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6113 QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
6114
6115 const size_t kMinRttMs = 40;
6116 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6117 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6118 QuicTime::Delta::Zero(), QuicTime::Zero());
6119 // The ack time should be based on min_rtt/8, since it's less than the
6120 // default delayed ack time.
6121 QuicTime ack_time = clock_.ApproximateNow() +
6122 QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
6123 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6124 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6125 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006126 SetDecrypter(ENCRYPTION_ZERO_RTT,
6127 QuicMakeUnique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006128 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
6129 QuicMakeUnique<TaggingEncrypter>(tag));
6130 // Process a packet from the non-crypto stream.
6131 frame1_.stream_id = 3;
6132
6133 // Process all the initial packets in order so there aren't missing packets.
6134 uint64_t kFirstDecimatedPacket = 101;
6135 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6136 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6137 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6138 }
6139 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6140 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006141 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006142 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6143 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6144 ENCRYPTION_ZERO_RTT);
6145
6146 // Check if delayed ack timer is running for the expected interval.
6147 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6148 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6149
6150 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6151 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6152 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 9, !kHasStopWaiting,
6153 ENCRYPTION_ZERO_RTT);
6154 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
6155 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6156 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6157
6158 // The 10th received packet causes an ack to be sent.
6159 for (int i = 0; i < 8; ++i) {
6160 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6161 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6162 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6163 ENCRYPTION_ZERO_RTT);
6164 }
6165 // Check that ack is sent and that delayed ack alarm is reset.
6166 if (GetParam().no_stop_waiting) {
6167 EXPECT_EQ(1u, writer_->frame_count());
6168 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6169 } else {
6170 EXPECT_EQ(2u, writer_->frame_count());
6171 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6172 }
6173 EXPECT_FALSE(writer_->ack_frames().empty());
6174 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6175}
6176
6177TEST_P(QuicConnectionTest,
6178 SendDelayedAckDecimationWithLargeReorderingEighthRtt) {
6179 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6180 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6181 QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
6182
6183 const size_t kMinRttMs = 40;
6184 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6185 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6186 QuicTime::Delta::Zero(), QuicTime::Zero());
6187 // The ack time should be based on min_rtt/8, since it's less than the
6188 // default delayed ack time.
6189 QuicTime ack_time = clock_.ApproximateNow() +
6190 QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
6191 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6192 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6193 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006194 SetDecrypter(ENCRYPTION_ZERO_RTT,
6195 QuicMakeUnique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006196 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
6197 QuicMakeUnique<TaggingEncrypter>(tag));
6198 // Process a packet from the non-crypto stream.
6199 frame1_.stream_id = 3;
6200
6201 // Process all the initial packets in order so there aren't missing packets.
6202 uint64_t kFirstDecimatedPacket = 101;
6203 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6204 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6205 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6206 }
6207 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6208 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006209 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006210 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6211 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6212 ENCRYPTION_ZERO_RTT);
6213
6214 // Check if delayed ack timer is running for the expected interval.
6215 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6216 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6217
6218 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6219 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6220 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 19, !kHasStopWaiting,
6221 ENCRYPTION_ZERO_RTT);
6222 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
6223 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6224 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6225
6226 // The 10th received packet causes an ack to be sent.
6227 for (int i = 0; i < 8; ++i) {
6228 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6229 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6230 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6231 ENCRYPTION_ZERO_RTT);
6232 }
6233 // Check that ack is sent and that delayed ack alarm is reset.
6234 if (GetParam().no_stop_waiting) {
6235 EXPECT_EQ(1u, writer_->frame_count());
6236 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6237 } else {
6238 EXPECT_EQ(2u, writer_->frame_count());
6239 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6240 }
6241 EXPECT_FALSE(writer_->ack_frames().empty());
6242 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6243
6244 // The next packet received in order will cause an immediate ack,
6245 // because it fills a hole.
6246 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6247 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6248 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 10, !kHasStopWaiting,
6249 ENCRYPTION_ZERO_RTT);
6250 // Check that ack is sent and that delayed ack alarm is reset.
6251 if (GetParam().no_stop_waiting) {
6252 EXPECT_EQ(1u, writer_->frame_count());
6253 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6254 } else {
6255 EXPECT_EQ(2u, writer_->frame_count());
6256 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6257 }
6258 EXPECT_FALSE(writer_->ack_frames().empty());
6259 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6260}
6261
6262TEST_P(QuicConnectionTest, SendDelayedAckOnHandshakeConfirmed) {
6263 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6264 ProcessPacket(1);
6265 // Check that ack is sent and that delayed ack alarm is set.
6266 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6267 QuicTime ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6268 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6269
6270 // Completing the handshake as the server does nothing.
6271 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_SERVER);
6272 connection_.OnHandshakeComplete();
6273 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6274 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6275
6276 // Complete the handshake as the client decreases the delayed ack time to 0ms.
6277 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_CLIENT);
6278 connection_.OnHandshakeComplete();
6279 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6280 EXPECT_EQ(clock_.ApproximateNow(), connection_.GetAckAlarm()->deadline());
6281}
6282
6283TEST_P(QuicConnectionTest, SendDelayedAckOnSecondPacket) {
6284 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6285 ProcessPacket(1);
6286 ProcessPacket(2);
6287 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006288 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006289 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006290 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006291 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6292 } else {
nharper55fa6132019-05-07 19:37:21 -07006293 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006294 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6295 }
6296 EXPECT_FALSE(writer_->ack_frames().empty());
6297 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6298}
6299
6300TEST_P(QuicConnectionTest, NoAckOnOldNacks) {
6301 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6302 // Drop one packet, triggering a sequence of acks.
6303 if (GetQuicRestartFlag(quic_enable_accept_random_ipn)) {
6304 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6305 } else {
6306 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
6307 }
6308 ProcessPacket(2);
6309 size_t frames_per_ack = GetParam().no_stop_waiting ? 1 : 2;
6310 if (!GetQuicRestartFlag(quic_enable_accept_random_ipn)) {
nharper55fa6132019-05-07 19:37:21 -07006311 size_t padding_frame_count = writer_->padding_frames().size();
6312 EXPECT_EQ(padding_frame_count + frames_per_ack, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006313 EXPECT_FALSE(writer_->ack_frames().empty());
6314 writer_->Reset();
6315 }
6316
6317 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
6318 ProcessPacket(3);
nharper55fa6132019-05-07 19:37:21 -07006319 size_t padding_frame_count = writer_->padding_frames().size();
6320 EXPECT_EQ(padding_frame_count + frames_per_ack, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006321 EXPECT_FALSE(writer_->ack_frames().empty());
6322 writer_->Reset();
6323
6324 if (GetQuicRestartFlag(quic_enable_accept_random_ipn)) {
6325 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6326 } else {
6327 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
6328 }
6329 ProcessPacket(4);
6330 if (GetQuicRestartFlag(quic_enable_accept_random_ipn)) {
6331 EXPECT_EQ(0u, writer_->frame_count());
6332 } else {
nharper55fa6132019-05-07 19:37:21 -07006333 EXPECT_EQ(padding_frame_count + frames_per_ack, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006334 EXPECT_FALSE(writer_->ack_frames().empty());
6335 writer_->Reset();
6336 }
6337
6338 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
6339 ProcessPacket(5);
nharper55fa6132019-05-07 19:37:21 -07006340 padding_frame_count = writer_->padding_frames().size();
6341 EXPECT_EQ(padding_frame_count + frames_per_ack, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006342 EXPECT_FALSE(writer_->ack_frames().empty());
6343 writer_->Reset();
6344
6345 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6346 // Now only set the timer on the 6th packet, instead of sending another ack.
6347 ProcessPacket(6);
nharper55fa6132019-05-07 19:37:21 -07006348 padding_frame_count = writer_->padding_frames().size();
6349 EXPECT_EQ(padding_frame_count, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006350 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6351}
6352
6353TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingPacket) {
6354 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
QUICHE team8c1daa22019-03-13 08:33:41 -07006355 EXPECT_CALL(visitor_, OnStreamFrame(_));
6356 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
6357 QuicMakeUnique<TaggingEncrypter>(0x01));
zhongyi546cc452019-04-12 15:27:49 -07006358 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
6359 QuicMakeUnique<StrictTaggingDecrypter>(0x01));
nharper2c9f02a2019-05-08 10:25:50 -07006360 ProcessDataPacket(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006361 connection_.SendStreamDataWithString(
6362 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6363 0, NO_FIN);
6364 // Check that ack is bundled with outgoing data and that delayed ack
6365 // alarm is reset.
6366 if (GetParam().no_stop_waiting) {
6367 EXPECT_EQ(2u, writer_->frame_count());
6368 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6369 } else {
6370 EXPECT_EQ(3u, writer_->frame_count());
6371 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6372 }
6373 EXPECT_FALSE(writer_->ack_frames().empty());
6374 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6375}
6376
6377TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingCryptoPacket) {
6378 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
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(1, ENCRYPTION_INITIAL);
nharper46833c32019-05-15 21:33:05 -07006385 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006386 // Check that ack is bundled with outgoing crypto data.
6387 if (GetParam().no_stop_waiting) {
6388 EXPECT_EQ(3u, writer_->frame_count());
6389 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6390 } else {
6391 EXPECT_EQ(4u, writer_->frame_count());
6392 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6393 }
6394 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6395}
6396
6397TEST_P(QuicConnectionTest, BlockAndBufferOnFirstCHLOPacketOfTwo) {
6398 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6399 ProcessPacket(1);
6400 BlockOnNextWrite();
6401 writer_->set_is_write_blocked_data_buffered(true);
nharper46833c32019-05-15 21:33:05 -07006402 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006403 EXPECT_TRUE(writer_->IsWriteBlocked());
6404 EXPECT_FALSE(connection_.HasQueuedData());
nharper46833c32019-05-15 21:33:05 -07006405 connection_.SendCryptoDataWithString("bar", 3);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006406 EXPECT_TRUE(writer_->IsWriteBlocked());
6407 EXPECT_TRUE(connection_.HasQueuedData());
6408}
6409
6410TEST_P(QuicConnectionTest, BundleAckForSecondCHLO) {
6411 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6412 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6413 EXPECT_CALL(visitor_, OnCanWrite())
6414 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6415 &connection_, &TestConnection::SendCryptoStreamData)));
6416 // Process a packet from the crypto stream, which is frame1_'s default.
6417 // Receiving the CHLO as packet 2 first will cause the connection to
6418 // immediately send an ack, due to the packet gap.
fayangc31c9952019-06-05 13:54:48 -07006419 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6420 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
6421 } else {
6422 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6423 }
6424 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006425 // Check that ack is sent and that delayed ack alarm is reset.
6426 if (GetParam().no_stop_waiting) {
6427 EXPECT_EQ(3u, writer_->frame_count());
6428 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6429 } else {
6430 EXPECT_EQ(4u, writer_->frame_count());
6431 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6432 }
QUICHE teamea740082019-03-11 17:58:43 -07006433 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006434 EXPECT_EQ(1u, writer_->stream_frames().size());
6435 } else {
6436 EXPECT_EQ(1u, writer_->crypto_frames().size());
6437 }
6438 EXPECT_EQ(1u, writer_->padding_frames().size());
6439 ASSERT_FALSE(writer_->ack_frames().empty());
6440 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(writer_->ack_frames().front()));
6441 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6442}
6443
6444TEST_P(QuicConnectionTest, BundleAckForSecondCHLOTwoPacketReject) {
6445 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6446 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6447
6448 // Process two packets from the crypto stream, which is frame1_'s default,
6449 // simulating a 2 packet reject.
6450 {
fayangc31c9952019-06-05 13:54:48 -07006451 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6452 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
6453 } else {
6454 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6455 }
6456 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006457 // Send the new CHLO when the REJ is processed.
fayangc31c9952019-06-05 13:54:48 -07006458 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6459 EXPECT_CALL(visitor_, OnCryptoFrame(_))
6460 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6461 &connection_, &TestConnection::SendCryptoStreamData)));
6462 } else {
6463 EXPECT_CALL(visitor_, OnStreamFrame(_))
6464 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6465 &connection_, &TestConnection::SendCryptoStreamData)));
6466 }
6467 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006468 }
6469 // Check that ack is sent and that delayed ack alarm is reset.
6470 if (GetParam().no_stop_waiting) {
6471 EXPECT_EQ(3u, writer_->frame_count());
6472 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6473 } else {
6474 EXPECT_EQ(4u, writer_->frame_count());
6475 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6476 }
QUICHE teamea740082019-03-11 17:58:43 -07006477 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006478 EXPECT_EQ(1u, writer_->stream_frames().size());
6479 } else {
6480 EXPECT_EQ(1u, writer_->crypto_frames().size());
6481 }
6482 EXPECT_EQ(1u, writer_->padding_frames().size());
6483 ASSERT_FALSE(writer_->ack_frames().empty());
6484 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(writer_->ack_frames().front()));
6485 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6486}
6487
6488TEST_P(QuicConnectionTest, BundleAckWithDataOnIncomingAck) {
6489 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6490 connection_.SendStreamDataWithString(
6491 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6492 0, NO_FIN);
6493 connection_.SendStreamDataWithString(
6494 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6495 3, NO_FIN);
6496 // Ack the second packet, which will retransmit the first packet.
6497 QuicAckFrame ack = ConstructAckFrame(2, 1);
6498 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07006499 lost_packets.push_back(
6500 LostPacket(QuicPacketNumber(1), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006501 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
6502 .WillOnce(SetArgPointee<5>(lost_packets));
6503 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
6504 ProcessAckPacket(&ack);
nharper55fa6132019-05-07 19:37:21 -07006505 size_t padding_frame_count = writer_->padding_frames().size();
6506 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006507 EXPECT_EQ(1u, writer_->stream_frames().size());
6508 writer_->Reset();
6509
6510 // Now ack the retransmission, which will both raise the high water mark
6511 // and see if there is more data to send.
6512 ack = ConstructAckFrame(3, 1);
6513 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
6514 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
6515 ProcessAckPacket(&ack);
6516
6517 // Check that no packet is sent and the ack alarm isn't set.
6518 EXPECT_EQ(0u, writer_->frame_count());
6519 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6520 writer_->Reset();
6521
6522 // Send the same ack, but send both data and an ack together.
6523 ack = ConstructAckFrame(3, 1);
6524 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
6525 EXPECT_CALL(visitor_, OnCanWrite())
6526 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6527 &connection_, &TestConnection::EnsureWritableAndSendStreamData5)));
6528 ProcessAckPacket(&ack);
6529
6530 // Check that ack is bundled with outgoing data and the delayed ack
6531 // alarm is reset.
6532 if (GetParam().no_stop_waiting) {
fayang03916692019-05-22 17:57:18 -07006533 if (GetQuicReloadableFlag(quic_simplify_stop_waiting)) {
6534 // Do not ACK acks.
6535 EXPECT_EQ(1u, writer_->frame_count());
6536 } else {
6537 EXPECT_EQ(2u, writer_->frame_count());
6538 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6539 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006540 } else {
6541 EXPECT_EQ(3u, writer_->frame_count());
6542 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6543 }
fayang03916692019-05-22 17:57:18 -07006544 if (GetParam().no_stop_waiting &&
6545 GetQuicReloadableFlag(quic_simplify_stop_waiting)) {
6546 EXPECT_TRUE(writer_->ack_frames().empty());
6547 } else {
6548 EXPECT_FALSE(writer_->ack_frames().empty());
6549 EXPECT_EQ(QuicPacketNumber(3u),
6550 LargestAcked(writer_->ack_frames().front()));
6551 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006552 EXPECT_EQ(1u, writer_->stream_frames().size());
6553 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6554}
6555
6556TEST_P(QuicConnectionTest, NoAckSentForClose) {
6557 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6558 ProcessPacket(1);
6559 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, _,
6560 ConnectionCloseSource::FROM_PEER));
6561 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6562 ProcessClosePacket(2);
6563}
6564
6565TEST_P(QuicConnectionTest, SendWhenDisconnected) {
6566 EXPECT_TRUE(connection_.connected());
6567 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, _,
6568 ConnectionCloseSource::FROM_SELF));
6569 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
6570 ConnectionCloseBehavior::SILENT_CLOSE);
6571 EXPECT_FALSE(connection_.connected());
6572 EXPECT_FALSE(connection_.CanWriteStreamData());
QUICHE team8c1daa22019-03-13 08:33:41 -07006573 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07006574 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006575 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6576 .Times(0);
QUICHE team6987b4a2019-03-15 16:23:04 -07006577 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05006578 HAS_RETRANSMITTABLE_DATA, false, false);
6579}
6580
6581TEST_P(QuicConnectionTest, SendConnectivityProbingWhenDisconnected) {
6582 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
fayangc31c9952019-06-05 13:54:48 -07006583 if (!IsDefaultTestConfiguration()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006584 return;
6585 }
6586
6587 EXPECT_TRUE(connection_.connected());
6588 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, _,
6589 ConnectionCloseSource::FROM_SELF));
6590 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
6591 ConnectionCloseBehavior::SILENT_CLOSE);
6592 EXPECT_FALSE(connection_.connected());
6593 EXPECT_FALSE(connection_.CanWriteStreamData());
6594
6595 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6596 .Times(0);
6597
6598 EXPECT_QUIC_BUG(connection_.SendConnectivityProbingPacket(
6599 writer_.get(), connection_.peer_address()),
6600 "Not sending connectivity probing packet as connection is "
6601 "disconnected.");
6602}
6603
6604TEST_P(QuicConnectionTest, WriteBlockedAfterClientSendsConnectivityProbe) {
6605 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
6606 TestPacketWriter probing_writer(version(), &clock_);
6607 // Block next write so that sending connectivity probe will encounter a
6608 // blocked write when send a connectivity probe to the peer.
6609 probing_writer.BlockOnNextWrite();
6610 // Connection will not be marked as write blocked as connectivity probe only
6611 // affects the probing_writer which is not the default.
6612 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
6613
6614 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6615 .Times(1);
6616 connection_.SendConnectivityProbingPacket(&probing_writer,
6617 connection_.peer_address());
6618}
6619
6620TEST_P(QuicConnectionTest, WriterBlockedAfterServerSendsConnectivityProbe) {
6621 set_perspective(Perspective::IS_SERVER);
6622 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
6623
6624 // Block next write so that sending connectivity probe will encounter a
6625 // blocked write when send a connectivity probe to the peer.
6626 writer_->BlockOnNextWrite();
6627 // Connection will be marked as write blocked as server uses the default
6628 // writer to send connectivity probes.
6629 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
6630
6631 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6632 .Times(1);
6633 connection_.SendConnectivityProbingPacket(writer_.get(),
6634 connection_.peer_address());
6635}
6636
6637TEST_P(QuicConnectionTest, WriterErrorWhenClientSendsConnectivityProbe) {
6638 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
6639 TestPacketWriter probing_writer(version(), &clock_);
6640 probing_writer.SetShouldWriteFail();
6641
6642 // Connection should not be closed if a connectivity probe is failed to be
6643 // sent.
6644 EXPECT_CALL(visitor_, OnConnectionClosed(_, _, _)).Times(0);
6645
6646 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6647 .Times(0);
6648 connection_.SendConnectivityProbingPacket(&probing_writer,
6649 connection_.peer_address());
6650}
6651
6652TEST_P(QuicConnectionTest, WriterErrorWhenServerSendsConnectivityProbe) {
6653 set_perspective(Perspective::IS_SERVER);
6654 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
6655
6656 writer_->SetShouldWriteFail();
6657 // Connection should not be closed if a connectivity probe is failed to be
6658 // sent.
6659 EXPECT_CALL(visitor_, OnConnectionClosed(_, _, _)).Times(0);
6660
6661 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6662 .Times(0);
6663 connection_.SendConnectivityProbingPacket(writer_.get(),
6664 connection_.peer_address());
6665}
6666
6667TEST_P(QuicConnectionTest, PublicReset) {
fayangc31c9952019-06-05 13:54:48 -07006668 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006669 return;
6670 }
6671 QuicPublicResetPacket header;
6672 // Public reset packet in only built by server.
6673 header.connection_id = connection_id_;
6674 std::unique_ptr<QuicEncryptedPacket> packet(
6675 framer_.BuildPublicResetPacket(header));
6676 std::unique_ptr<QuicReceivedPacket> received(
6677 ConstructReceivedPacket(*packet, QuicTime::Zero()));
6678 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PUBLIC_RESET, _,
6679 ConnectionCloseSource::FROM_PEER));
6680 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
6681}
6682
6683TEST_P(QuicConnectionTest, IetfStatelessReset) {
fayangc31c9952019-06-05 13:54:48 -07006684 if (!VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006685 return;
6686 }
6687 const QuicUint128 kTestStatelessResetToken = 1010101;
6688 QuicConfig config;
6689 QuicConfigPeer::SetReceivedStatelessResetToken(&config,
6690 kTestStatelessResetToken);
6691 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6692 connection_.SetFromConfig(config);
6693 std::unique_ptr<QuicEncryptedPacket> packet(
6694 QuicFramer::BuildIetfStatelessResetPacket(connection_id_,
6695 kTestStatelessResetToken));
6696 std::unique_ptr<QuicReceivedPacket> received(
6697 ConstructReceivedPacket(*packet, QuicTime::Zero()));
6698 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PUBLIC_RESET, _,
6699 ConnectionCloseSource::FROM_PEER));
6700 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
6701}
6702
6703TEST_P(QuicConnectionTest, GoAway) {
fayangc31c9952019-06-05 13:54:48 -07006704 if (GetParam().version.transport_version == QUIC_VERSION_99) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006705 // GoAway is not available in version 99.
6706 return;
6707 }
6708
6709 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6710
6711 QuicGoAwayFrame goaway;
6712 goaway.last_good_stream_id = 1;
6713 goaway.error_code = QUIC_PEER_GOING_AWAY;
6714 goaway.reason_phrase = "Going away.";
6715 EXPECT_CALL(visitor_, OnGoAway(_));
6716 ProcessGoAwayPacket(&goaway);
6717}
6718
6719TEST_P(QuicConnectionTest, WindowUpdate) {
6720 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6721
6722 QuicWindowUpdateFrame window_update;
6723 window_update.stream_id = 3;
6724 window_update.byte_offset = 1234;
6725 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
6726 ProcessFramePacket(QuicFrame(&window_update));
6727}
6728
6729TEST_P(QuicConnectionTest, Blocked) {
6730 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6731
6732 QuicBlockedFrame blocked;
6733 blocked.stream_id = 3;
6734 EXPECT_CALL(visitor_, OnBlockedFrame(_));
6735 ProcessFramePacket(QuicFrame(&blocked));
6736 EXPECT_EQ(1u, connection_.GetStats().blocked_frames_received);
6737 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
6738}
6739
6740TEST_P(QuicConnectionTest, ZeroBytePacket) {
6741 // Don't close the connection for zero byte packets.
6742 EXPECT_CALL(visitor_, OnConnectionClosed(_, _, _)).Times(0);
6743 QuicReceivedPacket encrypted(nullptr, 0, QuicTime::Zero());
6744 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, encrypted);
6745}
6746
6747TEST_P(QuicConnectionTest, MissingPacketsBeforeLeastUnacked) {
fayangd4291e42019-05-30 10:31:21 -07006748 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006749 return;
6750 }
6751 // Set the packet number of the ack packet to be least unacked (4).
6752 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 3);
6753 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6754 ProcessStopWaitingPacket(InitStopWaitingFrame(4));
fayangc31c9952019-06-05 13:54:48 -07006755 EXPECT_FALSE(connection_.ack_frame().packets.Empty());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006756}
6757
QUICHE teama6ef0a62019-03-07 20:34:33 -05006758TEST_P(QuicConnectionTest, ClientHandlesVersionNegotiation) {
dschinazi5a354c92019-05-09 12:18:53 -07006759 const bool expect_failure =
6760 GetQuicReloadableFlag(quic_no_client_conn_ver_negotiation) ||
6761 connection_.version().handshake_protocol !=
6762 QuicVersionReservedForNegotiation().handshake_protocol;
6763 // Start out with an unsupported version.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006764 QuicConnectionPeer::GetFramer(&connection_)
dschinazi5a354c92019-05-09 12:18:53 -07006765 ->set_version_for_tests(QuicVersionReservedForNegotiation());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006766
6767 // Send a version negotiation packet.
6768 std::unique_ptr<QuicEncryptedPacket> encrypted(
dschinazib417d602019-05-29 13:08:45 -07006769 QuicFramer::BuildVersionNegotiationPacket(
6770 connection_id_, EmptyQuicConnectionId(),
fayangd4291e42019-05-30 10:31:21 -07006771 VersionHasIetfInvariantHeader(connection_.transport_version()),
QUICHE teama6ef0a62019-03-07 20:34:33 -05006772 AllSupportedVersions()));
6773 std::unique_ptr<QuicReceivedPacket> received(
6774 ConstructReceivedPacket(*encrypted, QuicTime::Zero()));
dschinazi5a354c92019-05-09 12:18:53 -07006775 if (expect_failure) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006776 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_VERSION, _,
6777 ConnectionCloseSource::FROM_SELF));
6778 }
6779 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
dschinazi5a354c92019-05-09 12:18:53 -07006780 if (expect_failure) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006781 EXPECT_FALSE(connection_.connected());
6782 return;
6783 }
6784
6785 // Now force another packet. The connection should transition into
6786 // NEGOTIATED_VERSION state and tell the packet creator to StopSendingVersion.
6787 QuicPacketHeader header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05006788 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
QUICHE team2252b702019-05-14 23:55:14 -04006789 if (!GetQuicRestartFlag(quic_do_not_override_connection_id)) {
6790 header.destination_connection_id = connection_id_;
6791 } else {
6792 header.source_connection_id = connection_id_;
6793 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006794 header.packet_number = QuicPacketNumber(12);
6795 header.version_flag = false;
6796 QuicFrames frames;
6797 frames.push_back(QuicFrame(frame1_));
6798 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
dschinazi66dea072019-04-09 11:41:06 -07006799 char buffer[kMaxOutgoingPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07006800 size_t encrypted_length =
6801 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12),
dschinazi66dea072019-04-09 11:41:06 -07006802 *packet, buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006803 ASSERT_NE(0u, encrypted_length);
6804 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6805 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6806 connection_.ProcessUdpPacket(
6807 kSelfAddress, kPeerAddress,
6808 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
fayangd4291e42019-05-30 10:31:21 -07006809 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006810 // IETF QUIC stops sending version when switch to FORWARD_SECURE.
6811 EXPECT_NE(ENCRYPTION_FORWARD_SECURE, connection_.encryption_level());
6812 ASSERT_TRUE(QuicPacketCreatorPeer::SendVersionInPacket(creator_));
6813 } else {
6814 ASSERT_FALSE(QuicPacketCreatorPeer::SendVersionInPacket(creator_));
6815 }
6816}
6817
6818TEST_P(QuicConnectionTest, BadVersionNegotiation) {
6819 // Send a version negotiation packet with the version the client started with.
6820 // It should be rejected.
6821 EXPECT_CALL(visitor_,
6822 OnConnectionClosed(QUIC_INVALID_VERSION_NEGOTIATION_PACKET, _,
6823 ConnectionCloseSource::FROM_SELF));
6824 std::unique_ptr<QuicEncryptedPacket> encrypted(
dschinazib417d602019-05-29 13:08:45 -07006825 QuicFramer::BuildVersionNegotiationPacket(
6826 connection_id_, EmptyQuicConnectionId(),
fayangd4291e42019-05-30 10:31:21 -07006827 VersionHasIetfInvariantHeader(connection_.transport_version()),
QUICHE teama6ef0a62019-03-07 20:34:33 -05006828 AllSupportedVersions()));
6829 std::unique_ptr<QuicReceivedPacket> received(
6830 ConstructReceivedPacket(*encrypted, QuicTime::Zero()));
6831 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
6832}
6833
6834TEST_P(QuicConnectionTest, CheckSendStats) {
6835 connection_.SetMaxTailLossProbes(0);
6836
6837 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
6838 connection_.SendStreamDataWithString(3, "first", 0, NO_FIN);
6839 size_t first_packet_size = writer_->last_packet_size();
6840
6841 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
6842 connection_.SendStreamDataWithString(5, "second", 0, NO_FIN);
6843 size_t second_packet_size = writer_->last_packet_size();
6844
6845 // 2 retransmissions due to rto, 1 due to explicit nack.
6846 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
6847 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
6848
6849 // Retransmit due to RTO.
6850 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
6851 connection_.GetRetransmissionAlarm()->Fire();
6852
6853 // Retransmit due to explicit nacks.
6854 QuicAckFrame nack_three =
6855 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)},
6856 {QuicPacketNumber(4), QuicPacketNumber(5)}});
6857
6858 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07006859 lost_packets.push_back(
6860 LostPacket(QuicPacketNumber(1), kMaxOutgoingPacketSize));
6861 lost_packets.push_back(
6862 LostPacket(QuicPacketNumber(3), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006863 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
6864 .WillOnce(SetArgPointee<5>(lost_packets));
6865 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
6866 if (!connection_.session_decides_what_to_write()) {
6867 EXPECT_CALL(visitor_, OnCanWrite());
6868 }
6869 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6870 ProcessAckPacket(&nack_three);
6871
6872 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
6873 .WillOnce(Return(QuicBandwidth::Zero()));
6874
6875 const QuicConnectionStats& stats = connection_.GetStats();
6876 // For IETF QUIC, version is not included as the encryption level switches to
6877 // FORWARD_SECURE in SendStreamDataWithString.
6878 size_t save_on_version =
fayangd4291e42019-05-30 10:31:21 -07006879 VersionHasIetfInvariantHeader(GetParam().version.transport_version)
6880 ? 0
6881 : kQuicVersionSize;
QUICHE teama6ef0a62019-03-07 20:34:33 -05006882 EXPECT_EQ(3 * first_packet_size + 2 * second_packet_size - save_on_version,
6883 stats.bytes_sent);
6884 EXPECT_EQ(5u, stats.packets_sent);
6885 EXPECT_EQ(2 * first_packet_size + second_packet_size - save_on_version,
6886 stats.bytes_retransmitted);
6887 EXPECT_EQ(3u, stats.packets_retransmitted);
6888 EXPECT_EQ(1u, stats.rto_count);
6889 EXPECT_EQ(kDefaultMaxPacketSize, stats.max_packet_size);
6890}
6891
6892TEST_P(QuicConnectionTest, ProcessFramesIfPacketClosedConnection) {
6893 // Construct a packet with stream frame and connection close frame.
6894 QuicPacketHeader header;
QUICHE team2252b702019-05-14 23:55:14 -04006895 if (GetQuicRestartFlag(quic_do_not_override_connection_id) &&
6896 peer_framer_.perspective() == Perspective::IS_SERVER) {
6897 header.source_connection_id = connection_id_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05006898 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
fayangd4291e42019-05-30 10:31:21 -07006899 if (!VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04006900 header.source_connection_id_included = CONNECTION_ID_PRESENT;
6901 }
6902 } else {
6903 header.destination_connection_id = connection_id_;
fayangd4291e42019-05-30 10:31:21 -07006904 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04006905 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
6906 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006907 }
6908 header.packet_number = QuicPacketNumber(1);
6909 header.version_flag = false;
6910
fkastenholze9d71a82019-04-09 05:12:13 -07006911 QuicConnectionCloseFrame qccf(QUIC_PEER_GOING_AWAY);
fkastenholz72f509b2019-04-10 09:17:49 -07006912 if (peer_framer_.transport_version() == QUIC_VERSION_99) {
fkastenholz04bd4f32019-04-16 12:24:38 -07006913 // Default close-type is Google QUIC. If doing IETF/V99 then
6914 // set close type to be IETF CC/T.
fkastenholz72f509b2019-04-10 09:17:49 -07006915 qccf.close_type = IETF_QUIC_TRANSPORT_CONNECTION_CLOSE;
6916 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006917
6918 QuicFrames frames;
6919 frames.push_back(QuicFrame(frame1_));
6920 frames.push_back(QuicFrame(&qccf));
6921 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
6922 EXPECT_TRUE(nullptr != packet);
dschinazi66dea072019-04-09 11:41:06 -07006923 char buffer[kMaxOutgoingPacketSize];
6924 size_t encrypted_length =
6925 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(1),
6926 *packet, buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006927
6928 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, _,
6929 ConnectionCloseSource::FROM_PEER));
6930 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6931 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6932
6933 connection_.ProcessUdpPacket(
6934 kSelfAddress, kPeerAddress,
6935 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
6936}
6937
6938TEST_P(QuicConnectionTest, SelectMutualVersion) {
6939 connection_.SetSupportedVersions(AllSupportedVersions());
6940 // Set the connection to speak the lowest quic version.
6941 connection_.set_version(QuicVersionMin());
6942 EXPECT_EQ(QuicVersionMin(), connection_.version());
6943
6944 // Pass in available versions which includes a higher mutually supported
6945 // version. The higher mutually supported version should be selected.
6946 ParsedQuicVersionVector supported_versions = AllSupportedVersions();
6947 EXPECT_TRUE(connection_.SelectMutualVersion(supported_versions));
6948 EXPECT_EQ(QuicVersionMax(), connection_.version());
6949
6950 // Expect that the lowest version is selected.
6951 // Ensure the lowest supported version is less than the max, unless they're
6952 // the same.
6953 ParsedQuicVersionVector lowest_version_vector;
6954 lowest_version_vector.push_back(QuicVersionMin());
6955 EXPECT_TRUE(connection_.SelectMutualVersion(lowest_version_vector));
6956 EXPECT_EQ(QuicVersionMin(), connection_.version());
6957
6958 // Shouldn't be able to find a mutually supported version.
6959 ParsedQuicVersionVector unsupported_version;
6960 unsupported_version.push_back(UnsupportedQuicVersion());
6961 EXPECT_FALSE(connection_.SelectMutualVersion(unsupported_version));
6962}
6963
6964TEST_P(QuicConnectionTest, ConnectionCloseWhenWritable) {
6965 EXPECT_FALSE(writer_->IsWriteBlocked());
6966
6967 // Send a packet.
6968 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
6969 EXPECT_EQ(0u, connection_.NumQueuedPackets());
6970 EXPECT_EQ(1u, writer_->packets_write_attempts());
6971
6972 TriggerConnectionClose();
6973 EXPECT_EQ(2u, writer_->packets_write_attempts());
6974}
6975
6976TEST_P(QuicConnectionTest, ConnectionCloseGettingWriteBlocked) {
6977 BlockOnNextWrite();
6978 TriggerConnectionClose();
6979 EXPECT_EQ(1u, writer_->packets_write_attempts());
6980 EXPECT_TRUE(writer_->IsWriteBlocked());
6981}
6982
6983TEST_P(QuicConnectionTest, ConnectionCloseWhenWriteBlocked) {
6984 BlockOnNextWrite();
6985 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
6986 EXPECT_EQ(1u, connection_.NumQueuedPackets());
6987 EXPECT_EQ(1u, writer_->packets_write_attempts());
6988 EXPECT_TRUE(writer_->IsWriteBlocked());
6989 TriggerConnectionClose();
6990 EXPECT_EQ(1u, writer_->packets_write_attempts());
6991}
6992
6993TEST_P(QuicConnectionTest, OnPacketSentDebugVisitor) {
6994 MockQuicConnectionDebugVisitor debug_visitor;
6995 connection_.set_debug_visitor(&debug_visitor);
6996
6997 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _)).Times(1);
6998 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
6999
7000 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _)).Times(1);
7001 connection_.SendConnectivityProbingPacket(writer_.get(),
7002 connection_.peer_address());
7003}
7004
7005TEST_P(QuicConnectionTest, OnPacketHeaderDebugVisitor) {
7006 QuicPacketHeader header;
7007 header.packet_number = QuicPacketNumber(1);
fayangd4291e42019-05-30 10:31:21 -07007008 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007009 header.form = IETF_QUIC_LONG_HEADER_PACKET;
7010 }
7011
7012 MockQuicConnectionDebugVisitor debug_visitor;
7013 connection_.set_debug_visitor(&debug_visitor);
7014 EXPECT_CALL(debug_visitor, OnPacketHeader(Ref(header))).Times(1);
7015 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(1);
7016 EXPECT_CALL(debug_visitor, OnSuccessfulVersionNegotiation(_)).Times(1);
7017 connection_.OnPacketHeader(header);
7018}
7019
7020TEST_P(QuicConnectionTest, Pacing) {
7021 TestConnection server(connection_id_, kSelfAddress, helper_.get(),
7022 alarm_factory_.get(), writer_.get(),
7023 Perspective::IS_SERVER, version());
7024 TestConnection client(connection_id_, kPeerAddress, helper_.get(),
7025 alarm_factory_.get(), writer_.get(),
7026 Perspective::IS_CLIENT, version());
7027 EXPECT_FALSE(QuicSentPacketManagerPeer::UsingPacing(
7028 static_cast<const QuicSentPacketManager*>(
7029 &client.sent_packet_manager())));
7030 EXPECT_FALSE(QuicSentPacketManagerPeer::UsingPacing(
7031 static_cast<const QuicSentPacketManager*>(
7032 &server.sent_packet_manager())));
7033}
7034
7035TEST_P(QuicConnectionTest, WindowUpdateInstigateAcks) {
7036 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7037
7038 // Send a WINDOW_UPDATE frame.
7039 QuicWindowUpdateFrame window_update;
7040 window_update.stream_id = 3;
7041 window_update.byte_offset = 1234;
7042 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
7043 ProcessFramePacket(QuicFrame(&window_update));
7044
7045 // Ensure that this has caused the ACK alarm to be set.
7046 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
7047 EXPECT_TRUE(ack_alarm->IsSet());
7048}
7049
7050TEST_P(QuicConnectionTest, BlockedFrameInstigateAcks) {
7051 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7052
7053 // Send a BLOCKED frame.
7054 QuicBlockedFrame blocked;
7055 blocked.stream_id = 3;
7056 EXPECT_CALL(visitor_, OnBlockedFrame(_));
7057 ProcessFramePacket(QuicFrame(&blocked));
7058
7059 // Ensure that this has caused the ACK alarm to be set.
7060 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
7061 EXPECT_TRUE(ack_alarm->IsSet());
7062}
7063
7064TEST_P(QuicConnectionTest, ReevaluateTimeUntilSendOnAck) {
7065 // Enable pacing.
7066 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7067 QuicConfig config;
7068 connection_.SetFromConfig(config);
7069
7070 // Send two packets. One packet is not sufficient because if it gets acked,
7071 // there will be no packets in flight after that and the pacer will always
7072 // allow the next packet in that situation.
7073 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7074 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
7075 connection_.SendStreamDataWithString(
7076 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
7077 0, NO_FIN);
7078 connection_.SendStreamDataWithString(
7079 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "bar",
7080 3, NO_FIN);
7081 connection_.OnCanWrite();
7082
7083 // Schedule the next packet for a few milliseconds in future.
7084 QuicSentPacketManagerPeer::DisablePacerBursts(manager_);
7085 QuicTime scheduled_pacing_time =
7086 clock_.Now() + QuicTime::Delta::FromMilliseconds(5);
7087 QuicSentPacketManagerPeer::SetNextPacedPacketTime(manager_,
7088 scheduled_pacing_time);
7089
7090 // Send a packet and have it be blocked by congestion control.
7091 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(false));
7092 connection_.SendStreamDataWithString(
7093 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "baz",
7094 6, NO_FIN);
7095 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
7096
7097 // Process an ack and the send alarm will be set to the new 5ms delay.
7098 QuicAckFrame ack = InitAckFrame(1);
7099 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
7100 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7101 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
7102 ProcessAckPacket(&ack);
nharper55fa6132019-05-07 19:37:21 -07007103 size_t padding_frame_count = writer_->padding_frames().size();
7104 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007105 EXPECT_EQ(1u, writer_->stream_frames().size());
7106 EXPECT_TRUE(connection_.GetSendAlarm()->IsSet());
7107 EXPECT_EQ(scheduled_pacing_time, connection_.GetSendAlarm()->deadline());
7108 writer_->Reset();
7109}
7110
7111TEST_P(QuicConnectionTest, SendAcksImmediately) {
QUICHE teamcd098022019-03-22 18:49:55 -07007112 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7113 return;
7114 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007115 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7116 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7117 ProcessDataPacket(1);
7118 CongestionBlockWrites();
7119 SendAckPacketToPeer();
7120}
7121
7122TEST_P(QuicConnectionTest, SendPingImmediately) {
7123 MockQuicConnectionDebugVisitor debug_visitor;
7124 connection_.set_debug_visitor(&debug_visitor);
7125
7126 CongestionBlockWrites();
7127 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7128 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _)).Times(1);
7129 EXPECT_CALL(debug_visitor, OnPingSent()).Times(1);
7130 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
7131 EXPECT_FALSE(connection_.HasQueuedData());
7132}
7133
7134TEST_P(QuicConnectionTest, SendBlockedImmediately) {
7135 MockQuicConnectionDebugVisitor debug_visitor;
7136 connection_.set_debug_visitor(&debug_visitor);
7137
7138 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7139 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _)).Times(1);
7140 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7141 connection_.SendControlFrame(QuicFrame(new QuicBlockedFrame(1, 3)));
7142 EXPECT_EQ(1u, connection_.GetStats().blocked_frames_sent);
7143 EXPECT_FALSE(connection_.HasQueuedData());
7144}
7145
7146TEST_P(QuicConnectionTest, SendingUnencryptedStreamDataFails) {
7147 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
7148 if (!IsDefaultTestConfiguration()) {
7149 return;
7150 }
7151
7152 EXPECT_CALL(visitor_,
7153 OnConnectionClosed(QUIC_ATTEMPT_TO_SEND_UNENCRYPTED_STREAM_DATA,
7154 _, ConnectionCloseSource::FROM_SELF));
7155 struct iovec iov;
7156 MakeIOVector("", &iov);
7157 EXPECT_QUIC_BUG(connection_.SaveAndSendStreamData(3, &iov, 1, 0, 0, FIN),
fayang49523232019-05-03 06:28:22 -07007158 "Cannot send stream data with level: ENCRYPTION_INITIAL");
QUICHE teama6ef0a62019-03-07 20:34:33 -05007159 EXPECT_FALSE(connection_.connected());
7160}
7161
7162TEST_P(QuicConnectionTest, SetRetransmissionAlarmForCryptoPacket) {
7163 EXPECT_TRUE(connection_.connected());
7164 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
7165
7166 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7167 connection_.SendCryptoStreamData();
7168
7169 // Verify retransmission timer is correctly set after crypto packet has been
7170 // sent.
7171 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
7172 QuicTime retransmission_time =
7173 QuicConnectionPeer::GetSentPacketManager(&connection_)
7174 ->GetRetransmissionTime();
7175 EXPECT_NE(retransmission_time, clock_.ApproximateNow());
7176 EXPECT_EQ(retransmission_time,
7177 connection_.GetRetransmissionAlarm()->deadline());
7178
7179 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7180 connection_.GetRetransmissionAlarm()->Fire();
7181}
7182
7183TEST_P(QuicConnectionTest, PathDegradingAlarmForCryptoPacket) {
7184 EXPECT_TRUE(connection_.connected());
7185 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7186 EXPECT_FALSE(connection_.IsPathDegrading());
7187
7188 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7189 connection_.SendCryptoStreamData();
7190
7191 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7192 EXPECT_FALSE(connection_.IsPathDegrading());
7193 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7194 ->GetPathDegradingDelay();
7195 EXPECT_EQ(clock_.ApproximateNow() + delay,
7196 connection_.GetPathDegradingAlarm()->deadline());
7197
7198 // Fire the path degrading alarm, path degrading signal should be sent to
7199 // the visitor.
7200 EXPECT_CALL(visitor_, OnPathDegrading());
7201 clock_.AdvanceTime(delay);
7202 connection_.GetPathDegradingAlarm()->Fire();
7203 EXPECT_TRUE(connection_.IsPathDegrading());
7204 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7205}
7206
vasilvv693d5b02019-04-09 21:58:56 -07007207// Includes regression test for b/69979024.
QUICHE teama6ef0a62019-03-07 20:34:33 -05007208TEST_P(QuicConnectionTest, PathDegradingAlarmForNonCryptoPackets) {
7209 EXPECT_TRUE(connection_.connected());
7210 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7211 EXPECT_FALSE(connection_.IsPathDegrading());
7212
7213 const char data[] = "data";
7214 size_t data_size = strlen(data);
7215 QuicStreamOffset offset = 0;
7216
7217 for (int i = 0; i < 2; ++i) {
7218 // Send a packet. Now there's a retransmittable packet on the wire, so the
7219 // path degrading alarm should be set.
7220 connection_.SendStreamDataWithString(
7221 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
7222 offset, NO_FIN);
7223 offset += data_size;
7224 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7225 // Check the deadline of the path degrading alarm.
7226 QuicTime::Delta delay =
7227 QuicConnectionPeer::GetSentPacketManager(&connection_)
7228 ->GetPathDegradingDelay();
7229 EXPECT_EQ(clock_.ApproximateNow() + delay,
7230 connection_.GetPathDegradingAlarm()->deadline());
7231
7232 // Send a second packet. The path degrading alarm's deadline should remain
7233 // the same.
vasilvv693d5b02019-04-09 21:58:56 -07007234 // Regression test for b/69979024.
QUICHE teama6ef0a62019-03-07 20:34:33 -05007235 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7236 QuicTime prev_deadline = connection_.GetPathDegradingAlarm()->deadline();
7237 connection_.SendStreamDataWithString(
7238 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
7239 offset, NO_FIN);
7240 offset += data_size;
7241 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7242 EXPECT_EQ(prev_deadline, connection_.GetPathDegradingAlarm()->deadline());
7243
7244 // Now receive an ACK of the first packet. This should advance the path
7245 // degrading alarm's deadline since forward progress has been made.
7246 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7247 if (i == 0) {
7248 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7249 }
7250 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7251 QuicAckFrame frame = InitAckFrame(
7252 {{QuicPacketNumber(1u + 2u * i), QuicPacketNumber(2u + 2u * i)}});
7253 ProcessAckPacket(&frame);
7254 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7255 // Check the deadline of the path degrading alarm.
7256 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7257 ->GetPathDegradingDelay();
7258 EXPECT_EQ(clock_.ApproximateNow() + delay,
7259 connection_.GetPathDegradingAlarm()->deadline());
7260
7261 if (i == 0) {
7262 // Now receive an ACK of the second packet. Since there are no more
7263 // retransmittable packets on the wire, this should cancel the path
7264 // degrading alarm.
7265 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7266 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7267 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
7268 ProcessAckPacket(&frame);
7269 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7270 } else {
7271 // Advance time to the path degrading alarm's deadline and simulate
7272 // firing the alarm.
7273 clock_.AdvanceTime(delay);
7274 EXPECT_CALL(visitor_, OnPathDegrading());
7275 connection_.GetPathDegradingAlarm()->Fire();
7276 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7277 }
7278 }
7279 EXPECT_TRUE(connection_.IsPathDegrading());
7280}
7281
7282TEST_P(QuicConnectionTest, RetransmittableOnWireSetsPingAlarm) {
7283 const QuicTime::Delta retransmittable_on_wire_timeout =
7284 QuicTime::Delta::FromMilliseconds(50);
7285 connection_.set_retransmittable_on_wire_timeout(
7286 retransmittable_on_wire_timeout);
7287
7288 EXPECT_TRUE(connection_.connected());
7289 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7290 .WillRepeatedly(Return(true));
7291
7292 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7293 EXPECT_FALSE(connection_.IsPathDegrading());
7294 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
7295
7296 const char data[] = "data";
7297 size_t data_size = strlen(data);
7298 QuicStreamOffset offset = 0;
7299
7300 // Send a packet.
7301 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7302 offset += data_size;
7303 // Now there's a retransmittable packet on the wire, so the path degrading
7304 // alarm should be set.
7305 // The retransmittable-on-wire alarm should not be set.
7306 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7307 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7308 ->GetPathDegradingDelay();
7309 EXPECT_EQ(clock_.ApproximateNow() + delay,
7310 connection_.GetPathDegradingAlarm()->deadline());
7311 ASSERT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
7312 // The ping alarm is set for the ping timeout, not the shorter
7313 // retransmittable_on_wire_timeout.
7314 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7315 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
7316 EXPECT_EQ((clock_.ApproximateNow() + ping_delay),
7317 connection_.GetPingAlarm()->deadline());
7318
7319 // Now receive an ACK of the packet.
7320 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7321 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7322 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7323 QuicAckFrame frame =
7324 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7325 ProcessAckPacket(&frame);
7326 // No more retransmittable packets on the wire, so the path degrading alarm
7327 // should be cancelled, and the ping alarm should be set to the
7328 // retransmittable_on_wire_timeout.
7329 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7330 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7331 EXPECT_EQ(clock_.ApproximateNow() + retransmittable_on_wire_timeout,
7332 connection_.GetPingAlarm()->deadline());
7333
7334 // Simulate firing the ping alarm and sending a PING.
7335 clock_.AdvanceTime(retransmittable_on_wire_timeout);
7336 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
7337 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
7338 }));
7339 connection_.GetPingAlarm()->Fire();
7340
7341 // Now there's a retransmittable packet (PING) on the wire, so the path
7342 // degrading alarm should be set.
7343 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7344 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7345 ->GetPathDegradingDelay();
7346 EXPECT_EQ(clock_.ApproximateNow() + delay,
7347 connection_.GetPathDegradingAlarm()->deadline());
7348}
7349
7350// This test verifies that the connection marks path as degrading and does not
7351// spin timer to detect path degrading when a new packet is sent on the
7352// degraded path.
7353TEST_P(QuicConnectionTest, NoPathDegradingAlarmIfPathIsDegrading) {
7354 EXPECT_TRUE(connection_.connected());
7355 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7356 EXPECT_FALSE(connection_.IsPathDegrading());
7357
7358 const char data[] = "data";
7359 size_t data_size = strlen(data);
7360 QuicStreamOffset offset = 0;
7361
7362 // Send the first packet. Now there's a retransmittable packet on the wire, so
7363 // the path degrading alarm should be set.
7364 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7365 offset += data_size;
7366 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7367 // Check the deadline of the path degrading alarm.
7368 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7369 ->GetPathDegradingDelay();
7370 EXPECT_EQ(clock_.ApproximateNow() + delay,
7371 connection_.GetPathDegradingAlarm()->deadline());
7372
7373 // Send a second packet. The path degrading alarm's deadline should remain
7374 // the same.
7375 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7376 QuicTime prev_deadline = connection_.GetPathDegradingAlarm()->deadline();
7377 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7378 offset += data_size;
7379 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7380 EXPECT_EQ(prev_deadline, connection_.GetPathDegradingAlarm()->deadline());
7381
7382 // Now receive an ACK of the first packet. This should advance the path
7383 // degrading alarm's deadline since forward progress has been made.
7384 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7385 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7386 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7387 QuicAckFrame frame =
7388 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
7389 ProcessAckPacket(&frame);
7390 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7391 // Check the deadline of the path degrading alarm.
7392 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7393 ->GetPathDegradingDelay();
7394 EXPECT_EQ(clock_.ApproximateNow() + delay,
7395 connection_.GetPathDegradingAlarm()->deadline());
7396
7397 // Advance time to the path degrading alarm's deadline and simulate
7398 // firing the path degrading alarm. This path will be considered as
7399 // degrading.
7400 clock_.AdvanceTime(delay);
7401 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
7402 connection_.GetPathDegradingAlarm()->Fire();
7403 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7404 EXPECT_TRUE(connection_.IsPathDegrading());
7405
7406 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7407 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7408 // Send a third packet. The path degrading alarm is no longer set but path
7409 // should still be marked as degrading.
7410 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7411 offset += data_size;
7412 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7413 EXPECT_TRUE(connection_.IsPathDegrading());
7414}
7415
7416// This test verifies that the connection unmarks path as degrarding and spins
7417// the timer to detect future path degrading when forward progress is made
7418// after path has been marked degrading.
7419TEST_P(QuicConnectionTest, UnmarkPathDegradingOnForwardProgress) {
7420 EXPECT_TRUE(connection_.connected());
7421 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7422 EXPECT_FALSE(connection_.IsPathDegrading());
7423
7424 const char data[] = "data";
7425 size_t data_size = strlen(data);
7426 QuicStreamOffset offset = 0;
7427
7428 // Send the first packet. Now there's a retransmittable packet on the wire, so
7429 // the path degrading alarm should be set.
7430 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7431 offset += data_size;
7432 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7433 // Check the deadline of the path degrading alarm.
7434 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7435 ->GetPathDegradingDelay();
7436 EXPECT_EQ(clock_.ApproximateNow() + delay,
7437 connection_.GetPathDegradingAlarm()->deadline());
7438
7439 // Send a second packet. The path degrading alarm's deadline should remain
7440 // the same.
7441 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7442 QuicTime prev_deadline = connection_.GetPathDegradingAlarm()->deadline();
7443 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7444 offset += data_size;
7445 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7446 EXPECT_EQ(prev_deadline, connection_.GetPathDegradingAlarm()->deadline());
7447
7448 // Now receive an ACK of the first packet. This should advance the path
7449 // degrading alarm's deadline since forward progress has been made.
7450 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7451 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7452 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7453 QuicAckFrame frame =
7454 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
7455 ProcessAckPacket(&frame);
7456 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7457 // Check the deadline of the path degrading alarm.
7458 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7459 ->GetPathDegradingDelay();
7460 EXPECT_EQ(clock_.ApproximateNow() + delay,
7461 connection_.GetPathDegradingAlarm()->deadline());
7462
7463 // Advance time to the path degrading alarm's deadline and simulate
7464 // firing the alarm.
7465 clock_.AdvanceTime(delay);
7466 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
7467 connection_.GetPathDegradingAlarm()->Fire();
7468 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7469 EXPECT_TRUE(connection_.IsPathDegrading());
7470
7471 // Send a third packet. The path degrading alarm is no longer set but path
7472 // should still be marked as degrading.
7473 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7474 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7475 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7476 offset += data_size;
7477 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7478 EXPECT_TRUE(connection_.IsPathDegrading());
7479
7480 // Now receive an ACK of the second packet. This should unmark the path as
7481 // degrading. And will set a timer to detect new path degrading.
7482 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7483 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7484 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
7485 ProcessAckPacket(&frame);
7486 EXPECT_FALSE(connection_.IsPathDegrading());
7487 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7488}
7489
7490TEST_P(QuicConnectionTest, NoPathDegradingOnServer) {
QUICHE teamcd098022019-03-22 18:49:55 -07007491 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7492 return;
7493 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007494 set_perspective(Perspective::IS_SERVER);
7495 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
7496
7497 EXPECT_FALSE(connection_.IsPathDegrading());
7498 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7499
7500 // Send data.
7501 const char data[] = "data";
7502 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
7503 EXPECT_FALSE(connection_.IsPathDegrading());
7504 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7505
7506 // Ack data.
7507 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7508 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7509 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7510 QuicAckFrame frame =
7511 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
7512 ProcessAckPacket(&frame);
7513 EXPECT_FALSE(connection_.IsPathDegrading());
7514 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7515}
7516
7517TEST_P(QuicConnectionTest, NoPathDegradingAfterSendingAck) {
QUICHE teamcd098022019-03-22 18:49:55 -07007518 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7519 return;
7520 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007521 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7522 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7523 ProcessDataPacket(1);
7524 SendAckPacketToPeer();
7525 EXPECT_FALSE(connection_.sent_packet_manager().unacked_packets().empty());
7526 EXPECT_FALSE(connection_.sent_packet_manager().HasInFlightPackets());
7527 EXPECT_FALSE(connection_.IsPathDegrading());
7528 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7529}
7530
7531TEST_P(QuicConnectionTest, MultipleCallsToCloseConnection) {
7532 // Verifies that multiple calls to CloseConnection do not
7533 // result in multiple attempts to close the connection - it will be marked as
7534 // disconnected after the first call.
7535 EXPECT_CALL(visitor_, OnConnectionClosed(_, _, _)).Times(1);
7536 connection_.CloseConnection(QUIC_NO_ERROR, "no reason",
7537 ConnectionCloseBehavior::SILENT_CLOSE);
7538 connection_.CloseConnection(QUIC_NO_ERROR, "no reason",
7539 ConnectionCloseBehavior::SILENT_CLOSE);
7540}
7541
7542TEST_P(QuicConnectionTest, ServerReceivesChloOnNonCryptoStream) {
7543 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7544
7545 set_perspective(Perspective::IS_SERVER);
7546 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
7547
7548 CryptoHandshakeMessage message;
7549 CryptoFramer framer;
7550 message.set_tag(kCHLO);
QUICHE team3fe6a8b2019-03-14 09:10:38 -07007551 std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007552 frame1_.stream_id = 10;
7553 frame1_.data_buffer = data->data();
7554 frame1_.data_length = data->length();
7555
7556 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_MAYBE_CORRUPTED_MEMORY, _,
7557 ConnectionCloseSource::FROM_SELF));
7558 ForceProcessFramePacket(QuicFrame(frame1_));
7559}
7560
7561TEST_P(QuicConnectionTest, ClientReceivesRejOnNonCryptoStream) {
7562 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7563
7564 CryptoHandshakeMessage message;
7565 CryptoFramer framer;
7566 message.set_tag(kREJ);
QUICHE team3fe6a8b2019-03-14 09:10:38 -07007567 std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007568 frame1_.stream_id = 10;
7569 frame1_.data_buffer = data->data();
7570 frame1_.data_length = data->length();
7571
7572 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_MAYBE_CORRUPTED_MEMORY, _,
7573 ConnectionCloseSource::FROM_SELF));
7574 ForceProcessFramePacket(QuicFrame(frame1_));
7575}
7576
7577TEST_P(QuicConnectionTest, CloseConnectionOnPacketTooLarge) {
7578 SimulateNextPacketTooLarge();
7579 // A connection close packet is sent
7580 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PACKET_WRITE_ERROR, _,
7581 ConnectionCloseSource::FROM_SELF))
7582 .Times(1);
7583 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7584}
7585
7586TEST_P(QuicConnectionTest, AlwaysGetPacketTooLarge) {
7587 // Test even we always get packet too large, we do not infinitely try to send
7588 // close packet.
7589 AlwaysGetPacketTooLarge();
7590 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PACKET_WRITE_ERROR, _,
7591 ConnectionCloseSource::FROM_SELF))
7592 .Times(1);
7593 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7594}
7595
7596// Verify that if connection has no outstanding data, it notifies the send
7597// algorithm after the write.
7598TEST_P(QuicConnectionTest, SendDataAndBecomeApplicationLimited) {
7599 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
7600 {
7601 InSequence seq;
7602 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7603 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7604 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
7605 .WillRepeatedly(Return(false));
7606 }
7607
7608 connection_.SendStreamData3();
7609}
7610
7611// Verify that the connection does not become app-limited if there is
7612// outstanding data to send after the write.
7613TEST_P(QuicConnectionTest, NotBecomeApplicationLimitedIfMoreDataAvailable) {
7614 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
7615 {
7616 InSequence seq;
7617 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7618 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7619 }
7620
7621 connection_.SendStreamData3();
7622}
7623
7624// Verify that the connection does not become app-limited after blocked write
7625// even if there is outstanding data to send after the write.
7626TEST_P(QuicConnectionTest, NotBecomeApplicationLimitedDueToWriteBlock) {
7627 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
7628 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7629 BlockOnNextWrite();
7630
7631 connection_.SendStreamData3();
7632
7633 // Now unblock the writer, become congestion control blocked,
7634 // and ensure we become app-limited after writing.
7635 writer_->SetWritable();
7636 CongestionBlockWrites();
7637 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(false));
7638 {
7639 InSequence seq;
7640 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7641 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
7642 }
7643 connection_.OnCanWrite();
7644}
7645
7646// Test the mode in which the link is filled up with probing retransmissions if
7647// the connection becomes application-limited.
7648TEST_P(QuicConnectionTest, SendDataWhenApplicationLimited) {
7649 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7650 EXPECT_CALL(*send_algorithm_, ShouldSendProbingPacket())
7651 .WillRepeatedly(Return(true));
7652 {
7653 InSequence seq;
7654 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7655 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7656 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
7657 .WillRepeatedly(Return(false));
7658 }
QUICHE teamb8343252019-04-29 13:58:01 -07007659 EXPECT_CALL(visitor_, SendProbingData()).WillRepeatedly([this] {
7660 return connection_.sent_packet_manager().MaybeRetransmitOldestPacket(
7661 PROBING_RETRANSMISSION);
7662 });
QUICHE teama6ef0a62019-03-07 20:34:33 -05007663 // Fix congestion window to be 20,000 bytes.
7664 EXPECT_CALL(*send_algorithm_, CanSend(Ge(20000u)))
7665 .WillRepeatedly(Return(false));
7666 EXPECT_CALL(*send_algorithm_, CanSend(Lt(20000u)))
7667 .WillRepeatedly(Return(true));
7668
7669 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
7670 ASSERT_EQ(0u, connection_.GetStats().packets_sent);
7671 connection_.set_fill_up_link_during_probing(true);
7672 connection_.OnHandshakeComplete();
7673 connection_.SendStreamData3();
7674
7675 // We expect a lot of packets from a 20 kbyte window.
7676 EXPECT_GT(connection_.GetStats().packets_sent, 10u);
7677 // Ensure that the packets are padded.
7678 QuicByteCount average_packet_size =
7679 connection_.GetStats().bytes_sent / connection_.GetStats().packets_sent;
7680 EXPECT_GT(average_packet_size, 1000u);
7681
7682 // Acknowledge all packets sent, except for the last one.
7683 QuicAckFrame ack = InitAckFrame(
7684 connection_.sent_packet_manager().GetLargestSentPacket() - 1);
7685 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
7686 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7687
7688 // Ensure that since we no longer have retransmittable bytes in flight, this
7689 // will not cause any responses to be sent.
7690 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
7691 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
7692 ProcessAckPacket(&ack);
7693}
7694
7695TEST_P(QuicConnectionTest, DonotForceSendingAckOnPacketTooLarge) {
7696 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7697 // Send an ack by simulating delayed ack alarm firing.
7698 ProcessPacket(1);
7699 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
7700 EXPECT_TRUE(ack_alarm->IsSet());
7701 connection_.GetAckAlarm()->Fire();
7702 // Simulate data packet causes write error.
7703 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PACKET_WRITE_ERROR, _, _));
7704 SimulateNextPacketTooLarge();
7705 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7706 EXPECT_EQ(1u, writer_->frame_count());
7707 EXPECT_FALSE(writer_->connection_close_frames().empty());
7708 // Ack frame is not bundled in connection close packet.
7709 EXPECT_TRUE(writer_->ack_frames().empty());
7710}
7711
QUICHE teama6ef0a62019-03-07 20:34:33 -05007712// Regression test for b/63620844.
7713TEST_P(QuicConnectionTest, FailedToWriteHandshakePacket) {
7714 SimulateNextPacketTooLarge();
7715 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PACKET_WRITE_ERROR, _,
7716 ConnectionCloseSource::FROM_SELF))
7717 .Times(1);
7718 connection_.SendCryptoStreamData();
7719}
7720
7721TEST_P(QuicConnectionTest, MaxPacingRate) {
7722 EXPECT_EQ(0, connection_.MaxPacingRate().ToBytesPerSecond());
7723 connection_.SetMaxPacingRate(QuicBandwidth::FromBytesPerSecond(100));
7724 EXPECT_EQ(100, connection_.MaxPacingRate().ToBytesPerSecond());
7725}
7726
7727TEST_P(QuicConnectionTest, ClientAlwaysSendConnectionId) {
7728 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
7729 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7730 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7731 EXPECT_EQ(CONNECTION_ID_PRESENT,
7732 writer_->last_packet_header().destination_connection_id_included);
7733
7734 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7735 QuicConfig config;
7736 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
7737 connection_.SetFromConfig(config);
7738
7739 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7740 connection_.SendStreamDataWithString(3, "bar", 3, NO_FIN);
7741 // Verify connection id is still sent in the packet.
7742 EXPECT_EQ(CONNECTION_ID_PRESENT,
7743 writer_->last_packet_header().destination_connection_id_included);
7744}
7745
7746TEST_P(QuicConnectionTest, SendProbingRetransmissions) {
7747 MockQuicConnectionDebugVisitor debug_visitor;
7748 connection_.set_debug_visitor(&debug_visitor);
7749
7750 const QuicStreamId stream_id = 2;
7751 QuicPacketNumber last_packet;
7752 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
7753 SendStreamDataToPeer(stream_id, "bar", 3, NO_FIN, &last_packet);
7754 SendStreamDataToPeer(stream_id, "test", 6, NO_FIN, &last_packet);
7755
7756 const QuicByteCount old_bytes_in_flight =
7757 connection_.sent_packet_manager().GetBytesInFlight();
7758
7759 // Allow 9 probing retransmissions to be sent.
7760 {
7761 InSequence seq;
7762 EXPECT_CALL(*send_algorithm_, CanSend(_))
7763 .Times(9 * 2)
7764 .WillRepeatedly(Return(true));
7765 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(Return(false));
7766 }
7767 // Expect them retransmitted in cyclic order (foo, bar, test, foo, bar...).
7768 QuicPacketCount sent_count = 0;
7769 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _))
7770 .WillRepeatedly(Invoke([this, &sent_count](const SerializedPacket&,
7771 QuicPacketNumber,
7772 TransmissionType, QuicTime) {
7773 ASSERT_EQ(1u, writer_->stream_frames().size());
7774 // Identify the frames by stream offset (0, 3, 6, 0, 3...).
7775 EXPECT_EQ(3 * (sent_count % 3), writer_->stream_frames()[0]->offset);
7776 sent_count++;
7777 }));
7778 EXPECT_CALL(*send_algorithm_, ShouldSendProbingPacket())
7779 .WillRepeatedly(Return(true));
QUICHE teamb8343252019-04-29 13:58:01 -07007780 EXPECT_CALL(visitor_, SendProbingData()).WillRepeatedly([this] {
7781 return connection_.sent_packet_manager().MaybeRetransmitOldestPacket(
7782 PROBING_RETRANSMISSION);
7783 });
QUICHE teama6ef0a62019-03-07 20:34:33 -05007784
7785 connection_.SendProbingRetransmissions();
7786
7787 // Ensure that the in-flight has increased.
7788 const QuicByteCount new_bytes_in_flight =
7789 connection_.sent_packet_manager().GetBytesInFlight();
7790 EXPECT_GT(new_bytes_in_flight, old_bytes_in_flight);
7791}
7792
7793// Ensure that SendProbingRetransmissions() does not retransmit anything when
7794// there are no outstanding packets.
7795TEST_P(QuicConnectionTest,
7796 SendProbingRetransmissionsFailsWhenNothingToRetransmit) {
7797 ASSERT_TRUE(connection_.sent_packet_manager().unacked_packets().empty());
7798
7799 MockQuicConnectionDebugVisitor debug_visitor;
7800 connection_.set_debug_visitor(&debug_visitor);
7801 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _)).Times(0);
7802 EXPECT_CALL(*send_algorithm_, ShouldSendProbingPacket())
7803 .WillRepeatedly(Return(true));
QUICHE teamb8343252019-04-29 13:58:01 -07007804 EXPECT_CALL(visitor_, SendProbingData()).WillRepeatedly([this] {
7805 return connection_.sent_packet_manager().MaybeRetransmitOldestPacket(
7806 PROBING_RETRANSMISSION);
7807 });
QUICHE teama6ef0a62019-03-07 20:34:33 -05007808
7809 connection_.SendProbingRetransmissions();
7810}
7811
7812TEST_P(QuicConnectionTest, PingAfterLastRetransmittablePacketAcked) {
7813 const QuicTime::Delta retransmittable_on_wire_timeout =
7814 QuicTime::Delta::FromMilliseconds(50);
7815 connection_.set_retransmittable_on_wire_timeout(
7816 retransmittable_on_wire_timeout);
7817
7818 EXPECT_TRUE(connection_.connected());
7819 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7820 .WillRepeatedly(Return(true));
7821
7822 const char data[] = "data";
7823 size_t data_size = strlen(data);
7824 QuicStreamOffset offset = 0;
7825
7826 // Advance 5ms, send a retransmittable packet to the peer.
7827 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7828 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
7829 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7830 offset += data_size;
7831 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
7832 // The ping alarm is set for the ping timeout, not the shorter
7833 // retransmittable_on_wire_timeout.
7834 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7835 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
7836 EXPECT_EQ((clock_.ApproximateNow() + ping_delay),
7837 connection_.GetPingAlarm()->deadline());
7838
7839 // Advance 5ms, send a second retransmittable packet to the peer.
7840 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7841 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7842 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7843 offset += data_size;
7844 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7845
7846 // Now receive an ACK of the first packet. This should not set the
7847 // retransmittable-on-wire alarm since packet 2 is still on the wire.
7848 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7849 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7850 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7851 QuicAckFrame frame =
7852 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7853 ProcessAckPacket(&frame);
7854 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
7855 // The ping alarm is set for the ping timeout, not the shorter
7856 // retransmittable_on_wire_timeout.
7857 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7858 // The ping alarm has a 1 second granularity, and the clock has been advanced
7859 // 10ms since it was originally set.
7860 EXPECT_EQ((clock_.ApproximateNow() + ping_delay -
7861 QuicTime::Delta::FromMilliseconds(10)),
7862 connection_.GetPingAlarm()->deadline());
7863
7864 // Now receive an ACK of the second packet. This should set the
7865 // retransmittable-on-wire alarm now that no retransmittable packets are on
7866 // the wire.
7867 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7868 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7869 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
7870 ProcessAckPacket(&frame);
7871 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7872 EXPECT_EQ(clock_.ApproximateNow() + retransmittable_on_wire_timeout,
7873 connection_.GetPingAlarm()->deadline());
7874
7875 // Now receive a duplicate ACK of the second packet. This should not update
7876 // the ping alarm.
7877 QuicTime prev_deadline = connection_.GetPingAlarm()->deadline();
7878 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7879 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
7880 ProcessAckPacket(&frame);
7881 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7882 EXPECT_EQ(prev_deadline, connection_.GetPingAlarm()->deadline());
7883
7884 // Now receive a non-ACK packet. This should not update the ping alarm.
7885 prev_deadline = connection_.GetPingAlarm()->deadline();
7886 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7887 ProcessPacket(4);
7888 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7889 EXPECT_EQ(prev_deadline, connection_.GetPingAlarm()->deadline());
7890
7891 // Simulate the alarm firing and check that a PING is sent.
7892 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
7893 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
7894 }));
7895 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07007896 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05007897 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07007898 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007899 } else {
nharper55fa6132019-05-07 19:37:21 -07007900 EXPECT_EQ(padding_frame_count + 3u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007901 }
7902 ASSERT_EQ(1u, writer_->ping_frames().size());
7903}
7904
7905TEST_P(QuicConnectionTest, NoPingIfRetransmittablePacketSent) {
7906 const QuicTime::Delta retransmittable_on_wire_timeout =
7907 QuicTime::Delta::FromMilliseconds(50);
7908 connection_.set_retransmittable_on_wire_timeout(
7909 retransmittable_on_wire_timeout);
7910
7911 EXPECT_TRUE(connection_.connected());
7912 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7913 .WillRepeatedly(Return(true));
7914
7915 const char data[] = "data";
7916 size_t data_size = strlen(data);
7917 QuicStreamOffset offset = 0;
7918
7919 // Advance 5ms, send a retransmittable packet to the peer.
7920 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7921 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
7922 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7923 offset += data_size;
7924 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
7925 // The ping alarm is set for the ping timeout, not the shorter
7926 // retransmittable_on_wire_timeout.
7927 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7928 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
7929 EXPECT_EQ((clock_.ApproximateNow() + ping_delay),
7930 connection_.GetPingAlarm()->deadline());
7931
7932 // Now receive an ACK of the first packet. This should set the
7933 // retransmittable-on-wire alarm now that no retransmittable packets are on
7934 // the wire.
7935 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7936 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7937 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7938 QuicAckFrame frame =
7939 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7940 ProcessAckPacket(&frame);
7941 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7942 EXPECT_EQ(clock_.ApproximateNow() + retransmittable_on_wire_timeout,
7943 connection_.GetPingAlarm()->deadline());
7944
7945 // Before the alarm fires, send another retransmittable packet. This should
7946 // cancel the retransmittable-on-wire alarm since now there's a
7947 // retransmittable packet on the wire.
7948 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7949 offset += data_size;
7950 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7951
7952 // Now receive an ACK of the second packet. This should set the
7953 // retransmittable-on-wire alarm now that no retransmittable packets are on
7954 // the wire.
7955 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7956 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7957 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
7958 ProcessAckPacket(&frame);
7959 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7960 EXPECT_EQ(clock_.ApproximateNow() + retransmittable_on_wire_timeout,
7961 connection_.GetPingAlarm()->deadline());
7962
7963 // Simulate the alarm firing and check that a PING is sent.
7964 writer_->Reset();
7965 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
7966 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
7967 }));
7968 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07007969 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05007970 if (GetParam().no_stop_waiting) {
fayang03916692019-05-22 17:57:18 -07007971 if (GetQuicReloadableFlag(quic_simplify_stop_waiting)) {
7972 // Do not ACK acks.
7973 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
7974 } else {
7975 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
7976 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007977 } else {
nharper55fa6132019-05-07 19:37:21 -07007978 EXPECT_EQ(padding_frame_count + 3u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007979 }
7980 ASSERT_EQ(1u, writer_->ping_frames().size());
7981}
7982
7983TEST_P(QuicConnectionTest, OnForwardProgressConfirmed) {
7984 EXPECT_CALL(visitor_, OnForwardProgressConfirmed()).Times(Exactly(0));
7985 EXPECT_TRUE(connection_.connected());
7986
7987 const char data[] = "data";
7988 size_t data_size = strlen(data);
7989 QuicStreamOffset offset = 0;
7990
7991 // Send two packets.
7992 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7993 offset += data_size;
7994 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7995 offset += data_size;
7996
7997 // Ack packet 1. This increases the largest_acked to 1, so
7998 // OnForwardProgressConfirmed() should be called
7999 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8000 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8001 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8002 EXPECT_CALL(visitor_, OnForwardProgressConfirmed());
8003 QuicAckFrame frame =
8004 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8005 ProcessAckPacket(&frame);
8006
8007 // Ack packet 1 again. largest_acked remains at 1, so
8008 // OnForwardProgressConfirmed() should not be called.
8009 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8010 frame = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8011 ProcessAckPacket(&frame);
8012
8013 // Ack packet 2. This increases the largest_acked to 2, so
8014 // OnForwardProgressConfirmed() should be called.
8015 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8016 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8017 EXPECT_CALL(visitor_, OnForwardProgressConfirmed());
8018 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8019 ProcessAckPacket(&frame);
8020}
8021
8022TEST_P(QuicConnectionTest, ValidStatelessResetToken) {
8023 const QuicUint128 kTestToken = 1010101;
8024 const QuicUint128 kWrongTestToken = 1010100;
8025 QuicConfig config;
8026 // No token has been received.
8027 EXPECT_FALSE(connection_.IsValidStatelessResetToken(kTestToken));
8028
8029 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(2);
8030 // Token is different from received token.
8031 QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestToken);
8032 connection_.SetFromConfig(config);
8033 EXPECT_FALSE(connection_.IsValidStatelessResetToken(kWrongTestToken));
8034
8035 QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestToken);
8036 connection_.SetFromConfig(config);
8037 EXPECT_TRUE(connection_.IsValidStatelessResetToken(kTestToken));
8038}
8039
8040TEST_P(QuicConnectionTest, WriteBlockedWithInvalidAck) {
8041 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8042 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, _, _));
8043
8044 BlockOnNextWrite();
8045 connection_.SendStreamDataWithString(5, "foo", 0, FIN);
8046 // This causes connection to be closed because packet 1 has not been sent yet.
8047 QuicAckFrame frame = InitAckFrame(1);
8048 ProcessAckPacket(1, &frame);
8049}
8050
8051TEST_P(QuicConnectionTest, SendMessage) {
fayangc31c9952019-06-05 13:54:48 -07008052 if (!VersionSupportsMessageFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008053 return;
8054 }
ianswettb239f862019-04-05 09:15:06 -07008055 std::string message(connection_.GetCurrentLargestMessagePayload() * 2, 'a');
QUICHE teama6ef0a62019-03-07 20:34:33 -05008056 QuicStringPiece message_data(message);
8057 QuicMemSliceStorage storage(nullptr, 0, nullptr, 0);
8058 {
8059 QuicConnection::ScopedPacketFlusher flusher(&connection_,
8060 QuicConnection::SEND_ACK);
8061 connection_.SendStreamData3();
8062 // Send a message which cannot fit into current open packet, and 2 packets
8063 // get sent, one contains stream frame, and the other only contains the
8064 // message frame.
8065 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
8066 EXPECT_EQ(
8067 MESSAGE_STATUS_SUCCESS,
8068 connection_.SendMessage(
8069 1, MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(),
ianswettb239f862019-04-05 09:15:06 -07008070 QuicStringPiece(
8071 message_data.data(),
8072 connection_.GetCurrentLargestMessagePayload()),
QUICHE teama6ef0a62019-03-07 20:34:33 -05008073 &storage)));
8074 }
8075 // Fail to send a message if connection is congestion control blocked.
8076 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(Return(false));
8077 EXPECT_EQ(
8078 MESSAGE_STATUS_BLOCKED,
8079 connection_.SendMessage(
8080 2, MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(),
8081 "message", &storage)));
8082
8083 // Always fail to send a message which cannot fit into one packet.
8084 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8085 EXPECT_EQ(
8086 MESSAGE_STATUS_TOO_LARGE,
8087 connection_.SendMessage(
ianswettb239f862019-04-05 09:15:06 -07008088 3, MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(),
8089 QuicStringPiece(
8090 message_data.data(),
8091 connection_.GetCurrentLargestMessagePayload() + 1),
8092 &storage)));
QUICHE teama6ef0a62019-03-07 20:34:33 -05008093}
8094
8095// Test to check that the path challenge/path response logic works
8096// correctly. This test is only for version-99
8097TEST_P(QuicConnectionTest, PathChallengeResponse) {
fayangc31c9952019-06-05 13:54:48 -07008098 if (connection_.version().transport_version != QUIC_VERSION_99) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008099 return;
8100 }
8101 // First check if we can probe from server to client and back
8102 set_perspective(Perspective::IS_SERVER);
8103 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
8104
8105 // Create and send the probe request (PATH_CHALLENGE frame).
8106 // SendConnectivityProbingPacket ends up calling
8107 // TestPacketWriter::WritePacket() which in turns receives and parses the
8108 // packet by calling framer_.ProcessPacket() -- which in turn calls
8109 // SimpleQuicFramer::OnPathChallengeFrame(). SimpleQuicFramer saves
8110 // the packet in writer_->path_challenge_frames()
8111 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8112 connection_.SendConnectivityProbingPacket(writer_.get(),
8113 connection_.peer_address());
8114 // Save the random contents of the challenge for later comparison to the
8115 // response.
nharper55fa6132019-05-07 19:37:21 -07008116 ASSERT_GE(writer_->path_challenge_frames().size(), 1u);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008117 QuicPathFrameBuffer challenge_data =
8118 writer_->path_challenge_frames().front().data_buffer;
8119
8120 // Normally, QuicConnection::OnPathChallengeFrame and OnPaddingFrame would be
8121 // called and it will perform actions to ensure that the rest of the protocol
8122 // is performed (specifically, call UpdatePacketContent to say that this is a
8123 // path challenge so that when QuicConnection::OnPacketComplete is called
8124 // (again, out of the framer), the response is generated). Simulate those
8125 // calls so that the right internal state is set up for generating
8126 // the response.
8127 EXPECT_TRUE(connection_.OnPathChallengeFrame(
8128 writer_->path_challenge_frames().front()));
8129 EXPECT_TRUE(connection_.OnPaddingFrame(writer_->padding_frames().front()));
8130 // Cause the response to be created and sent. Result is that the response
8131 // should be stashed in writer's path_response_frames.
8132 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8133 connection_.SendConnectivityProbingResponsePacket(connection_.peer_address());
8134
8135 // The final check is to ensure that the random data in the response matches
8136 // the random data from the challenge.
8137 EXPECT_EQ(0, memcmp(&challenge_data,
8138 &(writer_->path_response_frames().front().data_buffer),
8139 sizeof(challenge_data)));
8140}
8141
8142// Regression test for b/110259444
8143TEST_P(QuicConnectionTest, DoNotScheduleSpuriousAckAlarm) {
8144 SetQuicReloadableFlag(quic_fix_spurious_ack_alarm, true);
8145 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8146 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
8147 writer_->SetWriteBlocked();
8148
8149 ProcessPacket(1);
8150 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
8151 // Verify ack alarm is set.
8152 EXPECT_TRUE(ack_alarm->IsSet());
8153 // Fire the ack alarm, verify no packet is sent because the writer is blocked.
8154 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8155 connection_.GetAckAlarm()->Fire();
8156
8157 writer_->SetWritable();
8158 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8159 ProcessPacket(2);
8160 // Verify ack alarm is not set.
8161 EXPECT_FALSE(ack_alarm->IsSet());
8162}
8163
8164TEST_P(QuicConnectionTest, DisablePacingOffloadConnectionOptions) {
8165 EXPECT_FALSE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
8166 writer_->set_supports_release_time(true);
8167 QuicConfig config;
8168 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8169 connection_.SetFromConfig(config);
8170 EXPECT_TRUE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
8171
8172 QuicTagVector connection_options;
8173 connection_options.push_back(kNPCO);
8174 config.SetConnectionOptionsToSend(connection_options);
8175 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8176 connection_.SetFromConfig(config);
8177 // Verify pacing offload is disabled.
8178 EXPECT_FALSE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
8179}
8180
8181// Regression test for b/110259444
8182// Get a path response without having issued a path challenge...
8183TEST_P(QuicConnectionTest, OrphanPathResponse) {
8184 QuicPathFrameBuffer data = {{0, 1, 2, 3, 4, 5, 6, 7}};
8185
8186 QuicPathResponseFrame frame(99, data);
8187 EXPECT_TRUE(connection_.OnPathResponseFrame(frame));
8188 // If PATH_RESPONSE was accepted (payload matches the payload saved
8189 // in QuicConnection::transmitted_connectivity_probe_payload_) then
8190 // current_packet_content_ would be set to FIRST_FRAME_IS_PING.
8191 // Since this PATH_RESPONSE does not match, current_packet_content_
8192 // must not be FIRST_FRAME_IS_PING.
8193 EXPECT_NE(QuicConnection::FIRST_FRAME_IS_PING,
8194 QuicConnectionPeer::GetCurrentPacketContent(&connection_));
8195}
8196
8197// Regression test for b/120791670
8198TEST_P(QuicConnectionTest, StopProcessingGQuicPacketInIetfQuicConnection) {
8199 // This test mimics a problematic scenario where an IETF QUIC connection
8200 // receives a Google QUIC packet and continue processing it using Google QUIC
8201 // wire format.
fayangd4291e42019-05-30 10:31:21 -07008202 if (!VersionHasIetfInvariantHeader(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008203 return;
8204 }
8205 set_perspective(Perspective::IS_SERVER);
nharper46833c32019-05-15 21:33:05 -07008206 QuicFrame frame;
8207 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
8208 frame = QuicFrame(&crypto_frame_);
8209 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
8210 } else {
8211 frame = QuicFrame(QuicStreamFrame(
8212 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
8213 0u, QuicStringPiece()));
8214 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
8215 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008216 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
nharper46833c32019-05-15 21:33:05 -07008217 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008218
8219 // Let connection process a Google QUIC packet.
8220 peer_framer_.set_version_for_tests(
8221 ParsedQuicVersion(PROTOCOL_QUIC_CRYPTO, QUIC_VERSION_43));
QUICHE team8c1daa22019-03-13 08:33:41 -07008222 std::unique_ptr<QuicPacket> packet(
QUICHE team6987b4a2019-03-15 16:23:04 -07008223 ConstructDataPacket(2, !kHasStopWaiting, ENCRYPTION_INITIAL));
dschinazi66dea072019-04-09 11:41:06 -07008224 char buffer[kMaxOutgoingPacketSize];
8225 size_t encrypted_length =
8226 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(2),
8227 *packet, buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008228 // Make sure no stream frame is processed.
8229 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(0);
8230 connection_.ProcessUdpPacket(
8231 kSelfAddress, kPeerAddress,
8232 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
8233
8234 EXPECT_EQ(2u, connection_.GetStats().packets_received);
8235 EXPECT_EQ(1u, connection_.GetStats().packets_processed);
8236}
8237
8238TEST_P(QuicConnectionTest, AcceptPacketNumberZero) {
fayangc31c9952019-06-05 13:54:48 -07008239 if (version().transport_version != QUIC_VERSION_99) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008240 return;
8241 }
8242 // Set first_sending_packet_number to be 0 to allow successfully processing
8243 // acks which ack packet number 0.
8244 QuicFramerPeer::SetFirstSendingPacketNumber(writer_->framer()->framer(), 0);
8245 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8246
8247 ProcessPacket(0);
fayangc31c9952019-06-05 13:54:48 -07008248 EXPECT_EQ(QuicPacketNumber(0), LargestAcked(connection_.ack_frame()));
8249 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008250
8251 ProcessPacket(1);
fayangc31c9952019-06-05 13:54:48 -07008252 EXPECT_EQ(QuicPacketNumber(1), LargestAcked(connection_.ack_frame()));
8253 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008254
8255 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07008256 EXPECT_EQ(QuicPacketNumber(2), LargestAcked(connection_.ack_frame()));
8257 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008258}
8259
QUICHE teamcd098022019-03-22 18:49:55 -07008260TEST_P(QuicConnectionTest, MultiplePacketNumberSpacesBasicSending) {
8261 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8262 return;
8263 }
8264 use_tagging_decrypter();
8265 connection_.SetEncrypter(ENCRYPTION_INITIAL,
8266 QuicMakeUnique<TaggingEncrypter>(0x01));
8267
8268 connection_.SendCryptoStreamData();
8269 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8270 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
8271 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8272 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8273 QuicAckFrame frame1 = InitAckFrame(1);
8274 // Received ACK for packet 1.
8275 ProcessFramePacketAtLevel(30, QuicFrame(&frame1), ENCRYPTION_INITIAL);
8276
8277 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(4);
8278 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
8279 NO_FIN);
8280 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 4,
8281 NO_FIN);
8282 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
8283 8, NO_FIN);
8284 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
8285 12, FIN);
8286 // Received ACK for packets 2, 4, 5.
8287 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
8288 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8289 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8290 QuicAckFrame frame2 =
8291 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)},
8292 {QuicPacketNumber(4), QuicPacketNumber(6)}});
8293 // Make sure although the same packet number is used, but they are in
8294 // different packet number spaces.
8295 ProcessFramePacketAtLevel(30, QuicFrame(&frame2), ENCRYPTION_FORWARD_SECURE);
8296}
8297
8298TEST_P(QuicConnectionTest, PeerAcksPacketsInWrongPacketNumberSpace) {
8299 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8300 return;
8301 }
8302 use_tagging_decrypter();
8303 connection_.SetEncrypter(ENCRYPTION_INITIAL,
8304 QuicMakeUnique<TaggingEncrypter>(0x01));
8305
8306 connection_.SendCryptoStreamData();
8307 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8308 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
8309 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8310 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8311 QuicAckFrame frame1 = InitAckFrame(1);
8312 // Received ACK for packet 1.
8313 ProcessFramePacketAtLevel(30, QuicFrame(&frame1), ENCRYPTION_INITIAL);
8314
8315 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
8316 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
8317 NO_FIN);
8318 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 4,
8319 NO_FIN);
8320
8321 // Received ACK for packets 2 and 3 in wrong packet number space.
8322 QuicAckFrame invalid_ack =
8323 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(4)}});
8324 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, _,
8325 ConnectionCloseSource::FROM_SELF));
8326 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8327 ProcessFramePacketAtLevel(300, QuicFrame(&invalid_ack), ENCRYPTION_INITIAL);
8328}
8329
8330TEST_P(QuicConnectionTest, MultiplePacketNumberSpacesBasicReceiving) {
8331 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8332 return;
8333 }
8334 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
nharper46833c32019-05-15 21:33:05 -07008335 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
8336 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
8337 }
QUICHE teamcd098022019-03-22 18:49:55 -07008338 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
8339 use_tagging_decrypter();
8340 // Receives packet 1000 in initial data.
nharper46833c32019-05-15 21:33:05 -07008341 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
QUICHE teamcd098022019-03-22 18:49:55 -07008342 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
8343 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
8344 QuicMakeUnique<TaggingEncrypter>(0x02));
zhongyi546cc452019-04-12 15:27:49 -07008345 SetDecrypter(ENCRYPTION_ZERO_RTT,
8346 QuicMakeUnique<StrictTaggingDecrypter>(0x02));
QUICHE teamcd098022019-03-22 18:49:55 -07008347 connection_.SetEncrypter(ENCRYPTION_INITIAL,
8348 QuicMakeUnique<TaggingEncrypter>(0x02));
8349 // Receives packet 1000 in application data.
8350 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
8351 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
8352 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
8353 NO_FIN);
8354 // Verify application data ACK gets bundled with outgoing data.
8355 EXPECT_EQ(2u, writer_->frame_count());
8356 // Make sure ACK alarm is still set because initial data is not ACKed.
8357 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
8358 // Receive packet 1001 in application data.
8359 ProcessDataPacketAtLevel(1001, false, ENCRYPTION_ZERO_RTT);
8360 clock_.AdvanceTime(DefaultRetransmissionTime());
8361 // Simulates ACK alarm fires and verify two ACKs are flushed.
8362 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
8363 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
8364 QuicMakeUnique<TaggingEncrypter>(0x02));
8365 connection_.GetAckAlarm()->Fire();
8366 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
8367 // Receives more packets in application data.
8368 ProcessDataPacketAtLevel(1002, false, ENCRYPTION_ZERO_RTT);
8369 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
8370
8371 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
8372 QuicMakeUnique<TaggingEncrypter>(0x02));
zhongyi546cc452019-04-12 15:27:49 -07008373 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
8374 QuicMakeUnique<StrictTaggingDecrypter>(0x02));
QUICHE teamcd098022019-03-22 18:49:55 -07008375 // Verify zero rtt and forward secure packets get acked in the same packet.
8376 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
nharper2c9f02a2019-05-08 10:25:50 -07008377 ProcessDataPacket(1003);
QUICHE teamcd098022019-03-22 18:49:55 -07008378 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
8379}
8380
QUICHE team552f71f2019-03-23 15:37:59 -07008381TEST_P(QuicConnectionTest, CancelAckAlarmOnWriteBlocked) {
8382 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8383 return;
8384 }
8385 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
nharper46833c32019-05-15 21:33:05 -07008386 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
8387 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
8388 }
QUICHE team552f71f2019-03-23 15:37:59 -07008389 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
8390 use_tagging_decrypter();
8391 // Receives packet 1000 in initial data.
nharper46833c32019-05-15 21:33:05 -07008392 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
QUICHE team552f71f2019-03-23 15:37:59 -07008393 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
8394 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
8395 QuicMakeUnique<TaggingEncrypter>(0x02));
zhongyi546cc452019-04-12 15:27:49 -07008396 SetDecrypter(ENCRYPTION_ZERO_RTT,
8397 QuicMakeUnique<StrictTaggingDecrypter>(0x02));
QUICHE team552f71f2019-03-23 15:37:59 -07008398 connection_.SetEncrypter(ENCRYPTION_INITIAL,
8399 QuicMakeUnique<TaggingEncrypter>(0x02));
8400 // Receives packet 1000 in application data.
8401 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
8402 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
8403
8404 writer_->SetWriteBlocked();
8405 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AnyNumber());
8406 // Simulates ACK alarm fires and verify no ACK is flushed because of write
8407 // blocked.
8408 clock_.AdvanceTime(DefaultDelayedAckTime());
8409 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8410 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
8411 QuicMakeUnique<TaggingEncrypter>(0x02));
8412 connection_.GetAckAlarm()->Fire();
8413 // Verify ACK alarm is not set.
8414 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
8415
8416 writer_->SetWritable();
8417 // Verify 2 ACKs are sent when connection gets unblocked.
8418 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
8419 connection_.OnCanWrite();
8420 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
8421}
8422
dschinazi346b7ce2019-06-05 01:38:18 -07008423// Make sure a packet received with the right client connection ID is processed.
8424TEST_P(QuicConnectionTest, ValidClientConnectionId) {
8425 SetQuicRestartFlag(quic_do_not_override_connection_id, true);
8426 if (!framer_.version().SupportsClientConnectionIds()) {
8427 return;
8428 }
8429 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8430 connection_.set_client_connection_id(TestConnectionId(0x33));
8431 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_FORWARD_SECURE);
8432 header.destination_connection_id = TestConnectionId(0x33);
8433 header.destination_connection_id_included = CONNECTION_ID_PRESENT;
8434 header.source_connection_id_included = CONNECTION_ID_ABSENT;
8435 QuicFrames frames;
8436 QuicPingFrame ping_frame;
8437 QuicPaddingFrame padding_frame;
8438 frames.push_back(QuicFrame(ping_frame));
8439 frames.push_back(QuicFrame(padding_frame));
8440 std::unique_ptr<QuicPacket> packet =
8441 BuildUnsizedDataPacket(&framer_, header, frames);
8442 char buffer[kMaxOutgoingPacketSize];
8443 size_t encrypted_length = peer_framer_.EncryptPayload(
8444 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
8445 kMaxOutgoingPacketSize);
8446 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
8447 false);
8448 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
8449 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
8450 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
8451}
8452
8453// Make sure a packet received with a different client connection ID is dropped.
8454TEST_P(QuicConnectionTest, InvalidClientConnectionId) {
8455 SetQuicRestartFlag(quic_do_not_override_connection_id, true);
8456 if (!framer_.version().SupportsClientConnectionIds()) {
8457 return;
8458 }
8459 connection_.set_client_connection_id(TestConnectionId(0x33));
8460 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_FORWARD_SECURE);
8461 header.destination_connection_id = TestConnectionId(0xbad);
8462 header.destination_connection_id_included = CONNECTION_ID_PRESENT;
8463 header.source_connection_id_included = CONNECTION_ID_ABSENT;
8464 QuicFrames frames;
8465 QuicPingFrame ping_frame;
8466 QuicPaddingFrame padding_frame;
8467 frames.push_back(QuicFrame(ping_frame));
8468 frames.push_back(QuicFrame(padding_frame));
8469 std::unique_ptr<QuicPacket> packet =
8470 BuildUnsizedDataPacket(&framer_, header, frames);
8471 char buffer[kMaxOutgoingPacketSize];
8472 size_t encrypted_length = peer_framer_.EncryptPayload(
8473 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
8474 kMaxOutgoingPacketSize);
8475 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
8476 false);
8477 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
8478 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
8479 EXPECT_EQ(1u, connection_.GetStats().packets_dropped);
8480}
8481
8482// Make sure the first packet received with a different client connection ID on
8483// the server is processed and it changes the client connection ID.
8484TEST_P(QuicConnectionTest, UpdateClientConnectionIdFromFirstPacket) {
8485 SetQuicRestartFlag(quic_do_not_override_connection_id, true);
8486 if (!framer_.version().SupportsClientConnectionIds()) {
8487 return;
8488 }
8489 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8490 set_perspective(Perspective::IS_SERVER);
8491 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_INITIAL);
8492 header.source_connection_id = TestConnectionId(0x33);
8493 header.source_connection_id_included = CONNECTION_ID_PRESENT;
8494 QuicFrames frames;
8495 QuicPingFrame ping_frame;
8496 QuicPaddingFrame padding_frame;
8497 frames.push_back(QuicFrame(ping_frame));
8498 frames.push_back(QuicFrame(padding_frame));
8499 std::unique_ptr<QuicPacket> packet =
8500 BuildUnsizedDataPacket(&framer_, header, frames);
8501 char buffer[kMaxOutgoingPacketSize];
8502 size_t encrypted_length = peer_framer_.EncryptPayload(
8503 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
8504 kMaxOutgoingPacketSize);
8505 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
8506 false);
8507 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
8508 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
8509 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
8510 EXPECT_EQ(TestConnectionId(0x33), connection_.client_connection_id());
8511}
8512
fayang40ec3ac2019-06-05 09:07:54 -07008513// Regression test for b/134416344.
8514TEST_P(QuicConnectionTest, CheckConnectedBeforeFlush) {
8515 // This test mimics a scenario where a connection processes 2 packets and the
8516 // 2nd packet contains connection close frame. When the 2nd flusher goes out
8517 // of scope, a delayed ACK is pending, and ACK alarm should not be scheduled
8518 // because connection is disconnected.
8519 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8520 EXPECT_CALL(visitor_, OnConnectionClosed(_, _, _));
8521 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
8522 std::unique_ptr<QuicConnectionCloseFrame> connection_close_frame(
8523 new QuicConnectionCloseFrame(QUIC_INTERNAL_ERROR));
8524 if (connection_.transport_version() == QUIC_VERSION_99) {
8525 connection_close_frame->close_type = IETF_QUIC_TRANSPORT_CONNECTION_CLOSE;
8526 }
8527 // Received 2 packets.
8528 QuicFrame frame;
8529 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
8530 frame = QuicFrame(&crypto_frame_);
8531 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
8532 } else {
8533 frame = QuicFrame(QuicStreamFrame(
8534 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
8535 0u, QuicStringPiece()));
8536 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
8537 }
8538 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
8539 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
8540 EXPECT_TRUE(ack_alarm->IsSet());
8541 ProcessFramePacketWithAddresses(QuicFrame(connection_close_frame.get()),
8542 kSelfAddress, kPeerAddress);
8543 if (GetQuicReloadableFlag(quic_check_connected_before_flush)) {
8544 // Verify ack alarm is not set.
8545 EXPECT_FALSE(ack_alarm->IsSet());
8546 } else {
8547 EXPECT_TRUE(ack_alarm->IsSet());
8548 }
8549}
8550
QUICHE teama6ef0a62019-03-07 20:34:33 -05008551} // namespace
8552} // namespace test
8553} // namespace quic