blob: fb3d21b0e1aa25f24dd8c20105efda5ca8d0d2c8 [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
425 bool SupportsReleaseTime() const { return supports_release_time_; }
426
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
613 void SendAck() { QuicConnectionPeer::SendAck(this); }
614
615 void SetSendAlgorithm(SendAlgorithmInterface* send_algorithm) {
616 QuicConnectionPeer::SetSendAlgorithm(this, send_algorithm);
617 }
618
619 void SetLossAlgorithm(LossDetectionInterface* loss_algorithm) {
620 QuicConnectionPeer::SetLossAlgorithm(this, loss_algorithm);
621 }
622
623 void SendPacket(EncryptionLevel level,
624 uint64_t packet_number,
625 std::unique_ptr<QuicPacket> packet,
626 HasRetransmittableData retransmittable,
627 bool has_ack,
628 bool has_pending_frames) {
dschinazi66dea072019-04-09 11:41:06 -0700629 char buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -0500630 size_t encrypted_length =
631 QuicConnectionPeer::GetFramer(this)->EncryptPayload(
QUICHE team6987b4a2019-03-15 16:23:04 -0700632 ENCRYPTION_INITIAL, QuicPacketNumber(packet_number), *packet,
dschinazi66dea072019-04-09 11:41:06 -0700633 buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500634 SerializedPacket serialized_packet(
635 QuicPacketNumber(packet_number), PACKET_4BYTE_PACKET_NUMBER, buffer,
636 encrypted_length, has_ack, has_pending_frames);
637 if (retransmittable == HAS_RETRANSMITTABLE_DATA) {
638 serialized_packet.retransmittable_frames.push_back(
639 QuicFrame(QuicStreamFrame()));
640 }
641 OnSerializedPacket(&serialized_packet);
642 }
643
644 QuicConsumedData SaveAndSendStreamData(QuicStreamId id,
645 const struct iovec* iov,
646 int iov_count,
647 size_t total_length,
648 QuicStreamOffset offset,
649 StreamSendingState state) {
650 ScopedPacketFlusher flusher(this, NO_ACK);
651 producer_.SaveStreamData(id, iov, iov_count, 0u, total_length);
652 if (notifier_ != nullptr) {
653 return notifier_->WriteOrBufferData(id, total_length, state);
654 }
655 return QuicConnection::SendStreamData(id, total_length, offset, state);
656 }
657
658 QuicConsumedData SendStreamDataWithString(QuicStreamId id,
659 QuicStringPiece data,
660 QuicStreamOffset offset,
661 StreamSendingState state) {
662 ScopedPacketFlusher flusher(this, NO_ACK);
nharper46833c32019-05-15 21:33:05 -0700663 if (!QuicUtils::IsCryptoStreamId(transport_version(), id) &&
QUICHE team6987b4a2019-03-15 16:23:04 -0700664 this->encryption_level() == ENCRYPTION_INITIAL) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500665 this->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
666 }
667 struct iovec iov;
668 MakeIOVector(data, &iov);
669 return SaveAndSendStreamData(id, &iov, 1, data.length(), offset, state);
670 }
671
QUICHE teamcd098022019-03-22 18:49:55 -0700672 QuicConsumedData SendApplicationDataAtLevel(EncryptionLevel encryption_level,
673 QuicStreamId id,
674 QuicStringPiece data,
675 QuicStreamOffset offset,
676 StreamSendingState state) {
677 ScopedPacketFlusher flusher(this, NO_ACK);
678 DCHECK(encryption_level >= ENCRYPTION_ZERO_RTT);
679 SetEncrypter(encryption_level, QuicMakeUnique<TaggingEncrypter>(0x01));
680 SetDefaultEncryptionLevel(encryption_level);
681 struct iovec iov;
682 MakeIOVector(data, &iov);
683 return SaveAndSendStreamData(id, &iov, 1, data.length(), offset, state);
684 }
685
QUICHE teama6ef0a62019-03-07 20:34:33 -0500686 QuicConsumedData SendStreamData3() {
687 return SendStreamDataWithString(
688 GetNthClientInitiatedStreamId(1, transport_version()), "food", 0,
689 NO_FIN);
690 }
691
692 QuicConsumedData SendStreamData5() {
693 return SendStreamDataWithString(
694 GetNthClientInitiatedStreamId(2, transport_version()), "food2", 0,
695 NO_FIN);
696 }
697
698 // Ensures the connection can write stream data before writing.
699 QuicConsumedData EnsureWritableAndSendStreamData5() {
700 EXPECT_TRUE(CanWriteStreamData());
701 return SendStreamData5();
702 }
703
704 // The crypto stream has special semantics so that it is not blocked by a
705 // congestion window limitation, and also so that it gets put into a separate
706 // packet (so that it is easier to reason about a crypto frame not being
707 // split needlessly across packet boundaries). As a result, we have separate
708 // tests for some cases for this stream.
709 QuicConsumedData SendCryptoStreamData() {
710 QuicStreamOffset offset = 0;
711 QuicStringPiece data("chlo");
nharper46833c32019-05-15 21:33:05 -0700712 return SendCryptoDataWithString(data, offset);
713 }
714
715 QuicConsumedData SendCryptoDataWithString(QuicStringPiece data,
716 QuicStreamOffset offset) {
QUICHE teamea740082019-03-11 17:58:43 -0700717 if (!QuicVersionUsesCryptoFrames(transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500718 return SendStreamDataWithString(
719 QuicUtils::GetCryptoStreamId(transport_version()), data, offset,
720 NO_FIN);
721 }
QUICHE team6987b4a2019-03-15 16:23:04 -0700722 producer_.SaveCryptoData(ENCRYPTION_INITIAL, offset, data);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500723 size_t bytes_written;
724 if (notifier_) {
725 bytes_written =
QUICHE team6987b4a2019-03-15 16:23:04 -0700726 notifier_->WriteCryptoData(ENCRYPTION_INITIAL, data.length(), offset);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500727 } else {
QUICHE team6987b4a2019-03-15 16:23:04 -0700728 bytes_written = QuicConnection::SendCryptoData(ENCRYPTION_INITIAL,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500729 data.length(), offset);
730 }
731 return QuicConsumedData(bytes_written, /*fin_consumed*/ false);
732 }
733
734 void set_version(ParsedQuicVersion version) {
735 QuicConnectionPeer::GetFramer(this)->set_version(version);
736 }
737
738 void SetSupportedVersions(const ParsedQuicVersionVector& versions) {
739 QuicConnectionPeer::GetFramer(this)->SetSupportedVersions(versions);
740 QuicConnectionPeer::SetNoVersionNegotiation(this, versions.size() == 1);
741 writer()->SetSupportedVersions(versions);
742 }
743
744 void set_perspective(Perspective perspective) {
745 writer()->set_perspective(perspective);
746 QuicConnectionPeer::SetPerspective(this, perspective);
747 }
748
749 // Enable path MTU discovery. Assumes that the test is performed from the
750 // client perspective and the higher value of MTU target is used.
751 void EnablePathMtuDiscovery(MockSendAlgorithm* send_algorithm) {
752 ASSERT_EQ(Perspective::IS_CLIENT, perspective());
753
754 QuicConfig config;
755 QuicTagVector connection_options;
756 connection_options.push_back(kMTUH);
757 config.SetConnectionOptionsToSend(connection_options);
758 EXPECT_CALL(*send_algorithm, SetFromConfig(_, _));
759 SetFromConfig(config);
760
761 // Normally, the pacing would be disabled in the test, but calling
762 // SetFromConfig enables it. Set nearly-infinite bandwidth to make the
763 // pacing algorithm work.
764 EXPECT_CALL(*send_algorithm, PacingRate(_))
765 .WillRepeatedly(Return(QuicBandwidth::Infinite()));
766 }
767
768 TestAlarmFactory::TestAlarm* GetAckAlarm() {
769 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
770 QuicConnectionPeer::GetAckAlarm(this));
771 }
772
773 TestAlarmFactory::TestAlarm* GetPingAlarm() {
774 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
775 QuicConnectionPeer::GetPingAlarm(this));
776 }
777
778 TestAlarmFactory::TestAlarm* GetRetransmissionAlarm() {
779 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
780 QuicConnectionPeer::GetRetransmissionAlarm(this));
781 }
782
783 TestAlarmFactory::TestAlarm* GetSendAlarm() {
784 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
785 QuicConnectionPeer::GetSendAlarm(this));
786 }
787
788 TestAlarmFactory::TestAlarm* GetTimeoutAlarm() {
789 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
790 QuicConnectionPeer::GetTimeoutAlarm(this));
791 }
792
793 TestAlarmFactory::TestAlarm* GetMtuDiscoveryAlarm() {
794 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
795 QuicConnectionPeer::GetMtuDiscoveryAlarm(this));
796 }
797
798 TestAlarmFactory::TestAlarm* GetPathDegradingAlarm() {
799 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
800 QuicConnectionPeer::GetPathDegradingAlarm(this));
801 }
802
803 TestAlarmFactory::TestAlarm* GetProcessUndecryptablePacketsAlarm() {
804 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
805 QuicConnectionPeer::GetProcessUndecryptablePacketsAlarm(this));
806 }
807
808 void SetMaxTailLossProbes(size_t max_tail_loss_probes) {
809 QuicSentPacketManagerPeer::SetMaxTailLossProbes(
810 QuicConnectionPeer::GetSentPacketManager(this), max_tail_loss_probes);
811 }
812
813 QuicByteCount GetBytesInFlight() {
ianswett9f459cb2019-04-21 06:39:59 -0700814 return QuicConnectionPeer::GetSentPacketManager(this)->GetBytesInFlight();
QUICHE teama6ef0a62019-03-07 20:34:33 -0500815 }
816
817 void set_notifier(SimpleSessionNotifier* notifier) { notifier_ = notifier; }
818
819 void ReturnEffectivePeerAddressForNextPacket(const QuicSocketAddress& addr) {
820 next_effective_peer_addr_ = QuicMakeUnique<QuicSocketAddress>(addr);
821 }
822
nharper46833c32019-05-15 21:33:05 -0700823 SimpleDataProducer* producer() { return &producer_; }
824
QUICHE teama6ef0a62019-03-07 20:34:33 -0500825 using QuicConnection::active_effective_peer_migration_type;
826 using QuicConnection::IsCurrentPacketConnectivityProbing;
827 using QuicConnection::SelectMutualVersion;
828 using QuicConnection::SendProbingRetransmissions;
829 using QuicConnection::set_defer_send_in_response_to_packets;
830
831 protected:
832 QuicSocketAddress GetEffectivePeerAddressFromCurrentPacket() const override {
833 if (next_effective_peer_addr_) {
834 return *std::move(next_effective_peer_addr_);
835 }
836 return QuicConnection::GetEffectivePeerAddressFromCurrentPacket();
837 }
838
839 private:
840 TestPacketWriter* writer() {
841 return static_cast<TestPacketWriter*>(QuicConnection::writer());
842 }
843
844 SimpleDataProducer producer_;
845
846 SimpleSessionNotifier* notifier_;
847
848 std::unique_ptr<QuicSocketAddress> next_effective_peer_addr_;
849};
850
851enum class AckResponse { kDefer, kImmediate };
852
853// Run tests with combinations of {ParsedQuicVersion, AckResponse}.
854struct TestParams {
855 TestParams(ParsedQuicVersion version,
856 AckResponse ack_response,
857 bool no_stop_waiting)
858 : version(version),
859 ack_response(ack_response),
860 no_stop_waiting(no_stop_waiting) {}
861
862 friend std::ostream& operator<<(std::ostream& os, const TestParams& p) {
863 os << "{ client_version: " << ParsedQuicVersionToString(p.version)
864 << " ack_response: "
865 << (p.ack_response == AckResponse::kDefer ? "defer" : "immediate")
866 << " no_stop_waiting: " << p.no_stop_waiting << " }";
867 return os;
868 }
869
870 ParsedQuicVersion version;
871 AckResponse ack_response;
872 bool no_stop_waiting;
873};
874
875// Constructs various test permutations.
876std::vector<TestParams> GetTestParams() {
877 QuicFlagSaver flags;
wub49855982019-05-01 14:16:26 -0700878 SetQuicFlag(FLAGS_quic_supports_tls_handshake, true);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500879 std::vector<TestParams> params;
880 ParsedQuicVersionVector all_supported_versions = AllSupportedVersions();
881 for (size_t i = 0; i < all_supported_versions.size(); ++i) {
882 for (AckResponse ack_response :
883 {AckResponse::kDefer, AckResponse::kImmediate}) {
884 for (bool no_stop_waiting : {true, false}) {
885 // After version 43, never use STOP_WAITING.
fayangd4291e42019-05-30 10:31:21 -0700886 params.push_back(
887 TestParams(all_supported_versions[i], ack_response,
888 !VersionHasIetfInvariantHeader(
889 all_supported_versions[i].transport_version)
890 ? no_stop_waiting
891 : true));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500892 }
893 }
894 }
895 return params;
896}
897
898class QuicConnectionTest : public QuicTestWithParam<TestParams> {
899 protected:
900 QuicConnectionTest()
901 : connection_id_(TestConnectionId()),
902 framer_(SupportedVersions(version()),
903 QuicTime::Zero(),
904 Perspective::IS_CLIENT,
905 connection_id_.length()),
906 send_algorithm_(new StrictMock<MockSendAlgorithm>),
907 loss_algorithm_(new MockLossAlgorithm()),
908 helper_(new TestConnectionHelper(&clock_, &random_generator_)),
909 alarm_factory_(new TestAlarmFactory()),
910 peer_framer_(SupportedVersions(version()),
911 QuicTime::Zero(),
912 Perspective::IS_SERVER,
913 connection_id_.length()),
914 peer_creator_(connection_id_,
915 &peer_framer_,
916 /*delegate=*/nullptr),
917 writer_(new TestPacketWriter(version(), &clock_)),
918 connection_(connection_id_,
919 kPeerAddress,
920 helper_.get(),
921 alarm_factory_.get(),
922 writer_.get(),
923 Perspective::IS_CLIENT,
924 version()),
925 creator_(QuicConnectionPeer::GetPacketCreator(&connection_)),
926 generator_(QuicConnectionPeer::GetPacketGenerator(&connection_)),
927 manager_(QuicConnectionPeer::GetSentPacketManager(&connection_)),
nharper46833c32019-05-15 21:33:05 -0700928 frame1_(0, false, 0, QuicStringPiece(data1)),
929 frame2_(0, false, 3, QuicStringPiece(data2)),
930 crypto_frame_(ENCRYPTION_INITIAL, 0, QuicStringPiece(data1)),
QUICHE teama6ef0a62019-03-07 20:34:33 -0500931 packet_number_length_(PACKET_4BYTE_PACKET_NUMBER),
932 connection_id_included_(CONNECTION_ID_PRESENT),
933 notifier_(&connection_) {
wub49855982019-05-01 14:16:26 -0700934 SetQuicFlag(FLAGS_quic_supports_tls_handshake, true);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500935 connection_.set_defer_send_in_response_to_packets(GetParam().ack_response ==
936 AckResponse::kDefer);
nharper2c9f02a2019-05-08 10:25:50 -0700937 for (EncryptionLevel level :
938 {ENCRYPTION_ZERO_RTT, ENCRYPTION_FORWARD_SECURE}) {
939 peer_creator_.SetEncrypter(
940 level, QuicMakeUnique<NullEncrypter>(peer_framer_.perspective()));
941 }
dschinazi6ece5002019-05-22 06:35:49 -0700942 if (version().handshake_protocol == PROTOCOL_TLS1_3) {
943 connection_.SetEncrypter(
944 ENCRYPTION_INITIAL,
945 QuicMakeUnique<NullEncrypter>(Perspective::IS_CLIENT));
946 connection_.InstallDecrypter(
947 ENCRYPTION_INITIAL,
948 QuicMakeUnique<NullDecrypter>(Perspective::IS_CLIENT));
949 }
dschinazi7b9278c2019-05-20 07:36:21 -0700950 QuicFramerPeer::SetLastSerializedServerConnectionId(
QUICHE teama6ef0a62019-03-07 20:34:33 -0500951 QuicConnectionPeer::GetFramer(&connection_), connection_id_);
fayangd4291e42019-05-30 10:31:21 -0700952 if (VersionHasIetfInvariantHeader(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500953 EXPECT_TRUE(QuicConnectionPeer::GetNoStopWaitingFrames(&connection_));
954 } else {
955 QuicConnectionPeer::SetNoStopWaitingFrames(&connection_,
956 GetParam().no_stop_waiting);
957 }
nharper46833c32019-05-15 21:33:05 -0700958 QuicStreamId stream_id;
959 if (QuicVersionUsesCryptoFrames(version().transport_version)) {
960 stream_id = QuicUtils::GetFirstBidirectionalStreamId(
961 version().transport_version, Perspective::IS_CLIENT);
962 } else {
963 stream_id = QuicUtils::GetCryptoStreamId(version().transport_version);
964 }
965 frame1_.stream_id = stream_id;
966 frame2_.stream_id = stream_id;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500967 connection_.set_visitor(&visitor_);
968 if (connection_.session_decides_what_to_write()) {
969 connection_.SetSessionNotifier(&notifier_);
970 connection_.set_notifier(&notifier_);
971 }
972 connection_.SetSendAlgorithm(send_algorithm_);
973 connection_.SetLossAlgorithm(loss_algorithm_.get());
974 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
975 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
976 .Times(AnyNumber());
977 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
978 .WillRepeatedly(Return(kDefaultTCPMSS));
979 EXPECT_CALL(*send_algorithm_, PacingRate(_))
980 .WillRepeatedly(Return(QuicBandwidth::Zero()));
981 EXPECT_CALL(*send_algorithm_, HasReliableBandwidthEstimate())
982 .Times(AnyNumber());
983 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
984 .Times(AnyNumber())
985 .WillRepeatedly(Return(QuicBandwidth::Zero()));
986 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
987 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
988 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
989 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).Times(AnyNumber());
990 EXPECT_CALL(visitor_, HasPendingHandshake()).Times(AnyNumber());
991 if (connection_.session_decides_what_to_write()) {
992 EXPECT_CALL(visitor_, OnCanWrite())
993 .WillRepeatedly(
994 Invoke(&notifier_, &SimpleSessionNotifier::OnCanWrite));
995 } else {
996 EXPECT_CALL(visitor_, OnCanWrite()).Times(AnyNumber());
997 }
998 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
999 .WillRepeatedly(Return(false));
1000 EXPECT_CALL(visitor_, OnCongestionWindowChange(_)).Times(AnyNumber());
1001 EXPECT_CALL(visitor_, OnConnectivityProbeReceived(_, _)).Times(AnyNumber());
1002 EXPECT_CALL(visitor_, OnForwardProgressConfirmed()).Times(AnyNumber());
1003
1004 EXPECT_CALL(*loss_algorithm_, GetLossTimeout())
1005 .WillRepeatedly(Return(QuicTime::Zero()));
1006 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
1007 .Times(AnyNumber());
zhongyi546cc452019-04-12 15:27:49 -07001008
1009 if (connection_.version().KnowsWhichDecrypterToUse()) {
1010 connection_.InstallDecrypter(
1011 ENCRYPTION_FORWARD_SECURE,
1012 QuicMakeUnique<NullDecrypter>(Perspective::IS_CLIENT));
1013 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001014 }
1015
1016 QuicConnectionTest(const QuicConnectionTest&) = delete;
1017 QuicConnectionTest& operator=(const QuicConnectionTest&) = delete;
1018
1019 ParsedQuicVersion version() { return GetParam().version; }
1020
1021 QuicAckFrame* outgoing_ack() {
1022 QuicFrame ack_frame = QuicConnectionPeer::GetUpdatedAckFrame(&connection_);
1023 ack_ = *ack_frame.ack_frame;
1024 return &ack_;
1025 }
1026
1027 QuicStopWaitingFrame* stop_waiting() {
1028 QuicConnectionPeer::PopulateStopWaitingFrame(&connection_, &stop_waiting_);
1029 return &stop_waiting_;
1030 }
1031
1032 QuicPacketNumber least_unacked() {
1033 if (writer_->stop_waiting_frames().empty()) {
1034 return QuicPacketNumber();
1035 }
1036 return writer_->stop_waiting_frames()[0].least_unacked;
1037 }
1038
1039 void use_tagging_decrypter() { writer_->use_tagging_decrypter(); }
1040
zhongyi546cc452019-04-12 15:27:49 -07001041 void SetDecrypter(EncryptionLevel level,
1042 std::unique_ptr<QuicDecrypter> decrypter) {
1043 if (connection_.version().KnowsWhichDecrypterToUse()) {
1044 connection_.InstallDecrypter(level, std::move(decrypter));
1045 connection_.RemoveDecrypter(ENCRYPTION_INITIAL);
1046 } else {
1047 connection_.SetDecrypter(level, std::move(decrypter));
1048 }
1049 }
1050
QUICHE teama6ef0a62019-03-07 20:34:33 -05001051 void ProcessPacket(uint64_t number) {
1052 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
1053 ProcessDataPacket(number);
1054 if (connection_.GetSendAlarm()->IsSet()) {
1055 connection_.GetSendAlarm()->Fire();
1056 }
1057 }
1058
1059 void ProcessReceivedPacket(const QuicSocketAddress& self_address,
1060 const QuicSocketAddress& peer_address,
1061 const QuicReceivedPacket& packet) {
1062 connection_.ProcessUdpPacket(self_address, peer_address, packet);
1063 if (connection_.GetSendAlarm()->IsSet()) {
1064 connection_.GetSendAlarm()->Fire();
1065 }
1066 }
1067
1068 void ProcessFramePacket(QuicFrame frame) {
1069 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
1070 }
1071
1072 void ProcessFramePacketWithAddresses(QuicFrame frame,
1073 QuicSocketAddress self_address,
1074 QuicSocketAddress peer_address) {
1075 QuicFrames frames;
1076 frames.push_back(QuicFrame(frame));
1077 QuicPacketCreatorPeer::SetSendVersionInPacket(
1078 &peer_creator_, connection_.perspective() == Perspective::IS_SERVER);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001079
dschinazi66dea072019-04-09 11:41:06 -07001080 char buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05001081 SerializedPacket serialized_packet =
dschinazi66dea072019-04-09 11:41:06 -07001082 QuicPacketCreatorPeer::SerializeAllFrames(
1083 &peer_creator_, frames, buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001084 connection_.ProcessUdpPacket(
1085 self_address, peer_address,
1086 QuicReceivedPacket(serialized_packet.encrypted_buffer,
1087 serialized_packet.encrypted_length, clock_.Now()));
1088 if (connection_.GetSendAlarm()->IsSet()) {
1089 connection_.GetSendAlarm()->Fire();
1090 }
1091 }
1092
1093 // Bypassing the packet creator is unrealistic, but allows us to process
1094 // packets the QuicPacketCreator won't allow us to create.
1095 void ForceProcessFramePacket(QuicFrame frame) {
1096 QuicFrames frames;
1097 frames.push_back(QuicFrame(frame));
zhongyi546cc452019-04-12 15:27:49 -07001098 bool send_version = connection_.perspective() == Perspective::IS_SERVER;
1099 if (connection_.version().KnowsWhichDecrypterToUse()) {
1100 send_version = true;
1101 }
1102 QuicPacketCreatorPeer::SetSendVersionInPacket(&peer_creator_, send_version);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001103 QuicPacketHeader header;
1104 QuicPacketCreatorPeer::FillPacketHeader(&peer_creator_, &header);
dschinazi66dea072019-04-09 11:41:06 -07001105 char encrypted_buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05001106 size_t length = peer_framer_.BuildDataPacket(
dschinazi66dea072019-04-09 11:41:06 -07001107 header, frames, encrypted_buffer, kMaxOutgoingPacketSize,
1108 ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001109 DCHECK_GT(length, 0u);
1110
1111 const size_t encrypted_length = peer_framer_.EncryptInPlace(
QUICHE team6987b4a2019-03-15 16:23:04 -07001112 ENCRYPTION_INITIAL, header.packet_number,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001113 GetStartOfEncryptedData(peer_framer_.version().transport_version,
1114 header),
dschinazi66dea072019-04-09 11:41:06 -07001115 length, kMaxOutgoingPacketSize, encrypted_buffer);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001116 DCHECK_GT(encrypted_length, 0u);
1117
1118 connection_.ProcessUdpPacket(
1119 kSelfAddress, kPeerAddress,
1120 QuicReceivedPacket(encrypted_buffer, encrypted_length, clock_.Now()));
1121 }
1122
1123 size_t ProcessFramePacketAtLevel(uint64_t number,
1124 QuicFrame frame,
1125 EncryptionLevel level) {
1126 QuicPacketHeader header;
1127 header.destination_connection_id = connection_id_;
1128 header.packet_number_length = packet_number_length_;
1129 header.destination_connection_id_included = connection_id_included_;
fayangd4291e42019-05-30 10:31:21 -07001130 if ((VersionHasIetfInvariantHeader(peer_framer_.transport_version()) ||
QUICHE team2252b702019-05-14 23:55:14 -04001131 GetQuicRestartFlag(quic_do_not_override_connection_id)) &&
QUICHE teama6ef0a62019-03-07 20:34:33 -05001132 peer_framer_.perspective() == Perspective::IS_SERVER) {
1133 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1134 }
zhongyi546cc452019-04-12 15:27:49 -07001135 if (level == ENCRYPTION_INITIAL &&
1136 peer_framer_.version().KnowsWhichDecrypterToUse()) {
1137 header.version_flag = true;
1138 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
1139 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
QUICHE team2252b702019-05-14 23:55:14 -04001140 }
1141 if ((GetQuicRestartFlag(quic_do_not_override_connection_id) ||
1142 (level == ENCRYPTION_INITIAL &&
1143 peer_framer_.version().KnowsWhichDecrypterToUse())) &&
1144 header.version_flag &&
1145 peer_framer_.perspective() == Perspective::IS_SERVER) {
1146 header.source_connection_id = connection_id_;
1147 header.source_connection_id_included = CONNECTION_ID_PRESENT;
zhongyi546cc452019-04-12 15:27:49 -07001148 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001149 header.packet_number = QuicPacketNumber(number);
1150 QuicFrames frames;
1151 frames.push_back(frame);
1152 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
QUICHE teamcd098022019-03-22 18:49:55 -07001153 // Set the correct encryption level and encrypter on peer_creator and
1154 // peer_framer, respectively.
1155 peer_creator_.set_encryption_level(level);
1156 if (QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_) >
1157 ENCRYPTION_INITIAL) {
1158 peer_framer_.SetEncrypter(
1159 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
1160 QuicMakeUnique<TaggingEncrypter>(0x01));
1161 // Set the corresponding decrypter.
zhongyi546cc452019-04-12 15:27:49 -07001162 if (connection_.version().KnowsWhichDecrypterToUse()) {
1163 connection_.InstallDecrypter(
1164 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
1165 QuicMakeUnique<StrictTaggingDecrypter>(0x01));
1166 connection_.RemoveDecrypter(ENCRYPTION_INITIAL);
1167 } else {
1168 connection_.SetDecrypter(
1169 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
1170 QuicMakeUnique<StrictTaggingDecrypter>(0x01));
1171 }
QUICHE teamcd098022019-03-22 18:49:55 -07001172 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001173
dschinazi66dea072019-04-09 11:41:06 -07001174 char buffer[kMaxOutgoingPacketSize];
1175 size_t encrypted_length =
1176 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
1177 buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001178 connection_.ProcessUdpPacket(
1179 kSelfAddress, kPeerAddress,
QUICHE teamcd098022019-03-22 18:49:55 -07001180 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1181 if (connection_.GetSendAlarm()->IsSet()) {
1182 connection_.GetSendAlarm()->Fire();
1183 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001184 return encrypted_length;
1185 }
1186
1187 size_t ProcessDataPacket(uint64_t number) {
nharper2c9f02a2019-05-08 10:25:50 -07001188 return ProcessDataPacketAtLevel(number, false, ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001189 }
1190
1191 size_t ProcessDataPacket(QuicPacketNumber packet_number) {
nharper2c9f02a2019-05-08 10:25:50 -07001192 return ProcessDataPacketAtLevel(packet_number, false,
1193 ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001194 }
1195
1196 size_t ProcessDataPacketAtLevel(QuicPacketNumber packet_number,
1197 bool has_stop_waiting,
1198 EncryptionLevel level) {
1199 return ProcessDataPacketAtLevel(packet_number.ToUint64(), has_stop_waiting,
1200 level);
1201 }
1202
nharper46833c32019-05-15 21:33:05 -07001203 size_t ProcessCryptoPacketAtLevel(uint64_t number, EncryptionLevel level) {
1204 QuicPacketHeader header = ConstructPacketHeader(1000, ENCRYPTION_INITIAL);
1205 QuicFrames frames;
1206 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1207 frames.push_back(QuicFrame(&crypto_frame_));
1208 } else {
1209 frames.push_back(QuicFrame(frame1_));
1210 }
1211 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
1212 char buffer[kMaxOutgoingPacketSize];
1213 peer_creator_.set_encryption_level(ENCRYPTION_INITIAL);
1214 size_t encrypted_length =
1215 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(1000),
1216 *packet, buffer, kMaxOutgoingPacketSize);
1217 connection_.ProcessUdpPacket(
1218 kSelfAddress, kPeerAddress,
1219 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1220 if (connection_.GetSendAlarm()->IsSet()) {
1221 connection_.GetSendAlarm()->Fire();
1222 }
1223 return encrypted_length;
1224 }
1225
QUICHE teama6ef0a62019-03-07 20:34:33 -05001226 size_t ProcessDataPacketAtLevel(uint64_t number,
1227 bool has_stop_waiting,
1228 EncryptionLevel level) {
1229 std::unique_ptr<QuicPacket> packet(
QUICHE team8c1daa22019-03-13 08:33:41 -07001230 ConstructDataPacket(number, has_stop_waiting, level));
dschinazi66dea072019-04-09 11:41:06 -07001231 char buffer[kMaxOutgoingPacketSize];
QUICHE teamcd098022019-03-22 18:49:55 -07001232 peer_creator_.set_encryption_level(level);
dschinazi66dea072019-04-09 11:41:06 -07001233 size_t encrypted_length =
1234 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
1235 buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001236 connection_.ProcessUdpPacket(
1237 kSelfAddress, kPeerAddress,
1238 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1239 if (connection_.GetSendAlarm()->IsSet()) {
1240 connection_.GetSendAlarm()->Fire();
1241 }
1242 return encrypted_length;
1243 }
1244
1245 void ProcessClosePacket(uint64_t number) {
1246 std::unique_ptr<QuicPacket> packet(ConstructClosePacket(number));
dschinazi66dea072019-04-09 11:41:06 -07001247 char buffer[kMaxOutgoingPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07001248 size_t encrypted_length = peer_framer_.EncryptPayload(
1249 ENCRYPTION_INITIAL, QuicPacketNumber(number), *packet, buffer,
dschinazi66dea072019-04-09 11:41:06 -07001250 kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001251 connection_.ProcessUdpPacket(
1252 kSelfAddress, kPeerAddress,
1253 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
1254 }
1255
1256 QuicByteCount SendStreamDataToPeer(QuicStreamId id,
1257 QuicStringPiece data,
1258 QuicStreamOffset offset,
1259 StreamSendingState state,
1260 QuicPacketNumber* last_packet) {
1261 QuicByteCount packet_size;
1262 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1263 .WillOnce(SaveArg<3>(&packet_size));
1264 connection_.SendStreamDataWithString(id, data, offset, state);
1265 if (last_packet != nullptr) {
1266 *last_packet = creator_->packet_number();
1267 }
1268 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1269 .Times(AnyNumber());
1270 return packet_size;
1271 }
1272
1273 void SendAckPacketToPeer() {
1274 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1275 {
1276 QuicConnection::ScopedPacketFlusher flusher(&connection_,
1277 QuicConnection::NO_ACK);
1278 connection_.SendAck();
1279 }
1280 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1281 .Times(AnyNumber());
1282 }
1283
1284 void SendRstStream(QuicStreamId id,
1285 QuicRstStreamErrorCode error,
1286 QuicStreamOffset bytes_written) {
1287 if (connection_.session_decides_what_to_write()) {
1288 notifier_.WriteOrBufferRstStream(id, error, bytes_written);
1289 connection_.OnStreamReset(id, error);
1290 return;
1291 }
1292 std::unique_ptr<QuicRstStreamFrame> rst_stream =
1293 QuicMakeUnique<QuicRstStreamFrame>(1, id, error, bytes_written);
1294 if (connection_.SendControlFrame(QuicFrame(rst_stream.get()))) {
1295 rst_stream.release();
1296 }
1297 connection_.OnStreamReset(id, error);
1298 }
1299
zhongyifbb25772019-04-10 16:54:08 -07001300 void SendPing() {
1301 if (connection_.session_decides_what_to_write()) {
1302 notifier_.WriteOrBufferPing();
1303 } else {
1304 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
1305 }
1306 }
1307
QUICHE teama6ef0a62019-03-07 20:34:33 -05001308 void ProcessAckPacket(uint64_t packet_number, QuicAckFrame* frame) {
1309 if (packet_number > 1) {
1310 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, packet_number - 1);
1311 } else {
1312 QuicPacketCreatorPeer::ClearPacketNumber(&peer_creator_);
1313 }
1314 ProcessFramePacket(QuicFrame(frame));
1315 }
1316
1317 void ProcessAckPacket(QuicAckFrame* frame) {
1318 ProcessFramePacket(QuicFrame(frame));
1319 }
1320
1321 void ProcessStopWaitingPacket(QuicStopWaitingFrame frame) {
1322 ProcessFramePacket(QuicFrame(frame));
1323 }
1324
1325 size_t ProcessStopWaitingPacketAtLevel(uint64_t number,
1326 QuicStopWaitingFrame frame,
1327 EncryptionLevel level) {
1328 return ProcessFramePacketAtLevel(number, QuicFrame(frame),
1329 ENCRYPTION_ZERO_RTT);
1330 }
1331
1332 void ProcessGoAwayPacket(QuicGoAwayFrame* frame) {
1333 ProcessFramePacket(QuicFrame(frame));
1334 }
1335
1336 bool IsMissing(uint64_t number) {
1337 return IsAwaitingPacket(*outgoing_ack(), QuicPacketNumber(number),
1338 QuicPacketNumber());
1339 }
1340
1341 std::unique_ptr<QuicPacket> ConstructPacket(const QuicPacketHeader& header,
1342 const QuicFrames& frames) {
1343 auto packet = BuildUnsizedDataPacket(&peer_framer_, header, frames);
1344 EXPECT_NE(nullptr, packet.get());
1345 return packet;
1346 }
1347
nharper46833c32019-05-15 21:33:05 -07001348 QuicPacketHeader ConstructPacketHeader(uint64_t number,
1349 EncryptionLevel level) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001350 QuicPacketHeader header;
fayangd4291e42019-05-30 10:31:21 -07001351 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version()) &&
QUICHE team8c1daa22019-03-13 08:33:41 -07001352 level < ENCRYPTION_FORWARD_SECURE) {
1353 // Set long header type accordingly.
1354 header.version_flag = true;
1355 header.long_packet_type = EncryptionlevelToLongHeaderType(level);
1356 if (QuicVersionHasLongHeaderLengths(
1357 peer_framer_.version().transport_version)) {
1358 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
1359 if (header.long_packet_type == INITIAL) {
1360 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
1361 }
1362 }
1363 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001364 // Set connection_id to peer's in memory representation as this data packet
1365 // is created by peer_framer.
QUICHE team2252b702019-05-14 23:55:14 -04001366 if (GetQuicRestartFlag(quic_do_not_override_connection_id) &&
1367 peer_framer_.perspective() == Perspective::IS_SERVER) {
1368 header.source_connection_id = connection_id_;
1369 header.source_connection_id_included = connection_id_included_;
1370 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1371 } else {
1372 header.destination_connection_id = connection_id_;
1373 header.destination_connection_id_included = connection_id_included_;
1374 }
fayangd4291e42019-05-30 10:31:21 -07001375 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version()) &&
QUICHE teama6ef0a62019-03-07 20:34:33 -05001376 peer_framer_.perspective() == Perspective::IS_SERVER) {
1377 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
QUICHE team8c1daa22019-03-13 08:33:41 -07001378 if (header.version_flag) {
1379 header.source_connection_id = connection_id_;
1380 header.source_connection_id_included = CONNECTION_ID_PRESENT;
1381 if (GetParam().version.handshake_protocol == PROTOCOL_QUIC_CRYPTO &&
1382 header.long_packet_type == ZERO_RTT_PROTECTED) {
QUICHE team548d51b2019-03-14 10:06:54 -07001383 header.nonce = &kTestDiversificationNonce;
QUICHE team8c1daa22019-03-13 08:33:41 -07001384 }
1385 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001386 }
QUICHE team2252b702019-05-14 23:55:14 -04001387 header.packet_number_length = packet_number_length_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001388 header.packet_number = QuicPacketNumber(number);
nharper46833c32019-05-15 21:33:05 -07001389 return header;
1390 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001391
nharper46833c32019-05-15 21:33:05 -07001392 std::unique_ptr<QuicPacket> ConstructDataPacket(uint64_t number,
1393 bool has_stop_waiting,
1394 EncryptionLevel level) {
1395 QuicPacketHeader header = ConstructPacketHeader(number, level);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001396 QuicFrames frames;
1397 frames.push_back(QuicFrame(frame1_));
1398 if (has_stop_waiting) {
1399 frames.push_back(QuicFrame(stop_waiting_));
1400 }
1401 return ConstructPacket(header, frames);
1402 }
1403
1404 OwningSerializedPacketPointer ConstructProbingPacket() {
1405 if (version().transport_version == QUIC_VERSION_99) {
1406 QuicPathFrameBuffer payload = {
1407 {0xde, 0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xfe}};
1408 return QuicPacketCreatorPeer::
1409 SerializePathChallengeConnectivityProbingPacket(&peer_creator_,
1410 &payload);
1411 }
1412 return QuicPacketCreatorPeer::SerializeConnectivityProbingPacket(
1413 &peer_creator_);
1414 }
1415
1416 std::unique_ptr<QuicPacket> ConstructClosePacket(uint64_t number) {
1417 QuicPacketHeader header;
1418 // Set connection_id to peer's in memory representation as this connection
1419 // close packet is created by peer_framer.
QUICHE team2252b702019-05-14 23:55:14 -04001420 if (GetQuicRestartFlag(quic_do_not_override_connection_id) &&
QUICHE teama6ef0a62019-03-07 20:34:33 -05001421 peer_framer_.perspective() == Perspective::IS_SERVER) {
QUICHE team2252b702019-05-14 23:55:14 -04001422 header.source_connection_id = connection_id_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001423 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
fayangd4291e42019-05-30 10:31:21 -07001424 if (!VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04001425 header.source_connection_id_included = CONNECTION_ID_PRESENT;
1426 }
1427 } else {
1428 header.destination_connection_id = connection_id_;
fayangd4291e42019-05-30 10:31:21 -07001429 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04001430 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1431 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001432 }
1433
QUICHE team2252b702019-05-14 23:55:14 -04001434 header.packet_number = QuicPacketNumber(number);
1435
fkastenholze9d71a82019-04-09 05:12:13 -07001436 QuicConnectionCloseFrame qccf(QUIC_PEER_GOING_AWAY);
fkastenholz72f509b2019-04-10 09:17:49 -07001437 if (peer_framer_.transport_version() == QUIC_VERSION_99) {
fkastenholz04bd4f32019-04-16 12:24:38 -07001438 // Default close-type is Google QUIC. If doing IETF/V99 then
1439 // set close type to be IETF CC/T.
fkastenholz72f509b2019-04-10 09:17:49 -07001440 qccf.close_type = IETF_QUIC_TRANSPORT_CONNECTION_CLOSE;
1441 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001442
1443 QuicFrames frames;
1444 frames.push_back(QuicFrame(&qccf));
1445 return ConstructPacket(header, frames);
1446 }
1447
1448 QuicTime::Delta DefaultRetransmissionTime() {
1449 return QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
1450 }
1451
1452 QuicTime::Delta DefaultDelayedAckTime() {
1453 return QuicTime::Delta::FromMilliseconds(kDefaultDelayedAckTimeMs);
1454 }
1455
1456 const QuicStopWaitingFrame InitStopWaitingFrame(uint64_t least_unacked) {
1457 QuicStopWaitingFrame frame;
1458 frame.least_unacked = QuicPacketNumber(least_unacked);
1459 return frame;
1460 }
1461
1462 // Construct a ack_frame that acks all packet numbers between 1 and
1463 // |largest_acked|, except |missing|.
1464 // REQUIRES: 1 <= |missing| < |largest_acked|
1465 QuicAckFrame ConstructAckFrame(uint64_t largest_acked, uint64_t missing) {
1466 return ConstructAckFrame(QuicPacketNumber(largest_acked),
1467 QuicPacketNumber(missing));
1468 }
1469
1470 QuicAckFrame ConstructAckFrame(QuicPacketNumber largest_acked,
1471 QuicPacketNumber missing) {
1472 if (missing == QuicPacketNumber(1)) {
1473 return InitAckFrame({{missing + 1, largest_acked + 1}});
1474 }
1475 return InitAckFrame(
1476 {{QuicPacketNumber(1), missing}, {missing + 1, largest_acked + 1}});
1477 }
1478
1479 // Undo nacking a packet within the frame.
1480 void AckPacket(QuicPacketNumber arrived, QuicAckFrame* frame) {
1481 EXPECT_FALSE(frame->packets.Contains(arrived));
1482 frame->packets.Add(arrived);
1483 }
1484
1485 void TriggerConnectionClose() {
1486 // Send an erroneous packet to close the connection.
QUICHE teamcd098022019-03-22 18:49:55 -07001487 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, _,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001488 ConnectionCloseSource::FROM_SELF));
QUICHE teamcd098022019-03-22 18:49:55 -07001489 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1490 // Triggers a connection by receiving ACK of unsent packet.
1491 QuicAckFrame frame = InitAckFrame(10000);
1492 ProcessAckPacket(1, &frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001493
1494 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1495 nullptr);
1496 }
1497
1498 void BlockOnNextWrite() {
1499 writer_->BlockOnNextWrite();
1500 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
1501 }
1502
1503 void SimulateNextPacketTooLarge() { writer_->SimulateNextPacketTooLarge(); }
1504
1505 void AlwaysGetPacketTooLarge() { writer_->AlwaysGetPacketTooLarge(); }
1506
1507 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
1508 writer_->SetWritePauseTimeDelta(delta);
1509 }
1510
1511 void CongestionBlockWrites() {
1512 EXPECT_CALL(*send_algorithm_, CanSend(_))
1513 .WillRepeatedly(testing::Return(false));
1514 }
1515
1516 void CongestionUnblockWrites() {
1517 EXPECT_CALL(*send_algorithm_, CanSend(_))
1518 .WillRepeatedly(testing::Return(true));
1519 }
1520
1521 void set_perspective(Perspective perspective) {
1522 connection_.set_perspective(perspective);
1523 if (perspective == Perspective::IS_SERVER) {
1524 connection_.set_can_truncate_connection_ids(true);
1525 }
1526 QuicFramerPeer::SetPerspective(&peer_framer_,
1527 InvertPerspective(perspective));
1528 }
1529
1530 void set_packets_between_probes_base(
1531 const QuicPacketCount packets_between_probes_base) {
1532 QuicConnectionPeer::SetPacketsBetweenMtuProbes(&connection_,
1533 packets_between_probes_base);
1534 QuicConnectionPeer::SetNextMtuProbeAt(
1535 &connection_, QuicPacketNumber(packets_between_probes_base));
1536 }
1537
1538 bool IsDefaultTestConfiguration() {
1539 TestParams p = GetParam();
1540 return p.ack_response == AckResponse::kImmediate &&
1541 p.version == AllSupportedVersions()[0] && p.no_stop_waiting;
1542 }
1543
1544 QuicConnectionId connection_id_;
1545 QuicFramer framer_;
1546
1547 MockSendAlgorithm* send_algorithm_;
1548 std::unique_ptr<MockLossAlgorithm> loss_algorithm_;
1549 MockClock clock_;
1550 MockRandom random_generator_;
1551 SimpleBufferAllocator buffer_allocator_;
1552 std::unique_ptr<TestConnectionHelper> helper_;
1553 std::unique_ptr<TestAlarmFactory> alarm_factory_;
1554 QuicFramer peer_framer_;
1555 QuicPacketCreator peer_creator_;
1556 std::unique_ptr<TestPacketWriter> writer_;
1557 TestConnection connection_;
1558 QuicPacketCreator* creator_;
1559 QuicPacketGenerator* generator_;
1560 QuicSentPacketManager* manager_;
1561 StrictMock<MockQuicConnectionVisitor> visitor_;
1562
1563 QuicStreamFrame frame1_;
1564 QuicStreamFrame frame2_;
nharper46833c32019-05-15 21:33:05 -07001565 QuicCryptoFrame crypto_frame_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001566 QuicAckFrame ack_;
1567 QuicStopWaitingFrame stop_waiting_;
1568 QuicPacketNumberLength packet_number_length_;
1569 QuicConnectionIdIncluded connection_id_included_;
1570
1571 SimpleSessionNotifier notifier_;
1572};
1573
1574// Run all end to end tests with all supported versions.
1575INSTANTIATE_TEST_SUITE_P(SupportedVersion,
1576 QuicConnectionTest,
1577 ::testing::ValuesIn(GetTestParams()));
1578
1579TEST_P(QuicConnectionTest, SelfAddressChangeAtClient) {
1580 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1581
1582 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
1583 EXPECT_TRUE(connection_.connected());
1584
nharper46833c32019-05-15 21:33:05 -07001585 QuicFrame frame;
1586 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1587 frame = QuicFrame(&crypto_frame_);
1588 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1589 } else {
1590 frame = QuicFrame(QuicStreamFrame(
1591 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
1592 0u, QuicStringPiece()));
1593 EXPECT_CALL(visitor_, OnStreamFrame(_));
1594 }
1595 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001596 // Cause change in self_address.
1597 QuicIpAddress host;
1598 host.FromString("1.1.1.1");
1599 QuicSocketAddress self_address(host, 123);
nharper46833c32019-05-15 21:33:05 -07001600 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1601 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1602 } else {
1603 EXPECT_CALL(visitor_, OnStreamFrame(_));
1604 }
1605 ProcessFramePacketWithAddresses(frame, self_address, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001606 EXPECT_TRUE(connection_.connected());
1607}
1608
1609TEST_P(QuicConnectionTest, SelfAddressChangeAtServer) {
1610 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1611
1612 set_perspective(Perspective::IS_SERVER);
1613 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1614
1615 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1616 EXPECT_TRUE(connection_.connected());
1617
nharper46833c32019-05-15 21:33:05 -07001618 QuicFrame frame;
1619 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1620 frame = QuicFrame(&crypto_frame_);
1621 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1622 } else {
1623 frame = QuicFrame(QuicStreamFrame(
1624 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
1625 0u, QuicStringPiece()));
1626 EXPECT_CALL(visitor_, OnStreamFrame(_));
1627 }
1628 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001629 // Cause change in self_address.
1630 QuicIpAddress host;
1631 host.FromString("1.1.1.1");
1632 QuicSocketAddress self_address(host, 123);
1633 EXPECT_CALL(visitor_, AllowSelfAddressChange()).WillOnce(Return(false));
1634 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_ERROR_MIGRATING_ADDRESS, _, _));
nharper46833c32019-05-15 21:33:05 -07001635 ProcessFramePacketWithAddresses(frame, self_address, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001636 EXPECT_FALSE(connection_.connected());
1637}
1638
1639TEST_P(QuicConnectionTest, AllowSelfAddressChangeToMappedIpv4AddressAtServer) {
1640 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1641
1642 set_perspective(Perspective::IS_SERVER);
1643 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1644
1645 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1646 EXPECT_TRUE(connection_.connected());
1647
nharper46833c32019-05-15 21:33:05 -07001648 QuicFrame frame;
1649 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1650 frame = QuicFrame(&crypto_frame_);
1651 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(3);
1652 } else {
1653 frame = QuicFrame(QuicStreamFrame(
1654 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
1655 0u, QuicStringPiece()));
1656 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(3);
1657 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001658 QuicIpAddress host;
1659 host.FromString("1.1.1.1");
1660 QuicSocketAddress self_address1(host, 443);
nharper46833c32019-05-15 21:33:05 -07001661 ProcessFramePacketWithAddresses(frame, self_address1, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001662 // Cause self_address change to mapped Ipv4 address.
1663 QuicIpAddress host2;
1664 host2.FromString(
1665 QuicStrCat("::ffff:", connection_.self_address().host().ToString()));
1666 QuicSocketAddress self_address2(host2, connection_.self_address().port());
nharper46833c32019-05-15 21:33:05 -07001667 ProcessFramePacketWithAddresses(frame, self_address2, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001668 EXPECT_TRUE(connection_.connected());
1669 // self_address change back to Ipv4 address.
nharper46833c32019-05-15 21:33:05 -07001670 ProcessFramePacketWithAddresses(frame, self_address1, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001671 EXPECT_TRUE(connection_.connected());
1672}
1673
1674TEST_P(QuicConnectionTest, ClientAddressChangeAndPacketReordered) {
1675 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1676 set_perspective(Perspective::IS_SERVER);
1677 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1678
1679 // Clear direct_peer_address.
1680 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1681 // Clear effective_peer_address, it is the same as direct_peer_address for
1682 // this test.
1683 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1684 QuicSocketAddress());
1685
nharper46833c32019-05-15 21:33:05 -07001686 QuicFrame frame;
1687 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1688 frame = QuicFrame(&crypto_frame_);
1689 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1690 } else {
1691 frame = QuicFrame(QuicStreamFrame(
1692 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
1693 0u, QuicStringPiece()));
1694 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1695 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001696 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001697 const QuicSocketAddress kNewPeerAddress =
1698 QuicSocketAddress(QuicIpAddress::Loopback6(),
1699 /*port=*/23456);
nharper46833c32019-05-15 21:33:05 -07001700 ProcessFramePacketWithAddresses(frame, kSelfAddress, kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001701 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1702 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1703
1704 // Decrease packet number to simulate out-of-order packets.
1705 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 4);
1706 // This is an old packet, do not migrate.
1707 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
nharper46833c32019-05-15 21:33:05 -07001708 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001709 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1710 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1711}
1712
1713TEST_P(QuicConnectionTest, PeerAddressChangeAtServer) {
1714 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1715 set_perspective(Perspective::IS_SERVER);
1716 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1717 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1718
1719 // Clear direct_peer_address.
1720 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1721 // Clear effective_peer_address, it is the same as direct_peer_address for
1722 // this test.
1723 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1724 QuicSocketAddress());
1725 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1726
nharper46833c32019-05-15 21:33:05 -07001727 QuicFrame frame;
1728 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1729 frame = QuicFrame(&crypto_frame_);
1730 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1731 } else {
1732 frame = QuicFrame(QuicStreamFrame(
1733 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
1734 0u, QuicStringPiece()));
1735 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1736 }
1737 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001738 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1739 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1740
1741 // Process another packet with a different peer address on server side will
1742 // start connection migration.
1743 const QuicSocketAddress kNewPeerAddress =
1744 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
1745 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
nharper46833c32019-05-15 21:33:05 -07001746 ProcessFramePacketWithAddresses(frame, kSelfAddress, kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001747 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1748 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1749}
1750
1751TEST_P(QuicConnectionTest, EffectivePeerAddressChangeAtServer) {
1752 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1753 set_perspective(Perspective::IS_SERVER);
1754 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1755 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1756
1757 // Clear direct_peer_address.
1758 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1759 // Clear effective_peer_address, it is different from direct_peer_address for
1760 // this test.
1761 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1762 QuicSocketAddress());
1763 const QuicSocketAddress kEffectivePeerAddress =
1764 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/43210);
1765 connection_.ReturnEffectivePeerAddressForNextPacket(kEffectivePeerAddress);
1766
nharper46833c32019-05-15 21:33:05 -07001767 QuicFrame frame;
1768 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1769 frame = QuicFrame(&crypto_frame_);
1770 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1771 } else {
1772 frame = QuicFrame(QuicStreamFrame(
1773 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
1774 0u, QuicStringPiece()));
1775 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1776 }
1777 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001778 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1779 EXPECT_EQ(kEffectivePeerAddress, connection_.effective_peer_address());
1780
1781 // Process another packet with the same direct peer address and different
1782 // effective peer address on server side will start connection migration.
1783 const QuicSocketAddress kNewEffectivePeerAddress =
1784 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/54321);
1785 connection_.ReturnEffectivePeerAddressForNextPacket(kNewEffectivePeerAddress);
1786 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
nharper46833c32019-05-15 21:33:05 -07001787 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001788 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1789 EXPECT_EQ(kNewEffectivePeerAddress, connection_.effective_peer_address());
1790
1791 // Process another packet with a different direct peer address and the same
1792 // effective peer address on server side will not start connection migration.
1793 const QuicSocketAddress kNewPeerAddress =
1794 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
1795 connection_.ReturnEffectivePeerAddressForNextPacket(kNewEffectivePeerAddress);
1796 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
1797 // ack_frame is used to complete the migration started by the last packet, we
1798 // need to make sure a new migration does not start after the previous one is
1799 // completed.
1800 QuicAckFrame ack_frame = InitAckFrame(1);
1801 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
1802 ProcessFramePacketWithAddresses(QuicFrame(&ack_frame), kSelfAddress,
1803 kNewPeerAddress);
1804 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1805 EXPECT_EQ(kNewEffectivePeerAddress, connection_.effective_peer_address());
1806
1807 // Process another packet with different direct peer address and different
1808 // effective peer address on server side will start connection migration.
1809 const QuicSocketAddress kNewerEffectivePeerAddress =
1810 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/65432);
1811 const QuicSocketAddress kFinalPeerAddress =
1812 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/34567);
1813 connection_.ReturnEffectivePeerAddressForNextPacket(
1814 kNewerEffectivePeerAddress);
1815 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
nharper46833c32019-05-15 21:33:05 -07001816 ProcessFramePacketWithAddresses(frame, kSelfAddress, kFinalPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001817 EXPECT_EQ(kFinalPeerAddress, connection_.peer_address());
1818 EXPECT_EQ(kNewerEffectivePeerAddress, connection_.effective_peer_address());
1819 EXPECT_EQ(PORT_CHANGE, connection_.active_effective_peer_migration_type());
1820
1821 // While the previous migration is ongoing, process another packet with the
1822 // same direct peer address and different effective peer address on server
1823 // side will start a new connection migration.
1824 const QuicSocketAddress kNewestEffectivePeerAddress =
1825 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/65430);
1826 connection_.ReturnEffectivePeerAddressForNextPacket(
1827 kNewestEffectivePeerAddress);
1828 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
1829 EXPECT_CALL(*send_algorithm_, OnConnectionMigration()).Times(1);
nharper46833c32019-05-15 21:33:05 -07001830 ProcessFramePacketWithAddresses(frame, kSelfAddress, kFinalPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001831 EXPECT_EQ(kFinalPeerAddress, connection_.peer_address());
1832 EXPECT_EQ(kNewestEffectivePeerAddress, connection_.effective_peer_address());
1833 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
1834 connection_.active_effective_peer_migration_type());
1835}
1836
1837TEST_P(QuicConnectionTest, ReceivePaddedPingAtServer) {
1838 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1839 set_perspective(Perspective::IS_SERVER);
1840 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1841 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1842
1843 // Clear direct_peer_address.
1844 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1845 // Clear effective_peer_address, it is the same as direct_peer_address for
1846 // this test.
1847 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1848 QuicSocketAddress());
1849 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1850
nharper46833c32019-05-15 21:33:05 -07001851 QuicFrame frame;
1852 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1853 frame = QuicFrame(&crypto_frame_);
1854 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1855 } else {
1856 frame = QuicFrame(QuicStreamFrame(
1857 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
1858 0u, QuicStringPiece()));
1859 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1860 }
1861 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001862 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1863 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1864
1865 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
1866 EXPECT_CALL(visitor_, OnConnectivityProbeReceived(_, _)).Times(0);
1867
1868 // Process a padded PING or PATH CHALLENGE packet with no peer address change
1869 // on server side will be ignored.
1870 OwningSerializedPacketPointer probing_packet;
1871 if (version().transport_version == QUIC_VERSION_99) {
1872 QuicPathFrameBuffer payload = {
1873 {0xde, 0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xfe}};
1874 probing_packet =
1875 QuicPacketCreatorPeer::SerializePathChallengeConnectivityProbingPacket(
1876 &peer_creator_, &payload);
1877 } else {
1878 probing_packet = QuicPacketCreatorPeer::SerializeConnectivityProbingPacket(
1879 &peer_creator_);
1880 }
1881 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
1882 QuicEncryptedPacket(probing_packet->encrypted_buffer,
1883 probing_packet->encrypted_length),
1884 clock_.Now()));
1885
1886 uint64_t num_probing_received =
1887 connection_.GetStats().num_connectivity_probing_received;
1888 ProcessReceivedPacket(kSelfAddress, kPeerAddress, *received);
1889
1890 EXPECT_EQ(num_probing_received,
1891 connection_.GetStats().num_connectivity_probing_received);
1892 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1893 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1894}
1895
1896TEST_P(QuicConnectionTest, WriteOutOfOrderQueuedPackets) {
1897 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
QUICHE teamcd098022019-03-22 18:49:55 -07001898 if (!IsDefaultTestConfiguration() ||
1899 connection_.SupportsMultiplePacketNumberSpaces()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001900 return;
1901 }
1902
1903 set_perspective(Perspective::IS_CLIENT);
1904
1905 BlockOnNextWrite();
1906
1907 QuicStreamId stream_id = 2;
1908 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
1909
1910 EXPECT_EQ(1u, connection_.NumQueuedPackets());
1911
1912 writer_->SetWritable();
1913 connection_.SendConnectivityProbingPacket(writer_.get(),
1914 connection_.peer_address());
1915
1916 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INTERNAL_ERROR,
1917 "Packet written out of order.",
1918 ConnectionCloseSource::FROM_SELF));
1919 EXPECT_QUIC_BUG(connection_.OnCanWrite(),
1920 "Attempt to write packet:1 after:2");
1921 EXPECT_FALSE(connection_.connected());
1922}
1923
1924TEST_P(QuicConnectionTest, DiscardQueuedPacketsAfterConnectionClose) {
1925 // Regression test for b/74073386.
1926 {
1927 InSequence seq;
1928 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1929 EXPECT_CALL(visitor_, OnConnectionClosed(_, _, _)).Times(1);
1930 }
1931
1932 set_perspective(Perspective::IS_CLIENT);
1933
1934 writer_->SimulateNextPacketTooLarge();
1935
1936 // This packet write should fail, which should cause the connection to close
1937 // after sending a connection close packet, then the failed packet should be
1938 // queued.
1939 connection_.SendStreamDataWithString(/*id=*/2, "foo", 0, NO_FIN);
1940
1941 EXPECT_FALSE(connection_.connected());
1942 EXPECT_EQ(1u, connection_.NumQueuedPackets());
1943
1944 EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
1945 connection_.OnCanWrite();
1946 EXPECT_EQ(1u, connection_.GetStats().packets_discarded);
1947}
1948
1949TEST_P(QuicConnectionTest, ReceiveConnectivityProbingAtServer) {
1950 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1951 set_perspective(Perspective::IS_SERVER);
1952 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1953 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1954
1955 // Clear direct_peer_address.
1956 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1957 // Clear effective_peer_address, it is the same as direct_peer_address for
1958 // this test.
1959 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1960 QuicSocketAddress());
1961 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1962
nharper46833c32019-05-15 21:33:05 -07001963 QuicFrame frame;
1964 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1965 frame = QuicFrame(&crypto_frame_);
1966 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1967 } else {
1968 frame = QuicFrame(QuicStreamFrame(
1969 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
1970 0u, QuicStringPiece()));
1971 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1972 }
1973 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001974 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1975 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1976
1977 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
1978 EXPECT_CALL(visitor_, OnConnectivityProbeReceived(_, _)).Times(1);
1979
1980 // Process a padded PING packet from a new peer address on server side
1981 // is effectively receiving a connectivity probing.
1982 const QuicSocketAddress kNewPeerAddress =
1983 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
1984
1985 OwningSerializedPacketPointer probing_packet = ConstructProbingPacket();
1986 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
1987 QuicEncryptedPacket(probing_packet->encrypted_buffer,
1988 probing_packet->encrypted_length),
1989 clock_.Now()));
1990
1991 uint64_t num_probing_received =
1992 connection_.GetStats().num_connectivity_probing_received;
1993 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
1994
1995 EXPECT_EQ(num_probing_received + 1,
1996 connection_.GetStats().num_connectivity_probing_received);
1997 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1998 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1999
2000 // Process another packet with the old peer address on server side will not
2001 // start peer migration.
2002 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
nharper46833c32019-05-15 21:33:05 -07002003 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002004 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2005 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2006}
2007
2008TEST_P(QuicConnectionTest, ReceiveReorderedConnectivityProbingAtServer) {
2009 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2010 set_perspective(Perspective::IS_SERVER);
2011 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2012 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2013
2014 // Clear direct_peer_address.
2015 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2016 // Clear effective_peer_address, it is the same as direct_peer_address for
2017 // this test.
2018 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2019 QuicSocketAddress());
2020 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2021
nharper46833c32019-05-15 21:33:05 -07002022 QuicFrame frame;
2023 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2024 frame = QuicFrame(&crypto_frame_);
2025 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2026 } else {
2027 frame = QuicFrame(QuicStreamFrame(
2028 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
2029 0u, QuicStringPiece()));
2030 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2031 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002032 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
nharper46833c32019-05-15 21:33:05 -07002033 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002034 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2035 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2036
2037 // Decrease packet number to simulate out-of-order packets.
2038 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 4);
2039
2040 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2041 EXPECT_CALL(visitor_, OnConnectivityProbeReceived(_, _)).Times(1);
2042
2043 // Process a padded PING packet from a new peer address on server side
2044 // is effectively receiving a connectivity probing, even if a newer packet has
2045 // been received before this one.
2046 const QuicSocketAddress kNewPeerAddress =
2047 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2048
2049 OwningSerializedPacketPointer probing_packet = ConstructProbingPacket();
2050 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2051 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2052 probing_packet->encrypted_length),
2053 clock_.Now()));
2054
2055 uint64_t num_probing_received =
2056 connection_.GetStats().num_connectivity_probing_received;
2057 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2058
2059 EXPECT_EQ(num_probing_received + 1,
2060 connection_.GetStats().num_connectivity_probing_received);
2061 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2062 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2063}
2064
2065TEST_P(QuicConnectionTest, MigrateAfterProbingAtServer) {
2066 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2067 set_perspective(Perspective::IS_SERVER);
2068 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2069 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2070
2071 // Clear direct_peer_address.
2072 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2073 // Clear effective_peer_address, it is the same as direct_peer_address for
2074 // this test.
2075 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2076 QuicSocketAddress());
2077 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2078
nharper46833c32019-05-15 21:33:05 -07002079 QuicFrame frame;
2080 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2081 frame = QuicFrame(&crypto_frame_);
2082 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2083 } else {
2084 frame = QuicFrame(QuicStreamFrame(
2085 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
2086 0u, QuicStringPiece()));
2087 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2088 }
2089 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002090 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2091 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2092
2093 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2094 EXPECT_CALL(visitor_, OnConnectivityProbeReceived(_, _)).Times(1);
2095
2096 // Process a padded PING packet from a new peer address on server side
2097 // is effectively receiving a connectivity probing.
2098 const QuicSocketAddress kNewPeerAddress =
2099 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2100
2101 OwningSerializedPacketPointer probing_packet = ConstructProbingPacket();
2102 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2103 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2104 probing_packet->encrypted_length),
2105 clock_.Now()));
2106 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2107 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2108 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2109
2110 // Process another non-probing packet with the new peer address on server
2111 // side will start peer migration.
2112 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2113
nharper46833c32019-05-15 21:33:05 -07002114 ProcessFramePacketWithAddresses(frame, kSelfAddress, kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002115 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2116 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2117}
2118
2119TEST_P(QuicConnectionTest, ReceivePaddedPingAtClient) {
2120 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2121 set_perspective(Perspective::IS_CLIENT);
2122 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2123
2124 // Clear direct_peer_address.
2125 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2126 // Clear effective_peer_address, it is the same as direct_peer_address for
2127 // this test.
2128 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2129 QuicSocketAddress());
2130 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2131
nharper46833c32019-05-15 21:33:05 -07002132 QuicFrame frame;
2133 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2134 frame = QuicFrame(&crypto_frame_);
2135 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2136 } else {
2137 frame = QuicFrame(QuicStreamFrame(
2138 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
2139 0u, QuicStringPiece()));
2140 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2141 }
2142 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002143 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2144 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2145
2146 // Client takes all padded PING packet as speculative connectivity
2147 // probing packet, and reports to visitor.
2148 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2149 EXPECT_CALL(visitor_, OnConnectivityProbeReceived(_, _)).Times(1);
2150
2151 OwningSerializedPacketPointer probing_packet = ConstructProbingPacket();
2152 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2153 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2154 probing_packet->encrypted_length),
2155 clock_.Now()));
2156 uint64_t num_probing_received =
2157 connection_.GetStats().num_connectivity_probing_received;
2158 ProcessReceivedPacket(kSelfAddress, kPeerAddress, *received);
2159
2160 EXPECT_EQ(num_probing_received,
2161 connection_.GetStats().num_connectivity_probing_received);
2162 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2163 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2164}
2165
2166TEST_P(QuicConnectionTest, ReceiveConnectivityProbingAtClient) {
2167 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2168 set_perspective(Perspective::IS_CLIENT);
2169 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2170
2171 // Clear direct_peer_address.
2172 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2173 // Clear effective_peer_address, it is the same as direct_peer_address for
2174 // this test.
2175 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2176 QuicSocketAddress());
2177 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2178
nharper46833c32019-05-15 21:33:05 -07002179 QuicFrame frame;
2180 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2181 frame = QuicFrame(&crypto_frame_);
2182 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2183 } else {
2184 frame = QuicFrame(QuicStreamFrame(
2185 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
2186 0u, QuicStringPiece()));
2187 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2188 }
2189 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002190 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2191 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2192
2193 // Process a padded PING packet with a different self address on client side
2194 // is effectively receiving a connectivity probing.
2195 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2196 EXPECT_CALL(visitor_, OnConnectivityProbeReceived(_, _)).Times(1);
2197
2198 const QuicSocketAddress kNewSelfAddress =
2199 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2200
2201 OwningSerializedPacketPointer probing_packet = ConstructProbingPacket();
2202 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2203 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2204 probing_packet->encrypted_length),
2205 clock_.Now()));
2206 uint64_t num_probing_received =
2207 connection_.GetStats().num_connectivity_probing_received;
2208 ProcessReceivedPacket(kNewSelfAddress, kPeerAddress, *received);
2209
2210 EXPECT_EQ(num_probing_received + 1,
2211 connection_.GetStats().num_connectivity_probing_received);
2212 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2213 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2214}
2215
2216TEST_P(QuicConnectionTest, PeerAddressChangeAtClient) {
2217 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2218 set_perspective(Perspective::IS_CLIENT);
2219 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2220
2221 // Clear direct_peer_address.
2222 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2223 // Clear effective_peer_address, it is the same as direct_peer_address for
2224 // this test.
2225 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2226 QuicSocketAddress());
2227 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2228
nharper46833c32019-05-15 21:33:05 -07002229 QuicFrame frame;
2230 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2231 frame = QuicFrame(&crypto_frame_);
2232 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2233 } else {
2234 frame = QuicFrame(QuicStreamFrame(
2235 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
2236 0u, QuicStringPiece()));
2237 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2238 }
2239 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002240 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2241 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2242
2243 // Process another packet with a different peer address on client side will
2244 // only update peer address.
2245 const QuicSocketAddress kNewPeerAddress =
2246 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2247 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
nharper46833c32019-05-15 21:33:05 -07002248 ProcessFramePacketWithAddresses(frame, kSelfAddress, kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002249 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2250 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2251}
2252
2253TEST_P(QuicConnectionTest, MaxPacketSize) {
2254 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2255 EXPECT_EQ(1350u, connection_.max_packet_length());
2256}
2257
2258TEST_P(QuicConnectionTest, SmallerServerMaxPacketSize) {
2259 TestConnection connection(TestConnectionId(), kPeerAddress, helper_.get(),
2260 alarm_factory_.get(), writer_.get(),
2261 Perspective::IS_SERVER, version());
2262 EXPECT_EQ(Perspective::IS_SERVER, connection.perspective());
2263 EXPECT_EQ(1000u, connection.max_packet_length());
2264}
2265
2266TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSize) {
2267 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2268
2269 set_perspective(Perspective::IS_SERVER);
2270 connection_.SetMaxPacketLength(1000);
2271
2272 QuicPacketHeader header;
2273 header.destination_connection_id = connection_id_;
2274 header.version_flag = true;
2275 header.packet_number = QuicPacketNumber(1);
2276
2277 if (QuicVersionHasLongHeaderLengths(
2278 peer_framer_.version().transport_version)) {
2279 header.long_packet_type = INITIAL;
2280 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
2281 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
2282 }
2283
2284 QuicFrames frames;
2285 QuicPaddingFrame padding;
nharper46833c32019-05-15 21:33:05 -07002286 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2287 frames.push_back(QuicFrame(&crypto_frame_));
2288 } else {
2289 frames.push_back(QuicFrame(frame1_));
2290 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002291 frames.push_back(QuicFrame(padding));
2292 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
dschinazi66dea072019-04-09 11:41:06 -07002293 char buffer[kMaxOutgoingPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07002294 size_t encrypted_length =
2295 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12),
dschinazi66dea072019-04-09 11:41:06 -07002296 *packet, buffer, kMaxOutgoingPacketSize);
2297 EXPECT_EQ(kMaxOutgoingPacketSize, encrypted_length);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002298
2299 framer_.set_version(version());
nharper46833c32019-05-15 21:33:05 -07002300 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2301 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
2302 } else {
2303 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2304 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002305 connection_.ProcessUdpPacket(
2306 kSelfAddress, kPeerAddress,
2307 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
2308
dschinazi66dea072019-04-09 11:41:06 -07002309 EXPECT_EQ(kMaxOutgoingPacketSize, connection_.max_packet_length());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002310}
2311
2312TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSizeWhileWriterLimited) {
2313 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2314
2315 const QuicByteCount lower_max_packet_size = 1240;
2316 writer_->set_max_packet_size(lower_max_packet_size);
2317 set_perspective(Perspective::IS_SERVER);
2318 connection_.SetMaxPacketLength(1000);
2319 EXPECT_EQ(1000u, connection_.max_packet_length());
2320
2321 QuicPacketHeader header;
2322 header.destination_connection_id = connection_id_;
2323 header.version_flag = true;
2324 header.packet_number = QuicPacketNumber(1);
2325
2326 if (QuicVersionHasLongHeaderLengths(
2327 peer_framer_.version().transport_version)) {
2328 header.long_packet_type = INITIAL;
2329 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
2330 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
2331 }
2332
2333 QuicFrames frames;
2334 QuicPaddingFrame padding;
nharper46833c32019-05-15 21:33:05 -07002335 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2336 frames.push_back(QuicFrame(&crypto_frame_));
2337 } else {
2338 frames.push_back(QuicFrame(frame1_));
2339 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002340 frames.push_back(QuicFrame(padding));
2341 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
dschinazi66dea072019-04-09 11:41:06 -07002342 char buffer[kMaxOutgoingPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07002343 size_t encrypted_length =
2344 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12),
dschinazi66dea072019-04-09 11:41:06 -07002345 *packet, buffer, kMaxOutgoingPacketSize);
2346 EXPECT_EQ(kMaxOutgoingPacketSize, encrypted_length);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002347
2348 framer_.set_version(version());
nharper46833c32019-05-15 21:33:05 -07002349 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2350 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
2351 } else {
2352 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2353 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002354 connection_.ProcessUdpPacket(
2355 kSelfAddress, kPeerAddress,
2356 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
2357
2358 // Here, the limit imposed by the writer is lower than the size of the packet
2359 // received, so the writer max packet size is used.
2360 EXPECT_EQ(lower_max_packet_size, connection_.max_packet_length());
2361}
2362
2363TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriter) {
2364 const QuicByteCount lower_max_packet_size = 1240;
2365 writer_->set_max_packet_size(lower_max_packet_size);
2366
2367 static_assert(lower_max_packet_size < kDefaultMaxPacketSize,
2368 "Default maximum packet size is too low");
2369 connection_.SetMaxPacketLength(kDefaultMaxPacketSize);
2370
2371 EXPECT_EQ(lower_max_packet_size, connection_.max_packet_length());
2372}
2373
2374TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriterForNewConnection) {
2375 const QuicConnectionId connection_id = TestConnectionId(17);
2376 const QuicByteCount lower_max_packet_size = 1240;
2377 writer_->set_max_packet_size(lower_max_packet_size);
2378 TestConnection connection(connection_id, kPeerAddress, helper_.get(),
2379 alarm_factory_.get(), writer_.get(),
2380 Perspective::IS_CLIENT, version());
2381 EXPECT_EQ(Perspective::IS_CLIENT, connection.perspective());
2382 EXPECT_EQ(lower_max_packet_size, connection.max_packet_length());
2383}
2384
2385TEST_P(QuicConnectionTest, PacketsInOrder) {
QUICHE teamcd098022019-03-22 18:49:55 -07002386 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2387 return;
2388 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002389 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2390
2391 ProcessPacket(1);
2392 EXPECT_EQ(QuicPacketNumber(1u), LargestAcked(*outgoing_ack()));
2393 EXPECT_EQ(1u, outgoing_ack()->packets.NumIntervals());
2394
2395 ProcessPacket(2);
2396 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(*outgoing_ack()));
2397 EXPECT_EQ(1u, outgoing_ack()->packets.NumIntervals());
2398
2399 ProcessPacket(3);
2400 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(*outgoing_ack()));
2401 EXPECT_EQ(1u, outgoing_ack()->packets.NumIntervals());
2402}
2403
2404TEST_P(QuicConnectionTest, PacketsOutOfOrder) {
QUICHE teamcd098022019-03-22 18:49:55 -07002405 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2406 return;
2407 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002408 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2409
2410 ProcessPacket(3);
2411 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(*outgoing_ack()));
2412 EXPECT_TRUE(IsMissing(2));
2413 EXPECT_TRUE(IsMissing(1));
2414
2415 ProcessPacket(2);
2416 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(*outgoing_ack()));
2417 EXPECT_FALSE(IsMissing(2));
2418 EXPECT_TRUE(IsMissing(1));
2419
2420 ProcessPacket(1);
2421 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(*outgoing_ack()));
2422 EXPECT_FALSE(IsMissing(2));
2423 EXPECT_FALSE(IsMissing(1));
2424}
2425
2426TEST_P(QuicConnectionTest, DuplicatePacket) {
QUICHE teamcd098022019-03-22 18:49:55 -07002427 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2428 return;
2429 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002430 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2431
2432 ProcessPacket(3);
2433 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(*outgoing_ack()));
2434 EXPECT_TRUE(IsMissing(2));
2435 EXPECT_TRUE(IsMissing(1));
2436
2437 // Send packet 3 again, but do not set the expectation that
2438 // the visitor OnStreamFrame() will be called.
2439 ProcessDataPacket(3);
2440 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(*outgoing_ack()));
2441 EXPECT_TRUE(IsMissing(2));
2442 EXPECT_TRUE(IsMissing(1));
2443}
2444
2445TEST_P(QuicConnectionTest, PacketsOutOfOrderWithAdditionsAndLeastAwaiting) {
QUICHE teamcd098022019-03-22 18:49:55 -07002446 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2447 return;
2448 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002449 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2450
2451 ProcessPacket(3);
2452 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(*outgoing_ack()));
2453 EXPECT_TRUE(IsMissing(2));
2454 EXPECT_TRUE(IsMissing(1));
2455
2456 ProcessPacket(2);
2457 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(*outgoing_ack()));
2458 EXPECT_TRUE(IsMissing(1));
2459
2460 ProcessPacket(5);
2461 EXPECT_EQ(QuicPacketNumber(5u), LargestAcked(*outgoing_ack()));
2462 EXPECT_TRUE(IsMissing(1));
2463 EXPECT_TRUE(IsMissing(4));
2464
2465 // Pretend at this point the client has gotten acks for 2 and 3 and 1 is a
2466 // packet the peer will not retransmit. It indicates this by sending 'least
2467 // awaiting' is 4. The connection should then realize 1 will not be
2468 // retransmitted, and will remove it from the missing list.
2469 QuicAckFrame frame = InitAckFrame(1);
2470 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
2471 ProcessAckPacket(6, &frame);
2472
2473 // Force an ack to be sent.
2474 SendAckPacketToPeer();
2475 EXPECT_TRUE(IsMissing(4));
2476}
2477
2478TEST_P(QuicConnectionTest, RejectPacketTooFarOut) {
QUICHE teamcd098022019-03-22 18:49:55 -07002479 if (GetQuicReloadableFlag(quic_use_uber_received_packet_manager)) {
2480 return;
2481 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002482 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_PACKET_HEADER, _,
2483 ConnectionCloseSource::FROM_SELF));
2484
2485 // Call ProcessDataPacket rather than ProcessPacket, as we should not get a
2486 // packet call to the visitor.
2487 if (GetQuicRestartFlag(quic_enable_accept_random_ipn)) {
2488 ProcessDataPacket(MaxRandomInitialPacketNumber() + 6000);
2489 } else {
2490 ProcessDataPacket(6000);
2491 }
2492 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
2493 nullptr);
2494}
2495
2496TEST_P(QuicConnectionTest, RejectUnencryptedStreamData) {
2497 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
2498 if (!IsDefaultTestConfiguration()) {
2499 return;
2500 }
2501
2502 // Process an unencrypted packet from the non-crypto stream.
2503 frame1_.stream_id = 3;
2504 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2505 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_UNENCRYPTED_STREAM_DATA, _,
2506 ConnectionCloseSource::FROM_SELF));
nharper2c9f02a2019-05-08 10:25:50 -07002507 EXPECT_QUIC_PEER_BUG(ProcessDataPacketAtLevel(1, false, ENCRYPTION_INITIAL),
2508 "");
QUICHE teama6ef0a62019-03-07 20:34:33 -05002509 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
2510 nullptr);
2511 const std::vector<QuicConnectionCloseFrame>& connection_close_frames =
2512 writer_->connection_close_frames();
nharper2c9f02a2019-05-08 10:25:50 -07002513 ASSERT_EQ(1u, connection_close_frames.size());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002514 EXPECT_EQ(QUIC_UNENCRYPTED_STREAM_DATA,
fkastenholze9d71a82019-04-09 05:12:13 -07002515 connection_close_frames[0].quic_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002516}
2517
2518TEST_P(QuicConnectionTest, OutOfOrderReceiptCausesAckSend) {
2519 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2520
2521 ProcessPacket(3);
2522 if (GetQuicRestartFlag(quic_enable_accept_random_ipn)) {
2523 // Should not cause an ack.
2524 EXPECT_EQ(0u, writer_->packets_write_attempts());
2525 } else {
2526 // Should ack immediately since we have missing packets.
2527 EXPECT_EQ(1u, writer_->packets_write_attempts());
2528 }
2529
2530 ProcessPacket(2);
2531 if (GetQuicRestartFlag(quic_enable_accept_random_ipn)) {
2532 // Should ack immediately, since this fills the last hole.
2533 EXPECT_EQ(1u, writer_->packets_write_attempts());
2534 } else {
2535 // Should ack immediately since we have missing packets.
2536 EXPECT_EQ(2u, writer_->packets_write_attempts());
2537 }
2538
2539 ProcessPacket(1);
2540 // Should ack immediately, since this fills the last hole.
2541 if (GetQuicRestartFlag(quic_enable_accept_random_ipn)) {
2542 EXPECT_EQ(2u, writer_->packets_write_attempts());
2543 } else {
2544 EXPECT_EQ(3u, writer_->packets_write_attempts());
2545 }
2546
2547 ProcessPacket(4);
2548 // Should not cause an ack.
2549 if (GetQuicRestartFlag(quic_enable_accept_random_ipn)) {
2550 EXPECT_EQ(2u, writer_->packets_write_attempts());
2551 } else {
2552 EXPECT_EQ(3u, writer_->packets_write_attempts());
2553 }
2554}
2555
2556TEST_P(QuicConnectionTest, OutOfOrderAckReceiptCausesNoAck) {
2557 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2558
2559 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
2560 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
2561 EXPECT_EQ(2u, writer_->packets_write_attempts());
2562
2563 QuicAckFrame ack1 = InitAckFrame(1);
2564 QuicAckFrame ack2 = InitAckFrame(2);
2565 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2566 ProcessAckPacket(2, &ack2);
2567 // Should ack immediately since we have missing packets.
2568 EXPECT_EQ(2u, writer_->packets_write_attempts());
2569
2570 ProcessAckPacket(1, &ack1);
2571 // Should not ack an ack filling a missing packet.
2572 EXPECT_EQ(2u, writer_->packets_write_attempts());
2573}
2574
2575TEST_P(QuicConnectionTest, AckReceiptCausesAckSend) {
2576 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2577 QuicPacketNumber original, second;
2578
2579 QuicByteCount packet_size =
2580 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &original); // 1st packet.
2581 SendStreamDataToPeer(3, "bar", 3, NO_FIN, &second); // 2nd packet.
2582
2583 QuicAckFrame frame = InitAckFrame({{second, second + 1}});
2584 // First nack triggers early retransmit.
2585 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07002586 lost_packets.push_back(LostPacket(original, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002587 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
2588 .WillOnce(SetArgPointee<5>(lost_packets));
2589 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2590 QuicPacketNumber retransmission;
2591 // Packet 1 is short header for IETF QUIC because the encryption level
2592 // switched to ENCRYPTION_FORWARD_SECURE in SendStreamDataToPeer.
fayangd4291e42019-05-30 10:31:21 -07002593 EXPECT_CALL(*send_algorithm_,
2594 OnPacketSent(_, _, _,
2595 VersionHasIetfInvariantHeader(
2596 GetParam().version.transport_version)
2597 ? packet_size
2598 : packet_size - kQuicVersionSize,
2599 _))
QUICHE teama6ef0a62019-03-07 20:34:33 -05002600 .WillOnce(SaveArg<2>(&retransmission));
2601
2602 ProcessAckPacket(&frame);
2603
2604 QuicAckFrame frame2 = ConstructAckFrame(retransmission, original);
2605 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2606 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
2607 ProcessAckPacket(&frame2);
2608
2609 // Now if the peer sends an ack which still reports the retransmitted packet
2610 // as missing, that will bundle an ack with data after two acks in a row
2611 // indicate the high water mark needs to be raised.
2612 EXPECT_CALL(*send_algorithm_,
2613 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA));
2614 connection_.SendStreamDataWithString(3, "foo", 6, NO_FIN);
2615 // No ack sent.
nharper55fa6132019-05-07 19:37:21 -07002616 size_t padding_frame_count = writer_->padding_frames().size();
2617 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002618 EXPECT_EQ(1u, writer_->stream_frames().size());
2619
2620 // No more packet loss for the rest of the test.
2621 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
2622 .Times(AnyNumber());
2623 ProcessAckPacket(&frame2);
2624 EXPECT_CALL(*send_algorithm_,
2625 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA));
fayang03916692019-05-22 17:57:18 -07002626 connection_.SendStreamDataWithString(3, "foofoofoo", 9, NO_FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002627 // Ack bundled.
2628 if (GetParam().no_stop_waiting) {
fayang03916692019-05-22 17:57:18 -07002629 if (GetQuicReloadableFlag(quic_simplify_stop_waiting)) {
2630 // Do not ACK acks.
2631 EXPECT_EQ(1u, writer_->frame_count());
2632 } else {
2633 EXPECT_EQ(2u, writer_->frame_count());
2634 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002635 } else {
2636 EXPECT_EQ(3u, writer_->frame_count());
2637 }
2638 EXPECT_EQ(1u, writer_->stream_frames().size());
fayang03916692019-05-22 17:57:18 -07002639 if (GetParam().no_stop_waiting &&
2640 GetQuicReloadableFlag(quic_simplify_stop_waiting)) {
2641 EXPECT_TRUE(writer_->ack_frames().empty());
2642 } else {
2643 EXPECT_FALSE(writer_->ack_frames().empty());
2644 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002645
2646 // But an ack with no missing packets will not send an ack.
2647 AckPacket(original, &frame2);
2648 ProcessAckPacket(&frame2);
2649 ProcessAckPacket(&frame2);
2650}
2651
2652TEST_P(QuicConnectionTest, AckSentEveryNthPacket) {
2653 connection_.set_ack_frequency_before_ack_decimation(3);
2654
2655 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2656 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(39);
2657
2658 // Expect 13 acks, every 3rd packet.
2659 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(13);
2660 // Receives packets 1 - 39.
2661 for (size_t i = 1; i <= 39; ++i) {
2662 ProcessDataPacket(i);
2663 }
2664}
2665
2666TEST_P(QuicConnectionTest, AckDecimationReducesAcks) {
2667 const size_t kMinRttMs = 40;
2668 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
2669 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
2670 QuicTime::Delta::Zero(), QuicTime::Zero());
2671 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
2672
2673 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
2674
2675 // Start ack decimation from 10th packet.
2676 connection_.set_min_received_before_ack_decimation(10);
2677
2678 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2679 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(30);
2680
2681 // Expect 6 acks: 5 acks between packets 1-10, and ack at 20.
2682 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(6);
2683 // Receives packets 1 - 29.
2684 for (size_t i = 1; i <= 29; ++i) {
2685 ProcessDataPacket(i);
2686 }
2687
2688 // We now receive the 30th packet, and so we send an ack.
2689 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2690 ProcessDataPacket(30);
2691}
2692
2693TEST_P(QuicConnectionTest, AckNeedsRetransmittableFrames) {
ianswett68cf0042019-05-09 08:37:58 -07002694 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002695 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2696 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(99);
2697
2698 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(19);
2699 // Receives packets 1 - 39.
2700 for (size_t i = 1; i <= 39; ++i) {
2701 ProcessDataPacket(i);
2702 }
2703 // Receiving Packet 40 causes 20th ack to send. Session is informed and adds
2704 // WINDOW_UPDATE.
2705 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
2706 .WillOnce(Invoke([this]() {
2707 connection_.SendControlFrame(
2708 QuicFrame(new QuicWindowUpdateFrame(1, 0, 0)));
2709 }));
2710 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2711 EXPECT_EQ(0u, writer_->window_update_frames().size());
2712 ProcessDataPacket(40);
2713 EXPECT_EQ(1u, writer_->window_update_frames().size());
2714
2715 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(9);
2716 // Receives packets 41 - 59.
2717 for (size_t i = 41; i <= 59; ++i) {
2718 ProcessDataPacket(i);
2719 }
2720 // Send a packet containing stream frame.
QUICHE team8c1daa22019-03-13 08:33:41 -07002721 SendStreamDataToPeer(
nharper46833c32019-05-15 21:33:05 -07002722 QuicUtils::GetFirstBidirectionalStreamId(
2723 connection_.version().transport_version, Perspective::IS_CLIENT),
QUICHE team8c1daa22019-03-13 08:33:41 -07002724 "bar", 0, NO_FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002725
2726 // Session will not be informed until receiving another 20 packets.
2727 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(19);
2728 for (size_t i = 60; i <= 98; ++i) {
2729 ProcessDataPacket(i);
2730 EXPECT_EQ(0u, writer_->window_update_frames().size());
2731 }
2732 // Session does not add a retransmittable frame.
2733 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
2734 .WillOnce(Invoke([this]() {
2735 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
2736 }));
2737 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2738 EXPECT_EQ(0u, writer_->ping_frames().size());
2739 ProcessDataPacket(99);
2740 EXPECT_EQ(0u, writer_->window_update_frames().size());
2741 // A ping frame will be added.
2742 EXPECT_EQ(1u, writer_->ping_frames().size());
2743}
2744
2745TEST_P(QuicConnectionTest, LeastUnackedLower) {
fayangd4291e42019-05-30 10:31:21 -07002746 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version) ||
QUICHE teamcd098022019-03-22 18:49:55 -07002747 connection_.SupportsMultiplePacketNumberSpaces()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002748 return;
2749 }
2750 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2751
2752 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
2753 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
2754 SendStreamDataToPeer(1, "eep", 6, NO_FIN, nullptr);
2755
2756 // Start out saying the least unacked is 2.
2757 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
2758 ProcessStopWaitingPacket(InitStopWaitingFrame(2));
2759
2760 // Change it to 1, but lower the packet number to fake out-of-order packets.
2761 // This should be fine.
2762 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 1);
2763 // The scheduler will not process out of order acks, but all packet processing
2764 // causes the connection to try to write.
2765 if (!GetParam().no_stop_waiting) {
2766 EXPECT_CALL(visitor_, OnCanWrite());
2767 }
2768 ProcessStopWaitingPacket(InitStopWaitingFrame(1));
2769
2770 // Now claim it's one, but set the ordering so it was sent "after" the first
2771 // one. This should cause a connection error.
2772 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 7);
2773 if (!GetParam().no_stop_waiting) {
2774 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2775 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_STOP_WAITING_DATA, _,
2776 ConnectionCloseSource::FROM_SELF));
2777 }
2778 ProcessStopWaitingPacket(InitStopWaitingFrame(1));
2779}
2780
2781TEST_P(QuicConnectionTest, TooManySentPackets) {
2782 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2783
2784 QuicPacketCount max_tracked_packets = 50;
2785 QuicConnectionPeer::SetMaxTrackedPackets(&connection_, max_tracked_packets);
2786
2787 const int num_packets = max_tracked_packets + 5;
2788
2789 for (int i = 0; i < num_packets; ++i) {
2790 SendStreamDataToPeer(1, "foo", 3 * i, NO_FIN, nullptr);
2791 }
2792
2793 // Ack packet 1, which leaves more than the limit outstanding.
2794 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2795 EXPECT_CALL(visitor_,
2796 OnConnectionClosed(QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS, _,
2797 ConnectionCloseSource::FROM_SELF));
2798
2799 // Nack the first packet and ack the rest, leaving a huge gap.
2800 QuicAckFrame frame1 = ConstructAckFrame(num_packets, 1);
2801 ProcessAckPacket(&frame1);
2802}
2803
2804TEST_P(QuicConnectionTest, LargestObservedLower) {
2805 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2806
2807 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
2808 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
2809 SendStreamDataToPeer(1, "eep", 6, NO_FIN, nullptr);
2810 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2811
2812 // Start out saying the largest observed is 2.
2813 QuicAckFrame frame1 = InitAckFrame(1);
2814 QuicAckFrame frame2 = InitAckFrame(2);
2815 ProcessAckPacket(&frame2);
2816
QUICHE team9929cc42019-03-13 08:17:43 -07002817 if (GetQuicReloadableFlag(quic_tolerate_reneging)) {
2818 EXPECT_CALL(visitor_, OnCanWrite());
2819 } else {
2820 // Now change it to 1, and it should cause a connection error.
2821 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, _,
2822 ConnectionCloseSource::FROM_SELF));
2823 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
2824 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002825 ProcessAckPacket(&frame1);
2826}
2827
2828TEST_P(QuicConnectionTest, AckUnsentData) {
2829 // Ack a packet which has not been sent.
2830 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, _,
2831 ConnectionCloseSource::FROM_SELF));
2832 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2833 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2834 QuicAckFrame frame = InitAckFrame(1);
2835 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
2836 ProcessAckPacket(&frame);
2837}
2838
2839TEST_P(QuicConnectionTest, BasicSending) {
QUICHE teamcd098022019-03-22 18:49:55 -07002840 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2841 return;
2842 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002843 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2844 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2845 ProcessDataPacket(1);
2846 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
2847 QuicPacketNumber last_packet;
2848 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
2849 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
2850 SendAckPacketToPeer(); // Packet 2
2851
2852 if (GetParam().no_stop_waiting) {
2853 // Expect no stop waiting frame is sent.
2854 EXPECT_FALSE(least_unacked().IsInitialized());
2855 } else {
2856 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
2857 }
2858
2859 SendAckPacketToPeer(); // Packet 3
2860 if (GetParam().no_stop_waiting) {
2861 // Expect no stop waiting frame is sent.
2862 EXPECT_FALSE(least_unacked().IsInitialized());
2863 } else {
2864 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
2865 }
2866
2867 SendStreamDataToPeer(1, "bar", 3, NO_FIN, &last_packet); // Packet 4
2868 EXPECT_EQ(QuicPacketNumber(4u), last_packet);
2869 SendAckPacketToPeer(); // Packet 5
2870 if (GetParam().no_stop_waiting) {
2871 // Expect no stop waiting frame is sent.
2872 EXPECT_FALSE(least_unacked().IsInitialized());
2873 } else {
2874 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
2875 }
2876
2877 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2878
2879 // Peer acks up to packet 3.
2880 QuicAckFrame frame = InitAckFrame(3);
2881 ProcessAckPacket(&frame);
2882 SendAckPacketToPeer(); // Packet 6
2883
2884 // As soon as we've acked one, we skip ack packets 2 and 3 and note lack of
2885 // ack for 4.
2886 if (GetParam().no_stop_waiting) {
2887 // Expect no stop waiting frame is sent.
2888 EXPECT_FALSE(least_unacked().IsInitialized());
2889 } else {
2890 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
2891 }
2892
2893 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2894
2895 // Peer acks up to packet 4, the last packet.
2896 QuicAckFrame frame2 = InitAckFrame(6);
2897 ProcessAckPacket(&frame2); // Acks don't instigate acks.
2898
2899 // Verify that we did not send an ack.
2900 EXPECT_EQ(QuicPacketNumber(6u), writer_->header().packet_number);
2901
2902 // So the last ack has not changed.
2903 if (GetParam().no_stop_waiting) {
2904 // Expect no stop waiting frame is sent.
2905 EXPECT_FALSE(least_unacked().IsInitialized());
2906 } else {
2907 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
2908 }
2909
2910 // If we force an ack, we shouldn't change our retransmit state.
2911 SendAckPacketToPeer(); // Packet 7
2912 if (GetParam().no_stop_waiting) {
2913 // Expect no stop waiting frame is sent.
2914 EXPECT_FALSE(least_unacked().IsInitialized());
2915 } else {
2916 EXPECT_EQ(QuicPacketNumber(7u), least_unacked());
2917 }
2918
2919 // But if we send more data it should.
2920 SendStreamDataToPeer(1, "eep", 6, NO_FIN, &last_packet); // Packet 8
2921 EXPECT_EQ(QuicPacketNumber(8u), last_packet);
2922 SendAckPacketToPeer(); // Packet 9
2923 if (GetParam().no_stop_waiting) {
2924 // Expect no stop waiting frame is sent.
2925 EXPECT_FALSE(least_unacked().IsInitialized());
2926 } else {
2927 EXPECT_EQ(QuicPacketNumber(7u), least_unacked());
2928 }
2929}
2930
2931// QuicConnection should record the packet sent-time prior to sending the
2932// packet.
2933TEST_P(QuicConnectionTest, RecordSentTimeBeforePacketSent) {
2934 // We're using a MockClock for the tests, so we have complete control over the
2935 // time.
2936 // Our recorded timestamp for the last packet sent time will be passed in to
2937 // the send_algorithm. Make sure that it is set to the correct value.
2938 QuicTime actual_recorded_send_time = QuicTime::Zero();
2939 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2940 .WillOnce(SaveArg<0>(&actual_recorded_send_time));
2941
2942 // First send without any pause and check the result.
2943 QuicTime expected_recorded_send_time = clock_.Now();
2944 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
2945 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
2946 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
2947 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
2948
2949 // Now pause during the write, and check the results.
2950 actual_recorded_send_time = QuicTime::Zero();
2951 const QuicTime::Delta write_pause_time_delta =
2952 QuicTime::Delta::FromMilliseconds(5000);
2953 SetWritePauseTimeDelta(write_pause_time_delta);
2954 expected_recorded_send_time = clock_.Now();
2955
2956 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2957 .WillOnce(SaveArg<0>(&actual_recorded_send_time));
2958 connection_.SendStreamDataWithString(2, "baz", 0, NO_FIN);
2959 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
2960 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
2961 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
2962}
2963
2964TEST_P(QuicConnectionTest, FramePacking) {
2965 // Send two stream frames in 1 packet by queueing them.
2966 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2967 {
2968 QuicConnection::ScopedPacketFlusher flusher(&connection_,
2969 QuicConnection::SEND_ACK);
2970 connection_.SendStreamData3();
2971 connection_.SendStreamData5();
2972 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2973 }
2974 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2975 EXPECT_FALSE(connection_.HasQueuedData());
2976
2977 // Parse the last packet and ensure it's an ack and two stream frames from
2978 // two different streams.
2979 if (GetParam().no_stop_waiting) {
2980 EXPECT_EQ(2u, writer_->frame_count());
2981 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
2982 } else {
2983 EXPECT_EQ(2u, writer_->frame_count());
2984 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
2985 }
2986
2987 EXPECT_TRUE(writer_->ack_frames().empty());
2988
2989 ASSERT_EQ(2u, writer_->stream_frames().size());
2990 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
2991 writer_->stream_frames()[0]->stream_id);
2992 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
2993 writer_->stream_frames()[1]->stream_id);
2994}
2995
2996TEST_P(QuicConnectionTest, FramePackingNonCryptoThenCrypto) {
2997 // Send two stream frames (one non-crypto, then one crypto) in 2 packets by
2998 // queueing them.
2999 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3000 {
3001 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3002 QuicConnection::ScopedPacketFlusher flusher(&connection_,
3003 QuicConnection::SEND_ACK);
3004 connection_.SendStreamData3();
3005 connection_.SendCryptoStreamData();
3006 }
3007 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3008 EXPECT_FALSE(connection_.HasQueuedData());
3009
3010 // Parse the last packet and ensure it's the crypto stream frame.
3011 EXPECT_EQ(2u, writer_->frame_count());
3012 ASSERT_EQ(1u, writer_->padding_frames().size());
QUICHE teamea740082019-03-11 17:58:43 -07003013 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003014 ASSERT_EQ(1u, writer_->stream_frames().size());
3015 EXPECT_EQ(QuicUtils::GetCryptoStreamId(connection_.transport_version()),
3016 writer_->stream_frames()[0]->stream_id);
3017 } else {
3018 EXPECT_EQ(1u, writer_->crypto_frames().size());
3019 }
3020}
3021
3022TEST_P(QuicConnectionTest, FramePackingCryptoThenNonCrypto) {
3023 // Send two stream frames (one crypto, then one non-crypto) in 2 packets by
3024 // queueing them.
3025 {
3026 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3027 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3028 QuicConnection::ScopedPacketFlusher flusher(&connection_,
3029 QuicConnection::SEND_ACK);
3030 connection_.SendCryptoStreamData();
3031 connection_.SendStreamData3();
3032 }
3033 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3034 EXPECT_FALSE(connection_.HasQueuedData());
3035
3036 // Parse the last packet and ensure it's the stream frame from stream 3.
nharper55fa6132019-05-07 19:37:21 -07003037 size_t padding_frame_count = writer_->padding_frames().size();
3038 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003039 ASSERT_EQ(1u, writer_->stream_frames().size());
3040 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3041 writer_->stream_frames()[0]->stream_id);
3042}
3043
3044TEST_P(QuicConnectionTest, FramePackingAckResponse) {
QUICHE teamcd098022019-03-22 18:49:55 -07003045 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3046 return;
3047 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003048 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3049 // Process a data packet to queue up a pending ack.
3050 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3051 ProcessDataPacket(1);
3052 QuicPacketNumber last_packet;
nharper46833c32019-05-15 21:33:05 -07003053 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3054 connection_.SendCryptoDataWithString("foo", 0);
3055 } else {
3056 SendStreamDataToPeer(
3057 QuicUtils::GetCryptoStreamId(connection_.transport_version()), "foo", 0,
3058 NO_FIN, &last_packet);
3059 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003060 // Verify ack is bundled with outging packet.
3061 EXPECT_FALSE(writer_->ack_frames().empty());
3062
3063 EXPECT_CALL(visitor_, OnCanWrite())
3064 .WillOnce(DoAll(IgnoreResult(InvokeWithoutArgs(
3065 &connection_, &TestConnection::SendStreamData3)),
3066 IgnoreResult(InvokeWithoutArgs(
3067 &connection_, &TestConnection::SendStreamData5))));
3068
3069 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3070
3071 // Process a data packet to cause the visitor's OnCanWrite to be invoked.
3072 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
QUICHE team8c1daa22019-03-13 08:33:41 -07003073 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
3074 QuicMakeUnique<TaggingEncrypter>(0x01));
zhongyi546cc452019-04-12 15:27:49 -07003075 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
3076 QuicMakeUnique<StrictTaggingDecrypter>(0x01));
nharper2c9f02a2019-05-08 10:25:50 -07003077 ProcessDataPacket(2);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003078
3079 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3080 EXPECT_FALSE(connection_.HasQueuedData());
3081
3082 // Parse the last packet and ensure it's an ack and two stream frames from
3083 // two different streams.
3084 if (GetParam().no_stop_waiting) {
3085 EXPECT_EQ(3u, writer_->frame_count());
3086 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
3087 } else {
3088 EXPECT_EQ(4u, writer_->frame_count());
3089 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3090 }
3091 EXPECT_FALSE(writer_->ack_frames().empty());
3092 ASSERT_EQ(2u, writer_->stream_frames().size());
3093 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3094 writer_->stream_frames()[0]->stream_id);
3095 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3096 writer_->stream_frames()[1]->stream_id);
3097}
3098
3099TEST_P(QuicConnectionTest, FramePackingSendv) {
nharper46833c32019-05-15 21:33:05 -07003100 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003101 // Send data in 1 packet by writing multiple blocks in a single iovector
3102 // using writev.
3103 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3104
3105 char data[] = "ABCDEF";
3106 struct iovec iov[2];
3107 iov[0].iov_base = data;
3108 iov[0].iov_len = 4;
3109 iov[1].iov_base = data + 4;
3110 iov[1].iov_len = 2;
nharper46833c32019-05-15 21:33:05 -07003111 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
3112 connection_.transport_version(), Perspective::IS_CLIENT);
3113 connection_.SaveAndSendStreamData(stream_id, iov, 2, 6, 0, NO_FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003114
3115 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3116 EXPECT_FALSE(connection_.HasQueuedData());
3117
3118 // Parse the last packet and ensure multiple iovector blocks have
3119 // been packed into a single stream frame from one stream.
nharper46833c32019-05-15 21:33:05 -07003120 EXPECT_EQ(1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003121 EXPECT_EQ(1u, writer_->stream_frames().size());
nharper46833c32019-05-15 21:33:05 -07003122 EXPECT_EQ(0u, writer_->padding_frames().size());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003123 QuicStreamFrame* frame = writer_->stream_frames()[0].get();
nharper46833c32019-05-15 21:33:05 -07003124 EXPECT_EQ(stream_id, frame->stream_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003125 EXPECT_EQ("ABCDEF", QuicStringPiece(frame->data_buffer, frame->data_length));
3126}
3127
3128TEST_P(QuicConnectionTest, FramePackingSendvQueued) {
nharper46833c32019-05-15 21:33:05 -07003129 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003130 // Try to send two stream frames in 1 packet by using writev.
3131 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3132
3133 BlockOnNextWrite();
3134 char data[] = "ABCDEF";
3135 struct iovec iov[2];
3136 iov[0].iov_base = data;
3137 iov[0].iov_len = 4;
3138 iov[1].iov_base = data + 4;
3139 iov[1].iov_len = 2;
nharper46833c32019-05-15 21:33:05 -07003140 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
3141 connection_.transport_version(), Perspective::IS_CLIENT);
3142 connection_.SaveAndSendStreamData(stream_id, iov, 2, 6, 0, NO_FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003143
3144 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3145 EXPECT_TRUE(connection_.HasQueuedData());
3146
3147 // Unblock the writes and actually send.
3148 writer_->SetWritable();
3149 connection_.OnCanWrite();
3150 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3151
3152 // Parse the last packet and ensure it's one stream frame from one stream.
nharper46833c32019-05-15 21:33:05 -07003153 EXPECT_EQ(1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003154 EXPECT_EQ(1u, writer_->stream_frames().size());
nharper46833c32019-05-15 21:33:05 -07003155 EXPECT_EQ(0u, writer_->padding_frames().size());
3156 EXPECT_EQ(stream_id, writer_->stream_frames()[0]->stream_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003157}
3158
3159TEST_P(QuicConnectionTest, SendingZeroBytes) {
3160 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3161 // Send a zero byte write with a fin using writev.
3162 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
nharper46833c32019-05-15 21:33:05 -07003163 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
3164 connection_.transport_version(), Perspective::IS_CLIENT);
3165 connection_.SaveAndSendStreamData(stream_id, nullptr, 0, 0, 0, FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003166
3167 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3168 EXPECT_FALSE(connection_.HasQueuedData());
3169
nharper55fa6132019-05-07 19:37:21 -07003170 // Padding frames are added by v99 to ensure a minimum packet size.
3171 size_t extra_padding_frames = 0;
3172 if (GetParam().version.HasHeaderProtection()) {
3173 extra_padding_frames = 1;
3174 }
3175
QUICHE teama6ef0a62019-03-07 20:34:33 -05003176 // Parse the last packet and ensure it's one stream frame from one stream.
nharper55fa6132019-05-07 19:37:21 -07003177 EXPECT_EQ(1u + extra_padding_frames, writer_->frame_count());
3178 EXPECT_EQ(extra_padding_frames, writer_->padding_frames().size());
3179 ASSERT_EQ(1u, writer_->stream_frames().size());
nharper46833c32019-05-15 21:33:05 -07003180 EXPECT_EQ(stream_id, writer_->stream_frames()[0]->stream_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003181 EXPECT_TRUE(writer_->stream_frames()[0]->fin);
3182}
3183
3184TEST_P(QuicConnectionTest, LargeSendWithPendingAck) {
3185 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3186 // Set the ack alarm by processing a ping frame.
3187 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3188
3189 // Processs a PING frame.
3190 ProcessFramePacket(QuicFrame(QuicPingFrame()));
3191 // Ensure that this has caused the ACK alarm to be set.
3192 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
3193 EXPECT_TRUE(ack_alarm->IsSet());
3194
3195 // Send data and ensure the ack is bundled.
3196 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(8);
3197 size_t len = 10000;
3198 std::unique_ptr<char[]> data_array(new char[len]);
3199 memset(data_array.get(), '?', len);
3200 struct iovec iov;
3201 iov.iov_base = data_array.get();
3202 iov.iov_len = len;
3203 QuicConsumedData consumed = connection_.SaveAndSendStreamData(
3204 QuicUtils::GetHeadersStreamId(connection_.transport_version()), &iov, 1,
3205 len, 0, FIN);
3206 EXPECT_EQ(len, consumed.bytes_consumed);
3207 EXPECT_TRUE(consumed.fin_consumed);
3208 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3209 EXPECT_FALSE(connection_.HasQueuedData());
3210
3211 // Parse the last packet and ensure it's one stream frame with a fin.
3212 EXPECT_EQ(1u, writer_->frame_count());
nharper55fa6132019-05-07 19:37:21 -07003213 ASSERT_EQ(1u, writer_->stream_frames().size());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003214 EXPECT_EQ(QuicUtils::GetHeadersStreamId(connection_.transport_version()),
3215 writer_->stream_frames()[0]->stream_id);
3216 EXPECT_TRUE(writer_->stream_frames()[0]->fin);
3217 // Ensure the ack alarm was cancelled when the ack was sent.
3218 EXPECT_FALSE(ack_alarm->IsSet());
3219}
3220
3221TEST_P(QuicConnectionTest, OnCanWrite) {
3222 // Visitor's OnCanWrite will send data, but will have more pending writes.
3223 EXPECT_CALL(visitor_, OnCanWrite())
3224 .WillOnce(DoAll(IgnoreResult(InvokeWithoutArgs(
3225 &connection_, &TestConnection::SendStreamData3)),
3226 IgnoreResult(InvokeWithoutArgs(
3227 &connection_, &TestConnection::SendStreamData5))));
3228 {
3229 InSequence seq;
3230 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillOnce(Return(true));
3231 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
3232 .WillRepeatedly(Return(false));
3233 }
3234
3235 EXPECT_CALL(*send_algorithm_, CanSend(_))
3236 .WillRepeatedly(testing::Return(true));
3237
3238 connection_.OnCanWrite();
3239
3240 // Parse the last packet and ensure it's the two stream frames from
3241 // two different streams.
3242 EXPECT_EQ(2u, writer_->frame_count());
3243 EXPECT_EQ(2u, writer_->stream_frames().size());
3244 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3245 writer_->stream_frames()[0]->stream_id);
3246 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3247 writer_->stream_frames()[1]->stream_id);
3248}
3249
3250TEST_P(QuicConnectionTest, RetransmitOnNack) {
3251 QuicPacketNumber last_packet;
3252 QuicByteCount second_packet_size;
3253 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet); // Packet 1
3254 second_packet_size =
3255 SendStreamDataToPeer(3, "foos", 3, NO_FIN, &last_packet); // Packet 2
3256 SendStreamDataToPeer(3, "fooos", 7, NO_FIN, &last_packet); // Packet 3
3257
3258 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3259
3260 // Don't lose a packet on an ack, and nothing is retransmitted.
3261 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3262 QuicAckFrame ack_one = InitAckFrame(1);
3263 ProcessAckPacket(&ack_one);
3264
3265 // Lose a packet and ensure it triggers retransmission.
3266 QuicAckFrame nack_two = ConstructAckFrame(3, 2);
3267 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003268 lost_packets.push_back(
3269 LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003270 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3271 .WillOnce(SetArgPointee<5>(lost_packets));
3272 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3273 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3274 EXPECT_FALSE(QuicPacketCreatorPeer::SendVersionInPacket(creator_));
3275 ProcessAckPacket(&nack_two);
3276}
3277
3278TEST_P(QuicConnectionTest, DoNotSendQueuedPacketForResetStream) {
3279 // Block the connection to queue the packet.
3280 BlockOnNextWrite();
3281
3282 QuicStreamId stream_id = 2;
3283 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
3284
3285 // Now that there is a queued packet, reset the stream.
3286 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
3287
3288 // Unblock the connection and verify that only the RST_STREAM is sent.
3289 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3290 writer_->SetWritable();
3291 connection_.OnCanWrite();
3292 if (!connection_.session_decides_what_to_write()) {
3293 // OnCanWrite will cause RST_STREAM be sent again.
3294 connection_.SendControlFrame(QuicFrame(new QuicRstStreamFrame(
3295 1, stream_id, QUIC_ERROR_PROCESSING_STREAM, 14)));
3296 }
nharper55fa6132019-05-07 19:37:21 -07003297 size_t padding_frame_count = writer_->padding_frames().size();
3298 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003299 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3300}
3301
3302TEST_P(QuicConnectionTest, SendQueuedPacketForQuicRstStreamNoError) {
3303 // Block the connection to queue the packet.
3304 BlockOnNextWrite();
3305
3306 QuicStreamId stream_id = 2;
3307 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
3308
3309 // Now that there is a queued packet, reset the stream.
3310 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 3);
3311
3312 // Unblock the connection and verify that the RST_STREAM is sent and the data
3313 // packet is sent.
3314 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(2));
3315 writer_->SetWritable();
3316 connection_.OnCanWrite();
3317 if (!connection_.session_decides_what_to_write()) {
3318 // OnCanWrite will cause RST_STREAM be sent again.
3319 connection_.SendControlFrame(QuicFrame(
3320 new QuicRstStreamFrame(1, stream_id, QUIC_STREAM_NO_ERROR, 14)));
3321 }
nharper55fa6132019-05-07 19:37:21 -07003322 size_t padding_frame_count = writer_->padding_frames().size();
3323 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003324 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3325}
3326
3327TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnNack) {
3328 QuicStreamId stream_id = 2;
3329 QuicPacketNumber last_packet;
3330 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3331 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3332 SendStreamDataToPeer(stream_id, "fooos", 7, NO_FIN, &last_packet);
3333
3334 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3335 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 12);
3336
3337 // Lose a packet and ensure it does not trigger retransmission.
3338 QuicAckFrame nack_two = ConstructAckFrame(last_packet, last_packet - 1);
3339 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3340 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3341 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3342 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3343 ProcessAckPacket(&nack_two);
3344}
3345
3346TEST_P(QuicConnectionTest, RetransmitForQuicRstStreamNoErrorOnNack) {
3347 QuicStreamId stream_id = 2;
3348 QuicPacketNumber last_packet;
3349 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3350 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3351 SendStreamDataToPeer(stream_id, "fooos", 7, NO_FIN, &last_packet);
3352
3353 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3354 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 12);
3355
3356 // Lose a packet, ensure it triggers retransmission.
3357 QuicAckFrame nack_two = ConstructAckFrame(last_packet, last_packet - 1);
3358 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3359 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003360 lost_packets.push_back(LostPacket(last_packet - 1, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003361 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3362 .WillOnce(SetArgPointee<5>(lost_packets));
3363 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3364 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
3365 ProcessAckPacket(&nack_two);
3366}
3367
3368TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnRTO) {
3369 QuicStreamId stream_id = 2;
3370 QuicPacketNumber last_packet;
3371 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3372
3373 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3374 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
3375
3376 // Fire the RTO and verify that the RST_STREAM is resent, not stream data.
3377 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3378 clock_.AdvanceTime(DefaultRetransmissionTime());
3379 connection_.GetRetransmissionAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07003380 size_t padding_frame_count = writer_->padding_frames().size();
3381 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003382 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3383 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
3384}
3385
3386// Ensure that if the only data in flight is non-retransmittable, the
3387// retransmission alarm is not set.
3388TEST_P(QuicConnectionTest, CancelRetransmissionAlarmAfterResetStream) {
3389 QuicStreamId stream_id = 2;
3390 QuicPacketNumber last_data_packet;
3391 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
3392
3393 // Cancel the stream.
3394 const QuicPacketNumber rst_packet = last_data_packet + 1;
3395 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, rst_packet, _, _)).Times(1);
3396 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
3397
3398 // Ack the RST_STREAM frame (since it's retransmittable), but not the data
3399 // packet, which is no longer retransmittable since the stream was cancelled.
3400 QuicAckFrame nack_stream_data =
3401 ConstructAckFrame(rst_packet, last_data_packet);
3402 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3403 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3404 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3405 ProcessAckPacket(&nack_stream_data);
3406
3407 // Ensure that the data is still in flight, but the retransmission alarm is no
3408 // longer set.
ianswett9f459cb2019-04-21 06:39:59 -07003409 EXPECT_GT(manager_->GetBytesInFlight(), 0u);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003410 if (GetQuicReloadableFlag(quic_optimize_inflight_check)) {
3411 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3412 // Firing the alarm should remove all bytes_in_flight.
3413 connection_.GetRetransmissionAlarm()->Fire();
ianswett9f459cb2019-04-21 06:39:59 -07003414 EXPECT_EQ(0u, manager_->GetBytesInFlight());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003415 }
3416 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3417}
3418
3419TEST_P(QuicConnectionTest, RetransmitForQuicRstStreamNoErrorOnRTO) {
3420 connection_.SetMaxTailLossProbes(0);
3421
3422 QuicStreamId stream_id = 2;
3423 QuicPacketNumber last_packet;
3424 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3425
3426 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3427 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 3);
3428
3429 // Fire the RTO and verify that the RST_STREAM is resent, the stream data
3430 // is sent.
3431 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(2));
3432 clock_.AdvanceTime(DefaultRetransmissionTime());
3433 connection_.GetRetransmissionAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07003434 size_t padding_frame_count = writer_->padding_frames().size();
3435 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003436 ASSERT_EQ(1u, writer_->rst_stream_frames().size());
3437 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
3438}
3439
3440TEST_P(QuicConnectionTest, DoNotSendPendingRetransmissionForResetStream) {
3441 QuicStreamId stream_id = 2;
3442 QuicPacketNumber last_packet;
3443 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3444 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3445 BlockOnNextWrite();
3446 connection_.SendStreamDataWithString(stream_id, "fooos", 7, NO_FIN);
3447
3448 // Lose a packet which will trigger a pending retransmission.
3449 QuicAckFrame ack = ConstructAckFrame(last_packet, last_packet - 1);
3450 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3451 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3452 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3453 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3454 ProcessAckPacket(&ack);
3455
3456 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 12);
3457
3458 // Unblock the connection and verify that the RST_STREAM is sent but not the
3459 // second data packet nor a retransmit.
3460 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3461 writer_->SetWritable();
3462 connection_.OnCanWrite();
3463 if (!connection_.session_decides_what_to_write()) {
3464 // OnCanWrite will cause this RST_STREAM_FRAME be sent again.
3465 connection_.SendControlFrame(QuicFrame(new QuicRstStreamFrame(
3466 1, stream_id, QUIC_ERROR_PROCESSING_STREAM, 14)));
3467 }
nharper55fa6132019-05-07 19:37:21 -07003468 size_t padding_frame_count = writer_->padding_frames().size();
3469 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
zhongyi546cc452019-04-12 15:27:49 -07003470 ASSERT_EQ(1u, writer_->rst_stream_frames().size());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003471 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
3472}
3473
3474TEST_P(QuicConnectionTest, SendPendingRetransmissionForQuicRstStreamNoError) {
3475 QuicStreamId stream_id = 2;
3476 QuicPacketNumber last_packet;
3477 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3478 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3479 BlockOnNextWrite();
3480 connection_.SendStreamDataWithString(stream_id, "fooos", 7, NO_FIN);
3481
3482 // Lose a packet which will trigger a pending retransmission.
3483 QuicAckFrame ack = ConstructAckFrame(last_packet, last_packet - 1);
3484 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3485 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003486 lost_packets.push_back(LostPacket(last_packet - 1, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003487 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3488 .WillOnce(SetArgPointee<5>(lost_packets));
3489 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3490 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3491 ProcessAckPacket(&ack);
3492
3493 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 12);
3494
3495 // Unblock the connection and verify that the RST_STREAM is sent and the
3496 // second data packet or a retransmit is sent.
3497 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(2));
3498 writer_->SetWritable();
3499 connection_.OnCanWrite();
3500 // The RST_STREAM_FRAME is sent after queued packets and pending
3501 // retransmission.
3502 connection_.SendControlFrame(QuicFrame(
3503 new QuicRstStreamFrame(1, stream_id, QUIC_STREAM_NO_ERROR, 14)));
nharper55fa6132019-05-07 19:37:21 -07003504 size_t padding_frame_count = writer_->padding_frames().size();
3505 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003506 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3507}
3508
3509TEST_P(QuicConnectionTest, RetransmitAckedPacket) {
3510 QuicPacketNumber last_packet;
3511 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
3512 SendStreamDataToPeer(1, "foos", 3, NO_FIN, &last_packet); // Packet 2
3513 SendStreamDataToPeer(1, "fooos", 7, NO_FIN, &last_packet); // Packet 3
3514
3515 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3516
3517 // Instigate a loss with an ack.
3518 QuicAckFrame nack_two = ConstructAckFrame(3, 2);
3519 // The first nack should trigger a fast retransmission, but we'll be
3520 // write blocked, so the packet will be queued.
3521 BlockOnNextWrite();
3522
3523 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003524 lost_packets.push_back(
3525 LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003526 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3527 .WillOnce(SetArgPointee<5>(lost_packets));
3528 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3529 ProcessAckPacket(&nack_two);
3530 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3531
3532 // Now, ack the previous transmission.
3533 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3534 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(false, _, _, _, _));
3535 QuicAckFrame ack_all = InitAckFrame(3);
3536 ProcessAckPacket(&ack_all);
3537
3538 // Unblock the socket and attempt to send the queued packets. We will always
3539 // send the retransmission.
3540 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _))
3541 .Times(1);
3542
3543 writer_->SetWritable();
3544 connection_.OnCanWrite();
3545
3546 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3547 // We do not store retransmittable frames of this retransmission.
3548 EXPECT_FALSE(QuicConnectionPeer::HasRetransmittableFrames(&connection_, 4));
3549}
3550
3551TEST_P(QuicConnectionTest, RetransmitNackedLargestObserved) {
3552 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3553 QuicPacketNumber original, second;
3554
3555 QuicByteCount packet_size =
3556 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &original); // 1st packet.
3557 SendStreamDataToPeer(3, "bar", 3, NO_FIN, &second); // 2nd packet.
3558
3559 QuicAckFrame frame = InitAckFrame({{second, second + 1}});
3560 // The first nack should retransmit the largest observed packet.
3561 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003562 lost_packets.push_back(LostPacket(original, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003563 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3564 .WillOnce(SetArgPointee<5>(lost_packets));
3565 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3566 // Packet 1 is short header for IETF QUIC because the encryption level
3567 // switched to ENCRYPTION_FORWARD_SECURE in SendStreamDataToPeer.
fayangd4291e42019-05-30 10:31:21 -07003568 EXPECT_CALL(*send_algorithm_,
3569 OnPacketSent(_, _, _,
3570 VersionHasIetfInvariantHeader(
3571 GetParam().version.transport_version)
3572 ? packet_size
3573 : packet_size - kQuicVersionSize,
3574 _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003575 ProcessAckPacket(&frame);
3576}
3577
3578TEST_P(QuicConnectionTest, QueueAfterTwoRTOs) {
3579 connection_.SetMaxTailLossProbes(0);
3580
3581 for (int i = 0; i < 10; ++i) {
3582 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3583 connection_.SendStreamDataWithString(3, "foo", i * 3, NO_FIN);
3584 }
3585
3586 // Block the writer and ensure they're queued.
3587 BlockOnNextWrite();
3588 clock_.AdvanceTime(DefaultRetransmissionTime());
3589 // Only one packet should be retransmitted.
3590 connection_.GetRetransmissionAlarm()->Fire();
3591 EXPECT_TRUE(connection_.HasQueuedData());
3592
3593 // Unblock the writer.
3594 writer_->SetWritable();
3595 clock_.AdvanceTime(QuicTime::Delta::FromMicroseconds(
3596 2 * DefaultRetransmissionTime().ToMicroseconds()));
3597 // Retransmit already retransmitted packets event though the packet number
3598 // greater than the largest observed.
3599 if (connection_.session_decides_what_to_write()) {
3600 // 2 RTOs + 1 TLP.
3601 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
3602 } else {
3603 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3604 }
3605 connection_.GetRetransmissionAlarm()->Fire();
3606 connection_.OnCanWrite();
3607}
3608
3609TEST_P(QuicConnectionTest, WriteBlockedBufferedThenSent) {
3610 BlockOnNextWrite();
3611 writer_->set_is_write_blocked_data_buffered(true);
3612 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3613 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3614 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3615
3616 writer_->SetWritable();
3617 connection_.OnCanWrite();
3618 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3619}
3620
3621TEST_P(QuicConnectionTest, WriteBlockedThenSent) {
3622 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3623 BlockOnNextWrite();
3624 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3625 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3626 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3627
3628 // The second packet should also be queued, in order to ensure packets are
3629 // never sent out of order.
3630 writer_->SetWritable();
3631 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3632 EXPECT_EQ(2u, connection_.NumQueuedPackets());
3633
3634 // Now both are sent in order when we unblock.
3635 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3636 connection_.OnCanWrite();
3637 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3638}
3639
3640TEST_P(QuicConnectionTest, RetransmitWriteBlockedAckedOriginalThenSent) {
3641 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3642 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
3643 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3644
3645 BlockOnNextWrite();
3646 writer_->set_is_write_blocked_data_buffered(true);
3647 // Simulate the retransmission alarm firing.
3648 clock_.AdvanceTime(DefaultRetransmissionTime());
3649 connection_.GetRetransmissionAlarm()->Fire();
3650
3651 // Ack the sent packet before the callback returns, which happens in
3652 // rare circumstances with write blocked sockets.
3653 QuicAckFrame ack = InitAckFrame(1);
3654 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3655 ProcessAckPacket(&ack);
3656
3657 writer_->SetWritable();
3658 connection_.OnCanWrite();
3659 // There is now a pending packet, but with no retransmittable frames.
3660 if (GetQuicReloadableFlag(quic_optimize_inflight_check)) {
3661 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3662 // Firing the alarm should remove all bytes_in_flight.
3663 connection_.GetRetransmissionAlarm()->Fire();
ianswett9f459cb2019-04-21 06:39:59 -07003664 EXPECT_EQ(0u, manager_->GetBytesInFlight());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003665 }
3666 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3667 EXPECT_FALSE(QuicConnectionPeer::HasRetransmittableFrames(&connection_, 2));
3668}
3669
3670TEST_P(QuicConnectionTest, AlarmsWhenWriteBlocked) {
3671 // Block the connection.
3672 BlockOnNextWrite();
3673 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
3674 EXPECT_EQ(1u, writer_->packets_write_attempts());
3675 EXPECT_TRUE(writer_->IsWriteBlocked());
3676
3677 // Set the send alarm. Fire the alarm and ensure it doesn't attempt to write.
3678 connection_.GetSendAlarm()->Set(clock_.ApproximateNow());
3679 connection_.GetSendAlarm()->Fire();
3680 EXPECT_TRUE(writer_->IsWriteBlocked());
3681 EXPECT_EQ(1u, writer_->packets_write_attempts());
3682}
3683
3684TEST_P(QuicConnectionTest, NoSendAlarmAfterProcessPacketWhenWriteBlocked) {
3685 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3686
3687 // Block the connection.
3688 BlockOnNextWrite();
3689 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
3690 EXPECT_TRUE(writer_->IsWriteBlocked());
3691 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3692 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
3693
3694 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3695 // Process packet number 1. Can not call ProcessPacket or ProcessDataPacket
3696 // here, because they will fire the alarm after QuicConnection::ProcessPacket
3697 // is returned.
3698 const uint64_t received_packet_num = 1;
3699 const bool has_stop_waiting = false;
QUICHE team6987b4a2019-03-15 16:23:04 -07003700 const EncryptionLevel level = ENCRYPTION_INITIAL;
QUICHE team8c1daa22019-03-13 08:33:41 -07003701 std::unique_ptr<QuicPacket> packet(ConstructDataPacket(
nharper46833c32019-05-15 21:33:05 -07003702 received_packet_num, has_stop_waiting, ENCRYPTION_FORWARD_SECURE));
dschinazi66dea072019-04-09 11:41:06 -07003703 char buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05003704 size_t encrypted_length =
3705 peer_framer_.EncryptPayload(level, QuicPacketNumber(received_packet_num),
dschinazi66dea072019-04-09 11:41:06 -07003706 *packet, buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003707 connection_.ProcessUdpPacket(
3708 kSelfAddress, kPeerAddress,
3709 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
3710
3711 EXPECT_TRUE(writer_->IsWriteBlocked());
3712 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
3713}
3714
3715TEST_P(QuicConnectionTest, AddToWriteBlockedListIfWriterBlockedWhenProcessing) {
3716 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3717 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
3718
3719 // Simulate the case where a shared writer gets blocked by another connection.
3720 writer_->SetWriteBlocked();
3721
3722 // Process an ACK, make sure the connection calls visitor_->OnWriteBlocked().
3723 QuicAckFrame ack1 = InitAckFrame(1);
3724 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
3725 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
3726 ProcessAckPacket(1, &ack1);
3727}
3728
3729TEST_P(QuicConnectionTest, DoNotAddToWriteBlockedListAfterDisconnect) {
3730 writer_->SetBatchMode(true);
3731 EXPECT_TRUE(connection_.connected());
3732 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, _,
3733 ConnectionCloseSource::FROM_SELF));
3734
3735 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
3736
3737 {
3738 QuicConnection::ScopedPacketFlusher flusher(&connection_,
3739 QuicConnection::NO_ACK);
3740 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
3741 ConnectionCloseBehavior::SILENT_CLOSE);
3742
3743 EXPECT_FALSE(connection_.connected());
3744 writer_->SetWriteBlocked();
3745 }
3746}
3747
3748TEST_P(QuicConnectionTest, AddToWriteBlockedListIfBlockedOnFlushPackets) {
3749 writer_->SetBatchMode(true);
3750 writer_->BlockOnNextFlush();
3751
3752 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
3753 {
3754 QuicConnection::ScopedPacketFlusher flusher(&connection_,
3755 QuicConnection::NO_ACK);
3756 // flusher's destructor will call connection_.FlushPackets, which should add
3757 // the connection to the write blocked list.
3758 }
3759}
3760
3761TEST_P(QuicConnectionTest, NoLimitPacketsPerNack) {
3762 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3763 int offset = 0;
3764 // Send packets 1 to 15.
3765 for (int i = 0; i < 15; ++i) {
3766 SendStreamDataToPeer(1, "foo", offset, NO_FIN, nullptr);
3767 offset += 3;
3768 }
3769
3770 // Ack 15, nack 1-14.
3771
3772 QuicAckFrame nack =
3773 InitAckFrame({{QuicPacketNumber(15), QuicPacketNumber(16)}});
3774
3775 // 14 packets have been NACK'd and lost.
3776 LostPacketVector lost_packets;
3777 for (int i = 1; i < 15; ++i) {
dschinazi66dea072019-04-09 11:41:06 -07003778 lost_packets.push_back(
3779 LostPacket(QuicPacketNumber(i), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003780 }
3781 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3782 .WillOnce(SetArgPointee<5>(lost_packets));
3783 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3784 if (connection_.session_decides_what_to_write()) {
3785 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3786 } else {
3787 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(14);
3788 }
3789 ProcessAckPacket(&nack);
3790}
3791
3792// Test sending multiple acks from the connection to the session.
3793TEST_P(QuicConnectionTest, MultipleAcks) {
QUICHE teamcd098022019-03-22 18:49:55 -07003794 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3795 return;
3796 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003797 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3798 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3799 ProcessDataPacket(1);
3800 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
3801 QuicPacketNumber last_packet;
3802 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
3803 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
3804 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet); // Packet 2
3805 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
3806 SendAckPacketToPeer(); // Packet 3
3807 SendStreamDataToPeer(5, "foo", 0, NO_FIN, &last_packet); // Packet 4
3808 EXPECT_EQ(QuicPacketNumber(4u), last_packet);
3809 SendStreamDataToPeer(1, "foo", 3, NO_FIN, &last_packet); // Packet 5
3810 EXPECT_EQ(QuicPacketNumber(5u), last_packet);
3811 SendStreamDataToPeer(3, "foo", 3, NO_FIN, &last_packet); // Packet 6
3812 EXPECT_EQ(QuicPacketNumber(6u), last_packet);
3813
3814 // Client will ack packets 1, 2, [!3], 4, 5.
3815 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3816 QuicAckFrame frame1 = ConstructAckFrame(5, 3);
3817 ProcessAckPacket(&frame1);
3818
3819 // Now the client implicitly acks 3, and explicitly acks 6.
3820 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3821 QuicAckFrame frame2 = InitAckFrame(6);
3822 ProcessAckPacket(&frame2);
3823}
3824
3825TEST_P(QuicConnectionTest, DontLatchUnackedPacket) {
QUICHE teamcd098022019-03-22 18:49:55 -07003826 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3827 return;
3828 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003829 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3830 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3831 ProcessDataPacket(1);
3832 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
3833 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr); // Packet 1;
3834 // From now on, we send acks, so the send algorithm won't mark them pending.
3835 SendAckPacketToPeer(); // Packet 2
3836
3837 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3838 QuicAckFrame frame = InitAckFrame(1);
3839 ProcessAckPacket(&frame);
3840
3841 // Verify that our internal state has least-unacked as 2, because we're still
3842 // waiting for a potential ack for 2.
3843
3844 EXPECT_EQ(QuicPacketNumber(2u), stop_waiting()->least_unacked);
3845
3846 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3847 frame = InitAckFrame(2);
3848 ProcessAckPacket(&frame);
3849 EXPECT_EQ(QuicPacketNumber(3u), stop_waiting()->least_unacked);
3850
3851 // When we send an ack, we make sure our least-unacked makes sense. In this
3852 // case since we're not waiting on an ack for 2 and all packets are acked, we
3853 // set it to 3.
3854 SendAckPacketToPeer(); // Packet 3
3855 // Least_unacked remains at 3 until another ack is received.
3856 EXPECT_EQ(QuicPacketNumber(3u), stop_waiting()->least_unacked);
3857 if (GetParam().no_stop_waiting) {
3858 // Expect no stop waiting frame is sent.
3859 EXPECT_FALSE(least_unacked().IsInitialized());
3860 } else {
3861 // Check that the outgoing ack had its packet number as least_unacked.
3862 EXPECT_EQ(QuicPacketNumber(3u), least_unacked());
3863 }
3864
3865 // Ack the ack, which updates the rtt and raises the least unacked.
3866 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3867 frame = InitAckFrame(3);
3868 ProcessAckPacket(&frame);
3869
3870 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr); // Packet 4
3871 EXPECT_EQ(QuicPacketNumber(4u), stop_waiting()->least_unacked);
3872 SendAckPacketToPeer(); // Packet 5
3873 if (GetParam().no_stop_waiting) {
3874 // Expect no stop waiting frame is sent.
3875 EXPECT_FALSE(least_unacked().IsInitialized());
3876 } else {
3877 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
3878 }
3879
3880 // Send two data packets at the end, and ensure if the last one is acked,
3881 // the least unacked is raised above the ack packets.
3882 SendStreamDataToPeer(1, "bar", 6, NO_FIN, nullptr); // Packet 6
3883 SendStreamDataToPeer(1, "bar", 9, NO_FIN, nullptr); // Packet 7
3884
3885 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3886 frame = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(5)},
3887 {QuicPacketNumber(7), QuicPacketNumber(8)}});
3888 ProcessAckPacket(&frame);
3889
3890 EXPECT_EQ(QuicPacketNumber(6u), stop_waiting()->least_unacked);
3891}
3892
3893TEST_P(QuicConnectionTest, TLP) {
3894 connection_.SetMaxTailLossProbes(1);
3895
3896 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
3897 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
3898 QuicTime retransmission_time =
3899 connection_.GetRetransmissionAlarm()->deadline();
3900 EXPECT_NE(QuicTime::Zero(), retransmission_time);
3901
3902 EXPECT_EQ(QuicPacketNumber(1u), writer_->header().packet_number);
3903 // Simulate the retransmission alarm firing and sending a tlp,
3904 // so send algorithm's OnRetransmissionTimeout is not called.
3905 clock_.AdvanceTime(retransmission_time - clock_.Now());
3906 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
3907 connection_.GetRetransmissionAlarm()->Fire();
3908 EXPECT_EQ(QuicPacketNumber(2u), writer_->header().packet_number);
3909 // We do not raise the high water mark yet.
3910 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
3911}
3912
zhongyifbb25772019-04-10 16:54:08 -07003913TEST_P(QuicConnectionTest, TailLossProbeDelayForStreamDataInTLPR) {
zhongyifbb25772019-04-10 16:54:08 -07003914 // Set TLPR from QuicConfig.
3915 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3916 QuicConfig config;
3917 QuicTagVector options;
3918 options.push_back(kTLPR);
3919 config.SetConnectionOptionsToSend(options);
3920 connection_.SetFromConfig(config);
3921 connection_.SetMaxTailLossProbes(1);
3922
3923 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
3924 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
3925
3926 QuicTime retransmission_time =
3927 connection_.GetRetransmissionAlarm()->deadline();
3928 EXPECT_NE(QuicTime::Zero(), retransmission_time);
3929 QuicTime::Delta expected_tlp_delay =
3930 0.5 * manager_->GetRttStats()->SmoothedOrInitialRtt();
3931 EXPECT_EQ(expected_tlp_delay, retransmission_time - clock_.Now());
3932
3933 EXPECT_EQ(QuicPacketNumber(1u), writer_->header().packet_number);
3934 // Simulate firing of the retransmission alarm and retransmit the packet.
3935 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
3936 clock_.AdvanceTime(retransmission_time - clock_.Now());
3937 connection_.GetRetransmissionAlarm()->Fire();
3938 EXPECT_EQ(QuicPacketNumber(2u), writer_->header().packet_number);
3939
3940 // We do not raise the high water mark yet.
3941 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
3942}
3943
3944TEST_P(QuicConnectionTest, TailLossProbeDelayForNonStreamDataInTLPR) {
zhongyifbb25772019-04-10 16:54:08 -07003945 // Set TLPR from QuicConfig.
3946 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3947 QuicConfig config;
3948 QuicTagVector options;
3949 options.push_back(kTLPR);
3950 config.SetConnectionOptionsToSend(options);
3951 connection_.SetFromConfig(config);
3952 connection_.SetMaxTailLossProbes(1);
3953
3954 // Sets retransmittable on wire.
3955 const QuicTime::Delta retransmittable_on_wire_timeout =
3956 QuicTime::Delta::FromMilliseconds(50);
3957 connection_.set_retransmittable_on_wire_timeout(
3958 retransmittable_on_wire_timeout);
3959
3960 EXPECT_TRUE(connection_.connected());
3961 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
3962 .WillRepeatedly(Return(true));
3963 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
3964 EXPECT_FALSE(connection_.IsPathDegrading());
3965 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
3966
3967 const char data[] = "data";
3968 size_t data_size = strlen(data);
3969 QuicStreamOffset offset = 0;
3970
3971 // Send a data packet.
3972 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
3973 offset += data_size;
3974
3975 // Path degrading alarm should be set when there is a retransmittable packet
3976 // on the wire.
3977 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
3978
3979 // Verify the path degrading delay.
3980 // First TLP with stream data.
3981 QuicTime::Delta srtt = manager_->GetRttStats()->SmoothedOrInitialRtt();
3982 QuicTime::Delta expected_delay = 0.5 * srtt;
3983 // Add 1st RTO.
3984 QuicTime::Delta retransmission_delay =
3985 QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
3986 expected_delay = expected_delay + retransmission_delay;
3987 // Add 2nd RTO.
3988 expected_delay = expected_delay + retransmission_delay * 2;
3989 EXPECT_EQ(expected_delay,
3990 QuicConnectionPeer::GetSentPacketManager(&connection_)
3991 ->GetPathDegradingDelay());
3992 ASSERT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
3993
3994 // The ping alarm is set for the ping timeout, not the shorter
3995 // retransmittable_on_wire_timeout.
3996 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
3997 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
3998 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
3999
4000 // Receive an ACK for the data packet.
4001 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4002 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4003 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4004 QuicAckFrame frame =
4005 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
4006 ProcessAckPacket(&frame);
4007
4008 // Path degrading alarm should be cancelled as there is no more
4009 // reretransmittable packets on the wire.
4010 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
4011 // The ping alarm should be set to the retransmittable_on_wire_timeout.
4012 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4013 EXPECT_EQ(retransmittable_on_wire_timeout,
4014 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
4015
4016 // Simulate firing of the retransmittable on wire and send a PING.
4017 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
4018 clock_.AdvanceTime(retransmittable_on_wire_timeout);
4019 connection_.GetPingAlarm()->Fire();
4020
4021 // The retransmission alarm and the path degrading alarm should be set as
4022 // there is a retransmittable packet (PING) on the wire,
4023 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4024 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
4025
4026 // Verify the retransmission delay.
4027 QuicTime::Delta min_rto_timeout =
4028 QuicTime::Delta::FromMilliseconds(kMinRetransmissionTimeMs);
4029 srtt = manager_->GetRttStats()->SmoothedOrInitialRtt();
4030 if (GetQuicReloadableFlag(quic_ignore_tlpr_if_sending_ping)) {
4031 // First TLP without unacked stream data will no longer use TLPR.
4032 expected_delay = std::max(2 * srtt, 1.5 * srtt + 0.5 * min_rto_timeout);
4033 } else {
4034 expected_delay =
4035 std::max(QuicTime::Delta::FromMilliseconds(kMinTailLossProbeTimeoutMs),
4036 srtt * 0.5);
4037 }
4038 EXPECT_EQ(expected_delay,
4039 connection_.GetRetransmissionAlarm()->deadline() - clock_.Now());
4040
4041 // Verify the path degrading delay.
4042 // Path degrading delay will count TLPR for the tail loss probe delay.
4043 expected_delay =
4044 std::max(QuicTime::Delta::FromMilliseconds(kMinTailLossProbeTimeoutMs),
4045 srtt * 0.5);
4046 // Add 1st RTO.
4047 retransmission_delay =
4048 std::max(manager_->GetRttStats()->smoothed_rtt() +
4049 4 * manager_->GetRttStats()->mean_deviation(),
4050 min_rto_timeout);
4051 expected_delay = expected_delay + retransmission_delay;
4052 // Add 2nd RTO.
4053 expected_delay = expected_delay + retransmission_delay * 2;
4054 EXPECT_EQ(expected_delay,
4055 QuicConnectionPeer::GetSentPacketManager(&connection_)
4056 ->GetPathDegradingDelay());
4057
4058 // The ping alarm is set for the ping timeout, not the shorter
4059 // retransmittable_on_wire_timeout.
4060 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4061 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
4062 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
4063}
4064
QUICHE teama6ef0a62019-03-07 20:34:33 -05004065TEST_P(QuicConnectionTest, RTO) {
4066 connection_.SetMaxTailLossProbes(0);
4067
4068 QuicTime default_retransmission_time =
4069 clock_.ApproximateNow() + DefaultRetransmissionTime();
4070 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
4071 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4072
4073 EXPECT_EQ(QuicPacketNumber(1u), writer_->header().packet_number);
4074 EXPECT_EQ(default_retransmission_time,
4075 connection_.GetRetransmissionAlarm()->deadline());
4076 // Simulate the retransmission alarm firing.
4077 clock_.AdvanceTime(DefaultRetransmissionTime());
4078 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
4079 connection_.GetRetransmissionAlarm()->Fire();
4080 EXPECT_EQ(QuicPacketNumber(2u), writer_->header().packet_number);
4081 // We do not raise the high water mark yet.
4082 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4083}
4084
4085TEST_P(QuicConnectionTest, RetransmitWithSameEncryptionLevel) {
4086 use_tagging_decrypter();
4087
4088 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
4089 // the end of the packet. We can test this to check which encrypter was used.
QUICHE team6987b4a2019-03-15 16:23:04 -07004090 connection_.SetEncrypter(ENCRYPTION_INITIAL,
QUICHE teama6ef0a62019-03-07 20:34:33 -05004091 QuicMakeUnique<TaggingEncrypter>(0x01));
nharper46833c32019-05-15 21:33:05 -07004092 QuicByteCount packet_size;
4093 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4094 .WillOnce(SaveArg<3>(&packet_size));
4095 connection_.SendCryptoDataWithString("foo", 0);
4096 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004097 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
4098
4099 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
4100 QuicMakeUnique<TaggingEncrypter>(0x02));
4101 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4102 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
4103 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
4104
4105 {
4106 InSequence s;
4107 EXPECT_CALL(*send_algorithm_,
4108 OnPacketSent(_, _, QuicPacketNumber(3), _, _));
4109 EXPECT_CALL(*send_algorithm_,
4110 OnPacketSent(_, _, QuicPacketNumber(4), _, _));
4111 }
4112
4113 // Manually mark both packets for retransmission.
4114 connection_.RetransmitUnackedPackets(ALL_UNACKED_RETRANSMISSION);
4115
QUICHE team6987b4a2019-03-15 16:23:04 -07004116 // Packet should have been sent with ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05004117 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_previous_packet());
4118
4119 // Packet should have been sent with ENCRYPTION_ZERO_RTT.
4120 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
4121}
4122
4123TEST_P(QuicConnectionTest, SendHandshakeMessages) {
4124 use_tagging_decrypter();
4125 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
4126 // the end of the packet. We can test this to check which encrypter was used.
QUICHE team6987b4a2019-03-15 16:23:04 -07004127 connection_.SetEncrypter(ENCRYPTION_INITIAL,
QUICHE teama6ef0a62019-03-07 20:34:33 -05004128 QuicMakeUnique<TaggingEncrypter>(0x01));
4129
4130 // Attempt to send a handshake message and have the socket block.
4131 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
4132 BlockOnNextWrite();
nharper46833c32019-05-15 21:33:05 -07004133 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004134 // The packet should be serialized, but not queued.
4135 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4136
4137 // Switch to the new encrypter.
4138 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
4139 QuicMakeUnique<TaggingEncrypter>(0x02));
4140 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4141
4142 // Now become writeable and flush the packets.
4143 writer_->SetWritable();
4144 EXPECT_CALL(visitor_, OnCanWrite());
4145 connection_.OnCanWrite();
4146 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4147
4148 // Verify that the handshake packet went out at the null encryption.
4149 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
4150}
4151
4152TEST_P(QuicConnectionTest,
4153 DropRetransmitsForNullEncryptedPacketAfterForwardSecure) {
4154 use_tagging_decrypter();
QUICHE team6987b4a2019-03-15 16:23:04 -07004155 connection_.SetEncrypter(ENCRYPTION_INITIAL,
QUICHE teama6ef0a62019-03-07 20:34:33 -05004156 QuicMakeUnique<TaggingEncrypter>(0x01));
4157 QuicPacketNumber packet_number;
4158 connection_.SendCryptoStreamData();
4159
4160 // Simulate the retransmission alarm firing and the socket blocking.
4161 BlockOnNextWrite();
4162 clock_.AdvanceTime(DefaultRetransmissionTime());
4163 connection_.GetRetransmissionAlarm()->Fire();
4164
4165 // Go forward secure.
4166 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
4167 QuicMakeUnique<TaggingEncrypter>(0x02));
4168 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4169 notifier_.NeuterUnencryptedData();
4170 connection_.NeuterUnencryptedPackets();
4171
4172 EXPECT_EQ(QuicTime::Zero(), connection_.GetRetransmissionAlarm()->deadline());
4173 // Unblock the socket and ensure that no packets are sent.
4174 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4175 writer_->SetWritable();
4176 connection_.OnCanWrite();
4177}
4178
4179TEST_P(QuicConnectionTest, RetransmitPacketsWithInitialEncryption) {
4180 use_tagging_decrypter();
QUICHE team6987b4a2019-03-15 16:23:04 -07004181 connection_.SetEncrypter(ENCRYPTION_INITIAL,
QUICHE teama6ef0a62019-03-07 20:34:33 -05004182 QuicMakeUnique<TaggingEncrypter>(0x01));
QUICHE team6987b4a2019-03-15 16:23:04 -07004183 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004184
nharper46833c32019-05-15 21:33:05 -07004185 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004186
4187 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
4188 QuicMakeUnique<TaggingEncrypter>(0x02));
4189 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4190
4191 SendStreamDataToPeer(2, "bar", 0, NO_FIN, nullptr);
4192 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4193
4194 connection_.RetransmitUnackedPackets(ALL_INITIAL_RETRANSMISSION);
4195}
4196
4197TEST_P(QuicConnectionTest, BufferNonDecryptablePackets) {
QUICHE teamcd098022019-03-22 18:49:55 -07004198 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4199 return;
4200 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004201 // SetFromConfig is always called after construction from InitializeSession.
4202 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4203 QuicConfig config;
4204 connection_.SetFromConfig(config);
4205 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4206 use_tagging_decrypter();
4207
4208 const uint8_t tag = 0x07;
4209 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
4210 QuicMakeUnique<TaggingEncrypter>(tag));
4211
4212 // Process an encrypted packet which can not yet be decrypted which should
4213 // result in the packet being buffered.
4214 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4215
4216 // Transition to the new encryption state and process another encrypted packet
4217 // which should result in the original packet being processed.
zhongyi546cc452019-04-12 15:27:49 -07004218 SetDecrypter(ENCRYPTION_ZERO_RTT,
4219 QuicMakeUnique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004220 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4221 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
4222 QuicMakeUnique<TaggingEncrypter>(tag));
4223 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(2);
4224 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4225
4226 // Finally, process a third packet and note that we do not reprocess the
4227 // buffered packet.
4228 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4229 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4230}
4231
4232TEST_P(QuicConnectionTest, TestRetransmitOrder) {
4233 connection_.SetMaxTailLossProbes(0);
4234
4235 QuicByteCount first_packet_size;
4236 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4237 .WillOnce(SaveArg<3>(&first_packet_size));
4238
4239 connection_.SendStreamDataWithString(3, "first_packet", 0, NO_FIN);
4240 QuicByteCount second_packet_size;
4241 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4242 .WillOnce(SaveArg<3>(&second_packet_size));
4243 connection_.SendStreamDataWithString(3, "second_packet", 12, NO_FIN);
4244 EXPECT_NE(first_packet_size, second_packet_size);
4245 // Advance the clock by huge time to make sure packets will be retransmitted.
4246 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
4247 {
4248 InSequence s;
4249 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, first_packet_size, _));
4250 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, second_packet_size, _));
4251 }
4252 connection_.GetRetransmissionAlarm()->Fire();
4253
4254 // Advance again and expect the packets to be sent again in the same order.
4255 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(20));
4256 {
4257 InSequence s;
4258 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, first_packet_size, _));
4259 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, second_packet_size, _));
4260 }
4261 connection_.GetRetransmissionAlarm()->Fire();
4262}
4263
4264TEST_P(QuicConnectionTest, Buffer100NonDecryptablePacketsThenKeyChange) {
QUICHE teamcd098022019-03-22 18:49:55 -07004265 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4266 return;
4267 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004268 // SetFromConfig is always called after construction from InitializeSession.
4269 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4270 QuicConfig config;
4271 config.set_max_undecryptable_packets(100);
4272 connection_.SetFromConfig(config);
4273 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4274 use_tagging_decrypter();
4275
4276 const uint8_t tag = 0x07;
4277 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
4278 QuicMakeUnique<TaggingEncrypter>(tag));
4279
4280 // Process an encrypted packet which can not yet be decrypted which should
4281 // result in the packet being buffered.
4282 for (uint64_t i = 1; i <= 100; ++i) {
4283 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4284 }
4285
4286 // Transition to the new encryption state and process another encrypted packet
4287 // which should result in the original packets being processed.
4288 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
zhongyi546cc452019-04-12 15:27:49 -07004289 SetDecrypter(ENCRYPTION_ZERO_RTT,
4290 QuicMakeUnique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004291 EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
4292 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4293 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
4294 QuicMakeUnique<TaggingEncrypter>(tag));
4295
4296 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(100);
4297 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
4298
4299 // Finally, process a third packet and note that we do not reprocess the
4300 // buffered packet.
4301 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4302 ProcessDataPacketAtLevel(102, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4303}
4304
4305TEST_P(QuicConnectionTest, SetRTOAfterWritingToSocket) {
4306 BlockOnNextWrite();
4307 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4308 // Make sure that RTO is not started when the packet is queued.
4309 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4310
4311 // Test that RTO is started once we write to the socket.
4312 writer_->SetWritable();
4313 connection_.OnCanWrite();
4314 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4315}
4316
4317TEST_P(QuicConnectionTest, DelayRTOWithAckReceipt) {
4318 connection_.SetMaxTailLossProbes(0);
4319
4320 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4321 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
4322 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
4323 connection_.SendStreamDataWithString(3, "bar", 0, NO_FIN);
4324 QuicAlarm* retransmission_alarm = connection_.GetRetransmissionAlarm();
4325 EXPECT_TRUE(retransmission_alarm->IsSet());
4326 EXPECT_EQ(clock_.Now() + DefaultRetransmissionTime(),
4327 retransmission_alarm->deadline());
4328
4329 // Advance the time right before the RTO, then receive an ack for the first
4330 // packet to delay the RTO.
4331 clock_.AdvanceTime(DefaultRetransmissionTime());
4332 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4333 QuicAckFrame ack = InitAckFrame(1);
4334 ProcessAckPacket(&ack);
4335 // Now we have an RTT sample of DefaultRetransmissionTime(500ms),
4336 // so the RTO has increased to 2 * SRTT.
4337 EXPECT_TRUE(retransmission_alarm->IsSet());
4338 EXPECT_EQ(retransmission_alarm->deadline(),
4339 clock_.Now() + 2 * DefaultRetransmissionTime());
4340
4341 // Move forward past the original RTO and ensure the RTO is still pending.
4342 clock_.AdvanceTime(2 * DefaultRetransmissionTime());
4343
4344 // Ensure the second packet gets retransmitted when it finally fires.
4345 EXPECT_TRUE(retransmission_alarm->IsSet());
4346 EXPECT_EQ(retransmission_alarm->deadline(), clock_.ApproximateNow());
4347 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4348 // Manually cancel the alarm to simulate a real test.
4349 connection_.GetRetransmissionAlarm()->Fire();
4350
4351 // The new retransmitted packet number should set the RTO to a larger value
4352 // than previously.
4353 EXPECT_TRUE(retransmission_alarm->IsSet());
4354 QuicTime next_rto_time = retransmission_alarm->deadline();
4355 QuicTime expected_rto_time =
4356 connection_.sent_packet_manager().GetRetransmissionTime();
4357 EXPECT_EQ(next_rto_time, expected_rto_time);
4358}
4359
4360TEST_P(QuicConnectionTest, TestQueued) {
4361 connection_.SetMaxTailLossProbes(0);
4362
4363 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4364 BlockOnNextWrite();
4365 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4366 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4367
4368 // Unblock the writes and actually send.
4369 writer_->SetWritable();
4370 connection_.OnCanWrite();
4371 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4372}
4373
4374TEST_P(QuicConnectionTest, InitialTimeout) {
4375 EXPECT_TRUE(connection_.connected());
4376 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4377 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4378
4379 // SetFromConfig sets the initial timeouts before negotiation.
4380 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4381 QuicConfig config;
4382 connection_.SetFromConfig(config);
4383 // Subtract a second from the idle timeout on the client side.
4384 QuicTime default_timeout =
4385 clock_.ApproximateNow() +
4386 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4387 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
4388
4389 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NETWORK_IDLE_TIMEOUT, _,
4390 ConnectionCloseSource::FROM_SELF));
4391 // Simulate the timeout alarm firing.
4392 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1));
4393 connection_.GetTimeoutAlarm()->Fire();
4394
4395 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4396 EXPECT_FALSE(connection_.connected());
4397
4398 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
4399 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4400 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4401 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4402 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
renjietang11e4a3d2019-05-03 11:27:26 -07004403 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004404}
4405
4406TEST_P(QuicConnectionTest, IdleTimeoutAfterFirstSentPacket) {
4407 EXPECT_TRUE(connection_.connected());
4408 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4409 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4410
4411 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4412 QuicConfig config;
4413 connection_.SetFromConfig(config);
4414 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4415 QuicTime initial_ddl =
4416 clock_.ApproximateNow() +
4417 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4418 EXPECT_EQ(initial_ddl, connection_.GetTimeoutAlarm()->deadline());
4419 EXPECT_TRUE(connection_.connected());
4420
4421 // Advance the time and send the first packet to the peer.
4422 clock_.AdvanceTime(QuicTime::Delta::FromMicroseconds(20));
4423 QuicPacketNumber last_packet;
4424 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4425 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4426 // This will be the updated deadline for the connection to idle time out.
4427 QuicTime new_ddl = clock_.ApproximateNow() +
4428 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4429
4430 // Simulate the timeout alarm firing, the connection should not be closed as
4431 // a new packet has been sent.
4432 EXPECT_CALL(visitor_, OnConnectionClosed(_, _, _)).Times(0);
4433 QuicTime::Delta delay = initial_ddl - clock_.ApproximateNow();
4434 clock_.AdvanceTime(delay);
4435 connection_.GetTimeoutAlarm()->Fire();
4436 // Verify the timeout alarm deadline is updated.
4437 EXPECT_TRUE(connection_.connected());
4438 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4439 EXPECT_EQ(new_ddl, connection_.GetTimeoutAlarm()->deadline());
4440
4441 // Simulate the timeout alarm firing again, the connection now should be
4442 // closed.
4443 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NETWORK_IDLE_TIMEOUT, _,
4444 ConnectionCloseSource::FROM_SELF));
4445 clock_.AdvanceTime(new_ddl - clock_.ApproximateNow());
4446 connection_.GetTimeoutAlarm()->Fire();
4447 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4448 EXPECT_FALSE(connection_.connected());
4449
4450 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
4451 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4452 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4453 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4454 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4455}
4456
4457TEST_P(QuicConnectionTest, IdleTimeoutAfterSendTwoPackets) {
4458 EXPECT_TRUE(connection_.connected());
4459 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4460 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4461
4462 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4463 QuicConfig config;
4464 connection_.SetFromConfig(config);
4465 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4466 QuicTime initial_ddl =
4467 clock_.ApproximateNow() +
4468 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4469 EXPECT_EQ(initial_ddl, connection_.GetTimeoutAlarm()->deadline());
4470 EXPECT_TRUE(connection_.connected());
4471
4472 // Immediately send the first packet, this is a rare case but test code will
4473 // hit this issue often as MockClock used for tests doesn't move with code
4474 // execution until manually adjusted.
4475 QuicPacketNumber last_packet;
4476 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4477 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4478
4479 // Advance the time and send the second packet to the peer.
4480 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
4481 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4482 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
4483
4484 if (GetQuicReloadableFlag(
4485 quic_fix_time_of_first_packet_sent_after_receiving)) {
4486 // Simulate the timeout alarm firing, the connection will be closed.
4487 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NETWORK_IDLE_TIMEOUT, _,
4488 ConnectionCloseSource::FROM_SELF));
4489 clock_.AdvanceTime(initial_ddl - clock_.ApproximateNow());
4490 connection_.GetTimeoutAlarm()->Fire();
4491 } else {
4492 // Simulate the timeout alarm firing, the connection will not be closed.
4493 EXPECT_CALL(visitor_, OnConnectionClosed(_, _, _)).Times(0);
4494 clock_.AdvanceTime(initial_ddl - clock_.ApproximateNow());
4495 connection_.GetTimeoutAlarm()->Fire();
4496 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4497 EXPECT_TRUE(connection_.connected());
4498
4499 // Advance another 20ms, and fire the alarm again. The connection will be
4500 // closed.
4501 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NETWORK_IDLE_TIMEOUT, _,
4502 ConnectionCloseSource::FROM_SELF));
4503 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
4504 connection_.GetTimeoutAlarm()->Fire();
4505 }
4506
4507 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4508 EXPECT_FALSE(connection_.connected());
4509
4510 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
4511 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4512 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4513 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4514 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4515}
4516
4517TEST_P(QuicConnectionTest, HandshakeTimeout) {
4518 // Use a shorter handshake timeout than idle timeout for this test.
4519 const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(5);
4520 connection_.SetNetworkTimeouts(timeout, timeout);
4521 EXPECT_TRUE(connection_.connected());
4522 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4523
4524 QuicTime handshake_timeout =
4525 clock_.ApproximateNow() + timeout - QuicTime::Delta::FromSeconds(1);
4526 EXPECT_EQ(handshake_timeout, connection_.GetTimeoutAlarm()->deadline());
4527 EXPECT_TRUE(connection_.connected());
4528
4529 // Send and ack new data 3 seconds later to lengthen the idle timeout.
4530 SendStreamDataToPeer(
4531 QuicUtils::GetHeadersStreamId(connection_.transport_version()), "GET /",
4532 0, FIN, nullptr);
4533 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(3));
4534 QuicAckFrame frame = InitAckFrame(1);
4535 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4536 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4537 ProcessAckPacket(&frame);
4538
4539 // Fire early to verify it wouldn't timeout yet.
4540 connection_.GetTimeoutAlarm()->Fire();
4541 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4542 EXPECT_TRUE(connection_.connected());
4543
4544 clock_.AdvanceTime(timeout - QuicTime::Delta::FromSeconds(2));
4545
4546 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_HANDSHAKE_TIMEOUT, _,
4547 ConnectionCloseSource::FROM_SELF));
4548 // Simulate the timeout alarm firing.
4549 connection_.GetTimeoutAlarm()->Fire();
4550
4551 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4552 EXPECT_FALSE(connection_.connected());
4553
4554 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
4555 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4556 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4557 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4558}
4559
4560TEST_P(QuicConnectionTest, PingAfterSend) {
QUICHE teamcd098022019-03-22 18:49:55 -07004561 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4562 return;
4563 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004564 EXPECT_TRUE(connection_.connected());
4565 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4566 .WillRepeatedly(Return(true));
4567 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4568
4569 // Advance to 5ms, and send a packet to the peer, which will set
4570 // the ping alarm.
4571 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4572 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4573 SendStreamDataToPeer(
4574 QuicUtils::GetHeadersStreamId(connection_.transport_version()), "GET /",
4575 0, FIN, nullptr);
4576 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4577 EXPECT_EQ(clock_.ApproximateNow() + QuicTime::Delta::FromSeconds(15),
4578 connection_.GetPingAlarm()->deadline());
4579
4580 // Now recevie an ACK of the previous packet, which will move the
4581 // ping alarm forward.
4582 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4583 QuicAckFrame frame = InitAckFrame(1);
4584 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4585 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4586 ProcessAckPacket(&frame);
4587 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4588 // The ping timer is set slightly less than 15 seconds in the future, because
4589 // of the 1s ping timer alarm granularity.
4590 EXPECT_EQ(clock_.ApproximateNow() + QuicTime::Delta::FromSeconds(15) -
4591 QuicTime::Delta::FromMilliseconds(5),
4592 connection_.GetPingAlarm()->deadline());
4593
4594 writer_->Reset();
4595 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15));
zhongyifbb25772019-04-10 16:54:08 -07004596 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004597 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07004598 size_t padding_frame_count = writer_->padding_frames().size();
4599 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004600 ASSERT_EQ(1u, writer_->ping_frames().size());
4601 writer_->Reset();
4602
4603 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4604 .WillRepeatedly(Return(false));
4605 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4606 SendAckPacketToPeer();
4607
4608 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4609}
4610
4611TEST_P(QuicConnectionTest, ReducedPingTimeout) {
QUICHE teamcd098022019-03-22 18:49:55 -07004612 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4613 return;
4614 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004615 EXPECT_TRUE(connection_.connected());
4616 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4617 .WillRepeatedly(Return(true));
4618 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4619
4620 // Use a reduced ping timeout for this connection.
4621 connection_.set_ping_timeout(QuicTime::Delta::FromSeconds(10));
4622
4623 // Advance to 5ms, and send a packet to the peer, which will set
4624 // the ping alarm.
4625 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4626 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4627 SendStreamDataToPeer(
4628 QuicUtils::GetHeadersStreamId(connection_.transport_version()), "GET /",
4629 0, FIN, nullptr);
4630 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4631 EXPECT_EQ(clock_.ApproximateNow() + QuicTime::Delta::FromSeconds(10),
4632 connection_.GetPingAlarm()->deadline());
4633
4634 // Now recevie an ACK of the previous packet, which will move the
4635 // ping alarm forward.
4636 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4637 QuicAckFrame frame = InitAckFrame(1);
4638 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4639 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4640 ProcessAckPacket(&frame);
4641 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4642 // The ping timer is set slightly less than 10 seconds in the future, because
4643 // of the 1s ping timer alarm granularity.
4644 EXPECT_EQ(clock_.ApproximateNow() + QuicTime::Delta::FromSeconds(10) -
4645 QuicTime::Delta::FromMilliseconds(5),
4646 connection_.GetPingAlarm()->deadline());
4647
4648 writer_->Reset();
4649 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
4650 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
4651 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
4652 }));
4653 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07004654 size_t padding_frame_count = writer_->padding_frames().size();
4655 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004656 ASSERT_EQ(1u, writer_->ping_frames().size());
4657 writer_->Reset();
4658
4659 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4660 .WillRepeatedly(Return(false));
4661 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4662 SendAckPacketToPeer();
4663
4664 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4665}
4666
4667// Tests whether sending an MTU discovery packet to peer successfully causes the
4668// maximum packet size to increase.
4669TEST_P(QuicConnectionTest, SendMtuDiscoveryPacket) {
QUICHE teamcd098022019-03-22 18:49:55 -07004670 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4671 return;
4672 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004673 EXPECT_TRUE(connection_.connected());
4674
4675 // Send an MTU probe.
4676 const size_t new_mtu = kDefaultMaxPacketSize + 100;
4677 QuicByteCount mtu_probe_size;
4678 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4679 .WillOnce(SaveArg<3>(&mtu_probe_size));
4680 connection_.SendMtuDiscoveryPacket(new_mtu);
4681 EXPECT_EQ(new_mtu, mtu_probe_size);
4682 EXPECT_EQ(QuicPacketNumber(1u), creator_->packet_number());
4683
4684 // Send more than MTU worth of data. No acknowledgement was received so far,
4685 // so the MTU should be at its old value.
vasilvvc48c8712019-03-11 13:38:16 -07004686 const std::string data(kDefaultMaxPacketSize + 1, '.');
QUICHE teama6ef0a62019-03-07 20:34:33 -05004687 QuicByteCount size_before_mtu_change;
4688 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4689 .Times(2)
4690 .WillOnce(SaveArg<3>(&size_before_mtu_change))
4691 .WillOnce(Return());
4692 connection_.SendStreamDataWithString(3, data, 0, FIN);
4693 EXPECT_EQ(QuicPacketNumber(3u), creator_->packet_number());
4694 EXPECT_EQ(kDefaultMaxPacketSize, size_before_mtu_change);
4695
4696 // Acknowledge all packets so far.
4697 QuicAckFrame probe_ack = InitAckFrame(3);
4698 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4699 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4700 ProcessAckPacket(&probe_ack);
4701 EXPECT_EQ(new_mtu, connection_.max_packet_length());
4702
4703 // Send the same data again. Check that it fits into a single packet now.
4704 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4705 connection_.SendStreamDataWithString(3, data, 0, FIN);
4706 EXPECT_EQ(QuicPacketNumber(4u), creator_->packet_number());
4707}
4708
4709// Tests whether MTU discovery does not happen when it is not explicitly enabled
4710// by the connection options.
4711TEST_P(QuicConnectionTest, MtuDiscoveryDisabled) {
4712 EXPECT_TRUE(connection_.connected());
4713
4714 const QuicPacketCount packets_between_probes_base = 10;
4715 set_packets_between_probes_base(packets_between_probes_base);
4716
4717 const QuicPacketCount number_of_packets = packets_between_probes_base * 2;
4718 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
4719 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
4720 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4721 EXPECT_EQ(0u, connection_.mtu_probe_count());
4722 }
4723}
4724
4725// Tests whether MTU discovery works when the probe gets acknowledged on the
4726// first try.
4727TEST_P(QuicConnectionTest, MtuDiscoveryEnabled) {
4728 EXPECT_TRUE(connection_.connected());
4729
4730 connection_.EnablePathMtuDiscovery(send_algorithm_);
4731
4732 const QuicPacketCount packets_between_probes_base = 5;
4733 set_packets_between_probes_base(packets_between_probes_base);
4734
4735 // Send enough packets so that the next one triggers path MTU discovery.
4736 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
4737 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
4738 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4739 }
4740
4741 // Trigger the probe.
4742 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
4743 nullptr);
4744 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4745 QuicByteCount probe_size;
4746 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4747 .WillOnce(SaveArg<3>(&probe_size));
4748 connection_.GetMtuDiscoveryAlarm()->Fire();
4749 EXPECT_EQ(kMtuDiscoveryTargetPacketSizeHigh, probe_size);
4750
4751 const QuicPacketNumber probe_packet_number =
4752 FirstSendingPacketNumber() + packets_between_probes_base;
4753 ASSERT_EQ(probe_packet_number, creator_->packet_number());
4754
4755 // Acknowledge all packets sent so far.
4756 QuicAckFrame probe_ack = InitAckFrame(probe_packet_number);
4757 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4758 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4759 ProcessAckPacket(&probe_ack);
4760 EXPECT_EQ(kMtuDiscoveryTargetPacketSizeHigh, connection_.max_packet_length());
4761 EXPECT_EQ(0u, connection_.GetBytesInFlight());
4762
4763 // Send more packets, and ensure that none of them sets the alarm.
4764 for (QuicPacketCount i = 0; i < 4 * packets_between_probes_base; i++) {
4765 SendStreamDataToPeer(3, ".", packets_between_probes_base + i, NO_FIN,
4766 nullptr);
4767 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4768 }
4769
4770 EXPECT_EQ(1u, connection_.mtu_probe_count());
4771}
4772
4773// Tests whether MTU discovery works correctly when the probes never get
4774// acknowledged.
4775TEST_P(QuicConnectionTest, MtuDiscoveryFailed) {
4776 EXPECT_TRUE(connection_.connected());
4777
4778 connection_.EnablePathMtuDiscovery(send_algorithm_);
4779
4780 const QuicTime::Delta rtt = QuicTime::Delta::FromMilliseconds(100);
4781
4782 EXPECT_EQ(kPacketsBetweenMtuProbesBase,
4783 QuicConnectionPeer::GetPacketsBetweenMtuProbes(&connection_));
4784 // Lower the number of probes between packets in order to make the test go
4785 // much faster.
4786 const QuicPacketCount packets_between_probes_base = 5;
4787 set_packets_between_probes_base(packets_between_probes_base);
4788
4789 // This tests sends more packets than strictly necessary to make sure that if
4790 // the connection was to send more discovery packets than needed, those would
4791 // get caught as well.
4792 const QuicPacketCount number_of_packets =
4793 packets_between_probes_base * (1 << (kMtuDiscoveryAttempts + 1));
4794 std::vector<QuicPacketNumber> mtu_discovery_packets;
4795 // Called by the first ack.
4796 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4797 // Called on many acks.
4798 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
4799 .Times(AnyNumber());
4800 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
4801 SendStreamDataToPeer(3, "!", i, NO_FIN, nullptr);
4802 clock_.AdvanceTime(rtt);
4803
4804 // Receive an ACK, which marks all data packets as received, and all MTU
4805 // discovery packets as missing.
4806
4807 QuicAckFrame ack;
4808
4809 if (!mtu_discovery_packets.empty()) {
4810 QuicPacketNumber min_packet = *min_element(mtu_discovery_packets.begin(),
4811 mtu_discovery_packets.end());
4812 QuicPacketNumber max_packet = *max_element(mtu_discovery_packets.begin(),
4813 mtu_discovery_packets.end());
4814 ack.packets.AddRange(QuicPacketNumber(1), min_packet);
4815 ack.packets.AddRange(QuicPacketNumber(max_packet + 1),
4816 creator_->packet_number() + 1);
4817 ack.largest_acked = creator_->packet_number();
4818
4819 } else {
4820 ack.packets.AddRange(QuicPacketNumber(1), creator_->packet_number() + 1);
4821 ack.largest_acked = creator_->packet_number();
4822 }
4823
4824 ProcessAckPacket(&ack);
4825
4826 // Trigger MTU probe if it would be scheduled now.
4827 if (!connection_.GetMtuDiscoveryAlarm()->IsSet()) {
4828 continue;
4829 }
4830
4831 // Fire the alarm. The alarm should cause a packet to be sent.
4832 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4833 connection_.GetMtuDiscoveryAlarm()->Fire();
4834 // Record the packet number of the MTU discovery packet in order to
4835 // mark it as NACK'd.
4836 mtu_discovery_packets.push_back(creator_->packet_number());
4837 }
4838
4839 // Ensure the number of packets between probes grows exponentially by checking
4840 // it against the closed-form expression for the packet number.
4841 ASSERT_EQ(kMtuDiscoveryAttempts, mtu_discovery_packets.size());
4842 for (uint64_t i = 0; i < kMtuDiscoveryAttempts; i++) {
4843 // 2^0 + 2^1 + 2^2 + ... + 2^n = 2^(n + 1) - 1
4844 const QuicPacketCount packets_between_probes =
4845 packets_between_probes_base * ((1 << (i + 1)) - 1);
4846 EXPECT_EQ(QuicPacketNumber(packets_between_probes + (i + 1)),
4847 mtu_discovery_packets[i]);
4848 }
4849
4850 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4851 EXPECT_EQ(kDefaultMaxPacketSize, connection_.max_packet_length());
4852 EXPECT_EQ(kMtuDiscoveryAttempts, connection_.mtu_probe_count());
4853}
4854
4855// Tests whether MTU discovery works when the writer has a limit on how large a
4856// packet can be.
4857TEST_P(QuicConnectionTest, MtuDiscoveryWriterLimited) {
4858 EXPECT_TRUE(connection_.connected());
4859
4860 const QuicByteCount mtu_limit = kMtuDiscoveryTargetPacketSizeHigh - 1;
4861 writer_->set_max_packet_size(mtu_limit);
4862 connection_.EnablePathMtuDiscovery(send_algorithm_);
4863
4864 const QuicPacketCount packets_between_probes_base = 5;
4865 set_packets_between_probes_base(packets_between_probes_base);
4866
4867 // Send enough packets so that the next one triggers path MTU discovery.
4868 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
4869 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
4870 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4871 }
4872
4873 // Trigger the probe.
4874 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
4875 nullptr);
4876 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4877 QuicByteCount probe_size;
4878 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4879 .WillOnce(SaveArg<3>(&probe_size));
4880 connection_.GetMtuDiscoveryAlarm()->Fire();
4881 EXPECT_EQ(mtu_limit, probe_size);
4882
4883 const QuicPacketNumber probe_sequence_number =
4884 FirstSendingPacketNumber() + packets_between_probes_base;
4885 ASSERT_EQ(probe_sequence_number, creator_->packet_number());
4886
4887 // Acknowledge all packets sent so far.
4888 QuicAckFrame probe_ack = InitAckFrame(probe_sequence_number);
4889 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4890 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4891 ProcessAckPacket(&probe_ack);
4892 EXPECT_EQ(mtu_limit, connection_.max_packet_length());
4893 EXPECT_EQ(0u, connection_.GetBytesInFlight());
4894
4895 // Send more packets, and ensure that none of them sets the alarm.
4896 for (QuicPacketCount i = 0; i < 4 * packets_between_probes_base; i++) {
4897 SendStreamDataToPeer(3, ".", packets_between_probes_base + i, NO_FIN,
4898 nullptr);
4899 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4900 }
4901
4902 EXPECT_EQ(1u, connection_.mtu_probe_count());
4903}
4904
4905// Tests whether MTU discovery works when the writer returns an error despite
4906// advertising higher packet length.
4907TEST_P(QuicConnectionTest, MtuDiscoveryWriterFailed) {
4908 EXPECT_TRUE(connection_.connected());
4909
4910 const QuicByteCount mtu_limit = kMtuDiscoveryTargetPacketSizeHigh - 1;
4911 const QuicByteCount initial_mtu = connection_.max_packet_length();
4912 EXPECT_LT(initial_mtu, mtu_limit);
4913 writer_->set_max_packet_size(mtu_limit);
4914 connection_.EnablePathMtuDiscovery(send_algorithm_);
4915
4916 const QuicPacketCount packets_between_probes_base = 5;
4917 set_packets_between_probes_base(packets_between_probes_base);
4918
4919 // Send enough packets so that the next one triggers path MTU discovery.
4920 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
4921 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
4922 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4923 }
4924
4925 // Trigger the probe.
4926 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
4927 nullptr);
4928 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4929 writer_->SimulateNextPacketTooLarge();
4930 connection_.GetMtuDiscoveryAlarm()->Fire();
4931 ASSERT_TRUE(connection_.connected());
4932
4933 // Send more data.
4934 QuicPacketNumber probe_number = creator_->packet_number();
4935 QuicPacketCount extra_packets = packets_between_probes_base * 3;
4936 for (QuicPacketCount i = 0; i < extra_packets; i++) {
4937 connection_.EnsureWritableAndSendStreamData5();
4938 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4939 }
4940
4941 // Acknowledge all packets sent so far, except for the lost probe.
4942 QuicAckFrame probe_ack =
4943 ConstructAckFrame(creator_->packet_number(), probe_number);
4944 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4945 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4946 ProcessAckPacket(&probe_ack);
4947 EXPECT_EQ(initial_mtu, connection_.max_packet_length());
4948
4949 // Send more packets, and ensure that none of them sets the alarm.
4950 for (QuicPacketCount i = 0; i < 4 * packets_between_probes_base; i++) {
4951 connection_.EnsureWritableAndSendStreamData5();
4952 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4953 }
4954
4955 EXPECT_EQ(initial_mtu, connection_.max_packet_length());
4956 EXPECT_EQ(1u, connection_.mtu_probe_count());
4957}
4958
4959TEST_P(QuicConnectionTest, NoMtuDiscoveryAfterConnectionClosed) {
4960 EXPECT_TRUE(connection_.connected());
4961
4962 connection_.EnablePathMtuDiscovery(send_algorithm_);
4963
4964 const QuicPacketCount packets_between_probes_base = 10;
4965 set_packets_between_probes_base(packets_between_probes_base);
4966
4967 // Send enough packets so that the next one triggers path MTU discovery.
4968 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
4969 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
4970 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4971 }
4972
4973 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
4974 nullptr);
4975 EXPECT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4976
4977 EXPECT_CALL(visitor_, OnConnectionClosed(_, _, _));
4978 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
4979 ConnectionCloseBehavior::SILENT_CLOSE);
4980 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4981}
4982
4983TEST_P(QuicConnectionTest, TimeoutAfterSend) {
4984 EXPECT_TRUE(connection_.connected());
4985 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4986 QuicConfig config;
4987 connection_.SetFromConfig(config);
4988 EXPECT_FALSE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
4989
4990 const QuicTime::Delta initial_idle_timeout =
4991 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4992 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
4993 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
4994
4995 // When we send a packet, the timeout will change to 5ms +
4996 // kInitialIdleTimeoutSecs.
4997 clock_.AdvanceTime(five_ms);
4998 SendStreamDataToPeer(
4999 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5000 0, FIN, nullptr);
5001 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5002
5003 // Now send more data. This will not move the timeout because
5004 // no data has been received since the previous write.
5005 clock_.AdvanceTime(five_ms);
5006 SendStreamDataToPeer(
5007 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5008 3, FIN, nullptr);
5009 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5010
5011 // The original alarm will fire. We should not time out because we had a
5012 // network event at t=5ms. The alarm will reregister.
5013 clock_.AdvanceTime(initial_idle_timeout - five_ms - five_ms);
5014 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
5015 connection_.GetTimeoutAlarm()->Fire();
5016 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5017 EXPECT_TRUE(connection_.connected());
5018 EXPECT_EQ(default_timeout + five_ms,
5019 connection_.GetTimeoutAlarm()->deadline());
5020
5021 // This time, we should time out.
5022 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NETWORK_IDLE_TIMEOUT, _,
5023 ConnectionCloseSource::FROM_SELF));
5024 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5025 clock_.AdvanceTime(five_ms);
5026 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5027 connection_.GetTimeoutAlarm()->Fire();
5028 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5029 EXPECT_FALSE(connection_.connected());
5030}
5031
5032TEST_P(QuicConnectionTest, TimeoutAfterRetransmission) {
5033 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5034 EXPECT_TRUE(connection_.connected());
5035 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5036 QuicConfig config;
5037 connection_.SetFromConfig(config);
5038 EXPECT_FALSE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
5039
5040 const QuicTime start_time = clock_.Now();
5041 const QuicTime::Delta initial_idle_timeout =
5042 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5043 QuicTime default_timeout = clock_.Now() + initial_idle_timeout;
5044
5045 connection_.SetMaxTailLossProbes(0);
5046 const QuicTime default_retransmission_time =
5047 start_time + DefaultRetransmissionTime();
5048
5049 ASSERT_LT(default_retransmission_time, default_timeout);
5050
5051 // When we send a packet, the timeout will change to 5 ms +
5052 // kInitialIdleTimeoutSecs (but it will not reschedule the alarm).
5053 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5054 const QuicTime send_time = start_time + five_ms;
5055 clock_.AdvanceTime(five_ms);
5056 ASSERT_EQ(send_time, clock_.Now());
5057 SendStreamDataToPeer(
5058 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5059 0, FIN, nullptr);
5060 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5061
5062 // Move forward 5 ms and receive a packet, which will move the timeout
5063 // forward 5 ms more (but will not reschedule the alarm).
5064 const QuicTime receive_time = send_time + five_ms;
5065 clock_.AdvanceTime(receive_time - clock_.Now());
5066 ASSERT_EQ(receive_time, clock_.Now());
5067 ProcessPacket(1);
5068
5069 // Now move forward to the retransmission time and retransmit the
5070 // packet, which should move the timeout forward again (but will not
5071 // reschedule the alarm).
5072 EXPECT_EQ(default_retransmission_time + five_ms,
5073 connection_.GetRetransmissionAlarm()->deadline());
5074 // Simulate the retransmission alarm firing.
5075 const QuicTime rto_time = send_time + DefaultRetransmissionTime();
5076 const QuicTime final_timeout = rto_time + initial_idle_timeout;
5077 clock_.AdvanceTime(rto_time - clock_.Now());
5078 ASSERT_EQ(rto_time, clock_.Now());
5079 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _));
5080 connection_.GetRetransmissionAlarm()->Fire();
5081
5082 // Advance to the original timeout and fire the alarm. The connection should
5083 // timeout, and the alarm should be registered based on the time of the
5084 // retransmission.
5085 clock_.AdvanceTime(default_timeout - clock_.Now());
5086 ASSERT_EQ(default_timeout.ToDebuggingValue(),
5087 clock_.Now().ToDebuggingValue());
5088 EXPECT_EQ(default_timeout, clock_.Now());
5089 connection_.GetTimeoutAlarm()->Fire();
5090 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5091 EXPECT_TRUE(connection_.connected());
5092 ASSERT_EQ(final_timeout.ToDebuggingValue(),
5093 connection_.GetTimeoutAlarm()->deadline().ToDebuggingValue());
5094
5095 // This time, we should time out.
5096 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NETWORK_IDLE_TIMEOUT, _,
5097 ConnectionCloseSource::FROM_SELF));
5098 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5099 clock_.AdvanceTime(final_timeout - clock_.Now());
5100 EXPECT_EQ(connection_.GetTimeoutAlarm()->deadline(), clock_.Now());
5101 EXPECT_EQ(final_timeout, clock_.Now());
5102 connection_.GetTimeoutAlarm()->Fire();
5103 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5104 EXPECT_FALSE(connection_.connected());
5105}
5106
5107TEST_P(QuicConnectionTest, NewTimeoutAfterSendSilentClose) {
5108 // Same test as above, but complete a handshake which enables silent close,
5109 // causing no connection close packet to be sent.
5110 EXPECT_TRUE(connection_.connected());
5111 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5112 QuicConfig config;
5113
5114 // Create a handshake message that also enables silent close.
5115 CryptoHandshakeMessage msg;
vasilvvc48c8712019-03-11 13:38:16 -07005116 std::string error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005117 QuicConfig client_config;
5118 client_config.SetInitialStreamFlowControlWindowToSend(
5119 kInitialStreamFlowControlWindowForTest);
5120 client_config.SetInitialSessionFlowControlWindowToSend(
5121 kInitialSessionFlowControlWindowForTest);
5122 client_config.SetIdleNetworkTimeout(
5123 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs),
5124 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs));
fkastenholzd3a1de92019-05-15 07:00:07 -07005125 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005126 const QuicErrorCode error =
5127 config.ProcessPeerHello(msg, CLIENT, &error_details);
5128 EXPECT_EQ(QUIC_NO_ERROR, error);
5129
5130 connection_.SetFromConfig(config);
5131 EXPECT_TRUE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
5132
5133 const QuicTime::Delta default_idle_timeout =
5134 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs - 1);
5135 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5136 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5137
5138 // When we send a packet, the timeout will change to 5ms +
5139 // kInitialIdleTimeoutSecs.
5140 clock_.AdvanceTime(five_ms);
5141 SendStreamDataToPeer(
5142 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5143 0, FIN, nullptr);
5144 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5145
5146 // Now send more data. This will not move the timeout because
5147 // no data has been received since the previous write.
5148 clock_.AdvanceTime(five_ms);
5149 SendStreamDataToPeer(
5150 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5151 3, FIN, nullptr);
5152 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5153
5154 // The original alarm will fire. We should not time out because we had a
5155 // network event at t=5ms. The alarm will reregister.
5156 clock_.AdvanceTime(default_idle_timeout - five_ms - five_ms);
5157 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
5158 connection_.GetTimeoutAlarm()->Fire();
5159 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5160 EXPECT_TRUE(connection_.connected());
5161 EXPECT_EQ(default_timeout + five_ms,
5162 connection_.GetTimeoutAlarm()->deadline());
5163
5164 // This time, we should time out.
5165 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NETWORK_IDLE_TIMEOUT, _,
5166 ConnectionCloseSource::FROM_SELF));
5167 clock_.AdvanceTime(five_ms);
5168 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5169 connection_.GetTimeoutAlarm()->Fire();
5170 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5171 EXPECT_FALSE(connection_.connected());
5172}
5173
5174TEST_P(QuicConnectionTest, TimeoutAfterSendSilentCloseAndTLP) {
5175 // Same test as above, but complete a handshake which enables silent close,
5176 // but sending TLPs causes the connection close to be sent.
5177 EXPECT_TRUE(connection_.connected());
5178 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5179 QuicConfig config;
5180
5181 // Create a handshake message that also enables silent close.
5182 CryptoHandshakeMessage msg;
vasilvvc48c8712019-03-11 13:38:16 -07005183 std::string error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005184 QuicConfig client_config;
5185 client_config.SetInitialStreamFlowControlWindowToSend(
5186 kInitialStreamFlowControlWindowForTest);
5187 client_config.SetInitialSessionFlowControlWindowToSend(
5188 kInitialSessionFlowControlWindowForTest);
5189 client_config.SetIdleNetworkTimeout(
5190 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs),
5191 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs));
fkastenholzd3a1de92019-05-15 07:00:07 -07005192 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005193 const QuicErrorCode error =
5194 config.ProcessPeerHello(msg, CLIENT, &error_details);
5195 EXPECT_EQ(QUIC_NO_ERROR, error);
5196
5197 connection_.SetFromConfig(config);
5198 EXPECT_TRUE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
5199
5200 const QuicTime::Delta default_idle_timeout =
5201 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs - 1);
5202 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5203 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5204
5205 // When we send a packet, the timeout will change to 5ms +
5206 // kInitialIdleTimeoutSecs.
5207 clock_.AdvanceTime(five_ms);
5208 SendStreamDataToPeer(
5209 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5210 0, FIN, nullptr);
5211 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5212
5213 // Retransmit the packet via tail loss probe.
5214 clock_.AdvanceTime(connection_.GetRetransmissionAlarm()->deadline() -
5215 clock_.Now());
5216 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _));
5217 connection_.GetRetransmissionAlarm()->Fire();
5218
5219 // This time, we should time out and send a connection close due to the TLP.
5220 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NETWORK_IDLE_TIMEOUT, _,
5221 ConnectionCloseSource::FROM_SELF));
5222 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5223 clock_.AdvanceTime(connection_.GetTimeoutAlarm()->deadline() -
5224 clock_.ApproximateNow() + five_ms);
5225 connection_.GetTimeoutAlarm()->Fire();
5226 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5227 EXPECT_FALSE(connection_.connected());
5228}
5229
5230TEST_P(QuicConnectionTest, TimeoutAfterSendSilentCloseWithOpenStreams) {
5231 // Same test as above, but complete a handshake which enables silent close,
5232 // but having open streams causes the connection close to be sent.
5233 EXPECT_TRUE(connection_.connected());
5234 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5235 QuicConfig config;
5236
5237 // Create a handshake message that also enables silent close.
5238 CryptoHandshakeMessage msg;
vasilvvc48c8712019-03-11 13:38:16 -07005239 std::string error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005240 QuicConfig client_config;
5241 client_config.SetInitialStreamFlowControlWindowToSend(
5242 kInitialStreamFlowControlWindowForTest);
5243 client_config.SetInitialSessionFlowControlWindowToSend(
5244 kInitialSessionFlowControlWindowForTest);
5245 client_config.SetIdleNetworkTimeout(
5246 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs),
5247 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs));
fkastenholzd3a1de92019-05-15 07:00:07 -07005248 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005249 const QuicErrorCode error =
5250 config.ProcessPeerHello(msg, CLIENT, &error_details);
5251 EXPECT_EQ(QUIC_NO_ERROR, error);
5252
5253 connection_.SetFromConfig(config);
5254 EXPECT_TRUE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
5255
5256 const QuicTime::Delta default_idle_timeout =
5257 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs - 1);
5258 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5259 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5260
5261 // When we send a packet, the timeout will change to 5ms +
5262 // kInitialIdleTimeoutSecs.
5263 clock_.AdvanceTime(five_ms);
5264 SendStreamDataToPeer(
5265 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5266 0, FIN, nullptr);
5267 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5268
5269 // Indicate streams are still open.
5270 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
5271 .WillRepeatedly(Return(true));
5272
5273 // This time, we should time out and send a connection close due to the TLP.
5274 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NETWORK_IDLE_TIMEOUT, _,
5275 ConnectionCloseSource::FROM_SELF));
5276 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5277 clock_.AdvanceTime(connection_.GetTimeoutAlarm()->deadline() -
5278 clock_.ApproximateNow() + five_ms);
5279 connection_.GetTimeoutAlarm()->Fire();
5280 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5281 EXPECT_FALSE(connection_.connected());
5282}
5283
5284TEST_P(QuicConnectionTest, TimeoutAfterReceive) {
5285 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5286 EXPECT_TRUE(connection_.connected());
5287 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5288 QuicConfig config;
5289 connection_.SetFromConfig(config);
5290 EXPECT_FALSE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
5291
5292 const QuicTime::Delta initial_idle_timeout =
5293 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5294 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5295 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
5296
5297 connection_.SendStreamDataWithString(
5298 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5299 0, NO_FIN);
5300 connection_.SendStreamDataWithString(
5301 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5302 3, NO_FIN);
5303
5304 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5305 clock_.AdvanceTime(five_ms);
5306
5307 // When we receive a packet, the timeout will change to 5ms +
5308 // kInitialIdleTimeoutSecs.
5309 QuicAckFrame ack = InitAckFrame(2);
5310 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5311 ProcessAckPacket(&ack);
5312
5313 // The original alarm will fire. We should not time out because we had a
5314 // network event at t=5ms. The alarm will reregister.
5315 clock_.AdvanceTime(initial_idle_timeout - five_ms);
5316 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
5317 connection_.GetTimeoutAlarm()->Fire();
5318 EXPECT_TRUE(connection_.connected());
5319 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5320 EXPECT_EQ(default_timeout + five_ms,
5321 connection_.GetTimeoutAlarm()->deadline());
5322
5323 // This time, we should time out.
5324 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NETWORK_IDLE_TIMEOUT, _,
5325 ConnectionCloseSource::FROM_SELF));
5326 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5327 clock_.AdvanceTime(five_ms);
5328 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5329 connection_.GetTimeoutAlarm()->Fire();
5330 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5331 EXPECT_FALSE(connection_.connected());
5332}
5333
5334TEST_P(QuicConnectionTest, TimeoutAfterReceiveNotSendWhenUnacked) {
5335 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5336 EXPECT_TRUE(connection_.connected());
5337 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5338 QuicConfig config;
5339 connection_.SetFromConfig(config);
5340 EXPECT_FALSE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
5341
5342 const QuicTime::Delta initial_idle_timeout =
5343 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5344 connection_.SetNetworkTimeouts(
5345 QuicTime::Delta::Infinite(),
5346 initial_idle_timeout + QuicTime::Delta::FromSeconds(1));
5347 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5348 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
5349
5350 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5351 connection_.SendStreamDataWithString(
5352 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5353 0, NO_FIN);
5354 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5355 connection_.SendStreamDataWithString(
5356 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5357 3, NO_FIN);
5358
5359 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5360
5361 clock_.AdvanceTime(five_ms);
5362
5363 // When we receive a packet, the timeout will change to 5ms +
5364 // kInitialIdleTimeoutSecs.
5365 QuicAckFrame ack = InitAckFrame(2);
5366 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5367 ProcessAckPacket(&ack);
5368
5369 // The original alarm will fire. We should not time out because we had a
5370 // network event at t=5ms. The alarm will reregister.
5371 clock_.AdvanceTime(initial_idle_timeout - five_ms);
5372 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
5373 connection_.GetTimeoutAlarm()->Fire();
5374 EXPECT_TRUE(connection_.connected());
5375 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5376 EXPECT_EQ(default_timeout + five_ms,
5377 connection_.GetTimeoutAlarm()->deadline());
5378
5379 // Now, send packets while advancing the time and verify that the connection
5380 // eventually times out.
5381 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NETWORK_IDLE_TIMEOUT, _,
5382 ConnectionCloseSource::FROM_SELF));
5383 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
5384 for (int i = 0; i < 100 && connection_.connected(); ++i) {
5385 QUIC_LOG(INFO) << "sending data packet";
5386 connection_.SendStreamDataWithString(
5387 GetNthClientInitiatedStreamId(1, connection_.transport_version()),
5388 "foo", 0, NO_FIN);
5389 connection_.GetTimeoutAlarm()->Fire();
5390 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
5391 }
5392 EXPECT_FALSE(connection_.connected());
5393 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5394}
5395
5396TEST_P(QuicConnectionTest, TimeoutAfter5ClientRTOs) {
5397 connection_.SetMaxTailLossProbes(2);
5398 EXPECT_TRUE(connection_.connected());
5399 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5400 QuicConfig config;
5401 QuicTagVector connection_options;
5402 connection_options.push_back(k5RTO);
5403 config.SetConnectionOptionsToSend(connection_options);
5404 connection_.SetFromConfig(config);
5405
5406 // Send stream data.
5407 SendStreamDataToPeer(
5408 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5409 0, FIN, nullptr);
5410
5411 // Fire the retransmission alarm 6 times, twice for TLP and 4 times for RTO.
5412 for (int i = 0; i < 6; ++i) {
5413 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5414 connection_.GetRetransmissionAlarm()->Fire();
5415 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5416 EXPECT_TRUE(connection_.connected());
5417 }
5418
5419 EXPECT_EQ(2u, connection_.sent_packet_manager().GetConsecutiveTlpCount());
5420 EXPECT_EQ(4u, connection_.sent_packet_manager().GetConsecutiveRtoCount());
5421 // This time, we should time out.
5422 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_TOO_MANY_RTOS, _,
5423 ConnectionCloseSource::FROM_SELF));
5424 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5425 connection_.GetRetransmissionAlarm()->Fire();
5426 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5427 EXPECT_FALSE(connection_.connected());
5428}
5429
5430TEST_P(QuicConnectionTest, SendScheduler) {
5431 // Test that if we send a packet without delay, it is not queued.
5432 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
QUICHE team8c1daa22019-03-13 08:33:41 -07005433 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07005434 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005435 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
5436 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
QUICHE team6987b4a2019-03-15 16:23:04 -07005437 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05005438 HAS_RETRANSMITTABLE_DATA, false, false);
5439 EXPECT_EQ(0u, connection_.NumQueuedPackets());
5440}
5441
5442TEST_P(QuicConnectionTest, FailToSendFirstPacket) {
5443 // Test that the connection does not crash when it fails to send the first
5444 // packet at which point self_address_ might be uninitialized.
5445 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
5446 EXPECT_CALL(visitor_, OnConnectionClosed(_, _, _)).Times(1);
QUICHE team8c1daa22019-03-13 08:33:41 -07005447 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07005448 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005449 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
5450 writer_->SetShouldWriteFail();
QUICHE team6987b4a2019-03-15 16:23:04 -07005451 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05005452 HAS_RETRANSMITTABLE_DATA, false, false);
5453}
5454
5455TEST_P(QuicConnectionTest, SendSchedulerEAGAIN) {
5456 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
QUICHE team8c1daa22019-03-13 08:33:41 -07005457 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07005458 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005459 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
5460 BlockOnNextWrite();
5461 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _))
5462 .Times(0);
QUICHE team6987b4a2019-03-15 16:23:04 -07005463 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05005464 HAS_RETRANSMITTABLE_DATA, false, false);
5465 EXPECT_EQ(1u, connection_.NumQueuedPackets());
5466}
5467
5468TEST_P(QuicConnectionTest, TestQueueLimitsOnSendStreamData) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005469 // Queue the first packet.
ianswett3085da82019-04-04 07:24:24 -07005470 size_t payload_length = connection_.max_packet_length();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005471 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(testing::Return(false));
vasilvvc48c8712019-03-11 13:38:16 -07005472 const std::string payload(payload_length, 'a');
ianswett3085da82019-04-04 07:24:24 -07005473 QuicStreamId first_bidi_stream_id(QuicUtils::GetFirstBidirectionalStreamId(
5474 connection_.version().transport_version, Perspective::IS_CLIENT));
5475 EXPECT_EQ(0u, connection_
5476 .SendStreamDataWithString(first_bidi_stream_id, payload, 0,
5477 NO_FIN)
QUICHE teama6ef0a62019-03-07 20:34:33 -05005478 .bytes_consumed);
5479 EXPECT_EQ(0u, connection_.NumQueuedPackets());
5480}
5481
ianswett3085da82019-04-04 07:24:24 -07005482TEST_P(QuicConnectionTest, SendingThreePackets) {
ianswett3085da82019-04-04 07:24:24 -07005483 // Make the payload twice the size of the packet, so 3 packets are written.
5484 size_t total_payload_length = 2 * connection_.max_packet_length();
vasilvvc48c8712019-03-11 13:38:16 -07005485 const std::string payload(total_payload_length, 'a');
ianswett3085da82019-04-04 07:24:24 -07005486 QuicStreamId first_bidi_stream_id(QuicUtils::GetFirstBidirectionalStreamId(
5487 connection_.version().transport_version, Perspective::IS_CLIENT));
5488 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
5489 EXPECT_EQ(payload.size(), connection_
5490 .SendStreamDataWithString(first_bidi_stream_id,
5491 payload, 0, NO_FIN)
5492 .bytes_consumed);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005493}
5494
5495TEST_P(QuicConnectionTest, LoopThroughSendingPacketsWithTruncation) {
5496 set_perspective(Perspective::IS_SERVER);
fayangd4291e42019-05-30 10:31:21 -07005497 if (!VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005498 // For IETF QUIC, encryption level will be switched to FORWARD_SECURE in
5499 // SendStreamDataWithString.
5500 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
5501 }
5502 // Set up a larger payload than will fit in one packet.
vasilvvc48c8712019-03-11 13:38:16 -07005503 const std::string payload(connection_.max_packet_length(), 'a');
QUICHE teama6ef0a62019-03-07 20:34:33 -05005504 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
5505
5506 // Now send some packets with no truncation.
5507 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
5508 EXPECT_EQ(payload.size(),
5509 connection_.SendStreamDataWithString(3, payload, 0, NO_FIN)
5510 .bytes_consumed);
5511 // Track the size of the second packet here. The overhead will be the largest
5512 // we see in this test, due to the non-truncated connection id.
5513 size_t non_truncated_packet_size = writer_->last_packet_size();
5514
5515 // Change to a 0 byte connection id.
5516 QuicConfig config;
5517 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
5518 connection_.SetFromConfig(config);
5519 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
5520 EXPECT_EQ(payload.size(),
5521 connection_.SendStreamDataWithString(3, payload, 1350, NO_FIN)
5522 .bytes_consumed);
fayangd4291e42019-05-30 10:31:21 -07005523 if (VersionHasIetfInvariantHeader(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005524 // Short header packets sent from server omit connection ID already, and
5525 // stream offset size increases from 0 to 2.
5526 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() - 2);
5527 } else {
5528 // Just like above, we save 8 bytes on payload, and 8 on truncation. -2
5529 // because stream offset size is 2 instead of 0.
5530 EXPECT_EQ(non_truncated_packet_size,
5531 writer_->last_packet_size() + 8 * 2 - 2);
5532 }
5533}
5534
5535TEST_P(QuicConnectionTest, SendDelayedAck) {
5536 QuicTime ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
5537 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5538 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5539 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07005540 SetDecrypter(ENCRYPTION_ZERO_RTT,
5541 QuicMakeUnique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005542 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
5543 QuicMakeUnique<TaggingEncrypter>(tag));
5544 // Process a packet from the non-crypto stream.
5545 frame1_.stream_id = 3;
5546
5547 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07005548 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005549 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5550 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5551
5552 // Check if delayed ack timer is running for the expected interval.
5553 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5554 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5555 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07005556 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005557 connection_.GetAckAlarm()->Fire();
5558 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07005559 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005560 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07005561 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005562 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
5563 } else {
nharper55fa6132019-05-07 19:37:21 -07005564 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005565 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
5566 }
5567 EXPECT_FALSE(writer_->ack_frames().empty());
5568 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5569}
5570
5571TEST_P(QuicConnectionTest, SendDelayedAfterQuiescence) {
5572 QuicConnectionPeer::SetFastAckAfterQuiescence(&connection_, true);
5573
5574 // The beginning of the connection counts as quiescence.
5575 QuicTime ack_time =
5576 clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
5577 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5578 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5579 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07005580 SetDecrypter(ENCRYPTION_ZERO_RTT,
5581 QuicMakeUnique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005582 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
5583 QuicMakeUnique<TaggingEncrypter>(tag));
5584 // Process a packet from the non-crypto stream.
5585 frame1_.stream_id = 3;
5586
5587 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07005588 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005589 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5590 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5591
5592 // Check if delayed ack timer is running for the expected interval.
5593 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5594 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5595 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07005596 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005597 connection_.GetAckAlarm()->Fire();
5598 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07005599 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005600 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07005601 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005602 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
5603 } else {
nharper55fa6132019-05-07 19:37:21 -07005604 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005605 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
5606 }
5607 EXPECT_FALSE(writer_->ack_frames().empty());
5608 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5609
5610 // Process another packet immedately after sending the ack and expect the
5611 // ack alarm to be set delayed ack time in the future.
5612 ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
5613 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5614 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5615
5616 // Check if delayed ack timer is running for the expected interval.
5617 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5618 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5619 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07005620 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005621 connection_.GetAckAlarm()->Fire();
5622 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07005623 padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005624 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07005625 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005626 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
5627 } else {
nharper55fa6132019-05-07 19:37:21 -07005628 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005629 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
5630 }
5631 EXPECT_FALSE(writer_->ack_frames().empty());
5632 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5633
5634 // Wait 1 second and enesure the ack alarm is set to 1ms in the future.
5635 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
5636 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
5637 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5638 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5639
5640 // Check if delayed ack timer is running for the expected interval.
5641 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5642 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5643}
5644
5645TEST_P(QuicConnectionTest, SendDelayedAckDecimation) {
5646 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
5647 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION);
5648
5649 const size_t kMinRttMs = 40;
5650 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
5651 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
5652 QuicTime::Delta::Zero(), QuicTime::Zero());
5653 // The ack time should be based on min_rtt/4, since it's less than the
5654 // default delayed ack time.
5655 QuicTime ack_time = clock_.ApproximateNow() +
5656 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
5657 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5658 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5659 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07005660 SetDecrypter(ENCRYPTION_ZERO_RTT,
5661 QuicMakeUnique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005662 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
5663 QuicMakeUnique<TaggingEncrypter>(tag));
5664 // Process a packet from the non-crypto stream.
5665 frame1_.stream_id = 3;
5666
5667 // Process all the initial packets in order so there aren't missing packets.
5668 uint64_t kFirstDecimatedPacket = 101;
5669 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
5670 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5671 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5672 }
5673 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5674 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07005675 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005676 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5677 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
5678 ENCRYPTION_ZERO_RTT);
5679
5680 // Check if delayed ack timer is running for the expected interval.
5681 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5682 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5683
5684 // The 10th received packet causes an ack to be sent.
5685 for (int i = 0; i < 9; ++i) {
5686 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5687 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5688 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
5689 ENCRYPTION_ZERO_RTT);
5690 }
5691 // Check that ack is sent and that delayed ack alarm is reset.
5692 if (GetParam().no_stop_waiting) {
5693 EXPECT_EQ(1u, writer_->frame_count());
5694 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
5695 } else {
5696 EXPECT_EQ(2u, writer_->frame_count());
5697 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
5698 }
5699 EXPECT_FALSE(writer_->ack_frames().empty());
5700 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5701}
5702
5703TEST_P(QuicConnectionTest, SendDelayedAckAckDecimationAfterQuiescence) {
5704 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
5705 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION);
5706 QuicConnectionPeer::SetFastAckAfterQuiescence(&connection_, true);
5707
5708 const size_t kMinRttMs = 40;
5709 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
5710 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
5711 QuicTime::Delta::Zero(), QuicTime::Zero());
5712
5713 // The beginning of the connection counts as quiescence.
5714 QuicTime ack_time =
5715 clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
5716 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5717 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5718 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07005719 SetDecrypter(ENCRYPTION_ZERO_RTT,
5720 QuicMakeUnique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005721 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
5722 QuicMakeUnique<TaggingEncrypter>(tag));
5723 // Process a packet from the non-crypto stream.
5724 frame1_.stream_id = 3;
5725
5726 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07005727 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005728 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5729 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5730
5731 // Check if delayed ack timer is running for the expected interval.
5732 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5733 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5734 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07005735 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005736 connection_.GetAckAlarm()->Fire();
5737 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07005738 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005739 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07005740 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005741 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
5742 } else {
nharper55fa6132019-05-07 19:37:21 -07005743 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005744 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
5745 }
5746 EXPECT_FALSE(writer_->ack_frames().empty());
5747 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5748
5749 // Process another packet immedately after sending the ack and expect the
5750 // ack alarm to be set delayed ack time in the future.
5751 ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
5752 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5753 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5754
5755 // Check if delayed ack timer is running for the expected interval.
5756 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5757 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5758 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07005759 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005760 connection_.GetAckAlarm()->Fire();
5761 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07005762 padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005763 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07005764 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005765 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
5766 } else {
nharper55fa6132019-05-07 19:37:21 -07005767 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005768 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
5769 }
5770 EXPECT_FALSE(writer_->ack_frames().empty());
5771 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5772
5773 // Wait 1 second and enesure the ack alarm is set to 1ms in the future.
5774 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
5775 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
5776 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5777 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5778
5779 // Check if delayed ack timer is running for the expected interval.
5780 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5781 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5782
5783 // Process enough packets to get into ack decimation behavior.
5784 // The ack time should be based on min_rtt/4, since it's less than the
5785 // default delayed ack time.
5786 ack_time = clock_.ApproximateNow() +
5787 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
5788 uint64_t kFirstDecimatedPacket = 101;
5789 for (unsigned int i = 0; i < kFirstDecimatedPacket - 4; ++i) {
5790 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5791 ProcessDataPacketAtLevel(4 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5792 }
5793 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5794 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07005795 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005796 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5797 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
5798 ENCRYPTION_ZERO_RTT);
5799
5800 // Check if delayed ack timer is running for the expected interval.
5801 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5802 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5803
5804 // The 10th received packet causes an ack to be sent.
5805 for (int i = 0; i < 9; ++i) {
5806 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5807 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5808 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
5809 ENCRYPTION_ZERO_RTT);
5810 }
5811 // Check that ack is sent and that delayed ack alarm is reset.
5812 if (GetParam().no_stop_waiting) {
5813 EXPECT_EQ(1u, writer_->frame_count());
5814 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
5815 } else {
5816 EXPECT_EQ(2u, writer_->frame_count());
5817 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
5818 }
5819 EXPECT_FALSE(writer_->ack_frames().empty());
5820 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5821
5822 // Wait 1 second and enesure the ack alarm is set to 1ms in the future.
5823 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
5824 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
5825 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5826 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 10, !kHasStopWaiting,
5827 ENCRYPTION_ZERO_RTT);
5828
5829 // Check if delayed ack timer is running for the expected interval.
5830 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5831 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5832}
5833
5834TEST_P(QuicConnectionTest, SendDelayedAckDecimationUnlimitedAggregation) {
5835 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
5836 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5837 QuicConfig config;
5838 QuicTagVector connection_options;
5839 connection_options.push_back(kACKD);
5840 // No limit on the number of packets received before sending an ack.
5841 connection_options.push_back(kAKDU);
5842 config.SetConnectionOptionsToSend(connection_options);
5843 connection_.SetFromConfig(config);
5844
5845 const size_t kMinRttMs = 40;
5846 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
5847 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
5848 QuicTime::Delta::Zero(), QuicTime::Zero());
5849 // The ack time should be based on min_rtt/4, since it's less than the
5850 // default delayed ack time.
5851 QuicTime ack_time = clock_.ApproximateNow() +
5852 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
5853 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5854 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5855 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07005856 SetDecrypter(ENCRYPTION_ZERO_RTT,
5857 QuicMakeUnique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005858 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
5859 QuicMakeUnique<TaggingEncrypter>(tag));
5860 // Process a packet from the non-crypto stream.
5861 frame1_.stream_id = 3;
5862
5863 // Process all the initial packets in order so there aren't missing packets.
5864 uint64_t kFirstDecimatedPacket = 101;
5865 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
5866 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5867 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5868 }
5869 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5870 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07005871 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005872 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5873 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
5874 ENCRYPTION_ZERO_RTT);
5875
5876 // Check if delayed ack timer is running for the expected interval.
5877 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5878 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5879
5880 // 18 packets will not cause an ack to be sent. 19 will because when
5881 // stop waiting frames are in use, we ack every 20 packets no matter what.
5882 for (int i = 0; i < 18; ++i) {
5883 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5884 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5885 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
5886 ENCRYPTION_ZERO_RTT);
5887 }
5888 // The delayed ack timer should still be set to the expected deadline.
5889 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5890 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5891}
5892
5893TEST_P(QuicConnectionTest, SendDelayedAckDecimationEighthRtt) {
5894 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
5895 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION);
5896 QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
5897
5898 const size_t kMinRttMs = 40;
5899 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
5900 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
5901 QuicTime::Delta::Zero(), QuicTime::Zero());
5902 // The ack time should be based on min_rtt/8, since it's less than the
5903 // default delayed ack time.
5904 QuicTime ack_time = clock_.ApproximateNow() +
5905 QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
5906 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5907 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5908 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07005909 SetDecrypter(ENCRYPTION_ZERO_RTT,
5910 QuicMakeUnique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005911 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
5912 QuicMakeUnique<TaggingEncrypter>(tag));
5913 // Process a packet from the non-crypto stream.
5914 frame1_.stream_id = 3;
5915
5916 // Process all the initial packets in order so there aren't missing packets.
5917 uint64_t kFirstDecimatedPacket = 101;
5918 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
5919 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5920 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5921 }
5922 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5923 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07005924 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005925 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5926 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
5927 ENCRYPTION_ZERO_RTT);
5928
5929 // Check if delayed ack timer is running for the expected interval.
5930 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5931 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5932
5933 // The 10th received packet causes an ack to be sent.
5934 for (int i = 0; i < 9; ++i) {
5935 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5936 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5937 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
5938 ENCRYPTION_ZERO_RTT);
5939 }
5940 // Check that ack is sent and that delayed ack alarm is reset.
5941 if (GetParam().no_stop_waiting) {
5942 EXPECT_EQ(1u, writer_->frame_count());
5943 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
5944 } else {
5945 EXPECT_EQ(2u, writer_->frame_count());
5946 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
5947 }
5948 EXPECT_FALSE(writer_->ack_frames().empty());
5949 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5950}
5951
5952TEST_P(QuicConnectionTest, SendDelayedAckDecimationWithReordering) {
5953 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
5954 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
5955
5956 const size_t kMinRttMs = 40;
5957 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
5958 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
5959 QuicTime::Delta::Zero(), QuicTime::Zero());
5960 // The ack time should be based on min_rtt/4, since it's less than the
5961 // default delayed ack time.
5962 QuicTime ack_time = clock_.ApproximateNow() +
5963 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
5964 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5965 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5966 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07005967 SetDecrypter(ENCRYPTION_ZERO_RTT,
5968 QuicMakeUnique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005969 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
5970 QuicMakeUnique<TaggingEncrypter>(tag));
5971 // Process a packet from the non-crypto stream.
5972 frame1_.stream_id = 3;
5973
5974 // Process all the initial packets in order so there aren't missing packets.
5975 uint64_t kFirstDecimatedPacket = 101;
5976 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
5977 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5978 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5979 }
5980 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5981
5982 // Receive one packet out of order and then the rest in order.
5983 // The loop leaves a one packet gap between acks sent to simulate some loss.
5984 for (int j = 0; j < 3; ++j) {
5985 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
5986 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5987 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 9 + (j * 11),
5988 !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5989 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
5990 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5991 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5992
5993 // The 10th received packet causes an ack to be sent.
5994 writer_->Reset();
5995 for (int i = 0; i < 9; ++i) {
5996 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5997 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5998 // The ACK shouldn't be sent until the 10th packet is processed.
5999 EXPECT_TRUE(writer_->ack_frames().empty());
6000 ProcessDataPacketAtLevel(kFirstDecimatedPacket + i + (j * 11),
6001 !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6002 }
6003 // Check that ack is sent and that delayed ack alarm is reset.
6004 if (GetParam().no_stop_waiting) {
6005 EXPECT_EQ(1u, writer_->frame_count());
6006 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6007 } else {
6008 EXPECT_EQ(2u, writer_->frame_count());
6009 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6010 }
6011 EXPECT_FALSE(writer_->ack_frames().empty());
6012 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6013 }
6014}
6015
6016TEST_P(QuicConnectionTest, SendDelayedAckDecimationWithLargeReordering) {
6017 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6018 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6019
6020 const size_t kMinRttMs = 40;
6021 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6022 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6023 QuicTime::Delta::Zero(), QuicTime::Zero());
6024 // The ack time should be based on min_rtt/4, since it's less than the
6025 // default delayed ack time.
6026 QuicTime ack_time = clock_.ApproximateNow() +
6027 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6028 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6029 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6030 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006031 SetDecrypter(ENCRYPTION_ZERO_RTT,
6032 QuicMakeUnique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006033 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
6034 QuicMakeUnique<TaggingEncrypter>(tag));
6035 // Process a packet from the non-crypto stream.
6036 frame1_.stream_id = 3;
6037
6038 // Process all the initial packets in order so there aren't missing packets.
6039 uint64_t kFirstDecimatedPacket = 101;
6040 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6041 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6042 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6043 }
6044 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6045 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006046 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006047 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6048 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6049 ENCRYPTION_ZERO_RTT);
6050
6051 // Check if delayed ack timer is running for the expected interval.
6052 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6053 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6054
6055 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6056 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6057 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 19, !kHasStopWaiting,
6058 ENCRYPTION_ZERO_RTT);
6059 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
6060 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6061 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6062
6063 // The 10th received packet causes an ack to be sent.
6064 for (int i = 0; i < 8; ++i) {
6065 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6066 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6067 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6068 ENCRYPTION_ZERO_RTT);
6069 }
6070 // Check that ack is sent and that delayed ack alarm is reset.
6071 if (GetParam().no_stop_waiting) {
6072 EXPECT_EQ(1u, writer_->frame_count());
6073 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6074 } else {
6075 EXPECT_EQ(2u, writer_->frame_count());
6076 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6077 }
6078 EXPECT_FALSE(writer_->ack_frames().empty());
6079 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6080
6081 // The next packet received in order will cause an immediate ack,
6082 // because it fills a hole.
6083 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6084 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6085 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 10, !kHasStopWaiting,
6086 ENCRYPTION_ZERO_RTT);
6087 // Check that ack is sent and that delayed ack alarm is reset.
6088 if (GetParam().no_stop_waiting) {
6089 EXPECT_EQ(1u, writer_->frame_count());
6090 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6091 } else {
6092 EXPECT_EQ(2u, writer_->frame_count());
6093 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6094 }
6095 EXPECT_FALSE(writer_->ack_frames().empty());
6096 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6097}
6098
6099TEST_P(QuicConnectionTest, SendDelayedAckDecimationWithReorderingEighthRtt) {
6100 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6101 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6102 QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
6103
6104 const size_t kMinRttMs = 40;
6105 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6106 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6107 QuicTime::Delta::Zero(), QuicTime::Zero());
6108 // The ack time should be based on min_rtt/8, since it's less than the
6109 // default delayed ack time.
6110 QuicTime ack_time = clock_.ApproximateNow() +
6111 QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
6112 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6113 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6114 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006115 SetDecrypter(ENCRYPTION_ZERO_RTT,
6116 QuicMakeUnique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006117 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
6118 QuicMakeUnique<TaggingEncrypter>(tag));
6119 // Process a packet from the non-crypto stream.
6120 frame1_.stream_id = 3;
6121
6122 // Process all the initial packets in order so there aren't missing packets.
6123 uint64_t kFirstDecimatedPacket = 101;
6124 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6125 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6126 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6127 }
6128 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6129 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006130 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006131 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6132 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6133 ENCRYPTION_ZERO_RTT);
6134
6135 // Check if delayed ack timer is running for the expected interval.
6136 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6137 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6138
6139 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6140 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6141 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 9, !kHasStopWaiting,
6142 ENCRYPTION_ZERO_RTT);
6143 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
6144 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6145 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6146
6147 // The 10th received packet causes an ack to be sent.
6148 for (int i = 0; i < 8; ++i) {
6149 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6150 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6151 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6152 ENCRYPTION_ZERO_RTT);
6153 }
6154 // Check that ack is sent and that delayed ack alarm is reset.
6155 if (GetParam().no_stop_waiting) {
6156 EXPECT_EQ(1u, writer_->frame_count());
6157 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6158 } else {
6159 EXPECT_EQ(2u, writer_->frame_count());
6160 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6161 }
6162 EXPECT_FALSE(writer_->ack_frames().empty());
6163 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6164}
6165
6166TEST_P(QuicConnectionTest,
6167 SendDelayedAckDecimationWithLargeReorderingEighthRtt) {
6168 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6169 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6170 QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
6171
6172 const size_t kMinRttMs = 40;
6173 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6174 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6175 QuicTime::Delta::Zero(), QuicTime::Zero());
6176 // The ack time should be based on min_rtt/8, since it's less than the
6177 // default delayed ack time.
6178 QuicTime ack_time = clock_.ApproximateNow() +
6179 QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
6180 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6181 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6182 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006183 SetDecrypter(ENCRYPTION_ZERO_RTT,
6184 QuicMakeUnique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006185 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
6186 QuicMakeUnique<TaggingEncrypter>(tag));
6187 // Process a packet from the non-crypto stream.
6188 frame1_.stream_id = 3;
6189
6190 // Process all the initial packets in order so there aren't missing packets.
6191 uint64_t kFirstDecimatedPacket = 101;
6192 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6193 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6194 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6195 }
6196 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6197 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006198 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006199 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6200 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6201 ENCRYPTION_ZERO_RTT);
6202
6203 // Check if delayed ack timer is running for the expected interval.
6204 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6205 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6206
6207 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6208 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6209 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 19, !kHasStopWaiting,
6210 ENCRYPTION_ZERO_RTT);
6211 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
6212 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6213 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6214
6215 // The 10th received packet causes an ack to be sent.
6216 for (int i = 0; i < 8; ++i) {
6217 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6218 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6219 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6220 ENCRYPTION_ZERO_RTT);
6221 }
6222 // Check that ack is sent and that delayed ack alarm is reset.
6223 if (GetParam().no_stop_waiting) {
6224 EXPECT_EQ(1u, writer_->frame_count());
6225 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6226 } else {
6227 EXPECT_EQ(2u, writer_->frame_count());
6228 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6229 }
6230 EXPECT_FALSE(writer_->ack_frames().empty());
6231 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6232
6233 // The next packet received in order will cause an immediate ack,
6234 // because it fills a hole.
6235 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6236 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6237 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 10, !kHasStopWaiting,
6238 ENCRYPTION_ZERO_RTT);
6239 // Check that ack is sent and that delayed ack alarm is reset.
6240 if (GetParam().no_stop_waiting) {
6241 EXPECT_EQ(1u, writer_->frame_count());
6242 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6243 } else {
6244 EXPECT_EQ(2u, writer_->frame_count());
6245 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6246 }
6247 EXPECT_FALSE(writer_->ack_frames().empty());
6248 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6249}
6250
6251TEST_P(QuicConnectionTest, SendDelayedAckOnHandshakeConfirmed) {
6252 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6253 ProcessPacket(1);
6254 // Check that ack is sent and that delayed ack alarm is set.
6255 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6256 QuicTime ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6257 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6258
6259 // Completing the handshake as the server does nothing.
6260 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_SERVER);
6261 connection_.OnHandshakeComplete();
6262 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6263 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6264
6265 // Complete the handshake as the client decreases the delayed ack time to 0ms.
6266 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_CLIENT);
6267 connection_.OnHandshakeComplete();
6268 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6269 EXPECT_EQ(clock_.ApproximateNow(), connection_.GetAckAlarm()->deadline());
6270}
6271
6272TEST_P(QuicConnectionTest, SendDelayedAckOnSecondPacket) {
6273 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6274 ProcessPacket(1);
6275 ProcessPacket(2);
6276 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006277 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006278 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006279 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006280 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6281 } else {
nharper55fa6132019-05-07 19:37:21 -07006282 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006283 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6284 }
6285 EXPECT_FALSE(writer_->ack_frames().empty());
6286 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6287}
6288
6289TEST_P(QuicConnectionTest, NoAckOnOldNacks) {
6290 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6291 // Drop one packet, triggering a sequence of acks.
6292 if (GetQuicRestartFlag(quic_enable_accept_random_ipn)) {
6293 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6294 } else {
6295 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
6296 }
6297 ProcessPacket(2);
6298 size_t frames_per_ack = GetParam().no_stop_waiting ? 1 : 2;
6299 if (!GetQuicRestartFlag(quic_enable_accept_random_ipn)) {
nharper55fa6132019-05-07 19:37:21 -07006300 size_t padding_frame_count = writer_->padding_frames().size();
6301 EXPECT_EQ(padding_frame_count + frames_per_ack, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006302 EXPECT_FALSE(writer_->ack_frames().empty());
6303 writer_->Reset();
6304 }
6305
6306 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
6307 ProcessPacket(3);
nharper55fa6132019-05-07 19:37:21 -07006308 size_t padding_frame_count = writer_->padding_frames().size();
6309 EXPECT_EQ(padding_frame_count + frames_per_ack, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006310 EXPECT_FALSE(writer_->ack_frames().empty());
6311 writer_->Reset();
6312
6313 if (GetQuicRestartFlag(quic_enable_accept_random_ipn)) {
6314 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6315 } else {
6316 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
6317 }
6318 ProcessPacket(4);
6319 if (GetQuicRestartFlag(quic_enable_accept_random_ipn)) {
6320 EXPECT_EQ(0u, writer_->frame_count());
6321 } else {
nharper55fa6132019-05-07 19:37:21 -07006322 EXPECT_EQ(padding_frame_count + frames_per_ack, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006323 EXPECT_FALSE(writer_->ack_frames().empty());
6324 writer_->Reset();
6325 }
6326
6327 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
6328 ProcessPacket(5);
nharper55fa6132019-05-07 19:37:21 -07006329 padding_frame_count = writer_->padding_frames().size();
6330 EXPECT_EQ(padding_frame_count + frames_per_ack, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006331 EXPECT_FALSE(writer_->ack_frames().empty());
6332 writer_->Reset();
6333
6334 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6335 // Now only set the timer on the 6th packet, instead of sending another ack.
6336 ProcessPacket(6);
nharper55fa6132019-05-07 19:37:21 -07006337 padding_frame_count = writer_->padding_frames().size();
6338 EXPECT_EQ(padding_frame_count, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006339 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6340}
6341
6342TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingPacket) {
6343 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
QUICHE team8c1daa22019-03-13 08:33:41 -07006344 EXPECT_CALL(visitor_, OnStreamFrame(_));
6345 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
6346 QuicMakeUnique<TaggingEncrypter>(0x01));
zhongyi546cc452019-04-12 15:27:49 -07006347 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
6348 QuicMakeUnique<StrictTaggingDecrypter>(0x01));
nharper2c9f02a2019-05-08 10:25:50 -07006349 ProcessDataPacket(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006350 connection_.SendStreamDataWithString(
6351 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6352 0, NO_FIN);
6353 // Check that ack is bundled with outgoing data and that delayed ack
6354 // alarm is reset.
6355 if (GetParam().no_stop_waiting) {
6356 EXPECT_EQ(2u, writer_->frame_count());
6357 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6358 } else {
6359 EXPECT_EQ(3u, writer_->frame_count());
6360 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6361 }
6362 EXPECT_FALSE(writer_->ack_frames().empty());
6363 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6364}
6365
6366TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingCryptoPacket) {
QUICHE teamcd098022019-03-22 18:49:55 -07006367 if (connection_.SupportsMultiplePacketNumberSpaces()) {
6368 return;
6369 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006370 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6371 ProcessPacket(1);
nharper46833c32019-05-15 21:33:05 -07006372 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006373 // Check that ack is bundled with outgoing crypto data.
6374 if (GetParam().no_stop_waiting) {
6375 EXPECT_EQ(3u, writer_->frame_count());
6376 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6377 } else {
6378 EXPECT_EQ(4u, writer_->frame_count());
6379 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6380 }
6381 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6382}
6383
6384TEST_P(QuicConnectionTest, BlockAndBufferOnFirstCHLOPacketOfTwo) {
6385 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6386 ProcessPacket(1);
6387 BlockOnNextWrite();
6388 writer_->set_is_write_blocked_data_buffered(true);
nharper46833c32019-05-15 21:33:05 -07006389 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006390 EXPECT_TRUE(writer_->IsWriteBlocked());
6391 EXPECT_FALSE(connection_.HasQueuedData());
nharper46833c32019-05-15 21:33:05 -07006392 connection_.SendCryptoDataWithString("bar", 3);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006393 EXPECT_TRUE(writer_->IsWriteBlocked());
6394 EXPECT_TRUE(connection_.HasQueuedData());
6395}
6396
6397TEST_P(QuicConnectionTest, BundleAckForSecondCHLO) {
QUICHE teamcd098022019-03-22 18:49:55 -07006398 if (connection_.SupportsMultiplePacketNumberSpaces()) {
6399 return;
6400 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006401 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6402 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6403 EXPECT_CALL(visitor_, OnCanWrite())
6404 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6405 &connection_, &TestConnection::SendCryptoStreamData)));
6406 // Process a packet from the crypto stream, which is frame1_'s default.
6407 // Receiving the CHLO as packet 2 first will cause the connection to
6408 // immediately send an ack, due to the packet gap.
6409 ProcessPacket(2);
6410 // Check that ack is sent and that delayed ack alarm is reset.
6411 if (GetParam().no_stop_waiting) {
6412 EXPECT_EQ(3u, writer_->frame_count());
6413 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6414 } else {
6415 EXPECT_EQ(4u, writer_->frame_count());
6416 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6417 }
QUICHE teamea740082019-03-11 17:58:43 -07006418 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006419 EXPECT_EQ(1u, writer_->stream_frames().size());
6420 } else {
6421 EXPECT_EQ(1u, writer_->crypto_frames().size());
6422 }
6423 EXPECT_EQ(1u, writer_->padding_frames().size());
6424 ASSERT_FALSE(writer_->ack_frames().empty());
6425 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(writer_->ack_frames().front()));
6426 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6427}
6428
6429TEST_P(QuicConnectionTest, BundleAckForSecondCHLOTwoPacketReject) {
QUICHE teamcd098022019-03-22 18:49:55 -07006430 if (connection_.SupportsMultiplePacketNumberSpaces()) {
6431 return;
6432 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006433 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6434 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6435
6436 // Process two packets from the crypto stream, which is frame1_'s default,
6437 // simulating a 2 packet reject.
6438 {
6439 ProcessPacket(1);
6440 // Send the new CHLO when the REJ is processed.
6441 EXPECT_CALL(visitor_, OnStreamFrame(_))
6442 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6443 &connection_, &TestConnection::SendCryptoStreamData)));
6444 ProcessDataPacket(2);
6445 }
6446 // Check that ack is sent and that delayed ack alarm is reset.
6447 if (GetParam().no_stop_waiting) {
6448 EXPECT_EQ(3u, writer_->frame_count());
6449 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6450 } else {
6451 EXPECT_EQ(4u, writer_->frame_count());
6452 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6453 }
QUICHE teamea740082019-03-11 17:58:43 -07006454 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006455 EXPECT_EQ(1u, writer_->stream_frames().size());
6456 } else {
6457 EXPECT_EQ(1u, writer_->crypto_frames().size());
6458 }
6459 EXPECT_EQ(1u, writer_->padding_frames().size());
6460 ASSERT_FALSE(writer_->ack_frames().empty());
6461 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(writer_->ack_frames().front()));
6462 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6463}
6464
6465TEST_P(QuicConnectionTest, BundleAckWithDataOnIncomingAck) {
6466 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6467 connection_.SendStreamDataWithString(
6468 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6469 0, NO_FIN);
6470 connection_.SendStreamDataWithString(
6471 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6472 3, NO_FIN);
6473 // Ack the second packet, which will retransmit the first packet.
6474 QuicAckFrame ack = ConstructAckFrame(2, 1);
6475 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07006476 lost_packets.push_back(
6477 LostPacket(QuicPacketNumber(1), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006478 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
6479 .WillOnce(SetArgPointee<5>(lost_packets));
6480 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
6481 ProcessAckPacket(&ack);
nharper55fa6132019-05-07 19:37:21 -07006482 size_t padding_frame_count = writer_->padding_frames().size();
6483 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006484 EXPECT_EQ(1u, writer_->stream_frames().size());
6485 writer_->Reset();
6486
6487 // Now ack the retransmission, which will both raise the high water mark
6488 // and see if there is more data to send.
6489 ack = ConstructAckFrame(3, 1);
6490 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
6491 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
6492 ProcessAckPacket(&ack);
6493
6494 // Check that no packet is sent and the ack alarm isn't set.
6495 EXPECT_EQ(0u, writer_->frame_count());
6496 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6497 writer_->Reset();
6498
6499 // Send the same ack, but send both data and an ack together.
6500 ack = ConstructAckFrame(3, 1);
6501 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
6502 EXPECT_CALL(visitor_, OnCanWrite())
6503 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6504 &connection_, &TestConnection::EnsureWritableAndSendStreamData5)));
6505 ProcessAckPacket(&ack);
6506
6507 // Check that ack is bundled with outgoing data and the delayed ack
6508 // alarm is reset.
6509 if (GetParam().no_stop_waiting) {
fayang03916692019-05-22 17:57:18 -07006510 if (GetQuicReloadableFlag(quic_simplify_stop_waiting)) {
6511 // Do not ACK acks.
6512 EXPECT_EQ(1u, writer_->frame_count());
6513 } else {
6514 EXPECT_EQ(2u, writer_->frame_count());
6515 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6516 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006517 } else {
6518 EXPECT_EQ(3u, writer_->frame_count());
6519 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6520 }
fayang03916692019-05-22 17:57:18 -07006521 if (GetParam().no_stop_waiting &&
6522 GetQuicReloadableFlag(quic_simplify_stop_waiting)) {
6523 EXPECT_TRUE(writer_->ack_frames().empty());
6524 } else {
6525 EXPECT_FALSE(writer_->ack_frames().empty());
6526 EXPECT_EQ(QuicPacketNumber(3u),
6527 LargestAcked(writer_->ack_frames().front()));
6528 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006529 EXPECT_EQ(1u, writer_->stream_frames().size());
6530 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6531}
6532
6533TEST_P(QuicConnectionTest, NoAckSentForClose) {
6534 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6535 ProcessPacket(1);
6536 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, _,
6537 ConnectionCloseSource::FROM_PEER));
6538 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6539 ProcessClosePacket(2);
6540}
6541
6542TEST_P(QuicConnectionTest, SendWhenDisconnected) {
6543 EXPECT_TRUE(connection_.connected());
6544 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, _,
6545 ConnectionCloseSource::FROM_SELF));
6546 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
6547 ConnectionCloseBehavior::SILENT_CLOSE);
6548 EXPECT_FALSE(connection_.connected());
6549 EXPECT_FALSE(connection_.CanWriteStreamData());
QUICHE team8c1daa22019-03-13 08:33:41 -07006550 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07006551 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006552 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6553 .Times(0);
QUICHE team6987b4a2019-03-15 16:23:04 -07006554 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05006555 HAS_RETRANSMITTABLE_DATA, false, false);
6556}
6557
6558TEST_P(QuicConnectionTest, SendConnectivityProbingWhenDisconnected) {
6559 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
QUICHE teamcd098022019-03-22 18:49:55 -07006560 if (!IsDefaultTestConfiguration() ||
6561 connection_.SupportsMultiplePacketNumberSpaces()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006562 return;
6563 }
6564
6565 EXPECT_TRUE(connection_.connected());
6566 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, _,
6567 ConnectionCloseSource::FROM_SELF));
6568 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
6569 ConnectionCloseBehavior::SILENT_CLOSE);
6570 EXPECT_FALSE(connection_.connected());
6571 EXPECT_FALSE(connection_.CanWriteStreamData());
6572
6573 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6574 .Times(0);
6575
6576 EXPECT_QUIC_BUG(connection_.SendConnectivityProbingPacket(
6577 writer_.get(), connection_.peer_address()),
6578 "Not sending connectivity probing packet as connection is "
6579 "disconnected.");
6580}
6581
6582TEST_P(QuicConnectionTest, WriteBlockedAfterClientSendsConnectivityProbe) {
6583 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
6584 TestPacketWriter probing_writer(version(), &clock_);
6585 // Block next write so that sending connectivity probe will encounter a
6586 // blocked write when send a connectivity probe to the peer.
6587 probing_writer.BlockOnNextWrite();
6588 // Connection will not be marked as write blocked as connectivity probe only
6589 // affects the probing_writer which is not the default.
6590 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
6591
6592 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6593 .Times(1);
6594 connection_.SendConnectivityProbingPacket(&probing_writer,
6595 connection_.peer_address());
6596}
6597
6598TEST_P(QuicConnectionTest, WriterBlockedAfterServerSendsConnectivityProbe) {
6599 set_perspective(Perspective::IS_SERVER);
6600 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
6601
6602 // Block next write so that sending connectivity probe will encounter a
6603 // blocked write when send a connectivity probe to the peer.
6604 writer_->BlockOnNextWrite();
6605 // Connection will be marked as write blocked as server uses the default
6606 // writer to send connectivity probes.
6607 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
6608
6609 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6610 .Times(1);
6611 connection_.SendConnectivityProbingPacket(writer_.get(),
6612 connection_.peer_address());
6613}
6614
6615TEST_P(QuicConnectionTest, WriterErrorWhenClientSendsConnectivityProbe) {
6616 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
6617 TestPacketWriter probing_writer(version(), &clock_);
6618 probing_writer.SetShouldWriteFail();
6619
6620 // Connection should not be closed if a connectivity probe is failed to be
6621 // sent.
6622 EXPECT_CALL(visitor_, OnConnectionClosed(_, _, _)).Times(0);
6623
6624 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6625 .Times(0);
6626 connection_.SendConnectivityProbingPacket(&probing_writer,
6627 connection_.peer_address());
6628}
6629
6630TEST_P(QuicConnectionTest, WriterErrorWhenServerSendsConnectivityProbe) {
6631 set_perspective(Perspective::IS_SERVER);
6632 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
6633
6634 writer_->SetShouldWriteFail();
6635 // Connection should not be closed if a connectivity probe is failed to be
6636 // sent.
6637 EXPECT_CALL(visitor_, OnConnectionClosed(_, _, _)).Times(0);
6638
6639 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6640 .Times(0);
6641 connection_.SendConnectivityProbingPacket(writer_.get(),
6642 connection_.peer_address());
6643}
6644
6645TEST_P(QuicConnectionTest, PublicReset) {
fayangd4291e42019-05-30 10:31:21 -07006646 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version) ||
QUICHE teamcd098022019-03-22 18:49:55 -07006647 connection_.SupportsMultiplePacketNumberSpaces()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006648 return;
6649 }
6650 QuicPublicResetPacket header;
6651 // Public reset packet in only built by server.
6652 header.connection_id = connection_id_;
6653 std::unique_ptr<QuicEncryptedPacket> packet(
6654 framer_.BuildPublicResetPacket(header));
6655 std::unique_ptr<QuicReceivedPacket> received(
6656 ConstructReceivedPacket(*packet, QuicTime::Zero()));
6657 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PUBLIC_RESET, _,
6658 ConnectionCloseSource::FROM_PEER));
6659 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
6660}
6661
6662TEST_P(QuicConnectionTest, IetfStatelessReset) {
fayangd4291e42019-05-30 10:31:21 -07006663 if (!VersionHasIetfInvariantHeader(GetParam().version.transport_version) ||
QUICHE teamcd098022019-03-22 18:49:55 -07006664 connection_.SupportsMultiplePacketNumberSpaces()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006665 return;
6666 }
6667 const QuicUint128 kTestStatelessResetToken = 1010101;
6668 QuicConfig config;
6669 QuicConfigPeer::SetReceivedStatelessResetToken(&config,
6670 kTestStatelessResetToken);
6671 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6672 connection_.SetFromConfig(config);
6673 std::unique_ptr<QuicEncryptedPacket> packet(
6674 QuicFramer::BuildIetfStatelessResetPacket(connection_id_,
6675 kTestStatelessResetToken));
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, GoAway) {
QUICHE teamcd098022019-03-22 18:49:55 -07006684 if (GetParam().version.transport_version == QUIC_VERSION_99 ||
6685 connection_.SupportsMultiplePacketNumberSpaces()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006686 // GoAway is not available in version 99.
6687 return;
6688 }
6689
6690 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6691
6692 QuicGoAwayFrame goaway;
6693 goaway.last_good_stream_id = 1;
6694 goaway.error_code = QUIC_PEER_GOING_AWAY;
6695 goaway.reason_phrase = "Going away.";
6696 EXPECT_CALL(visitor_, OnGoAway(_));
6697 ProcessGoAwayPacket(&goaway);
6698}
6699
6700TEST_P(QuicConnectionTest, WindowUpdate) {
6701 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6702
6703 QuicWindowUpdateFrame window_update;
6704 window_update.stream_id = 3;
6705 window_update.byte_offset = 1234;
6706 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
6707 ProcessFramePacket(QuicFrame(&window_update));
6708}
6709
6710TEST_P(QuicConnectionTest, Blocked) {
6711 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6712
6713 QuicBlockedFrame blocked;
6714 blocked.stream_id = 3;
6715 EXPECT_CALL(visitor_, OnBlockedFrame(_));
6716 ProcessFramePacket(QuicFrame(&blocked));
6717 EXPECT_EQ(1u, connection_.GetStats().blocked_frames_received);
6718 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
6719}
6720
6721TEST_P(QuicConnectionTest, ZeroBytePacket) {
6722 // Don't close the connection for zero byte packets.
6723 EXPECT_CALL(visitor_, OnConnectionClosed(_, _, _)).Times(0);
6724 QuicReceivedPacket encrypted(nullptr, 0, QuicTime::Zero());
6725 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, encrypted);
6726}
6727
6728TEST_P(QuicConnectionTest, MissingPacketsBeforeLeastUnacked) {
fayangd4291e42019-05-30 10:31:21 -07006729 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006730 return;
6731 }
6732 // Set the packet number of the ack packet to be least unacked (4).
6733 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 3);
6734 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6735 ProcessStopWaitingPacket(InitStopWaitingFrame(4));
6736 EXPECT_FALSE(outgoing_ack()->packets.Empty());
6737}
6738
6739TEST_P(QuicConnectionTest, ServerSendsVersionNegotiationPacket) {
6740 // Turn off QUIC_VERSION_99.
6741 SetQuicReloadableFlag(quic_enable_version_99, false);
6742 connection_.SetSupportedVersions(CurrentSupportedVersions());
6743 set_perspective(Perspective::IS_SERVER);
fayangd4291e42019-05-30 10:31:21 -07006744 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006745 peer_framer_.set_version_for_tests(
6746 ParsedQuicVersion(PROTOCOL_QUIC_CRYPTO, QUIC_VERSION_99));
6747 } else {
6748 peer_framer_.set_version_for_tests(UnsupportedQuicVersion());
6749 }
6750
6751 QuicPacketHeader header;
6752 header.destination_connection_id = connection_id_;
6753 header.version_flag = true;
6754 header.packet_number = QuicPacketNumber(12);
6755
6756 if (QuicVersionHasLongHeaderLengths(
6757 peer_framer_.version().transport_version)) {
6758 header.long_packet_type = INITIAL;
6759 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
6760 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
6761 }
6762
6763 QuicFrames frames;
6764 frames.push_back(QuicFrame(frame1_));
6765 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
dschinazi66dea072019-04-09 11:41:06 -07006766 char buffer[kMaxOutgoingPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07006767 size_t encrypted_length =
6768 framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12), *packet,
dschinazi66dea072019-04-09 11:41:06 -07006769 buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006770
6771 framer_.set_version(version());
6772 // Writer's framer's perspective is client, so that it needs to have the right
6773 // version to process either IETF or GQUIC version negotiation packet.
6774 writer_->SetSupportedVersions({version()});
6775 connection_.ProcessUdpPacket(
6776 kSelfAddress, kPeerAddress,
6777 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
6778 EXPECT_TRUE(writer_->version_negotiation_packet() != nullptr);
6779
6780 ParsedQuicVersionVector supported_versions = CurrentSupportedVersions();
6781 ASSERT_EQ(supported_versions.size(),
6782 writer_->version_negotiation_packet()->versions.size());
6783
6784 // We expect all versions in supported_versions to be
6785 // included in the packet.
6786 for (size_t i = 0; i < supported_versions.size(); ++i) {
6787 EXPECT_EQ(supported_versions[i],
6788 writer_->version_negotiation_packet()->versions[i]);
6789 }
6790}
6791
6792TEST_P(QuicConnectionTest, ServerSendsVersionNegotiationPacketSocketBlocked) {
6793 // Turn off QUIC_VERSION_99.
6794 SetQuicReloadableFlag(quic_enable_version_99, false);
6795 connection_.SetSupportedVersions(CurrentSupportedVersions());
6796 set_perspective(Perspective::IS_SERVER);
fayangd4291e42019-05-30 10:31:21 -07006797 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006798 peer_framer_.set_version_for_tests(
6799 ParsedQuicVersion(PROTOCOL_QUIC_CRYPTO, QUIC_VERSION_99));
6800 } else {
6801 peer_framer_.set_version_for_tests(UnsupportedQuicVersion());
6802 }
6803
6804 QuicPacketHeader header;
6805 header.destination_connection_id = connection_id_;
6806 header.version_flag = true;
6807 header.packet_number = QuicPacketNumber(12);
6808
6809 if (QuicVersionHasLongHeaderLengths(
6810 peer_framer_.version().transport_version)) {
6811 header.long_packet_type = INITIAL;
6812 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
6813 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
6814 }
6815
6816 QuicFrames frames;
6817 frames.push_back(QuicFrame(frame1_));
6818 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
dschinazi66dea072019-04-09 11:41:06 -07006819 char buffer[kMaxOutgoingPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07006820 size_t encrypted_length =
6821 framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12), *packet,
dschinazi66dea072019-04-09 11:41:06 -07006822 buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006823
6824 framer_.set_version(version());
6825 BlockOnNextWrite();
6826 // Writer's framer's perspective is client, so that it needs to have the right
6827 // version to process either IETF or GQUIC version negotiation packet.
6828 writer_->SetSupportedVersions({version()});
6829 connection_.ProcessUdpPacket(
6830 kSelfAddress, kPeerAddress,
6831 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
6832 EXPECT_EQ(0u, writer_->last_packet_size());
6833 EXPECT_TRUE(connection_.HasQueuedData());
6834
6835 writer_->SetWritable();
6836 connection_.OnCanWrite();
6837 EXPECT_TRUE(writer_->version_negotiation_packet() != nullptr);
6838
6839 ParsedQuicVersionVector supported_versions = CurrentSupportedVersions();
6840 ASSERT_EQ(supported_versions.size(),
6841 writer_->version_negotiation_packet()->versions.size());
6842
6843 // We expect all versions in supported_versions to be
6844 // included in the packet.
6845 for (size_t i = 0; i < supported_versions.size(); ++i) {
6846 EXPECT_EQ(supported_versions[i],
6847 writer_->version_negotiation_packet()->versions[i]);
6848 }
6849}
6850
6851TEST_P(QuicConnectionTest,
6852 ServerSendsVersionNegotiationPacketSocketBlockedDataBuffered) {
6853 // Turn off QUIC_VERSION_99.
6854 SetQuicReloadableFlag(quic_enable_version_99, false);
6855 connection_.SetSupportedVersions(CurrentSupportedVersions());
6856 set_perspective(Perspective::IS_SERVER);
fayangd4291e42019-05-30 10:31:21 -07006857 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006858 peer_framer_.set_version_for_tests(
6859 ParsedQuicVersion(PROTOCOL_QUIC_CRYPTO, QUIC_VERSION_99));
6860 } else {
6861 peer_framer_.set_version_for_tests(UnsupportedQuicVersion());
6862 }
6863
6864 QuicPacketHeader header;
6865 header.destination_connection_id = connection_id_;
6866 header.version_flag = true;
6867 header.packet_number = QuicPacketNumber(12);
6868
6869 if (QuicVersionHasLongHeaderLengths(
6870 peer_framer_.version().transport_version)) {
6871 header.long_packet_type = INITIAL;
6872 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
6873 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
6874 }
6875
6876 QuicFrames frames;
6877 frames.push_back(QuicFrame(frame1_));
6878 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
dschinazi66dea072019-04-09 11:41:06 -07006879 char buffer[kMaxOutgoingPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07006880 size_t encryped_length =
6881 framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12), *packet,
dschinazi66dea072019-04-09 11:41:06 -07006882 buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006883
6884 framer_.set_version(version());
6885 set_perspective(Perspective::IS_SERVER);
6886 BlockOnNextWrite();
6887 writer_->set_is_write_blocked_data_buffered(true);
6888 // Writer's framer's perspective is client, so that it needs to have the right
6889 // version to process either IETF or GQUIC version negotiation packet.
6890 writer_->SetSupportedVersions({version()});
6891 connection_.ProcessUdpPacket(
6892 kSelfAddress, kPeerAddress,
6893 QuicReceivedPacket(buffer, encryped_length, QuicTime::Zero(), false));
6894 EXPECT_EQ(0u, writer_->last_packet_size());
6895 EXPECT_FALSE(connection_.HasQueuedData());
6896}
6897
6898TEST_P(QuicConnectionTest, ClientHandlesVersionNegotiation) {
dschinazi5a354c92019-05-09 12:18:53 -07006899 const bool expect_failure =
6900 GetQuicReloadableFlag(quic_no_client_conn_ver_negotiation) ||
6901 connection_.version().handshake_protocol !=
6902 QuicVersionReservedForNegotiation().handshake_protocol;
6903 // Start out with an unsupported version.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006904 QuicConnectionPeer::GetFramer(&connection_)
dschinazi5a354c92019-05-09 12:18:53 -07006905 ->set_version_for_tests(QuicVersionReservedForNegotiation());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006906
6907 // Send a version negotiation packet.
6908 std::unique_ptr<QuicEncryptedPacket> encrypted(
dschinazib417d602019-05-29 13:08:45 -07006909 QuicFramer::BuildVersionNegotiationPacket(
6910 connection_id_, EmptyQuicConnectionId(),
fayangd4291e42019-05-30 10:31:21 -07006911 VersionHasIetfInvariantHeader(connection_.transport_version()),
QUICHE teama6ef0a62019-03-07 20:34:33 -05006912 AllSupportedVersions()));
6913 std::unique_ptr<QuicReceivedPacket> received(
6914 ConstructReceivedPacket(*encrypted, QuicTime::Zero()));
dschinazi5a354c92019-05-09 12:18:53 -07006915 if (expect_failure) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006916 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_VERSION, _,
6917 ConnectionCloseSource::FROM_SELF));
6918 }
6919 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
dschinazi5a354c92019-05-09 12:18:53 -07006920 if (expect_failure) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006921 EXPECT_FALSE(connection_.connected());
6922 return;
6923 }
6924
6925 // Now force another packet. The connection should transition into
6926 // NEGOTIATED_VERSION state and tell the packet creator to StopSendingVersion.
6927 QuicPacketHeader header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05006928 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
QUICHE team2252b702019-05-14 23:55:14 -04006929 if (!GetQuicRestartFlag(quic_do_not_override_connection_id)) {
6930 header.destination_connection_id = connection_id_;
6931 } else {
6932 header.source_connection_id = connection_id_;
6933 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006934 header.packet_number = QuicPacketNumber(12);
6935 header.version_flag = false;
6936 QuicFrames frames;
6937 frames.push_back(QuicFrame(frame1_));
6938 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
dschinazi66dea072019-04-09 11:41:06 -07006939 char buffer[kMaxOutgoingPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07006940 size_t encrypted_length =
6941 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12),
dschinazi66dea072019-04-09 11:41:06 -07006942 *packet, buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006943 ASSERT_NE(0u, encrypted_length);
6944 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6945 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6946 connection_.ProcessUdpPacket(
6947 kSelfAddress, kPeerAddress,
6948 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
fayangd4291e42019-05-30 10:31:21 -07006949 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006950 // IETF QUIC stops sending version when switch to FORWARD_SECURE.
6951 EXPECT_NE(ENCRYPTION_FORWARD_SECURE, connection_.encryption_level());
6952 ASSERT_TRUE(QuicPacketCreatorPeer::SendVersionInPacket(creator_));
6953 } else {
6954 ASSERT_FALSE(QuicPacketCreatorPeer::SendVersionInPacket(creator_));
6955 }
6956}
6957
6958TEST_P(QuicConnectionTest, BadVersionNegotiation) {
6959 // Send a version negotiation packet with the version the client started with.
6960 // It should be rejected.
6961 EXPECT_CALL(visitor_,
6962 OnConnectionClosed(QUIC_INVALID_VERSION_NEGOTIATION_PACKET, _,
6963 ConnectionCloseSource::FROM_SELF));
6964 std::unique_ptr<QuicEncryptedPacket> encrypted(
dschinazib417d602019-05-29 13:08:45 -07006965 QuicFramer::BuildVersionNegotiationPacket(
6966 connection_id_, EmptyQuicConnectionId(),
fayangd4291e42019-05-30 10:31:21 -07006967 VersionHasIetfInvariantHeader(connection_.transport_version()),
QUICHE teama6ef0a62019-03-07 20:34:33 -05006968 AllSupportedVersions()));
6969 std::unique_ptr<QuicReceivedPacket> received(
6970 ConstructReceivedPacket(*encrypted, QuicTime::Zero()));
6971 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
6972}
6973
6974TEST_P(QuicConnectionTest, CheckSendStats) {
6975 connection_.SetMaxTailLossProbes(0);
6976
6977 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
6978 connection_.SendStreamDataWithString(3, "first", 0, NO_FIN);
6979 size_t first_packet_size = writer_->last_packet_size();
6980
6981 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
6982 connection_.SendStreamDataWithString(5, "second", 0, NO_FIN);
6983 size_t second_packet_size = writer_->last_packet_size();
6984
6985 // 2 retransmissions due to rto, 1 due to explicit nack.
6986 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
6987 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
6988
6989 // Retransmit due to RTO.
6990 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
6991 connection_.GetRetransmissionAlarm()->Fire();
6992
6993 // Retransmit due to explicit nacks.
6994 QuicAckFrame nack_three =
6995 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)},
6996 {QuicPacketNumber(4), QuicPacketNumber(5)}});
6997
6998 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07006999 lost_packets.push_back(
7000 LostPacket(QuicPacketNumber(1), kMaxOutgoingPacketSize));
7001 lost_packets.push_back(
7002 LostPacket(QuicPacketNumber(3), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007003 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
7004 .WillOnce(SetArgPointee<5>(lost_packets));
7005 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7006 if (!connection_.session_decides_what_to_write()) {
7007 EXPECT_CALL(visitor_, OnCanWrite());
7008 }
7009 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7010 ProcessAckPacket(&nack_three);
7011
7012 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
7013 .WillOnce(Return(QuicBandwidth::Zero()));
7014
7015 const QuicConnectionStats& stats = connection_.GetStats();
7016 // For IETF QUIC, version is not included as the encryption level switches to
7017 // FORWARD_SECURE in SendStreamDataWithString.
7018 size_t save_on_version =
fayangd4291e42019-05-30 10:31:21 -07007019 VersionHasIetfInvariantHeader(GetParam().version.transport_version)
7020 ? 0
7021 : kQuicVersionSize;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007022 EXPECT_EQ(3 * first_packet_size + 2 * second_packet_size - save_on_version,
7023 stats.bytes_sent);
7024 EXPECT_EQ(5u, stats.packets_sent);
7025 EXPECT_EQ(2 * first_packet_size + second_packet_size - save_on_version,
7026 stats.bytes_retransmitted);
7027 EXPECT_EQ(3u, stats.packets_retransmitted);
7028 EXPECT_EQ(1u, stats.rto_count);
7029 EXPECT_EQ(kDefaultMaxPacketSize, stats.max_packet_size);
7030}
7031
7032TEST_P(QuicConnectionTest, ProcessFramesIfPacketClosedConnection) {
7033 // Construct a packet with stream frame and connection close frame.
7034 QuicPacketHeader header;
QUICHE team2252b702019-05-14 23:55:14 -04007035 if (GetQuicRestartFlag(quic_do_not_override_connection_id) &&
7036 peer_framer_.perspective() == Perspective::IS_SERVER) {
7037 header.source_connection_id = connection_id_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007038 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
fayangd4291e42019-05-30 10:31:21 -07007039 if (!VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04007040 header.source_connection_id_included = CONNECTION_ID_PRESENT;
7041 }
7042 } else {
7043 header.destination_connection_id = connection_id_;
fayangd4291e42019-05-30 10:31:21 -07007044 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04007045 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
7046 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007047 }
7048 header.packet_number = QuicPacketNumber(1);
7049 header.version_flag = false;
7050
fkastenholze9d71a82019-04-09 05:12:13 -07007051 QuicConnectionCloseFrame qccf(QUIC_PEER_GOING_AWAY);
fkastenholz72f509b2019-04-10 09:17:49 -07007052 if (peer_framer_.transport_version() == QUIC_VERSION_99) {
fkastenholz04bd4f32019-04-16 12:24:38 -07007053 // Default close-type is Google QUIC. If doing IETF/V99 then
7054 // set close type to be IETF CC/T.
fkastenholz72f509b2019-04-10 09:17:49 -07007055 qccf.close_type = IETF_QUIC_TRANSPORT_CONNECTION_CLOSE;
7056 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007057
7058 QuicFrames frames;
7059 frames.push_back(QuicFrame(frame1_));
7060 frames.push_back(QuicFrame(&qccf));
7061 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
7062 EXPECT_TRUE(nullptr != packet);
dschinazi66dea072019-04-09 11:41:06 -07007063 char buffer[kMaxOutgoingPacketSize];
7064 size_t encrypted_length =
7065 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(1),
7066 *packet, buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007067
7068 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, _,
7069 ConnectionCloseSource::FROM_PEER));
7070 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7071 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7072
7073 connection_.ProcessUdpPacket(
7074 kSelfAddress, kPeerAddress,
7075 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
7076}
7077
7078TEST_P(QuicConnectionTest, SelectMutualVersion) {
7079 connection_.SetSupportedVersions(AllSupportedVersions());
7080 // Set the connection to speak the lowest quic version.
7081 connection_.set_version(QuicVersionMin());
7082 EXPECT_EQ(QuicVersionMin(), connection_.version());
7083
7084 // Pass in available versions which includes a higher mutually supported
7085 // version. The higher mutually supported version should be selected.
7086 ParsedQuicVersionVector supported_versions = AllSupportedVersions();
7087 EXPECT_TRUE(connection_.SelectMutualVersion(supported_versions));
7088 EXPECT_EQ(QuicVersionMax(), connection_.version());
7089
7090 // Expect that the lowest version is selected.
7091 // Ensure the lowest supported version is less than the max, unless they're
7092 // the same.
7093 ParsedQuicVersionVector lowest_version_vector;
7094 lowest_version_vector.push_back(QuicVersionMin());
7095 EXPECT_TRUE(connection_.SelectMutualVersion(lowest_version_vector));
7096 EXPECT_EQ(QuicVersionMin(), connection_.version());
7097
7098 // Shouldn't be able to find a mutually supported version.
7099 ParsedQuicVersionVector unsupported_version;
7100 unsupported_version.push_back(UnsupportedQuicVersion());
7101 EXPECT_FALSE(connection_.SelectMutualVersion(unsupported_version));
7102}
7103
7104TEST_P(QuicConnectionTest, ConnectionCloseWhenWritable) {
7105 EXPECT_FALSE(writer_->IsWriteBlocked());
7106
7107 // Send a packet.
7108 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7109 EXPECT_EQ(0u, connection_.NumQueuedPackets());
7110 EXPECT_EQ(1u, writer_->packets_write_attempts());
7111
7112 TriggerConnectionClose();
7113 EXPECT_EQ(2u, writer_->packets_write_attempts());
7114}
7115
7116TEST_P(QuicConnectionTest, ConnectionCloseGettingWriteBlocked) {
7117 BlockOnNextWrite();
7118 TriggerConnectionClose();
7119 EXPECT_EQ(1u, writer_->packets_write_attempts());
7120 EXPECT_TRUE(writer_->IsWriteBlocked());
7121}
7122
7123TEST_P(QuicConnectionTest, ConnectionCloseWhenWriteBlocked) {
7124 BlockOnNextWrite();
7125 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7126 EXPECT_EQ(1u, connection_.NumQueuedPackets());
7127 EXPECT_EQ(1u, writer_->packets_write_attempts());
7128 EXPECT_TRUE(writer_->IsWriteBlocked());
7129 TriggerConnectionClose();
7130 EXPECT_EQ(1u, writer_->packets_write_attempts());
7131}
7132
7133TEST_P(QuicConnectionTest, OnPacketSentDebugVisitor) {
7134 MockQuicConnectionDebugVisitor debug_visitor;
7135 connection_.set_debug_visitor(&debug_visitor);
7136
7137 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _)).Times(1);
7138 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7139
7140 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _)).Times(1);
7141 connection_.SendConnectivityProbingPacket(writer_.get(),
7142 connection_.peer_address());
7143}
7144
7145TEST_P(QuicConnectionTest, OnPacketHeaderDebugVisitor) {
7146 QuicPacketHeader header;
7147 header.packet_number = QuicPacketNumber(1);
fayangd4291e42019-05-30 10:31:21 -07007148 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007149 header.form = IETF_QUIC_LONG_HEADER_PACKET;
7150 }
7151
7152 MockQuicConnectionDebugVisitor debug_visitor;
7153 connection_.set_debug_visitor(&debug_visitor);
7154 EXPECT_CALL(debug_visitor, OnPacketHeader(Ref(header))).Times(1);
7155 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(1);
7156 EXPECT_CALL(debug_visitor, OnSuccessfulVersionNegotiation(_)).Times(1);
7157 connection_.OnPacketHeader(header);
7158}
7159
7160TEST_P(QuicConnectionTest, Pacing) {
7161 TestConnection server(connection_id_, kSelfAddress, helper_.get(),
7162 alarm_factory_.get(), writer_.get(),
7163 Perspective::IS_SERVER, version());
7164 TestConnection client(connection_id_, kPeerAddress, helper_.get(),
7165 alarm_factory_.get(), writer_.get(),
7166 Perspective::IS_CLIENT, version());
7167 EXPECT_FALSE(QuicSentPacketManagerPeer::UsingPacing(
7168 static_cast<const QuicSentPacketManager*>(
7169 &client.sent_packet_manager())));
7170 EXPECT_FALSE(QuicSentPacketManagerPeer::UsingPacing(
7171 static_cast<const QuicSentPacketManager*>(
7172 &server.sent_packet_manager())));
7173}
7174
7175TEST_P(QuicConnectionTest, WindowUpdateInstigateAcks) {
7176 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7177
7178 // Send a WINDOW_UPDATE frame.
7179 QuicWindowUpdateFrame window_update;
7180 window_update.stream_id = 3;
7181 window_update.byte_offset = 1234;
7182 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
7183 ProcessFramePacket(QuicFrame(&window_update));
7184
7185 // Ensure that this has caused the ACK alarm to be set.
7186 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
7187 EXPECT_TRUE(ack_alarm->IsSet());
7188}
7189
7190TEST_P(QuicConnectionTest, BlockedFrameInstigateAcks) {
7191 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7192
7193 // Send a BLOCKED frame.
7194 QuicBlockedFrame blocked;
7195 blocked.stream_id = 3;
7196 EXPECT_CALL(visitor_, OnBlockedFrame(_));
7197 ProcessFramePacket(QuicFrame(&blocked));
7198
7199 // Ensure that this has caused the ACK alarm to be set.
7200 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
7201 EXPECT_TRUE(ack_alarm->IsSet());
7202}
7203
7204TEST_P(QuicConnectionTest, ReevaluateTimeUntilSendOnAck) {
7205 // Enable pacing.
7206 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7207 QuicConfig config;
7208 connection_.SetFromConfig(config);
7209
7210 // Send two packets. One packet is not sufficient because if it gets acked,
7211 // there will be no packets in flight after that and the pacer will always
7212 // allow the next packet in that situation.
7213 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7214 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
7215 connection_.SendStreamDataWithString(
7216 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
7217 0, NO_FIN);
7218 connection_.SendStreamDataWithString(
7219 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "bar",
7220 3, NO_FIN);
7221 connection_.OnCanWrite();
7222
7223 // Schedule the next packet for a few milliseconds in future.
7224 QuicSentPacketManagerPeer::DisablePacerBursts(manager_);
7225 QuicTime scheduled_pacing_time =
7226 clock_.Now() + QuicTime::Delta::FromMilliseconds(5);
7227 QuicSentPacketManagerPeer::SetNextPacedPacketTime(manager_,
7228 scheduled_pacing_time);
7229
7230 // Send a packet and have it be blocked by congestion control.
7231 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(false));
7232 connection_.SendStreamDataWithString(
7233 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "baz",
7234 6, NO_FIN);
7235 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
7236
7237 // Process an ack and the send alarm will be set to the new 5ms delay.
7238 QuicAckFrame ack = InitAckFrame(1);
7239 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
7240 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7241 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
7242 ProcessAckPacket(&ack);
nharper55fa6132019-05-07 19:37:21 -07007243 size_t padding_frame_count = writer_->padding_frames().size();
7244 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007245 EXPECT_EQ(1u, writer_->stream_frames().size());
7246 EXPECT_TRUE(connection_.GetSendAlarm()->IsSet());
7247 EXPECT_EQ(scheduled_pacing_time, connection_.GetSendAlarm()->deadline());
7248 writer_->Reset();
7249}
7250
7251TEST_P(QuicConnectionTest, SendAcksImmediately) {
QUICHE teamcd098022019-03-22 18:49:55 -07007252 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7253 return;
7254 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007255 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7256 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7257 ProcessDataPacket(1);
7258 CongestionBlockWrites();
7259 SendAckPacketToPeer();
7260}
7261
7262TEST_P(QuicConnectionTest, SendPingImmediately) {
7263 MockQuicConnectionDebugVisitor debug_visitor;
7264 connection_.set_debug_visitor(&debug_visitor);
7265
7266 CongestionBlockWrites();
7267 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7268 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _)).Times(1);
7269 EXPECT_CALL(debug_visitor, OnPingSent()).Times(1);
7270 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
7271 EXPECT_FALSE(connection_.HasQueuedData());
7272}
7273
7274TEST_P(QuicConnectionTest, SendBlockedImmediately) {
7275 MockQuicConnectionDebugVisitor debug_visitor;
7276 connection_.set_debug_visitor(&debug_visitor);
7277
7278 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7279 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _)).Times(1);
7280 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7281 connection_.SendControlFrame(QuicFrame(new QuicBlockedFrame(1, 3)));
7282 EXPECT_EQ(1u, connection_.GetStats().blocked_frames_sent);
7283 EXPECT_FALSE(connection_.HasQueuedData());
7284}
7285
7286TEST_P(QuicConnectionTest, SendingUnencryptedStreamDataFails) {
7287 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
7288 if (!IsDefaultTestConfiguration()) {
7289 return;
7290 }
7291
7292 EXPECT_CALL(visitor_,
7293 OnConnectionClosed(QUIC_ATTEMPT_TO_SEND_UNENCRYPTED_STREAM_DATA,
7294 _, ConnectionCloseSource::FROM_SELF));
7295 struct iovec iov;
7296 MakeIOVector("", &iov);
7297 EXPECT_QUIC_BUG(connection_.SaveAndSendStreamData(3, &iov, 1, 0, 0, FIN),
fayang49523232019-05-03 06:28:22 -07007298 "Cannot send stream data with level: ENCRYPTION_INITIAL");
QUICHE teama6ef0a62019-03-07 20:34:33 -05007299 EXPECT_FALSE(connection_.connected());
7300}
7301
7302TEST_P(QuicConnectionTest, SetRetransmissionAlarmForCryptoPacket) {
7303 EXPECT_TRUE(connection_.connected());
7304 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
7305
7306 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7307 connection_.SendCryptoStreamData();
7308
7309 // Verify retransmission timer is correctly set after crypto packet has been
7310 // sent.
7311 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
7312 QuicTime retransmission_time =
7313 QuicConnectionPeer::GetSentPacketManager(&connection_)
7314 ->GetRetransmissionTime();
7315 EXPECT_NE(retransmission_time, clock_.ApproximateNow());
7316 EXPECT_EQ(retransmission_time,
7317 connection_.GetRetransmissionAlarm()->deadline());
7318
7319 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7320 connection_.GetRetransmissionAlarm()->Fire();
7321}
7322
7323TEST_P(QuicConnectionTest, PathDegradingAlarmForCryptoPacket) {
7324 EXPECT_TRUE(connection_.connected());
7325 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7326 EXPECT_FALSE(connection_.IsPathDegrading());
7327
7328 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7329 connection_.SendCryptoStreamData();
7330
7331 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7332 EXPECT_FALSE(connection_.IsPathDegrading());
7333 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7334 ->GetPathDegradingDelay();
7335 EXPECT_EQ(clock_.ApproximateNow() + delay,
7336 connection_.GetPathDegradingAlarm()->deadline());
7337
7338 // Fire the path degrading alarm, path degrading signal should be sent to
7339 // the visitor.
7340 EXPECT_CALL(visitor_, OnPathDegrading());
7341 clock_.AdvanceTime(delay);
7342 connection_.GetPathDegradingAlarm()->Fire();
7343 EXPECT_TRUE(connection_.IsPathDegrading());
7344 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7345}
7346
vasilvv693d5b02019-04-09 21:58:56 -07007347// Includes regression test for b/69979024.
QUICHE teama6ef0a62019-03-07 20:34:33 -05007348TEST_P(QuicConnectionTest, PathDegradingAlarmForNonCryptoPackets) {
7349 EXPECT_TRUE(connection_.connected());
7350 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7351 EXPECT_FALSE(connection_.IsPathDegrading());
7352
7353 const char data[] = "data";
7354 size_t data_size = strlen(data);
7355 QuicStreamOffset offset = 0;
7356
7357 for (int i = 0; i < 2; ++i) {
7358 // Send a packet. Now there's a retransmittable packet on the wire, so the
7359 // path degrading alarm should be set.
7360 connection_.SendStreamDataWithString(
7361 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
7362 offset, NO_FIN);
7363 offset += data_size;
7364 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7365 // Check the deadline of the path degrading alarm.
7366 QuicTime::Delta delay =
7367 QuicConnectionPeer::GetSentPacketManager(&connection_)
7368 ->GetPathDegradingDelay();
7369 EXPECT_EQ(clock_.ApproximateNow() + delay,
7370 connection_.GetPathDegradingAlarm()->deadline());
7371
7372 // Send a second packet. The path degrading alarm's deadline should remain
7373 // the same.
vasilvv693d5b02019-04-09 21:58:56 -07007374 // Regression test for b/69979024.
QUICHE teama6ef0a62019-03-07 20:34:33 -05007375 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7376 QuicTime prev_deadline = connection_.GetPathDegradingAlarm()->deadline();
7377 connection_.SendStreamDataWithString(
7378 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
7379 offset, NO_FIN);
7380 offset += data_size;
7381 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7382 EXPECT_EQ(prev_deadline, connection_.GetPathDegradingAlarm()->deadline());
7383
7384 // Now receive an ACK of the first packet. This should advance the path
7385 // degrading alarm's deadline since forward progress has been made.
7386 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7387 if (i == 0) {
7388 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7389 }
7390 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7391 QuicAckFrame frame = InitAckFrame(
7392 {{QuicPacketNumber(1u + 2u * i), QuicPacketNumber(2u + 2u * i)}});
7393 ProcessAckPacket(&frame);
7394 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7395 // Check the deadline of the path degrading alarm.
7396 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7397 ->GetPathDegradingDelay();
7398 EXPECT_EQ(clock_.ApproximateNow() + delay,
7399 connection_.GetPathDegradingAlarm()->deadline());
7400
7401 if (i == 0) {
7402 // Now receive an ACK of the second packet. Since there are no more
7403 // retransmittable packets on the wire, this should cancel the path
7404 // degrading alarm.
7405 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7406 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7407 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
7408 ProcessAckPacket(&frame);
7409 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7410 } else {
7411 // Advance time to the path degrading alarm's deadline and simulate
7412 // firing the alarm.
7413 clock_.AdvanceTime(delay);
7414 EXPECT_CALL(visitor_, OnPathDegrading());
7415 connection_.GetPathDegradingAlarm()->Fire();
7416 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7417 }
7418 }
7419 EXPECT_TRUE(connection_.IsPathDegrading());
7420}
7421
7422TEST_P(QuicConnectionTest, RetransmittableOnWireSetsPingAlarm) {
7423 const QuicTime::Delta retransmittable_on_wire_timeout =
7424 QuicTime::Delta::FromMilliseconds(50);
7425 connection_.set_retransmittable_on_wire_timeout(
7426 retransmittable_on_wire_timeout);
7427
7428 EXPECT_TRUE(connection_.connected());
7429 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7430 .WillRepeatedly(Return(true));
7431
7432 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7433 EXPECT_FALSE(connection_.IsPathDegrading());
7434 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
7435
7436 const char data[] = "data";
7437 size_t data_size = strlen(data);
7438 QuicStreamOffset offset = 0;
7439
7440 // Send a packet.
7441 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7442 offset += data_size;
7443 // Now there's a retransmittable packet on the wire, so the path degrading
7444 // alarm should be set.
7445 // The retransmittable-on-wire alarm should not be set.
7446 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7447 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7448 ->GetPathDegradingDelay();
7449 EXPECT_EQ(clock_.ApproximateNow() + delay,
7450 connection_.GetPathDegradingAlarm()->deadline());
7451 ASSERT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
7452 // The ping alarm is set for the ping timeout, not the shorter
7453 // retransmittable_on_wire_timeout.
7454 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7455 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
7456 EXPECT_EQ((clock_.ApproximateNow() + ping_delay),
7457 connection_.GetPingAlarm()->deadline());
7458
7459 // Now receive an ACK of the packet.
7460 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7461 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7462 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7463 QuicAckFrame frame =
7464 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7465 ProcessAckPacket(&frame);
7466 // No more retransmittable packets on the wire, so the path degrading alarm
7467 // should be cancelled, and the ping alarm should be set to the
7468 // retransmittable_on_wire_timeout.
7469 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7470 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7471 EXPECT_EQ(clock_.ApproximateNow() + retransmittable_on_wire_timeout,
7472 connection_.GetPingAlarm()->deadline());
7473
7474 // Simulate firing the ping alarm and sending a PING.
7475 clock_.AdvanceTime(retransmittable_on_wire_timeout);
7476 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
7477 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
7478 }));
7479 connection_.GetPingAlarm()->Fire();
7480
7481 // Now there's a retransmittable packet (PING) on the wire, so the path
7482 // degrading alarm should be set.
7483 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7484 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7485 ->GetPathDegradingDelay();
7486 EXPECT_EQ(clock_.ApproximateNow() + delay,
7487 connection_.GetPathDegradingAlarm()->deadline());
7488}
7489
7490// This test verifies that the connection marks path as degrading and does not
7491// spin timer to detect path degrading when a new packet is sent on the
7492// degraded path.
7493TEST_P(QuicConnectionTest, NoPathDegradingAlarmIfPathIsDegrading) {
7494 EXPECT_TRUE(connection_.connected());
7495 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7496 EXPECT_FALSE(connection_.IsPathDegrading());
7497
7498 const char data[] = "data";
7499 size_t data_size = strlen(data);
7500 QuicStreamOffset offset = 0;
7501
7502 // Send the first packet. Now there's a retransmittable packet on the wire, so
7503 // the path degrading alarm should be set.
7504 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7505 offset += data_size;
7506 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7507 // Check the deadline of the path degrading alarm.
7508 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7509 ->GetPathDegradingDelay();
7510 EXPECT_EQ(clock_.ApproximateNow() + delay,
7511 connection_.GetPathDegradingAlarm()->deadline());
7512
7513 // Send a second packet. The path degrading alarm's deadline should remain
7514 // the same.
7515 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7516 QuicTime prev_deadline = connection_.GetPathDegradingAlarm()->deadline();
7517 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7518 offset += data_size;
7519 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7520 EXPECT_EQ(prev_deadline, connection_.GetPathDegradingAlarm()->deadline());
7521
7522 // Now receive an ACK of the first packet. This should advance the path
7523 // degrading alarm's deadline since forward progress has been made.
7524 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7525 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7526 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7527 QuicAckFrame frame =
7528 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
7529 ProcessAckPacket(&frame);
7530 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7531 // Check the deadline of the path degrading alarm.
7532 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7533 ->GetPathDegradingDelay();
7534 EXPECT_EQ(clock_.ApproximateNow() + delay,
7535 connection_.GetPathDegradingAlarm()->deadline());
7536
7537 // Advance time to the path degrading alarm's deadline and simulate
7538 // firing the path degrading alarm. This path will be considered as
7539 // degrading.
7540 clock_.AdvanceTime(delay);
7541 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
7542 connection_.GetPathDegradingAlarm()->Fire();
7543 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7544 EXPECT_TRUE(connection_.IsPathDegrading());
7545
7546 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7547 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7548 // Send a third packet. The path degrading alarm is no longer set but path
7549 // should still be marked as degrading.
7550 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7551 offset += data_size;
7552 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7553 EXPECT_TRUE(connection_.IsPathDegrading());
7554}
7555
7556// This test verifies that the connection unmarks path as degrarding and spins
7557// the timer to detect future path degrading when forward progress is made
7558// after path has been marked degrading.
7559TEST_P(QuicConnectionTest, UnmarkPathDegradingOnForwardProgress) {
7560 EXPECT_TRUE(connection_.connected());
7561 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7562 EXPECT_FALSE(connection_.IsPathDegrading());
7563
7564 const char data[] = "data";
7565 size_t data_size = strlen(data);
7566 QuicStreamOffset offset = 0;
7567
7568 // Send the first packet. Now there's a retransmittable packet on the wire, so
7569 // the path degrading alarm should be set.
7570 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7571 offset += data_size;
7572 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7573 // Check the deadline of the path degrading alarm.
7574 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7575 ->GetPathDegradingDelay();
7576 EXPECT_EQ(clock_.ApproximateNow() + delay,
7577 connection_.GetPathDegradingAlarm()->deadline());
7578
7579 // Send a second packet. The path degrading alarm's deadline should remain
7580 // the same.
7581 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7582 QuicTime prev_deadline = connection_.GetPathDegradingAlarm()->deadline();
7583 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7584 offset += data_size;
7585 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7586 EXPECT_EQ(prev_deadline, connection_.GetPathDegradingAlarm()->deadline());
7587
7588 // Now receive an ACK of the first packet. This should advance the path
7589 // degrading alarm's deadline since forward progress has been made.
7590 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7591 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7592 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7593 QuicAckFrame frame =
7594 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
7595 ProcessAckPacket(&frame);
7596 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7597 // Check the deadline of the path degrading alarm.
7598 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7599 ->GetPathDegradingDelay();
7600 EXPECT_EQ(clock_.ApproximateNow() + delay,
7601 connection_.GetPathDegradingAlarm()->deadline());
7602
7603 // Advance time to the path degrading alarm's deadline and simulate
7604 // firing the alarm.
7605 clock_.AdvanceTime(delay);
7606 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
7607 connection_.GetPathDegradingAlarm()->Fire();
7608 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7609 EXPECT_TRUE(connection_.IsPathDegrading());
7610
7611 // Send a third packet. The path degrading alarm is no longer set but path
7612 // should still be marked as degrading.
7613 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7614 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7615 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7616 offset += data_size;
7617 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7618 EXPECT_TRUE(connection_.IsPathDegrading());
7619
7620 // Now receive an ACK of the second packet. This should unmark the path as
7621 // degrading. And will set a timer to detect new path degrading.
7622 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7623 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7624 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
7625 ProcessAckPacket(&frame);
7626 EXPECT_FALSE(connection_.IsPathDegrading());
7627 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7628}
7629
7630TEST_P(QuicConnectionTest, NoPathDegradingOnServer) {
QUICHE teamcd098022019-03-22 18:49:55 -07007631 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7632 return;
7633 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007634 set_perspective(Perspective::IS_SERVER);
7635 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
7636
7637 EXPECT_FALSE(connection_.IsPathDegrading());
7638 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7639
7640 // Send data.
7641 const char data[] = "data";
7642 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
7643 EXPECT_FALSE(connection_.IsPathDegrading());
7644 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7645
7646 // Ack data.
7647 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7648 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7649 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7650 QuicAckFrame frame =
7651 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
7652 ProcessAckPacket(&frame);
7653 EXPECT_FALSE(connection_.IsPathDegrading());
7654 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7655}
7656
7657TEST_P(QuicConnectionTest, NoPathDegradingAfterSendingAck) {
QUICHE teamcd098022019-03-22 18:49:55 -07007658 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7659 return;
7660 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007661 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7662 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7663 ProcessDataPacket(1);
7664 SendAckPacketToPeer();
7665 EXPECT_FALSE(connection_.sent_packet_manager().unacked_packets().empty());
7666 EXPECT_FALSE(connection_.sent_packet_manager().HasInFlightPackets());
7667 EXPECT_FALSE(connection_.IsPathDegrading());
7668 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7669}
7670
7671TEST_P(QuicConnectionTest, MultipleCallsToCloseConnection) {
7672 // Verifies that multiple calls to CloseConnection do not
7673 // result in multiple attempts to close the connection - it will be marked as
7674 // disconnected after the first call.
7675 EXPECT_CALL(visitor_, OnConnectionClosed(_, _, _)).Times(1);
7676 connection_.CloseConnection(QUIC_NO_ERROR, "no reason",
7677 ConnectionCloseBehavior::SILENT_CLOSE);
7678 connection_.CloseConnection(QUIC_NO_ERROR, "no reason",
7679 ConnectionCloseBehavior::SILENT_CLOSE);
7680}
7681
7682TEST_P(QuicConnectionTest, ServerReceivesChloOnNonCryptoStream) {
7683 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7684
7685 set_perspective(Perspective::IS_SERVER);
7686 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
7687
7688 CryptoHandshakeMessage message;
7689 CryptoFramer framer;
7690 message.set_tag(kCHLO);
QUICHE team3fe6a8b2019-03-14 09:10:38 -07007691 std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007692 frame1_.stream_id = 10;
7693 frame1_.data_buffer = data->data();
7694 frame1_.data_length = data->length();
7695
7696 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_MAYBE_CORRUPTED_MEMORY, _,
7697 ConnectionCloseSource::FROM_SELF));
7698 ForceProcessFramePacket(QuicFrame(frame1_));
7699}
7700
7701TEST_P(QuicConnectionTest, ClientReceivesRejOnNonCryptoStream) {
7702 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7703
7704 CryptoHandshakeMessage message;
7705 CryptoFramer framer;
7706 message.set_tag(kREJ);
QUICHE team3fe6a8b2019-03-14 09:10:38 -07007707 std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007708 frame1_.stream_id = 10;
7709 frame1_.data_buffer = data->data();
7710 frame1_.data_length = data->length();
7711
7712 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_MAYBE_CORRUPTED_MEMORY, _,
7713 ConnectionCloseSource::FROM_SELF));
7714 ForceProcessFramePacket(QuicFrame(frame1_));
7715}
7716
7717TEST_P(QuicConnectionTest, CloseConnectionOnPacketTooLarge) {
7718 SimulateNextPacketTooLarge();
7719 // A connection close packet is sent
7720 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PACKET_WRITE_ERROR, _,
7721 ConnectionCloseSource::FROM_SELF))
7722 .Times(1);
7723 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7724}
7725
7726TEST_P(QuicConnectionTest, AlwaysGetPacketTooLarge) {
7727 // Test even we always get packet too large, we do not infinitely try to send
7728 // close packet.
7729 AlwaysGetPacketTooLarge();
7730 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PACKET_WRITE_ERROR, _,
7731 ConnectionCloseSource::FROM_SELF))
7732 .Times(1);
7733 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7734}
7735
7736// Verify that if connection has no outstanding data, it notifies the send
7737// algorithm after the write.
7738TEST_P(QuicConnectionTest, SendDataAndBecomeApplicationLimited) {
7739 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
7740 {
7741 InSequence seq;
7742 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7743 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7744 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
7745 .WillRepeatedly(Return(false));
7746 }
7747
7748 connection_.SendStreamData3();
7749}
7750
7751// Verify that the connection does not become app-limited if there is
7752// outstanding data to send after the write.
7753TEST_P(QuicConnectionTest, NotBecomeApplicationLimitedIfMoreDataAvailable) {
7754 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
7755 {
7756 InSequence seq;
7757 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7758 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7759 }
7760
7761 connection_.SendStreamData3();
7762}
7763
7764// Verify that the connection does not become app-limited after blocked write
7765// even if there is outstanding data to send after the write.
7766TEST_P(QuicConnectionTest, NotBecomeApplicationLimitedDueToWriteBlock) {
7767 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
7768 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7769 BlockOnNextWrite();
7770
7771 connection_.SendStreamData3();
7772
7773 // Now unblock the writer, become congestion control blocked,
7774 // and ensure we become app-limited after writing.
7775 writer_->SetWritable();
7776 CongestionBlockWrites();
7777 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(false));
7778 {
7779 InSequence seq;
7780 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7781 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
7782 }
7783 connection_.OnCanWrite();
7784}
7785
7786// Test the mode in which the link is filled up with probing retransmissions if
7787// the connection becomes application-limited.
7788TEST_P(QuicConnectionTest, SendDataWhenApplicationLimited) {
7789 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7790 EXPECT_CALL(*send_algorithm_, ShouldSendProbingPacket())
7791 .WillRepeatedly(Return(true));
7792 {
7793 InSequence seq;
7794 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7795 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7796 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
7797 .WillRepeatedly(Return(false));
7798 }
QUICHE teamb8343252019-04-29 13:58:01 -07007799 EXPECT_CALL(visitor_, SendProbingData()).WillRepeatedly([this] {
7800 return connection_.sent_packet_manager().MaybeRetransmitOldestPacket(
7801 PROBING_RETRANSMISSION);
7802 });
QUICHE teama6ef0a62019-03-07 20:34:33 -05007803 // Fix congestion window to be 20,000 bytes.
7804 EXPECT_CALL(*send_algorithm_, CanSend(Ge(20000u)))
7805 .WillRepeatedly(Return(false));
7806 EXPECT_CALL(*send_algorithm_, CanSend(Lt(20000u)))
7807 .WillRepeatedly(Return(true));
7808
7809 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
7810 ASSERT_EQ(0u, connection_.GetStats().packets_sent);
7811 connection_.set_fill_up_link_during_probing(true);
7812 connection_.OnHandshakeComplete();
7813 connection_.SendStreamData3();
7814
7815 // We expect a lot of packets from a 20 kbyte window.
7816 EXPECT_GT(connection_.GetStats().packets_sent, 10u);
7817 // Ensure that the packets are padded.
7818 QuicByteCount average_packet_size =
7819 connection_.GetStats().bytes_sent / connection_.GetStats().packets_sent;
7820 EXPECT_GT(average_packet_size, 1000u);
7821
7822 // Acknowledge all packets sent, except for the last one.
7823 QuicAckFrame ack = InitAckFrame(
7824 connection_.sent_packet_manager().GetLargestSentPacket() - 1);
7825 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
7826 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7827
7828 // Ensure that since we no longer have retransmittable bytes in flight, this
7829 // will not cause any responses to be sent.
7830 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
7831 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
7832 ProcessAckPacket(&ack);
7833}
7834
7835TEST_P(QuicConnectionTest, DonotForceSendingAckOnPacketTooLarge) {
7836 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7837 // Send an ack by simulating delayed ack alarm firing.
7838 ProcessPacket(1);
7839 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
7840 EXPECT_TRUE(ack_alarm->IsSet());
7841 connection_.GetAckAlarm()->Fire();
7842 // Simulate data packet causes write error.
7843 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PACKET_WRITE_ERROR, _, _));
7844 SimulateNextPacketTooLarge();
7845 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7846 EXPECT_EQ(1u, writer_->frame_count());
7847 EXPECT_FALSE(writer_->connection_close_frames().empty());
7848 // Ack frame is not bundled in connection close packet.
7849 EXPECT_TRUE(writer_->ack_frames().empty());
7850}
7851
7852TEST_P(QuicConnectionTest, CloseConnectionForStatelessReject) {
vasilvvc48c8712019-03-11 13:38:16 -07007853 std::string error_details("stateless reject");
QUICHE teama6ef0a62019-03-07 20:34:33 -05007854 EXPECT_CALL(visitor_, OnConnectionClosed(
7855 QUIC_CRYPTO_HANDSHAKE_STATELESS_REJECT,
7856 error_details, ConnectionCloseSource::FROM_PEER));
7857 connection_.set_perspective(Perspective::IS_CLIENT);
7858 connection_.CloseConnection(QUIC_CRYPTO_HANDSHAKE_STATELESS_REJECT,
7859 error_details,
7860 ConnectionCloseBehavior::SILENT_CLOSE);
7861}
7862
7863// Regression test for b/63620844.
7864TEST_P(QuicConnectionTest, FailedToWriteHandshakePacket) {
7865 SimulateNextPacketTooLarge();
7866 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PACKET_WRITE_ERROR, _,
7867 ConnectionCloseSource::FROM_SELF))
7868 .Times(1);
7869 connection_.SendCryptoStreamData();
7870}
7871
7872TEST_P(QuicConnectionTest, MaxPacingRate) {
7873 EXPECT_EQ(0, connection_.MaxPacingRate().ToBytesPerSecond());
7874 connection_.SetMaxPacingRate(QuicBandwidth::FromBytesPerSecond(100));
7875 EXPECT_EQ(100, connection_.MaxPacingRate().ToBytesPerSecond());
7876}
7877
7878TEST_P(QuicConnectionTest, ClientAlwaysSendConnectionId) {
7879 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
7880 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7881 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7882 EXPECT_EQ(CONNECTION_ID_PRESENT,
7883 writer_->last_packet_header().destination_connection_id_included);
7884
7885 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7886 QuicConfig config;
7887 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
7888 connection_.SetFromConfig(config);
7889
7890 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7891 connection_.SendStreamDataWithString(3, "bar", 3, NO_FIN);
7892 // Verify connection id is still sent in the packet.
7893 EXPECT_EQ(CONNECTION_ID_PRESENT,
7894 writer_->last_packet_header().destination_connection_id_included);
7895}
7896
7897TEST_P(QuicConnectionTest, SendProbingRetransmissions) {
7898 MockQuicConnectionDebugVisitor debug_visitor;
7899 connection_.set_debug_visitor(&debug_visitor);
7900
7901 const QuicStreamId stream_id = 2;
7902 QuicPacketNumber last_packet;
7903 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
7904 SendStreamDataToPeer(stream_id, "bar", 3, NO_FIN, &last_packet);
7905 SendStreamDataToPeer(stream_id, "test", 6, NO_FIN, &last_packet);
7906
7907 const QuicByteCount old_bytes_in_flight =
7908 connection_.sent_packet_manager().GetBytesInFlight();
7909
7910 // Allow 9 probing retransmissions to be sent.
7911 {
7912 InSequence seq;
7913 EXPECT_CALL(*send_algorithm_, CanSend(_))
7914 .Times(9 * 2)
7915 .WillRepeatedly(Return(true));
7916 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(Return(false));
7917 }
7918 // Expect them retransmitted in cyclic order (foo, bar, test, foo, bar...).
7919 QuicPacketCount sent_count = 0;
7920 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _))
7921 .WillRepeatedly(Invoke([this, &sent_count](const SerializedPacket&,
7922 QuicPacketNumber,
7923 TransmissionType, QuicTime) {
7924 ASSERT_EQ(1u, writer_->stream_frames().size());
7925 // Identify the frames by stream offset (0, 3, 6, 0, 3...).
7926 EXPECT_EQ(3 * (sent_count % 3), writer_->stream_frames()[0]->offset);
7927 sent_count++;
7928 }));
7929 EXPECT_CALL(*send_algorithm_, ShouldSendProbingPacket())
7930 .WillRepeatedly(Return(true));
QUICHE teamb8343252019-04-29 13:58:01 -07007931 EXPECT_CALL(visitor_, SendProbingData()).WillRepeatedly([this] {
7932 return connection_.sent_packet_manager().MaybeRetransmitOldestPacket(
7933 PROBING_RETRANSMISSION);
7934 });
QUICHE teama6ef0a62019-03-07 20:34:33 -05007935
7936 connection_.SendProbingRetransmissions();
7937
7938 // Ensure that the in-flight has increased.
7939 const QuicByteCount new_bytes_in_flight =
7940 connection_.sent_packet_manager().GetBytesInFlight();
7941 EXPECT_GT(new_bytes_in_flight, old_bytes_in_flight);
7942}
7943
7944// Ensure that SendProbingRetransmissions() does not retransmit anything when
7945// there are no outstanding packets.
7946TEST_P(QuicConnectionTest,
7947 SendProbingRetransmissionsFailsWhenNothingToRetransmit) {
7948 ASSERT_TRUE(connection_.sent_packet_manager().unacked_packets().empty());
7949
7950 MockQuicConnectionDebugVisitor debug_visitor;
7951 connection_.set_debug_visitor(&debug_visitor);
7952 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _)).Times(0);
7953 EXPECT_CALL(*send_algorithm_, ShouldSendProbingPacket())
7954 .WillRepeatedly(Return(true));
QUICHE teamb8343252019-04-29 13:58:01 -07007955 EXPECT_CALL(visitor_, SendProbingData()).WillRepeatedly([this] {
7956 return connection_.sent_packet_manager().MaybeRetransmitOldestPacket(
7957 PROBING_RETRANSMISSION);
7958 });
QUICHE teama6ef0a62019-03-07 20:34:33 -05007959
7960 connection_.SendProbingRetransmissions();
7961}
7962
7963TEST_P(QuicConnectionTest, PingAfterLastRetransmittablePacketAcked) {
7964 const QuicTime::Delta retransmittable_on_wire_timeout =
7965 QuicTime::Delta::FromMilliseconds(50);
7966 connection_.set_retransmittable_on_wire_timeout(
7967 retransmittable_on_wire_timeout);
7968
7969 EXPECT_TRUE(connection_.connected());
7970 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7971 .WillRepeatedly(Return(true));
7972
7973 const char data[] = "data";
7974 size_t data_size = strlen(data);
7975 QuicStreamOffset offset = 0;
7976
7977 // Advance 5ms, send a retransmittable packet to the peer.
7978 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7979 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
7980 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7981 offset += data_size;
7982 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
7983 // The ping alarm is set for the ping timeout, not the shorter
7984 // retransmittable_on_wire_timeout.
7985 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7986 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
7987 EXPECT_EQ((clock_.ApproximateNow() + ping_delay),
7988 connection_.GetPingAlarm()->deadline());
7989
7990 // Advance 5ms, send a second retransmittable packet to the peer.
7991 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7992 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7993 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7994 offset += data_size;
7995 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7996
7997 // Now receive an ACK of the first packet. This should not set the
7998 // retransmittable-on-wire alarm since packet 2 is still on the wire.
7999 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8000 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8001 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8002 QuicAckFrame frame =
8003 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8004 ProcessAckPacket(&frame);
8005 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8006 // The ping alarm is set for the ping timeout, not the shorter
8007 // retransmittable_on_wire_timeout.
8008 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8009 // The ping alarm has a 1 second granularity, and the clock has been advanced
8010 // 10ms since it was originally set.
8011 EXPECT_EQ((clock_.ApproximateNow() + ping_delay -
8012 QuicTime::Delta::FromMilliseconds(10)),
8013 connection_.GetPingAlarm()->deadline());
8014
8015 // Now receive an ACK of the second packet. This should set the
8016 // retransmittable-on-wire alarm now that no retransmittable packets are on
8017 // the wire.
8018 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8019 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8020 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8021 ProcessAckPacket(&frame);
8022 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8023 EXPECT_EQ(clock_.ApproximateNow() + retransmittable_on_wire_timeout,
8024 connection_.GetPingAlarm()->deadline());
8025
8026 // Now receive a duplicate ACK of the second packet. This should not update
8027 // the ping alarm.
8028 QuicTime prev_deadline = connection_.GetPingAlarm()->deadline();
8029 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8030 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8031 ProcessAckPacket(&frame);
8032 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8033 EXPECT_EQ(prev_deadline, connection_.GetPingAlarm()->deadline());
8034
8035 // Now receive a non-ACK packet. This should not update the ping alarm.
8036 prev_deadline = connection_.GetPingAlarm()->deadline();
8037 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8038 ProcessPacket(4);
8039 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8040 EXPECT_EQ(prev_deadline, connection_.GetPingAlarm()->deadline());
8041
8042 // Simulate the alarm firing and check that a PING is sent.
8043 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8044 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
8045 }));
8046 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07008047 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05008048 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07008049 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008050 } else {
nharper55fa6132019-05-07 19:37:21 -07008051 EXPECT_EQ(padding_frame_count + 3u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008052 }
8053 ASSERT_EQ(1u, writer_->ping_frames().size());
8054}
8055
8056TEST_P(QuicConnectionTest, NoPingIfRetransmittablePacketSent) {
8057 const QuicTime::Delta retransmittable_on_wire_timeout =
8058 QuicTime::Delta::FromMilliseconds(50);
8059 connection_.set_retransmittable_on_wire_timeout(
8060 retransmittable_on_wire_timeout);
8061
8062 EXPECT_TRUE(connection_.connected());
8063 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8064 .WillRepeatedly(Return(true));
8065
8066 const char data[] = "data";
8067 size_t data_size = strlen(data);
8068 QuicStreamOffset offset = 0;
8069
8070 // Advance 5ms, send a retransmittable packet to the peer.
8071 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8072 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8073 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8074 offset += data_size;
8075 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8076 // The ping alarm is set for the ping timeout, not the shorter
8077 // retransmittable_on_wire_timeout.
8078 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8079 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
8080 EXPECT_EQ((clock_.ApproximateNow() + ping_delay),
8081 connection_.GetPingAlarm()->deadline());
8082
8083 // Now receive an ACK of the first packet. This should set the
8084 // retransmittable-on-wire alarm now that no retransmittable packets are on
8085 // the wire.
8086 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8087 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8088 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8089 QuicAckFrame frame =
8090 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8091 ProcessAckPacket(&frame);
8092 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8093 EXPECT_EQ(clock_.ApproximateNow() + retransmittable_on_wire_timeout,
8094 connection_.GetPingAlarm()->deadline());
8095
8096 // Before the alarm fires, send another retransmittable packet. This should
8097 // cancel the retransmittable-on-wire alarm since now there's a
8098 // retransmittable packet on the wire.
8099 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8100 offset += data_size;
8101 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8102
8103 // Now receive an ACK of the second packet. This should set the
8104 // retransmittable-on-wire alarm now that no retransmittable packets are on
8105 // the wire.
8106 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8107 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8108 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8109 ProcessAckPacket(&frame);
8110 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8111 EXPECT_EQ(clock_.ApproximateNow() + retransmittable_on_wire_timeout,
8112 connection_.GetPingAlarm()->deadline());
8113
8114 // Simulate the alarm firing and check that a PING is sent.
8115 writer_->Reset();
8116 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8117 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
8118 }));
8119 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07008120 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05008121 if (GetParam().no_stop_waiting) {
fayang03916692019-05-22 17:57:18 -07008122 if (GetQuicReloadableFlag(quic_simplify_stop_waiting)) {
8123 // Do not ACK acks.
8124 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
8125 } else {
8126 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
8127 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008128 } else {
nharper55fa6132019-05-07 19:37:21 -07008129 EXPECT_EQ(padding_frame_count + 3u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008130 }
8131 ASSERT_EQ(1u, writer_->ping_frames().size());
8132}
8133
8134TEST_P(QuicConnectionTest, OnForwardProgressConfirmed) {
8135 EXPECT_CALL(visitor_, OnForwardProgressConfirmed()).Times(Exactly(0));
8136 EXPECT_TRUE(connection_.connected());
8137
8138 const char data[] = "data";
8139 size_t data_size = strlen(data);
8140 QuicStreamOffset offset = 0;
8141
8142 // Send two packets.
8143 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8144 offset += data_size;
8145 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8146 offset += data_size;
8147
8148 // Ack packet 1. This increases the largest_acked to 1, so
8149 // OnForwardProgressConfirmed() should be called
8150 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8151 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8152 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8153 EXPECT_CALL(visitor_, OnForwardProgressConfirmed());
8154 QuicAckFrame frame =
8155 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8156 ProcessAckPacket(&frame);
8157
8158 // Ack packet 1 again. largest_acked remains at 1, so
8159 // OnForwardProgressConfirmed() should not be called.
8160 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8161 frame = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8162 ProcessAckPacket(&frame);
8163
8164 // Ack packet 2. This increases the largest_acked to 2, so
8165 // OnForwardProgressConfirmed() should be called.
8166 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8167 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8168 EXPECT_CALL(visitor_, OnForwardProgressConfirmed());
8169 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8170 ProcessAckPacket(&frame);
8171}
8172
8173TEST_P(QuicConnectionTest, ValidStatelessResetToken) {
8174 const QuicUint128 kTestToken = 1010101;
8175 const QuicUint128 kWrongTestToken = 1010100;
8176 QuicConfig config;
8177 // No token has been received.
8178 EXPECT_FALSE(connection_.IsValidStatelessResetToken(kTestToken));
8179
8180 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(2);
8181 // Token is different from received token.
8182 QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestToken);
8183 connection_.SetFromConfig(config);
8184 EXPECT_FALSE(connection_.IsValidStatelessResetToken(kWrongTestToken));
8185
8186 QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestToken);
8187 connection_.SetFromConfig(config);
8188 EXPECT_TRUE(connection_.IsValidStatelessResetToken(kTestToken));
8189}
8190
8191TEST_P(QuicConnectionTest, WriteBlockedWithInvalidAck) {
8192 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8193 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, _, _));
8194
8195 BlockOnNextWrite();
8196 connection_.SendStreamDataWithString(5, "foo", 0, FIN);
8197 // This causes connection to be closed because packet 1 has not been sent yet.
8198 QuicAckFrame frame = InitAckFrame(1);
8199 ProcessAckPacket(1, &frame);
8200}
8201
8202TEST_P(QuicConnectionTest, SendMessage) {
fayangd4291e42019-05-30 10:31:21 -07008203 if (!VersionSupportsMessageFrames(connection_.transport_version()) ||
QUICHE teamcd098022019-03-22 18:49:55 -07008204 connection_.SupportsMultiplePacketNumberSpaces()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008205 return;
8206 }
ianswettb239f862019-04-05 09:15:06 -07008207 std::string message(connection_.GetCurrentLargestMessagePayload() * 2, 'a');
QUICHE teama6ef0a62019-03-07 20:34:33 -05008208 QuicStringPiece message_data(message);
8209 QuicMemSliceStorage storage(nullptr, 0, nullptr, 0);
8210 {
8211 QuicConnection::ScopedPacketFlusher flusher(&connection_,
8212 QuicConnection::SEND_ACK);
8213 connection_.SendStreamData3();
8214 // Send a message which cannot fit into current open packet, and 2 packets
8215 // get sent, one contains stream frame, and the other only contains the
8216 // message frame.
8217 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
8218 EXPECT_EQ(
8219 MESSAGE_STATUS_SUCCESS,
8220 connection_.SendMessage(
8221 1, MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(),
ianswettb239f862019-04-05 09:15:06 -07008222 QuicStringPiece(
8223 message_data.data(),
8224 connection_.GetCurrentLargestMessagePayload()),
QUICHE teama6ef0a62019-03-07 20:34:33 -05008225 &storage)));
8226 }
8227 // Fail to send a message if connection is congestion control blocked.
8228 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(Return(false));
8229 EXPECT_EQ(
8230 MESSAGE_STATUS_BLOCKED,
8231 connection_.SendMessage(
8232 2, MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(),
8233 "message", &storage)));
8234
8235 // Always fail to send a message which cannot fit into one packet.
8236 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8237 EXPECT_EQ(
8238 MESSAGE_STATUS_TOO_LARGE,
8239 connection_.SendMessage(
ianswettb239f862019-04-05 09:15:06 -07008240 3, MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(),
8241 QuicStringPiece(
8242 message_data.data(),
8243 connection_.GetCurrentLargestMessagePayload() + 1),
8244 &storage)));
QUICHE teama6ef0a62019-03-07 20:34:33 -05008245}
8246
8247// Test to check that the path challenge/path response logic works
8248// correctly. This test is only for version-99
8249TEST_P(QuicConnectionTest, PathChallengeResponse) {
QUICHE teamcd098022019-03-22 18:49:55 -07008250 if (connection_.version().transport_version != QUIC_VERSION_99 ||
8251 connection_.SupportsMultiplePacketNumberSpaces()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008252 return;
8253 }
8254 // First check if we can probe from server to client and back
8255 set_perspective(Perspective::IS_SERVER);
8256 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
8257
8258 // Create and send the probe request (PATH_CHALLENGE frame).
8259 // SendConnectivityProbingPacket ends up calling
8260 // TestPacketWriter::WritePacket() which in turns receives and parses the
8261 // packet by calling framer_.ProcessPacket() -- which in turn calls
8262 // SimpleQuicFramer::OnPathChallengeFrame(). SimpleQuicFramer saves
8263 // the packet in writer_->path_challenge_frames()
8264 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8265 connection_.SendConnectivityProbingPacket(writer_.get(),
8266 connection_.peer_address());
8267 // Save the random contents of the challenge for later comparison to the
8268 // response.
nharper55fa6132019-05-07 19:37:21 -07008269 ASSERT_GE(writer_->path_challenge_frames().size(), 1u);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008270 QuicPathFrameBuffer challenge_data =
8271 writer_->path_challenge_frames().front().data_buffer;
8272
8273 // Normally, QuicConnection::OnPathChallengeFrame and OnPaddingFrame would be
8274 // called and it will perform actions to ensure that the rest of the protocol
8275 // is performed (specifically, call UpdatePacketContent to say that this is a
8276 // path challenge so that when QuicConnection::OnPacketComplete is called
8277 // (again, out of the framer), the response is generated). Simulate those
8278 // calls so that the right internal state is set up for generating
8279 // the response.
8280 EXPECT_TRUE(connection_.OnPathChallengeFrame(
8281 writer_->path_challenge_frames().front()));
8282 EXPECT_TRUE(connection_.OnPaddingFrame(writer_->padding_frames().front()));
8283 // Cause the response to be created and sent. Result is that the response
8284 // should be stashed in writer's path_response_frames.
8285 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8286 connection_.SendConnectivityProbingResponsePacket(connection_.peer_address());
8287
8288 // The final check is to ensure that the random data in the response matches
8289 // the random data from the challenge.
8290 EXPECT_EQ(0, memcmp(&challenge_data,
8291 &(writer_->path_response_frames().front().data_buffer),
8292 sizeof(challenge_data)));
8293}
8294
8295// Regression test for b/110259444
8296TEST_P(QuicConnectionTest, DoNotScheduleSpuriousAckAlarm) {
8297 SetQuicReloadableFlag(quic_fix_spurious_ack_alarm, true);
8298 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8299 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
8300 writer_->SetWriteBlocked();
8301
8302 ProcessPacket(1);
8303 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
8304 // Verify ack alarm is set.
8305 EXPECT_TRUE(ack_alarm->IsSet());
8306 // Fire the ack alarm, verify no packet is sent because the writer is blocked.
8307 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8308 connection_.GetAckAlarm()->Fire();
8309
8310 writer_->SetWritable();
8311 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8312 ProcessPacket(2);
8313 // Verify ack alarm is not set.
8314 EXPECT_FALSE(ack_alarm->IsSet());
8315}
8316
8317TEST_P(QuicConnectionTest, DisablePacingOffloadConnectionOptions) {
8318 EXPECT_FALSE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
8319 writer_->set_supports_release_time(true);
8320 QuicConfig config;
8321 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8322 connection_.SetFromConfig(config);
8323 EXPECT_TRUE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
8324
8325 QuicTagVector connection_options;
8326 connection_options.push_back(kNPCO);
8327 config.SetConnectionOptionsToSend(connection_options);
8328 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8329 connection_.SetFromConfig(config);
8330 // Verify pacing offload is disabled.
8331 EXPECT_FALSE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
8332}
8333
8334// Regression test for b/110259444
8335// Get a path response without having issued a path challenge...
8336TEST_P(QuicConnectionTest, OrphanPathResponse) {
8337 QuicPathFrameBuffer data = {{0, 1, 2, 3, 4, 5, 6, 7}};
8338
8339 QuicPathResponseFrame frame(99, data);
8340 EXPECT_TRUE(connection_.OnPathResponseFrame(frame));
8341 // If PATH_RESPONSE was accepted (payload matches the payload saved
8342 // in QuicConnection::transmitted_connectivity_probe_payload_) then
8343 // current_packet_content_ would be set to FIRST_FRAME_IS_PING.
8344 // Since this PATH_RESPONSE does not match, current_packet_content_
8345 // must not be FIRST_FRAME_IS_PING.
8346 EXPECT_NE(QuicConnection::FIRST_FRAME_IS_PING,
8347 QuicConnectionPeer::GetCurrentPacketContent(&connection_));
8348}
8349
8350// Regression test for b/120791670
8351TEST_P(QuicConnectionTest, StopProcessingGQuicPacketInIetfQuicConnection) {
8352 // This test mimics a problematic scenario where an IETF QUIC connection
8353 // receives a Google QUIC packet and continue processing it using Google QUIC
8354 // wire format.
fayangd4291e42019-05-30 10:31:21 -07008355 if (!VersionHasIetfInvariantHeader(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008356 return;
8357 }
8358 set_perspective(Perspective::IS_SERVER);
nharper46833c32019-05-15 21:33:05 -07008359 QuicFrame frame;
8360 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
8361 frame = QuicFrame(&crypto_frame_);
8362 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
8363 } else {
8364 frame = QuicFrame(QuicStreamFrame(
8365 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
8366 0u, QuicStringPiece()));
8367 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
8368 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008369 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
nharper46833c32019-05-15 21:33:05 -07008370 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008371
8372 // Let connection process a Google QUIC packet.
8373 peer_framer_.set_version_for_tests(
8374 ParsedQuicVersion(PROTOCOL_QUIC_CRYPTO, QUIC_VERSION_43));
QUICHE team8c1daa22019-03-13 08:33:41 -07008375 std::unique_ptr<QuicPacket> packet(
QUICHE team6987b4a2019-03-15 16:23:04 -07008376 ConstructDataPacket(2, !kHasStopWaiting, ENCRYPTION_INITIAL));
dschinazi66dea072019-04-09 11:41:06 -07008377 char buffer[kMaxOutgoingPacketSize];
8378 size_t encrypted_length =
8379 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(2),
8380 *packet, buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008381 // Make sure no stream frame is processed.
8382 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(0);
8383 connection_.ProcessUdpPacket(
8384 kSelfAddress, kPeerAddress,
8385 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
8386
8387 EXPECT_EQ(2u, connection_.GetStats().packets_received);
8388 EXPECT_EQ(1u, connection_.GetStats().packets_processed);
8389}
8390
8391TEST_P(QuicConnectionTest, AcceptPacketNumberZero) {
QUICHE teamcd098022019-03-22 18:49:55 -07008392 if (version().transport_version != QUIC_VERSION_99 ||
8393 connection_.SupportsMultiplePacketNumberSpaces()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008394 return;
8395 }
8396 // Set first_sending_packet_number to be 0 to allow successfully processing
8397 // acks which ack packet number 0.
8398 QuicFramerPeer::SetFirstSendingPacketNumber(writer_->framer()->framer(), 0);
8399 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8400
8401 ProcessPacket(0);
8402 EXPECT_EQ(QuicPacketNumber(0), LargestAcked(*outgoing_ack()));
8403 EXPECT_EQ(1u, outgoing_ack()->packets.NumIntervals());
8404
8405 ProcessPacket(1);
8406 EXPECT_EQ(QuicPacketNumber(1), LargestAcked(*outgoing_ack()));
8407 EXPECT_EQ(1u, outgoing_ack()->packets.NumIntervals());
8408
8409 ProcessPacket(2);
8410 EXPECT_EQ(QuicPacketNumber(2), LargestAcked(*outgoing_ack()));
8411 EXPECT_EQ(1u, outgoing_ack()->packets.NumIntervals());
8412}
8413
QUICHE teamcd098022019-03-22 18:49:55 -07008414TEST_P(QuicConnectionTest, MultiplePacketNumberSpacesBasicSending) {
8415 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8416 return;
8417 }
8418 use_tagging_decrypter();
8419 connection_.SetEncrypter(ENCRYPTION_INITIAL,
8420 QuicMakeUnique<TaggingEncrypter>(0x01));
8421
8422 connection_.SendCryptoStreamData();
8423 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8424 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
8425 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8426 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8427 QuicAckFrame frame1 = InitAckFrame(1);
8428 // Received ACK for packet 1.
8429 ProcessFramePacketAtLevel(30, QuicFrame(&frame1), ENCRYPTION_INITIAL);
8430
8431 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(4);
8432 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
8433 NO_FIN);
8434 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 4,
8435 NO_FIN);
8436 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
8437 8, NO_FIN);
8438 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
8439 12, FIN);
8440 // Received ACK for packets 2, 4, 5.
8441 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
8442 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8443 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8444 QuicAckFrame frame2 =
8445 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)},
8446 {QuicPacketNumber(4), QuicPacketNumber(6)}});
8447 // Make sure although the same packet number is used, but they are in
8448 // different packet number spaces.
8449 ProcessFramePacketAtLevel(30, QuicFrame(&frame2), ENCRYPTION_FORWARD_SECURE);
8450}
8451
8452TEST_P(QuicConnectionTest, PeerAcksPacketsInWrongPacketNumberSpace) {
8453 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8454 return;
8455 }
8456 use_tagging_decrypter();
8457 connection_.SetEncrypter(ENCRYPTION_INITIAL,
8458 QuicMakeUnique<TaggingEncrypter>(0x01));
8459
8460 connection_.SendCryptoStreamData();
8461 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8462 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
8463 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8464 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8465 QuicAckFrame frame1 = InitAckFrame(1);
8466 // Received ACK for packet 1.
8467 ProcessFramePacketAtLevel(30, QuicFrame(&frame1), ENCRYPTION_INITIAL);
8468
8469 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
8470 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
8471 NO_FIN);
8472 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 4,
8473 NO_FIN);
8474
8475 // Received ACK for packets 2 and 3 in wrong packet number space.
8476 QuicAckFrame invalid_ack =
8477 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(4)}});
8478 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, _,
8479 ConnectionCloseSource::FROM_SELF));
8480 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8481 ProcessFramePacketAtLevel(300, QuicFrame(&invalid_ack), ENCRYPTION_INITIAL);
8482}
8483
8484TEST_P(QuicConnectionTest, MultiplePacketNumberSpacesBasicReceiving) {
8485 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8486 return;
8487 }
8488 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
nharper46833c32019-05-15 21:33:05 -07008489 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
8490 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
8491 }
QUICHE teamcd098022019-03-22 18:49:55 -07008492 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
8493 use_tagging_decrypter();
8494 // Receives packet 1000 in initial data.
nharper46833c32019-05-15 21:33:05 -07008495 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
QUICHE teamcd098022019-03-22 18:49:55 -07008496 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
8497 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
8498 QuicMakeUnique<TaggingEncrypter>(0x02));
zhongyi546cc452019-04-12 15:27:49 -07008499 SetDecrypter(ENCRYPTION_ZERO_RTT,
8500 QuicMakeUnique<StrictTaggingDecrypter>(0x02));
QUICHE teamcd098022019-03-22 18:49:55 -07008501 connection_.SetEncrypter(ENCRYPTION_INITIAL,
8502 QuicMakeUnique<TaggingEncrypter>(0x02));
8503 // Receives packet 1000 in application data.
8504 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
8505 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
8506 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
8507 NO_FIN);
8508 // Verify application data ACK gets bundled with outgoing data.
8509 EXPECT_EQ(2u, writer_->frame_count());
8510 // Make sure ACK alarm is still set because initial data is not ACKed.
8511 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
8512 // Receive packet 1001 in application data.
8513 ProcessDataPacketAtLevel(1001, false, ENCRYPTION_ZERO_RTT);
8514 clock_.AdvanceTime(DefaultRetransmissionTime());
8515 // Simulates ACK alarm fires and verify two ACKs are flushed.
8516 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
8517 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
8518 QuicMakeUnique<TaggingEncrypter>(0x02));
8519 connection_.GetAckAlarm()->Fire();
8520 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
8521 // Receives more packets in application data.
8522 ProcessDataPacketAtLevel(1002, false, ENCRYPTION_ZERO_RTT);
8523 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
8524
8525 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
8526 QuicMakeUnique<TaggingEncrypter>(0x02));
zhongyi546cc452019-04-12 15:27:49 -07008527 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
8528 QuicMakeUnique<StrictTaggingDecrypter>(0x02));
QUICHE teamcd098022019-03-22 18:49:55 -07008529 // Verify zero rtt and forward secure packets get acked in the same packet.
8530 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
nharper2c9f02a2019-05-08 10:25:50 -07008531 ProcessDataPacket(1003);
QUICHE teamcd098022019-03-22 18:49:55 -07008532 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
8533}
8534
QUICHE team552f71f2019-03-23 15:37:59 -07008535TEST_P(QuicConnectionTest, CancelAckAlarmOnWriteBlocked) {
8536 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8537 return;
8538 }
8539 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
nharper46833c32019-05-15 21:33:05 -07008540 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
8541 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
8542 }
QUICHE team552f71f2019-03-23 15:37:59 -07008543 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
8544 use_tagging_decrypter();
8545 // Receives packet 1000 in initial data.
nharper46833c32019-05-15 21:33:05 -07008546 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
QUICHE team552f71f2019-03-23 15:37:59 -07008547 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
8548 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
8549 QuicMakeUnique<TaggingEncrypter>(0x02));
zhongyi546cc452019-04-12 15:27:49 -07008550 SetDecrypter(ENCRYPTION_ZERO_RTT,
8551 QuicMakeUnique<StrictTaggingDecrypter>(0x02));
QUICHE team552f71f2019-03-23 15:37:59 -07008552 connection_.SetEncrypter(ENCRYPTION_INITIAL,
8553 QuicMakeUnique<TaggingEncrypter>(0x02));
8554 // Receives packet 1000 in application data.
8555 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
8556 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
8557
8558 writer_->SetWriteBlocked();
8559 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AnyNumber());
8560 // Simulates ACK alarm fires and verify no ACK is flushed because of write
8561 // blocked.
8562 clock_.AdvanceTime(DefaultDelayedAckTime());
8563 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8564 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
8565 QuicMakeUnique<TaggingEncrypter>(0x02));
8566 connection_.GetAckAlarm()->Fire();
8567 // Verify ACK alarm is not set.
8568 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
8569
8570 writer_->SetWritable();
8571 // Verify 2 ACKs are sent when connection gets unblocked.
8572 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
8573 connection_.OnCanWrite();
8574 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
8575}
8576
QUICHE teama6ef0a62019-03-07 20:34:33 -05008577} // namespace
8578} // namespace test
8579} // namespace quic