blob: f7d1583b403871d8eaf18506bc88e68eed56cc9f [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>
8#include <memory>
9#include <ostream>
10#include <utility>
11
vasilvv872e7a32019-03-12 16:42:44 -070012#include <string>
13
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"
16#include "net/third_party/quiche/src/quic/core/crypto/null_encrypter.h"
17#include "net/third_party/quiche/src/quic/core/crypto/quic_decrypter.h"
18#include "net/third_party/quiche/src/quic/core/crypto/quic_encrypter.h"
19#include "net/third_party/quiche/src/quic/core/quic_connection_id.h"
20#include "net/third_party/quiche/src/quic/core/quic_packets.h"
21#include "net/third_party/quiche/src/quic/core/quic_simple_buffer_allocator.h"
22#include "net/third_party/quiche/src/quic/core/quic_types.h"
23#include "net/third_party/quiche/src/quic/core/quic_utils.h"
24#include "net/third_party/quiche/src/quic/platform/api/quic_error_code_wrappers.h"
25#include "net/third_party/quiche/src/quic/platform/api/quic_expect_bug.h"
26#include "net/third_party/quiche/src/quic/platform/api/quic_flags.h"
27#include "net/third_party/quiche/src/quic/platform/api/quic_logging.h"
28#include "net/third_party/quiche/src/quic/platform/api/quic_ptr_util.h"
29#include "net/third_party/quiche/src/quic/platform/api/quic_reference_counted.h"
30#include "net/third_party/quiche/src/quic/platform/api/quic_str_cat.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050031#include "net/third_party/quiche/src/quic/platform/api/quic_string_piece.h"
32#include "net/third_party/quiche/src/quic/platform/api/quic_test.h"
33#include "net/third_party/quiche/src/quic/test_tools/mock_clock.h"
34#include "net/third_party/quiche/src/quic/test_tools/mock_random.h"
35#include "net/third_party/quiche/src/quic/test_tools/quic_config_peer.h"
36#include "net/third_party/quiche/src/quic/test_tools/quic_connection_peer.h"
37#include "net/third_party/quiche/src/quic/test_tools/quic_framer_peer.h"
38#include "net/third_party/quiche/src/quic/test_tools/quic_packet_creator_peer.h"
39#include "net/third_party/quiche/src/quic/test_tools/quic_packet_generator_peer.h"
40#include "net/third_party/quiche/src/quic/test_tools/quic_sent_packet_manager_peer.h"
41#include "net/third_party/quiche/src/quic/test_tools/quic_test_utils.h"
42#include "net/third_party/quiche/src/quic/test_tools/simple_data_producer.h"
43#include "net/third_party/quiche/src/quic/test_tools/simple_quic_framer.h"
44#include "net/third_party/quiche/src/quic/test_tools/simple_session_notifier.h"
45
46using testing::_;
47using testing::AnyNumber;
48using testing::AtLeast;
49using testing::DoAll;
50using testing::Exactly;
51using testing::Ge;
52using testing::IgnoreResult;
53using testing::InSequence;
54using testing::Invoke;
55using testing::InvokeWithoutArgs;
56using testing::Lt;
57using testing::Ref;
58using testing::Return;
59using testing::SaveArg;
60using testing::SetArgPointee;
61using testing::StrictMock;
62
63namespace quic {
64namespace test {
65namespace {
66
67const char data1[] = "foo";
68const char data2[] = "bar";
69
70const bool kHasStopWaiting = true;
71
72const int kDefaultRetransmissionTimeMs = 500;
73
QUICHE team548d51b2019-03-14 10:06:54 -070074DiversificationNonce kTestDiversificationNonce = {
75 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a',
76 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b',
77 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b',
78};
79
QUICHE teama6ef0a62019-03-07 20:34:33 -050080const QuicSocketAddress kPeerAddress =
81 QuicSocketAddress(QuicIpAddress::Loopback6(),
82 /*port=*/12345);
83const QuicSocketAddress kSelfAddress =
84 QuicSocketAddress(QuicIpAddress::Loopback6(),
85 /*port=*/443);
86
87Perspective InvertPerspective(Perspective perspective) {
88 return perspective == Perspective::IS_CLIENT ? Perspective::IS_SERVER
89 : Perspective::IS_CLIENT;
90}
91
92QuicStreamId GetNthClientInitiatedStreamId(int n,
93 QuicTransportVersion version) {
94 return QuicUtils::GetHeadersStreamId(version) + n * 2;
95}
96
QUICHE team8c1daa22019-03-13 08:33:41 -070097QuicLongHeaderType EncryptionlevelToLongHeaderType(EncryptionLevel level) {
98 switch (level) {
QUICHE team6987b4a2019-03-15 16:23:04 -070099 case ENCRYPTION_INITIAL:
QUICHE team8c1daa22019-03-13 08:33:41 -0700100 return INITIAL;
QUICHE team88ea0082019-03-15 10:05:26 -0700101 case ENCRYPTION_HANDSHAKE:
102 return HANDSHAKE;
QUICHE team8c1daa22019-03-13 08:33:41 -0700103 case ENCRYPTION_ZERO_RTT:
104 return ZERO_RTT_PROTECTED;
105 case ENCRYPTION_FORWARD_SECURE:
106 DCHECK(false);
107 return INVALID_PACKET_TYPE;
108 default:
109 DCHECK(false);
110 return INVALID_PACKET_TYPE;
111 }
112}
113
QUICHE teama6ef0a62019-03-07 20:34:33 -0500114// TaggingEncrypter appends kTagSize bytes of |tag| to the end of each message.
115class TaggingEncrypter : public QuicEncrypter {
116 public:
117 explicit TaggingEncrypter(uint8_t tag) : tag_(tag) {}
118 TaggingEncrypter(const TaggingEncrypter&) = delete;
119 TaggingEncrypter& operator=(const TaggingEncrypter&) = delete;
120
121 ~TaggingEncrypter() override {}
122
123 // QuicEncrypter interface.
124 bool SetKey(QuicStringPiece key) override { return true; }
125
126 bool SetNoncePrefix(QuicStringPiece nonce_prefix) override { return true; }
127
128 bool SetIV(QuicStringPiece iv) override { return true; }
129
QUICHE team2d187972019-03-19 16:23:47 -0700130 bool SetHeaderProtectionKey(QuicStringPiece key) override { return true; }
131
QUICHE teama6ef0a62019-03-07 20:34:33 -0500132 bool EncryptPacket(uint64_t packet_number,
133 QuicStringPiece associated_data,
134 QuicStringPiece plaintext,
135 char* output,
136 size_t* output_length,
137 size_t max_output_length) override {
138 const size_t len = plaintext.size() + kTagSize;
139 if (max_output_length < len) {
140 return false;
141 }
142 // Memmove is safe for inplace encryption.
143 memmove(output, plaintext.data(), plaintext.size());
144 output += plaintext.size();
145 memset(output, tag_, kTagSize);
146 *output_length = len;
147 return true;
148 }
149
QUICHE team2d187972019-03-19 16:23:47 -0700150 std::string GenerateHeaderProtectionMask(QuicStringPiece sample) override {
151 return std::string(5, 0);
152 }
153
QUICHE teama6ef0a62019-03-07 20:34:33 -0500154 size_t GetKeySize() const override { return 0; }
155 size_t GetNoncePrefixSize() const override { return 0; }
156 size_t GetIVSize() const override { return 0; }
157
158 size_t GetMaxPlaintextSize(size_t ciphertext_size) const override {
159 return ciphertext_size - kTagSize;
160 }
161
162 size_t GetCiphertextSize(size_t plaintext_size) const override {
163 return plaintext_size + kTagSize;
164 }
165
166 QuicStringPiece GetKey() const override { return QuicStringPiece(); }
167
168 QuicStringPiece GetNoncePrefix() const override { return QuicStringPiece(); }
169
170 private:
171 enum {
172 kTagSize = 12,
173 };
174
175 const uint8_t tag_;
176};
177
178// TaggingDecrypter ensures that the final kTagSize bytes of the message all
179// have the same value and then removes them.
180class TaggingDecrypter : public QuicDecrypter {
181 public:
182 ~TaggingDecrypter() override {}
183
184 // QuicDecrypter interface
185 bool SetKey(QuicStringPiece key) override { return true; }
186
187 bool SetNoncePrefix(QuicStringPiece nonce_prefix) override { return true; }
188
189 bool SetIV(QuicStringPiece iv) override { return true; }
190
QUICHE team2d187972019-03-19 16:23:47 -0700191 bool SetHeaderProtectionKey(QuicStringPiece key) override { return true; }
192
QUICHE teama6ef0a62019-03-07 20:34:33 -0500193 bool SetPreliminaryKey(QuicStringPiece key) override {
194 QUIC_BUG << "should not be called";
195 return false;
196 }
197
198 bool SetDiversificationNonce(const DiversificationNonce& key) override {
199 return true;
200 }
201
202 bool DecryptPacket(uint64_t packet_number,
203 QuicStringPiece associated_data,
204 QuicStringPiece ciphertext,
205 char* output,
206 size_t* output_length,
207 size_t max_output_length) override {
208 if (ciphertext.size() < kTagSize) {
209 return false;
210 }
211 if (!CheckTag(ciphertext, GetTag(ciphertext))) {
212 return false;
213 }
214 *output_length = ciphertext.size() - kTagSize;
215 memcpy(output, ciphertext.data(), *output_length);
216 return true;
217 }
218
QUICHE team2d187972019-03-19 16:23:47 -0700219 std::string GenerateHeaderProtectionMask(
220 QuicDataReader* sample_reader) override {
221 return std::string(5, 0);
222 }
223
QUICHE teama6ef0a62019-03-07 20:34:33 -0500224 size_t GetKeySize() const override { return 0; }
225 size_t GetIVSize() const override { return 0; }
226 QuicStringPiece GetKey() const override { return QuicStringPiece(); }
227 QuicStringPiece GetNoncePrefix() const override { return QuicStringPiece(); }
228 // Use a distinct value starting with 0xFFFFFF, which is never used by TLS.
229 uint32_t cipher_id() const override { return 0xFFFFFFF0; }
230
231 protected:
232 virtual uint8_t GetTag(QuicStringPiece ciphertext) {
233 return ciphertext.data()[ciphertext.size() - 1];
234 }
235
236 private:
237 enum {
238 kTagSize = 12,
239 };
240
241 bool CheckTag(QuicStringPiece ciphertext, uint8_t tag) {
242 for (size_t i = ciphertext.size() - kTagSize; i < ciphertext.size(); i++) {
243 if (ciphertext.data()[i] != tag) {
244 return false;
245 }
246 }
247
248 return true;
249 }
250};
251
252// StringTaggingDecrypter ensures that the final kTagSize bytes of the message
253// match the expected value.
254class StrictTaggingDecrypter : public TaggingDecrypter {
255 public:
256 explicit StrictTaggingDecrypter(uint8_t tag) : tag_(tag) {}
257 ~StrictTaggingDecrypter() override {}
258
259 // TaggingQuicDecrypter
260 uint8_t GetTag(QuicStringPiece ciphertext) override { return tag_; }
261
262 // Use a distinct value starting with 0xFFFFFF, which is never used by TLS.
263 uint32_t cipher_id() const override { return 0xFFFFFFF1; }
264
265 private:
266 const uint8_t tag_;
267};
268
269class TestConnectionHelper : public QuicConnectionHelperInterface {
270 public:
271 TestConnectionHelper(MockClock* clock, MockRandom* random_generator)
272 : clock_(clock), random_generator_(random_generator) {
273 clock_->AdvanceTime(QuicTime::Delta::FromSeconds(1));
274 }
275 TestConnectionHelper(const TestConnectionHelper&) = delete;
276 TestConnectionHelper& operator=(const TestConnectionHelper&) = delete;
277
278 // QuicConnectionHelperInterface
279 const QuicClock* GetClock() const override { return clock_; }
280
281 QuicRandom* GetRandomGenerator() override { return random_generator_; }
282
283 QuicBufferAllocator* GetStreamSendBufferAllocator() override {
284 return &buffer_allocator_;
285 }
286
287 private:
288 MockClock* clock_;
289 MockRandom* random_generator_;
290 SimpleBufferAllocator buffer_allocator_;
291};
292
293class TestAlarmFactory : public QuicAlarmFactory {
294 public:
295 class TestAlarm : public QuicAlarm {
296 public:
297 explicit TestAlarm(QuicArenaScopedPtr<QuicAlarm::Delegate> delegate)
298 : QuicAlarm(std::move(delegate)) {}
299
300 void SetImpl() override {}
301 void CancelImpl() override {}
302 using QuicAlarm::Fire;
303 };
304
305 TestAlarmFactory() {}
306 TestAlarmFactory(const TestAlarmFactory&) = delete;
307 TestAlarmFactory& operator=(const TestAlarmFactory&) = delete;
308
309 QuicAlarm* CreateAlarm(QuicAlarm::Delegate* delegate) override {
310 return new TestAlarm(QuicArenaScopedPtr<QuicAlarm::Delegate>(delegate));
311 }
312
313 QuicArenaScopedPtr<QuicAlarm> CreateAlarm(
314 QuicArenaScopedPtr<QuicAlarm::Delegate> delegate,
315 QuicConnectionArena* arena) override {
316 return arena->New<TestAlarm>(std::move(delegate));
317 }
318};
319
320class TestPacketWriter : public QuicPacketWriter {
321 public:
322 TestPacketWriter(ParsedQuicVersion version, MockClock* clock)
323 : version_(version),
324 framer_(SupportedVersions(version_), Perspective::IS_SERVER),
325 last_packet_size_(0),
326 write_blocked_(false),
327 write_should_fail_(false),
328 block_on_next_flush_(false),
329 block_on_next_write_(false),
330 next_packet_too_large_(false),
331 always_get_packet_too_large_(false),
332 is_write_blocked_data_buffered_(false),
333 is_batch_mode_(false),
334 final_bytes_of_last_packet_(0),
335 final_bytes_of_previous_packet_(0),
336 use_tagging_decrypter_(false),
337 packets_write_attempts_(0),
338 clock_(clock),
339 write_pause_time_delta_(QuicTime::Delta::Zero()),
340 max_packet_size_(kMaxPacketSize),
341 supports_release_time_(false) {}
342 TestPacketWriter(const TestPacketWriter&) = delete;
343 TestPacketWriter& operator=(const TestPacketWriter&) = delete;
344
345 // QuicPacketWriter interface
346 WriteResult WritePacket(const char* buffer,
347 size_t buf_len,
348 const QuicIpAddress& self_address,
349 const QuicSocketAddress& peer_address,
350 PerPacketOptions* options) override {
351 QuicEncryptedPacket packet(buffer, buf_len);
352 ++packets_write_attempts_;
353
354 if (packet.length() >= sizeof(final_bytes_of_last_packet_)) {
355 final_bytes_of_previous_packet_ = final_bytes_of_last_packet_;
356 memcpy(&final_bytes_of_last_packet_, packet.data() + packet.length() - 4,
357 sizeof(final_bytes_of_last_packet_));
358 }
359
360 if (use_tagging_decrypter_) {
QUICHE team6987b4a2019-03-15 16:23:04 -0700361 framer_.framer()->SetDecrypter(ENCRYPTION_INITIAL,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500362 QuicMakeUnique<TaggingDecrypter>());
363 }
364 EXPECT_TRUE(framer_.ProcessPacket(packet));
365 if (block_on_next_write_) {
366 write_blocked_ = true;
367 block_on_next_write_ = false;
368 }
369 if (next_packet_too_large_) {
370 next_packet_too_large_ = false;
371 return WriteResult(WRITE_STATUS_ERROR, QUIC_EMSGSIZE);
372 }
373 if (always_get_packet_too_large_) {
374 return WriteResult(WRITE_STATUS_ERROR, QUIC_EMSGSIZE);
375 }
376 if (IsWriteBlocked()) {
377 return WriteResult(is_write_blocked_data_buffered_
378 ? WRITE_STATUS_BLOCKED_DATA_BUFFERED
379 : WRITE_STATUS_BLOCKED,
380 0);
381 }
382
383 if (ShouldWriteFail()) {
384 return WriteResult(WRITE_STATUS_ERROR, 0);
385 }
386
387 last_packet_size_ = packet.length();
388 last_packet_header_ = framer_.header();
389
390 if (!write_pause_time_delta_.IsZero()) {
391 clock_->AdvanceTime(write_pause_time_delta_);
392 }
393 return WriteResult(WRITE_STATUS_OK, last_packet_size_);
394 }
395
396 bool ShouldWriteFail() { return write_should_fail_; }
397
398 bool IsWriteBlocked() const override { return write_blocked_; }
399
400 void SetWriteBlocked() { write_blocked_ = true; }
401
402 void SetWritable() override { write_blocked_ = false; }
403
404 void SetShouldWriteFail() { write_should_fail_ = true; }
405
406 QuicByteCount GetMaxPacketSize(
407 const QuicSocketAddress& /*peer_address*/) const override {
408 return max_packet_size_;
409 }
410
411 bool SupportsReleaseTime() const { return supports_release_time_; }
412
413 bool IsBatchMode() const override { return is_batch_mode_; }
414
415 char* GetNextWriteLocation(const QuicIpAddress& self_address,
416 const QuicSocketAddress& peer_address) override {
417 return nullptr;
418 }
419
420 WriteResult Flush() override {
421 if (block_on_next_flush_) {
422 block_on_next_flush_ = false;
423 SetWriteBlocked();
424 return WriteResult(WRITE_STATUS_BLOCKED, /*errno*/ -1);
425 }
426 return WriteResult(WRITE_STATUS_OK, 0);
427 }
428
429 void BlockOnNextFlush() { block_on_next_flush_ = true; }
430
431 void BlockOnNextWrite() { block_on_next_write_ = true; }
432
433 void SimulateNextPacketTooLarge() { next_packet_too_large_ = true; }
434
435 void AlwaysGetPacketTooLarge() { always_get_packet_too_large_ = true; }
436
437 // Sets the amount of time that the writer should before the actual write.
438 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
439 write_pause_time_delta_ = delta;
440 }
441
442 void SetBatchMode(bool new_value) { is_batch_mode_ = new_value; }
443
444 const QuicPacketHeader& header() { return framer_.header(); }
445
446 size_t frame_count() const { return framer_.num_frames(); }
447
448 const std::vector<QuicAckFrame>& ack_frames() const {
449 return framer_.ack_frames();
450 }
451
452 const std::vector<QuicStopWaitingFrame>& stop_waiting_frames() const {
453 return framer_.stop_waiting_frames();
454 }
455
456 const std::vector<QuicConnectionCloseFrame>& connection_close_frames() const {
457 return framer_.connection_close_frames();
458 }
459
460 const std::vector<QuicRstStreamFrame>& rst_stream_frames() const {
461 return framer_.rst_stream_frames();
462 }
463
464 const std::vector<std::unique_ptr<QuicStreamFrame>>& stream_frames() const {
465 return framer_.stream_frames();
466 }
467
468 const std::vector<std::unique_ptr<QuicCryptoFrame>>& crypto_frames() const {
469 return framer_.crypto_frames();
470 }
471
472 const std::vector<QuicPingFrame>& ping_frames() const {
473 return framer_.ping_frames();
474 }
475
476 const std::vector<QuicMessageFrame>& message_frames() const {
477 return framer_.message_frames();
478 }
479
480 const std::vector<QuicWindowUpdateFrame>& window_update_frames() const {
481 return framer_.window_update_frames();
482 }
483
484 const std::vector<QuicPaddingFrame>& padding_frames() const {
485 return framer_.padding_frames();
486 }
487
488 const std::vector<QuicPathChallengeFrame>& path_challenge_frames() const {
489 return framer_.path_challenge_frames();
490 }
491
492 const std::vector<QuicPathResponseFrame>& path_response_frames() const {
493 return framer_.path_response_frames();
494 }
495
496 size_t last_packet_size() { return last_packet_size_; }
497
498 const QuicPacketHeader& last_packet_header() const {
499 return last_packet_header_;
500 }
501
502 const QuicVersionNegotiationPacket* version_negotiation_packet() {
503 return framer_.version_negotiation_packet();
504 }
505
506 void set_is_write_blocked_data_buffered(bool buffered) {
507 is_write_blocked_data_buffered_ = buffered;
508 }
509
510 void set_perspective(Perspective perspective) {
511 // We invert perspective here, because the framer needs to parse packets
512 // we send.
513 QuicFramerPeer::SetPerspective(framer_.framer(),
514 InvertPerspective(perspective));
515 }
516
517 // final_bytes_of_last_packet_ returns the last four bytes of the previous
518 // packet as a little-endian, uint32_t. This is intended to be used with a
519 // TaggingEncrypter so that tests can determine which encrypter was used for
520 // a given packet.
521 uint32_t final_bytes_of_last_packet() { return final_bytes_of_last_packet_; }
522
523 // Returns the final bytes of the second to last packet.
524 uint32_t final_bytes_of_previous_packet() {
525 return final_bytes_of_previous_packet_;
526 }
527
528 void use_tagging_decrypter() { use_tagging_decrypter_ = true; }
529
530 uint32_t packets_write_attempts() { return packets_write_attempts_; }
531
532 void Reset() { framer_.Reset(); }
533
534 void SetSupportedVersions(const ParsedQuicVersionVector& versions) {
535 framer_.SetSupportedVersions(versions);
536 }
537
538 void set_max_packet_size(QuicByteCount max_packet_size) {
539 max_packet_size_ = max_packet_size;
540 }
541
542 void set_supports_release_time(bool supports_release_time) {
543 supports_release_time_ = supports_release_time;
544 }
545
546 SimpleQuicFramer* framer() { return &framer_; }
547
548 private:
549 ParsedQuicVersion version_;
550 SimpleQuicFramer framer_;
551 size_t last_packet_size_;
552 QuicPacketHeader last_packet_header_;
553 bool write_blocked_;
554 bool write_should_fail_;
555 bool block_on_next_flush_;
556 bool block_on_next_write_;
557 bool next_packet_too_large_;
558 bool always_get_packet_too_large_;
559 bool is_write_blocked_data_buffered_;
560 bool is_batch_mode_;
561 uint32_t final_bytes_of_last_packet_;
562 uint32_t final_bytes_of_previous_packet_;
563 bool use_tagging_decrypter_;
564 uint32_t packets_write_attempts_;
565 MockClock* clock_;
566 // If non-zero, the clock will pause during WritePacket for this amount of
567 // time.
568 QuicTime::Delta write_pause_time_delta_;
569 QuicByteCount max_packet_size_;
570 bool supports_release_time_;
571};
572
573class TestConnection : public QuicConnection {
574 public:
575 TestConnection(QuicConnectionId connection_id,
576 QuicSocketAddress address,
577 TestConnectionHelper* helper,
578 TestAlarmFactory* alarm_factory,
579 TestPacketWriter* writer,
580 Perspective perspective,
581 ParsedQuicVersion version)
582 : QuicConnection(connection_id,
583 address,
584 helper,
585 alarm_factory,
586 writer,
587 /* owns_writer= */ false,
588 perspective,
589 SupportedVersions(version)),
590 notifier_(nullptr) {
591 writer->set_perspective(perspective);
592 SetEncrypter(ENCRYPTION_FORWARD_SECURE,
593 QuicMakeUnique<NullEncrypter>(perspective));
594 SetDataProducer(&producer_);
595 }
596 TestConnection(const TestConnection&) = delete;
597 TestConnection& operator=(const TestConnection&) = delete;
598
599 void SendAck() { QuicConnectionPeer::SendAck(this); }
600
601 void SetSendAlgorithm(SendAlgorithmInterface* send_algorithm) {
602 QuicConnectionPeer::SetSendAlgorithm(this, send_algorithm);
603 }
604
605 void SetLossAlgorithm(LossDetectionInterface* loss_algorithm) {
606 QuicConnectionPeer::SetLossAlgorithm(this, loss_algorithm);
607 }
608
609 void SendPacket(EncryptionLevel level,
610 uint64_t packet_number,
611 std::unique_ptr<QuicPacket> packet,
612 HasRetransmittableData retransmittable,
613 bool has_ack,
614 bool has_pending_frames) {
615 char buffer[kMaxPacketSize];
616 size_t encrypted_length =
617 QuicConnectionPeer::GetFramer(this)->EncryptPayload(
QUICHE team6987b4a2019-03-15 16:23:04 -0700618 ENCRYPTION_INITIAL, QuicPacketNumber(packet_number), *packet,
619 buffer, kMaxPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500620 SerializedPacket serialized_packet(
621 QuicPacketNumber(packet_number), PACKET_4BYTE_PACKET_NUMBER, buffer,
622 encrypted_length, has_ack, has_pending_frames);
623 if (retransmittable == HAS_RETRANSMITTABLE_DATA) {
624 serialized_packet.retransmittable_frames.push_back(
625 QuicFrame(QuicStreamFrame()));
626 }
627 OnSerializedPacket(&serialized_packet);
628 }
629
630 QuicConsumedData SaveAndSendStreamData(QuicStreamId id,
631 const struct iovec* iov,
632 int iov_count,
633 size_t total_length,
634 QuicStreamOffset offset,
635 StreamSendingState state) {
636 ScopedPacketFlusher flusher(this, NO_ACK);
637 producer_.SaveStreamData(id, iov, iov_count, 0u, total_length);
638 if (notifier_ != nullptr) {
639 return notifier_->WriteOrBufferData(id, total_length, state);
640 }
641 return QuicConnection::SendStreamData(id, total_length, offset, state);
642 }
643
644 QuicConsumedData SendStreamDataWithString(QuicStreamId id,
645 QuicStringPiece data,
646 QuicStreamOffset offset,
647 StreamSendingState state) {
648 ScopedPacketFlusher flusher(this, NO_ACK);
649 if (id != QuicUtils::GetCryptoStreamId(transport_version()) &&
QUICHE team6987b4a2019-03-15 16:23:04 -0700650 this->encryption_level() == ENCRYPTION_INITIAL) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500651 this->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
652 }
653 struct iovec iov;
654 MakeIOVector(data, &iov);
655 return SaveAndSendStreamData(id, &iov, 1, data.length(), offset, state);
656 }
657
QUICHE teamcd098022019-03-22 18:49:55 -0700658 QuicConsumedData SendApplicationDataAtLevel(EncryptionLevel encryption_level,
659 QuicStreamId id,
660 QuicStringPiece data,
661 QuicStreamOffset offset,
662 StreamSendingState state) {
663 ScopedPacketFlusher flusher(this, NO_ACK);
664 DCHECK(encryption_level >= ENCRYPTION_ZERO_RTT);
665 SetEncrypter(encryption_level, QuicMakeUnique<TaggingEncrypter>(0x01));
666 SetDefaultEncryptionLevel(encryption_level);
667 struct iovec iov;
668 MakeIOVector(data, &iov);
669 return SaveAndSendStreamData(id, &iov, 1, data.length(), offset, state);
670 }
671
QUICHE teama6ef0a62019-03-07 20:34:33 -0500672 QuicConsumedData SendStreamData3() {
673 return SendStreamDataWithString(
674 GetNthClientInitiatedStreamId(1, transport_version()), "food", 0,
675 NO_FIN);
676 }
677
678 QuicConsumedData SendStreamData5() {
679 return SendStreamDataWithString(
680 GetNthClientInitiatedStreamId(2, transport_version()), "food2", 0,
681 NO_FIN);
682 }
683
684 // Ensures the connection can write stream data before writing.
685 QuicConsumedData EnsureWritableAndSendStreamData5() {
686 EXPECT_TRUE(CanWriteStreamData());
687 return SendStreamData5();
688 }
689
690 // The crypto stream has special semantics so that it is not blocked by a
691 // congestion window limitation, and also so that it gets put into a separate
692 // packet (so that it is easier to reason about a crypto frame not being
693 // split needlessly across packet boundaries). As a result, we have separate
694 // tests for some cases for this stream.
695 QuicConsumedData SendCryptoStreamData() {
696 QuicStreamOffset offset = 0;
697 QuicStringPiece data("chlo");
QUICHE teamea740082019-03-11 17:58:43 -0700698 if (!QuicVersionUsesCryptoFrames(transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500699 return SendStreamDataWithString(
700 QuicUtils::GetCryptoStreamId(transport_version()), data, offset,
701 NO_FIN);
702 }
QUICHE team6987b4a2019-03-15 16:23:04 -0700703 producer_.SaveCryptoData(ENCRYPTION_INITIAL, offset, data);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500704 size_t bytes_written;
705 if (notifier_) {
706 bytes_written =
QUICHE team6987b4a2019-03-15 16:23:04 -0700707 notifier_->WriteCryptoData(ENCRYPTION_INITIAL, data.length(), offset);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500708 } else {
QUICHE team6987b4a2019-03-15 16:23:04 -0700709 bytes_written = QuicConnection::SendCryptoData(ENCRYPTION_INITIAL,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500710 data.length(), offset);
711 }
712 return QuicConsumedData(bytes_written, /*fin_consumed*/ false);
713 }
714
715 void set_version(ParsedQuicVersion version) {
716 QuicConnectionPeer::GetFramer(this)->set_version(version);
717 }
718
719 void SetSupportedVersions(const ParsedQuicVersionVector& versions) {
720 QuicConnectionPeer::GetFramer(this)->SetSupportedVersions(versions);
721 QuicConnectionPeer::SetNoVersionNegotiation(this, versions.size() == 1);
722 writer()->SetSupportedVersions(versions);
723 }
724
725 void set_perspective(Perspective perspective) {
726 writer()->set_perspective(perspective);
727 QuicConnectionPeer::SetPerspective(this, perspective);
728 }
729
730 // Enable path MTU discovery. Assumes that the test is performed from the
731 // client perspective and the higher value of MTU target is used.
732 void EnablePathMtuDiscovery(MockSendAlgorithm* send_algorithm) {
733 ASSERT_EQ(Perspective::IS_CLIENT, perspective());
734
735 QuicConfig config;
736 QuicTagVector connection_options;
737 connection_options.push_back(kMTUH);
738 config.SetConnectionOptionsToSend(connection_options);
739 EXPECT_CALL(*send_algorithm, SetFromConfig(_, _));
740 SetFromConfig(config);
741
742 // Normally, the pacing would be disabled in the test, but calling
743 // SetFromConfig enables it. Set nearly-infinite bandwidth to make the
744 // pacing algorithm work.
745 EXPECT_CALL(*send_algorithm, PacingRate(_))
746 .WillRepeatedly(Return(QuicBandwidth::Infinite()));
747 }
748
749 TestAlarmFactory::TestAlarm* GetAckAlarm() {
750 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
751 QuicConnectionPeer::GetAckAlarm(this));
752 }
753
754 TestAlarmFactory::TestAlarm* GetPingAlarm() {
755 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
756 QuicConnectionPeer::GetPingAlarm(this));
757 }
758
759 TestAlarmFactory::TestAlarm* GetRetransmissionAlarm() {
760 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
761 QuicConnectionPeer::GetRetransmissionAlarm(this));
762 }
763
764 TestAlarmFactory::TestAlarm* GetSendAlarm() {
765 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
766 QuicConnectionPeer::GetSendAlarm(this));
767 }
768
769 TestAlarmFactory::TestAlarm* GetTimeoutAlarm() {
770 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
771 QuicConnectionPeer::GetTimeoutAlarm(this));
772 }
773
774 TestAlarmFactory::TestAlarm* GetMtuDiscoveryAlarm() {
775 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
776 QuicConnectionPeer::GetMtuDiscoveryAlarm(this));
777 }
778
779 TestAlarmFactory::TestAlarm* GetPathDegradingAlarm() {
780 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
781 QuicConnectionPeer::GetPathDegradingAlarm(this));
782 }
783
784 TestAlarmFactory::TestAlarm* GetProcessUndecryptablePacketsAlarm() {
785 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
786 QuicConnectionPeer::GetProcessUndecryptablePacketsAlarm(this));
787 }
788
789 void SetMaxTailLossProbes(size_t max_tail_loss_probes) {
790 QuicSentPacketManagerPeer::SetMaxTailLossProbes(
791 QuicConnectionPeer::GetSentPacketManager(this), max_tail_loss_probes);
792 }
793
794 QuicByteCount GetBytesInFlight() {
795 return QuicSentPacketManagerPeer::GetBytesInFlight(
796 QuicConnectionPeer::GetSentPacketManager(this));
797 }
798
799 void set_notifier(SimpleSessionNotifier* notifier) { notifier_ = notifier; }
800
801 void ReturnEffectivePeerAddressForNextPacket(const QuicSocketAddress& addr) {
802 next_effective_peer_addr_ = QuicMakeUnique<QuicSocketAddress>(addr);
803 }
804
805 using QuicConnection::active_effective_peer_migration_type;
806 using QuicConnection::IsCurrentPacketConnectivityProbing;
807 using QuicConnection::SelectMutualVersion;
808 using QuicConnection::SendProbingRetransmissions;
809 using QuicConnection::set_defer_send_in_response_to_packets;
810
811 protected:
812 QuicSocketAddress GetEffectivePeerAddressFromCurrentPacket() const override {
813 if (next_effective_peer_addr_) {
814 return *std::move(next_effective_peer_addr_);
815 }
816 return QuicConnection::GetEffectivePeerAddressFromCurrentPacket();
817 }
818
819 private:
820 TestPacketWriter* writer() {
821 return static_cast<TestPacketWriter*>(QuicConnection::writer());
822 }
823
824 SimpleDataProducer producer_;
825
826 SimpleSessionNotifier* notifier_;
827
828 std::unique_ptr<QuicSocketAddress> next_effective_peer_addr_;
829};
830
831enum class AckResponse { kDefer, kImmediate };
832
833// Run tests with combinations of {ParsedQuicVersion, AckResponse}.
834struct TestParams {
835 TestParams(ParsedQuicVersion version,
836 AckResponse ack_response,
837 bool no_stop_waiting)
838 : version(version),
839 ack_response(ack_response),
840 no_stop_waiting(no_stop_waiting) {}
841
842 friend std::ostream& operator<<(std::ostream& os, const TestParams& p) {
843 os << "{ client_version: " << ParsedQuicVersionToString(p.version)
844 << " ack_response: "
845 << (p.ack_response == AckResponse::kDefer ? "defer" : "immediate")
846 << " no_stop_waiting: " << p.no_stop_waiting << " }";
847 return os;
848 }
849
850 ParsedQuicVersion version;
851 AckResponse ack_response;
852 bool no_stop_waiting;
853};
854
855// Constructs various test permutations.
856std::vector<TestParams> GetTestParams() {
857 QuicFlagSaver flags;
858 SetQuicFlag(&FLAGS_quic_supports_tls_handshake, true);
859 std::vector<TestParams> params;
860 ParsedQuicVersionVector all_supported_versions = AllSupportedVersions();
861 for (size_t i = 0; i < all_supported_versions.size(); ++i) {
862 for (AckResponse ack_response :
863 {AckResponse::kDefer, AckResponse::kImmediate}) {
864 for (bool no_stop_waiting : {true, false}) {
865 // After version 43, never use STOP_WAITING.
866 if (all_supported_versions[i].transport_version <= QUIC_VERSION_43 ||
867 no_stop_waiting) {
868 params.push_back(TestParams(all_supported_versions[i], ack_response,
869 no_stop_waiting));
870 }
871 }
872 }
873 }
874 return params;
875}
876
877class QuicConnectionTest : public QuicTestWithParam<TestParams> {
878 protected:
879 QuicConnectionTest()
880 : connection_id_(TestConnectionId()),
881 framer_(SupportedVersions(version()),
882 QuicTime::Zero(),
883 Perspective::IS_CLIENT,
884 connection_id_.length()),
885 send_algorithm_(new StrictMock<MockSendAlgorithm>),
886 loss_algorithm_(new MockLossAlgorithm()),
887 helper_(new TestConnectionHelper(&clock_, &random_generator_)),
888 alarm_factory_(new TestAlarmFactory()),
889 peer_framer_(SupportedVersions(version()),
890 QuicTime::Zero(),
891 Perspective::IS_SERVER,
892 connection_id_.length()),
893 peer_creator_(connection_id_,
894 &peer_framer_,
895 /*delegate=*/nullptr),
896 writer_(new TestPacketWriter(version(), &clock_)),
897 connection_(connection_id_,
898 kPeerAddress,
899 helper_.get(),
900 alarm_factory_.get(),
901 writer_.get(),
902 Perspective::IS_CLIENT,
903 version()),
904 creator_(QuicConnectionPeer::GetPacketCreator(&connection_)),
905 generator_(QuicConnectionPeer::GetPacketGenerator(&connection_)),
906 manager_(QuicConnectionPeer::GetSentPacketManager(&connection_)),
907 frame1_(QuicUtils::GetCryptoStreamId(version().transport_version),
908 false,
909 0,
910 QuicStringPiece(data1)),
911 frame2_(QuicUtils::GetCryptoStreamId(version().transport_version),
912 false,
913 3,
914 QuicStringPiece(data2)),
915 packet_number_length_(PACKET_4BYTE_PACKET_NUMBER),
916 connection_id_included_(CONNECTION_ID_PRESENT),
917 notifier_(&connection_) {
918 SetQuicFlag(&FLAGS_quic_supports_tls_handshake, true);
919 connection_.set_defer_send_in_response_to_packets(GetParam().ack_response ==
920 AckResponse::kDefer);
921 QuicFramerPeer::SetLastSerializedConnectionId(
922 QuicConnectionPeer::GetFramer(&connection_), connection_id_);
923 if (version().transport_version > QUIC_VERSION_43) {
924 EXPECT_TRUE(QuicConnectionPeer::GetNoStopWaitingFrames(&connection_));
925 } else {
926 QuicConnectionPeer::SetNoStopWaitingFrames(&connection_,
927 GetParam().no_stop_waiting);
928 }
929 connection_.set_visitor(&visitor_);
930 if (connection_.session_decides_what_to_write()) {
931 connection_.SetSessionNotifier(&notifier_);
932 connection_.set_notifier(&notifier_);
933 }
934 connection_.SetSendAlgorithm(send_algorithm_);
935 connection_.SetLossAlgorithm(loss_algorithm_.get());
936 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
937 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
938 .Times(AnyNumber());
939 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
940 .WillRepeatedly(Return(kDefaultTCPMSS));
941 EXPECT_CALL(*send_algorithm_, PacingRate(_))
942 .WillRepeatedly(Return(QuicBandwidth::Zero()));
943 EXPECT_CALL(*send_algorithm_, HasReliableBandwidthEstimate())
944 .Times(AnyNumber());
945 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
946 .Times(AnyNumber())
947 .WillRepeatedly(Return(QuicBandwidth::Zero()));
948 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
949 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
950 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
951 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).Times(AnyNumber());
952 EXPECT_CALL(visitor_, HasPendingHandshake()).Times(AnyNumber());
953 if (connection_.session_decides_what_to_write()) {
954 EXPECT_CALL(visitor_, OnCanWrite())
955 .WillRepeatedly(
956 Invoke(&notifier_, &SimpleSessionNotifier::OnCanWrite));
957 } else {
958 EXPECT_CALL(visitor_, OnCanWrite()).Times(AnyNumber());
959 }
960 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
961 .WillRepeatedly(Return(false));
962 EXPECT_CALL(visitor_, OnCongestionWindowChange(_)).Times(AnyNumber());
963 EXPECT_CALL(visitor_, OnConnectivityProbeReceived(_, _)).Times(AnyNumber());
964 EXPECT_CALL(visitor_, OnForwardProgressConfirmed()).Times(AnyNumber());
965
966 EXPECT_CALL(*loss_algorithm_, GetLossTimeout())
967 .WillRepeatedly(Return(QuicTime::Zero()));
968 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
969 .Times(AnyNumber());
970 }
971
972 QuicConnectionTest(const QuicConnectionTest&) = delete;
973 QuicConnectionTest& operator=(const QuicConnectionTest&) = delete;
974
975 ParsedQuicVersion version() { return GetParam().version; }
976
977 QuicAckFrame* outgoing_ack() {
978 QuicFrame ack_frame = QuicConnectionPeer::GetUpdatedAckFrame(&connection_);
979 ack_ = *ack_frame.ack_frame;
980 return &ack_;
981 }
982
983 QuicStopWaitingFrame* stop_waiting() {
984 QuicConnectionPeer::PopulateStopWaitingFrame(&connection_, &stop_waiting_);
985 return &stop_waiting_;
986 }
987
988 QuicPacketNumber least_unacked() {
989 if (writer_->stop_waiting_frames().empty()) {
990 return QuicPacketNumber();
991 }
992 return writer_->stop_waiting_frames()[0].least_unacked;
993 }
994
995 void use_tagging_decrypter() { writer_->use_tagging_decrypter(); }
996
997 void ProcessPacket(uint64_t number) {
998 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
999 ProcessDataPacket(number);
1000 if (connection_.GetSendAlarm()->IsSet()) {
1001 connection_.GetSendAlarm()->Fire();
1002 }
1003 }
1004
1005 void ProcessReceivedPacket(const QuicSocketAddress& self_address,
1006 const QuicSocketAddress& peer_address,
1007 const QuicReceivedPacket& packet) {
1008 connection_.ProcessUdpPacket(self_address, peer_address, packet);
1009 if (connection_.GetSendAlarm()->IsSet()) {
1010 connection_.GetSendAlarm()->Fire();
1011 }
1012 }
1013
1014 void ProcessFramePacket(QuicFrame frame) {
1015 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
1016 }
1017
1018 void ProcessFramePacketWithAddresses(QuicFrame frame,
1019 QuicSocketAddress self_address,
1020 QuicSocketAddress peer_address) {
1021 QuicFrames frames;
1022 frames.push_back(QuicFrame(frame));
1023 QuicPacketCreatorPeer::SetSendVersionInPacket(
1024 &peer_creator_, connection_.perspective() == Perspective::IS_SERVER);
1025 if (QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_) >
QUICHE team6987b4a2019-03-15 16:23:04 -07001026 ENCRYPTION_INITIAL) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001027 // Set peer_framer_'s corresponding encrypter.
1028 peer_creator_.SetEncrypter(
1029 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
1030 QuicMakeUnique<NullEncrypter>(peer_framer_.perspective()));
1031 }
1032
1033 char buffer[kMaxPacketSize];
1034 SerializedPacket serialized_packet =
1035 QuicPacketCreatorPeer::SerializeAllFrames(&peer_creator_, frames,
1036 buffer, kMaxPacketSize);
1037 connection_.ProcessUdpPacket(
1038 self_address, peer_address,
1039 QuicReceivedPacket(serialized_packet.encrypted_buffer,
1040 serialized_packet.encrypted_length, clock_.Now()));
1041 if (connection_.GetSendAlarm()->IsSet()) {
1042 connection_.GetSendAlarm()->Fire();
1043 }
1044 }
1045
1046 // Bypassing the packet creator is unrealistic, but allows us to process
1047 // packets the QuicPacketCreator won't allow us to create.
1048 void ForceProcessFramePacket(QuicFrame frame) {
1049 QuicFrames frames;
1050 frames.push_back(QuicFrame(frame));
1051 QuicPacketCreatorPeer::SetSendVersionInPacket(
1052 &peer_creator_, connection_.perspective() == Perspective::IS_SERVER);
1053 QuicPacketHeader header;
1054 QuicPacketCreatorPeer::FillPacketHeader(&peer_creator_, &header);
1055 char encrypted_buffer[kMaxPacketSize];
1056 size_t length = peer_framer_.BuildDataPacket(
QUICHE team6987b4a2019-03-15 16:23:04 -07001057 header, frames, encrypted_buffer, kMaxPacketSize, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001058 DCHECK_GT(length, 0u);
1059
1060 const size_t encrypted_length = peer_framer_.EncryptInPlace(
QUICHE team6987b4a2019-03-15 16:23:04 -07001061 ENCRYPTION_INITIAL, header.packet_number,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001062 GetStartOfEncryptedData(peer_framer_.version().transport_version,
1063 header),
1064 length, kMaxPacketSize, encrypted_buffer);
1065 DCHECK_GT(encrypted_length, 0u);
1066
1067 connection_.ProcessUdpPacket(
1068 kSelfAddress, kPeerAddress,
1069 QuicReceivedPacket(encrypted_buffer, encrypted_length, clock_.Now()));
1070 }
1071
1072 size_t ProcessFramePacketAtLevel(uint64_t number,
1073 QuicFrame frame,
1074 EncryptionLevel level) {
1075 QuicPacketHeader header;
1076 header.destination_connection_id = connection_id_;
1077 header.packet_number_length = packet_number_length_;
1078 header.destination_connection_id_included = connection_id_included_;
1079 if (peer_framer_.transport_version() > QUIC_VERSION_43 &&
1080 peer_framer_.perspective() == Perspective::IS_SERVER) {
1081 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1082 }
1083 header.packet_number = QuicPacketNumber(number);
1084 QuicFrames frames;
1085 frames.push_back(frame);
1086 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
QUICHE teamcd098022019-03-22 18:49:55 -07001087 // Set the correct encryption level and encrypter on peer_creator and
1088 // peer_framer, respectively.
1089 peer_creator_.set_encryption_level(level);
1090 if (QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_) >
1091 ENCRYPTION_INITIAL) {
1092 peer_framer_.SetEncrypter(
1093 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
1094 QuicMakeUnique<TaggingEncrypter>(0x01));
1095 // Set the corresponding decrypter.
1096 connection_.SetDecrypter(
1097 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
1098 QuicMakeUnique<StrictTaggingDecrypter>(0x01));
1099 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001100
1101 char buffer[kMaxPacketSize];
QUICHE teamcd098022019-03-22 18:49:55 -07001102 size_t encrypted_length = peer_framer_.EncryptPayload(
QUICHE teama6ef0a62019-03-07 20:34:33 -05001103 level, QuicPacketNumber(number), *packet, buffer, kMaxPacketSize);
1104 connection_.ProcessUdpPacket(
1105 kSelfAddress, kPeerAddress,
QUICHE teamcd098022019-03-22 18:49:55 -07001106 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1107 if (connection_.GetSendAlarm()->IsSet()) {
1108 connection_.GetSendAlarm()->Fire();
1109 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001110 return encrypted_length;
1111 }
1112
1113 size_t ProcessDataPacket(uint64_t number) {
QUICHE team6987b4a2019-03-15 16:23:04 -07001114 return ProcessDataPacketAtLevel(number, false, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001115 }
1116
1117 size_t ProcessDataPacket(QuicPacketNumber packet_number) {
QUICHE team6987b4a2019-03-15 16:23:04 -07001118 return ProcessDataPacketAtLevel(packet_number, false, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001119 }
1120
1121 size_t ProcessDataPacketAtLevel(QuicPacketNumber packet_number,
1122 bool has_stop_waiting,
1123 EncryptionLevel level) {
1124 return ProcessDataPacketAtLevel(packet_number.ToUint64(), has_stop_waiting,
1125 level);
1126 }
1127
1128 size_t ProcessDataPacketAtLevel(uint64_t number,
1129 bool has_stop_waiting,
1130 EncryptionLevel level) {
1131 std::unique_ptr<QuicPacket> packet(
QUICHE team8c1daa22019-03-13 08:33:41 -07001132 ConstructDataPacket(number, has_stop_waiting, level));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001133 char buffer[kMaxPacketSize];
QUICHE teamcd098022019-03-22 18:49:55 -07001134 peer_creator_.set_encryption_level(level);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001135 size_t encrypted_length = peer_framer_.EncryptPayload(
1136 level, QuicPacketNumber(number), *packet, buffer, kMaxPacketSize);
1137 connection_.ProcessUdpPacket(
1138 kSelfAddress, kPeerAddress,
1139 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1140 if (connection_.GetSendAlarm()->IsSet()) {
1141 connection_.GetSendAlarm()->Fire();
1142 }
1143 return encrypted_length;
1144 }
1145
1146 void ProcessClosePacket(uint64_t number) {
1147 std::unique_ptr<QuicPacket> packet(ConstructClosePacket(number));
1148 char buffer[kMaxPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07001149 size_t encrypted_length = peer_framer_.EncryptPayload(
1150 ENCRYPTION_INITIAL, QuicPacketNumber(number), *packet, buffer,
1151 kMaxPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001152 connection_.ProcessUdpPacket(
1153 kSelfAddress, kPeerAddress,
1154 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
1155 }
1156
1157 QuicByteCount SendStreamDataToPeer(QuicStreamId id,
1158 QuicStringPiece data,
1159 QuicStreamOffset offset,
1160 StreamSendingState state,
1161 QuicPacketNumber* last_packet) {
1162 QuicByteCount packet_size;
1163 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1164 .WillOnce(SaveArg<3>(&packet_size));
1165 connection_.SendStreamDataWithString(id, data, offset, state);
1166 if (last_packet != nullptr) {
1167 *last_packet = creator_->packet_number();
1168 }
1169 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1170 .Times(AnyNumber());
1171 return packet_size;
1172 }
1173
1174 void SendAckPacketToPeer() {
1175 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1176 {
1177 QuicConnection::ScopedPacketFlusher flusher(&connection_,
1178 QuicConnection::NO_ACK);
1179 connection_.SendAck();
1180 }
1181 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1182 .Times(AnyNumber());
1183 }
1184
1185 void SendRstStream(QuicStreamId id,
1186 QuicRstStreamErrorCode error,
1187 QuicStreamOffset bytes_written) {
1188 if (connection_.session_decides_what_to_write()) {
1189 notifier_.WriteOrBufferRstStream(id, error, bytes_written);
1190 connection_.OnStreamReset(id, error);
1191 return;
1192 }
1193 std::unique_ptr<QuicRstStreamFrame> rst_stream =
1194 QuicMakeUnique<QuicRstStreamFrame>(1, id, error, bytes_written);
1195 if (connection_.SendControlFrame(QuicFrame(rst_stream.get()))) {
1196 rst_stream.release();
1197 }
1198 connection_.OnStreamReset(id, error);
1199 }
1200
1201 void ProcessAckPacket(uint64_t packet_number, QuicAckFrame* frame) {
1202 if (packet_number > 1) {
1203 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, packet_number - 1);
1204 } else {
1205 QuicPacketCreatorPeer::ClearPacketNumber(&peer_creator_);
1206 }
1207 ProcessFramePacket(QuicFrame(frame));
1208 }
1209
1210 void ProcessAckPacket(QuicAckFrame* frame) {
1211 ProcessFramePacket(QuicFrame(frame));
1212 }
1213
1214 void ProcessStopWaitingPacket(QuicStopWaitingFrame frame) {
1215 ProcessFramePacket(QuicFrame(frame));
1216 }
1217
1218 size_t ProcessStopWaitingPacketAtLevel(uint64_t number,
1219 QuicStopWaitingFrame frame,
1220 EncryptionLevel level) {
1221 return ProcessFramePacketAtLevel(number, QuicFrame(frame),
1222 ENCRYPTION_ZERO_RTT);
1223 }
1224
1225 void ProcessGoAwayPacket(QuicGoAwayFrame* frame) {
1226 ProcessFramePacket(QuicFrame(frame));
1227 }
1228
1229 bool IsMissing(uint64_t number) {
1230 return IsAwaitingPacket(*outgoing_ack(), QuicPacketNumber(number),
1231 QuicPacketNumber());
1232 }
1233
1234 std::unique_ptr<QuicPacket> ConstructPacket(const QuicPacketHeader& header,
1235 const QuicFrames& frames) {
1236 auto packet = BuildUnsizedDataPacket(&peer_framer_, header, frames);
1237 EXPECT_NE(nullptr, packet.get());
1238 return packet;
1239 }
1240
1241 std::unique_ptr<QuicPacket> ConstructDataPacket(uint64_t number,
QUICHE team8c1daa22019-03-13 08:33:41 -07001242 bool has_stop_waiting,
1243 EncryptionLevel level) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001244 QuicPacketHeader header;
QUICHE team8c1daa22019-03-13 08:33:41 -07001245 if (peer_framer_.transport_version() > QUIC_VERSION_43 &&
1246 level < ENCRYPTION_FORWARD_SECURE) {
1247 // Set long header type accordingly.
1248 header.version_flag = true;
1249 header.long_packet_type = EncryptionlevelToLongHeaderType(level);
1250 if (QuicVersionHasLongHeaderLengths(
1251 peer_framer_.version().transport_version)) {
1252 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
1253 if (header.long_packet_type == INITIAL) {
1254 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
1255 }
1256 }
1257 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001258 // Set connection_id to peer's in memory representation as this data packet
1259 // is created by peer_framer.
1260 header.destination_connection_id = connection_id_;
1261 header.packet_number_length = packet_number_length_;
1262 header.destination_connection_id_included = connection_id_included_;
1263 if (peer_framer_.transport_version() > QUIC_VERSION_43 &&
1264 peer_framer_.perspective() == Perspective::IS_SERVER) {
1265 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
QUICHE team8c1daa22019-03-13 08:33:41 -07001266 if (header.version_flag) {
1267 header.source_connection_id = connection_id_;
1268 header.source_connection_id_included = CONNECTION_ID_PRESENT;
1269 if (GetParam().version.handshake_protocol == PROTOCOL_QUIC_CRYPTO &&
1270 header.long_packet_type == ZERO_RTT_PROTECTED) {
QUICHE team548d51b2019-03-14 10:06:54 -07001271 header.nonce = &kTestDiversificationNonce;
QUICHE team8c1daa22019-03-13 08:33:41 -07001272 }
1273 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001274 }
1275 header.packet_number = QuicPacketNumber(number);
1276
1277 QuicFrames frames;
1278 frames.push_back(QuicFrame(frame1_));
1279 if (has_stop_waiting) {
1280 frames.push_back(QuicFrame(stop_waiting_));
1281 }
1282 return ConstructPacket(header, frames);
1283 }
1284
1285 OwningSerializedPacketPointer ConstructProbingPacket() {
1286 if (version().transport_version == QUIC_VERSION_99) {
1287 QuicPathFrameBuffer payload = {
1288 {0xde, 0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xfe}};
1289 return QuicPacketCreatorPeer::
1290 SerializePathChallengeConnectivityProbingPacket(&peer_creator_,
1291 &payload);
1292 }
1293 return QuicPacketCreatorPeer::SerializeConnectivityProbingPacket(
1294 &peer_creator_);
1295 }
1296
1297 std::unique_ptr<QuicPacket> ConstructClosePacket(uint64_t number) {
1298 QuicPacketHeader header;
1299 // Set connection_id to peer's in memory representation as this connection
1300 // close packet is created by peer_framer.
1301 header.destination_connection_id = connection_id_;
1302 header.packet_number = QuicPacketNumber(number);
1303 if (peer_framer_.transport_version() > QUIC_VERSION_43 &&
1304 peer_framer_.perspective() == Perspective::IS_SERVER) {
1305 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1306 }
1307
1308 QuicConnectionCloseFrame qccf;
1309 qccf.error_code = QUIC_PEER_GOING_AWAY;
1310
1311 QuicFrames frames;
1312 frames.push_back(QuicFrame(&qccf));
1313 return ConstructPacket(header, frames);
1314 }
1315
1316 QuicTime::Delta DefaultRetransmissionTime() {
1317 return QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
1318 }
1319
1320 QuicTime::Delta DefaultDelayedAckTime() {
1321 return QuicTime::Delta::FromMilliseconds(kDefaultDelayedAckTimeMs);
1322 }
1323
1324 const QuicStopWaitingFrame InitStopWaitingFrame(uint64_t least_unacked) {
1325 QuicStopWaitingFrame frame;
1326 frame.least_unacked = QuicPacketNumber(least_unacked);
1327 return frame;
1328 }
1329
1330 // Construct a ack_frame that acks all packet numbers between 1 and
1331 // |largest_acked|, except |missing|.
1332 // REQUIRES: 1 <= |missing| < |largest_acked|
1333 QuicAckFrame ConstructAckFrame(uint64_t largest_acked, uint64_t missing) {
1334 return ConstructAckFrame(QuicPacketNumber(largest_acked),
1335 QuicPacketNumber(missing));
1336 }
1337
1338 QuicAckFrame ConstructAckFrame(QuicPacketNumber largest_acked,
1339 QuicPacketNumber missing) {
1340 if (missing == QuicPacketNumber(1)) {
1341 return InitAckFrame({{missing + 1, largest_acked + 1}});
1342 }
1343 return InitAckFrame(
1344 {{QuicPacketNumber(1), missing}, {missing + 1, largest_acked + 1}});
1345 }
1346
1347 // Undo nacking a packet within the frame.
1348 void AckPacket(QuicPacketNumber arrived, QuicAckFrame* frame) {
1349 EXPECT_FALSE(frame->packets.Contains(arrived));
1350 frame->packets.Add(arrived);
1351 }
1352
1353 void TriggerConnectionClose() {
1354 // Send an erroneous packet to close the connection.
QUICHE teamcd098022019-03-22 18:49:55 -07001355 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, _,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001356 ConnectionCloseSource::FROM_SELF));
QUICHE teamcd098022019-03-22 18:49:55 -07001357 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1358 // Triggers a connection by receiving ACK of unsent packet.
1359 QuicAckFrame frame = InitAckFrame(10000);
1360 ProcessAckPacket(1, &frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001361
1362 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1363 nullptr);
1364 }
1365
1366 void BlockOnNextWrite() {
1367 writer_->BlockOnNextWrite();
1368 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
1369 }
1370
1371 void SimulateNextPacketTooLarge() { writer_->SimulateNextPacketTooLarge(); }
1372
1373 void AlwaysGetPacketTooLarge() { writer_->AlwaysGetPacketTooLarge(); }
1374
1375 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
1376 writer_->SetWritePauseTimeDelta(delta);
1377 }
1378
1379 void CongestionBlockWrites() {
1380 EXPECT_CALL(*send_algorithm_, CanSend(_))
1381 .WillRepeatedly(testing::Return(false));
1382 }
1383
1384 void CongestionUnblockWrites() {
1385 EXPECT_CALL(*send_algorithm_, CanSend(_))
1386 .WillRepeatedly(testing::Return(true));
1387 }
1388
1389 void set_perspective(Perspective perspective) {
1390 connection_.set_perspective(perspective);
1391 if (perspective == Perspective::IS_SERVER) {
1392 connection_.set_can_truncate_connection_ids(true);
1393 }
1394 QuicFramerPeer::SetPerspective(&peer_framer_,
1395 InvertPerspective(perspective));
1396 }
1397
1398 void set_packets_between_probes_base(
1399 const QuicPacketCount packets_between_probes_base) {
1400 QuicConnectionPeer::SetPacketsBetweenMtuProbes(&connection_,
1401 packets_between_probes_base);
1402 QuicConnectionPeer::SetNextMtuProbeAt(
1403 &connection_, QuicPacketNumber(packets_between_probes_base));
1404 }
1405
1406 bool IsDefaultTestConfiguration() {
1407 TestParams p = GetParam();
1408 return p.ack_response == AckResponse::kImmediate &&
1409 p.version == AllSupportedVersions()[0] && p.no_stop_waiting;
1410 }
1411
1412 QuicConnectionId connection_id_;
1413 QuicFramer framer_;
1414
1415 MockSendAlgorithm* send_algorithm_;
1416 std::unique_ptr<MockLossAlgorithm> loss_algorithm_;
1417 MockClock clock_;
1418 MockRandom random_generator_;
1419 SimpleBufferAllocator buffer_allocator_;
1420 std::unique_ptr<TestConnectionHelper> helper_;
1421 std::unique_ptr<TestAlarmFactory> alarm_factory_;
1422 QuicFramer peer_framer_;
1423 QuicPacketCreator peer_creator_;
1424 std::unique_ptr<TestPacketWriter> writer_;
1425 TestConnection connection_;
1426 QuicPacketCreator* creator_;
1427 QuicPacketGenerator* generator_;
1428 QuicSentPacketManager* manager_;
1429 StrictMock<MockQuicConnectionVisitor> visitor_;
1430
1431 QuicStreamFrame frame1_;
1432 QuicStreamFrame frame2_;
1433 QuicAckFrame ack_;
1434 QuicStopWaitingFrame stop_waiting_;
1435 QuicPacketNumberLength packet_number_length_;
1436 QuicConnectionIdIncluded connection_id_included_;
1437
1438 SimpleSessionNotifier notifier_;
1439};
1440
1441// Run all end to end tests with all supported versions.
1442INSTANTIATE_TEST_SUITE_P(SupportedVersion,
1443 QuicConnectionTest,
1444 ::testing::ValuesIn(GetTestParams()));
1445
1446TEST_P(QuicConnectionTest, SelfAddressChangeAtClient) {
QUICHE teamcd098022019-03-22 18:49:55 -07001447 if (connection_.SupportsMultiplePacketNumberSpaces()) {
1448 return;
1449 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001450 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1451
1452 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
1453 EXPECT_TRUE(connection_.connected());
1454
1455 QuicStreamFrame stream_frame(
1456 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false, 0u,
1457 QuicStringPiece());
1458 EXPECT_CALL(visitor_, OnStreamFrame(_));
1459 ProcessFramePacketWithAddresses(QuicFrame(stream_frame), kSelfAddress,
1460 kPeerAddress);
1461 // Cause change in self_address.
1462 QuicIpAddress host;
1463 host.FromString("1.1.1.1");
1464 QuicSocketAddress self_address(host, 123);
1465 EXPECT_CALL(visitor_, OnStreamFrame(_));
1466 ProcessFramePacketWithAddresses(QuicFrame(stream_frame), self_address,
1467 kPeerAddress);
1468 EXPECT_TRUE(connection_.connected());
1469}
1470
1471TEST_P(QuicConnectionTest, SelfAddressChangeAtServer) {
QUICHE teamcd098022019-03-22 18:49:55 -07001472 if (connection_.SupportsMultiplePacketNumberSpaces()) {
1473 return;
1474 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001475 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1476
1477 set_perspective(Perspective::IS_SERVER);
1478 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1479
1480 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1481 EXPECT_TRUE(connection_.connected());
1482
1483 QuicStreamFrame stream_frame(
1484 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false, 0u,
1485 QuicStringPiece());
1486 EXPECT_CALL(visitor_, OnStreamFrame(_));
1487 ProcessFramePacketWithAddresses(QuicFrame(stream_frame), kSelfAddress,
1488 kPeerAddress);
1489 // Cause change in self_address.
1490 QuicIpAddress host;
1491 host.FromString("1.1.1.1");
1492 QuicSocketAddress self_address(host, 123);
1493 EXPECT_CALL(visitor_, AllowSelfAddressChange()).WillOnce(Return(false));
1494 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_ERROR_MIGRATING_ADDRESS, _, _));
1495 ProcessFramePacketWithAddresses(QuicFrame(stream_frame), self_address,
1496 kPeerAddress);
1497 EXPECT_FALSE(connection_.connected());
1498}
1499
1500TEST_P(QuicConnectionTest, AllowSelfAddressChangeToMappedIpv4AddressAtServer) {
QUICHE teamcd098022019-03-22 18:49:55 -07001501 if (connection_.SupportsMultiplePacketNumberSpaces()) {
1502 return;
1503 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001504 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1505
1506 set_perspective(Perspective::IS_SERVER);
1507 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1508
1509 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1510 EXPECT_TRUE(connection_.connected());
1511
1512 QuicStreamFrame stream_frame(
1513 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false, 0u,
1514 QuicStringPiece());
1515 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(3);
1516 QuicIpAddress host;
1517 host.FromString("1.1.1.1");
1518 QuicSocketAddress self_address1(host, 443);
1519 ProcessFramePacketWithAddresses(QuicFrame(stream_frame), self_address1,
1520 kPeerAddress);
1521 // Cause self_address change to mapped Ipv4 address.
1522 QuicIpAddress host2;
1523 host2.FromString(
1524 QuicStrCat("::ffff:", connection_.self_address().host().ToString()));
1525 QuicSocketAddress self_address2(host2, connection_.self_address().port());
1526 ProcessFramePacketWithAddresses(QuicFrame(stream_frame), self_address2,
1527 kPeerAddress);
1528 EXPECT_TRUE(connection_.connected());
1529 // self_address change back to Ipv4 address.
1530 ProcessFramePacketWithAddresses(QuicFrame(stream_frame), self_address1,
1531 kPeerAddress);
1532 EXPECT_TRUE(connection_.connected());
1533}
1534
1535TEST_P(QuicConnectionTest, ClientAddressChangeAndPacketReordered) {
QUICHE teamcd098022019-03-22 18:49:55 -07001536 if (connection_.SupportsMultiplePacketNumberSpaces()) {
1537 return;
1538 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001539 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1540 set_perspective(Perspective::IS_SERVER);
1541 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1542
1543 // Clear direct_peer_address.
1544 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1545 // Clear effective_peer_address, it is the same as direct_peer_address for
1546 // this test.
1547 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1548 QuicSocketAddress());
1549
1550 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
1551 QuicStreamFrame stream_frame(
1552 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false, 0u,
1553 QuicStringPiece());
1554 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1555 const QuicSocketAddress kNewPeerAddress =
1556 QuicSocketAddress(QuicIpAddress::Loopback6(),
1557 /*port=*/23456);
1558 ProcessFramePacketWithAddresses(QuicFrame(stream_frame), kSelfAddress,
1559 kNewPeerAddress);
1560 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1561 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1562
1563 // Decrease packet number to simulate out-of-order packets.
1564 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 4);
1565 // This is an old packet, do not migrate.
1566 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
1567 ProcessFramePacketWithAddresses(QuicFrame(stream_frame), kSelfAddress,
1568 kPeerAddress);
1569 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1570 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1571}
1572
1573TEST_P(QuicConnectionTest, PeerAddressChangeAtServer) {
QUICHE teamcd098022019-03-22 18:49:55 -07001574 if (connection_.SupportsMultiplePacketNumberSpaces()) {
1575 return;
1576 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001577 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1578 set_perspective(Perspective::IS_SERVER);
1579 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1580 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1581
1582 // Clear direct_peer_address.
1583 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1584 // Clear effective_peer_address, it is the same as direct_peer_address for
1585 // this test.
1586 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1587 QuicSocketAddress());
1588 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1589
1590 QuicStreamFrame stream_frame(
1591 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false, 0u,
1592 QuicStringPiece());
1593 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1594 ProcessFramePacketWithAddresses(QuicFrame(stream_frame), kSelfAddress,
1595 kPeerAddress);
1596 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1597 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1598
1599 // Process another packet with a different peer address on server side will
1600 // start connection migration.
1601 const QuicSocketAddress kNewPeerAddress =
1602 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
1603 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
1604 ProcessFramePacketWithAddresses(QuicFrame(stream_frame), kSelfAddress,
1605 kNewPeerAddress);
1606 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1607 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1608}
1609
1610TEST_P(QuicConnectionTest, EffectivePeerAddressChangeAtServer) {
QUICHE teamcd098022019-03-22 18:49:55 -07001611 if (connection_.SupportsMultiplePacketNumberSpaces()) {
1612 return;
1613 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001614 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1615 set_perspective(Perspective::IS_SERVER);
1616 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1617 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1618
1619 // Clear direct_peer_address.
1620 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1621 // Clear effective_peer_address, it is different from direct_peer_address for
1622 // this test.
1623 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1624 QuicSocketAddress());
1625 const QuicSocketAddress kEffectivePeerAddress =
1626 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/43210);
1627 connection_.ReturnEffectivePeerAddressForNextPacket(kEffectivePeerAddress);
1628
1629 QuicStreamFrame stream_frame(
1630 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false, 0u,
1631 QuicStringPiece());
1632 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1633 ProcessFramePacketWithAddresses(QuicFrame(stream_frame), kSelfAddress,
1634 kPeerAddress);
1635 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1636 EXPECT_EQ(kEffectivePeerAddress, connection_.effective_peer_address());
1637
1638 // Process another packet with the same direct peer address and different
1639 // effective peer address on server side will start connection migration.
1640 const QuicSocketAddress kNewEffectivePeerAddress =
1641 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/54321);
1642 connection_.ReturnEffectivePeerAddressForNextPacket(kNewEffectivePeerAddress);
1643 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
1644 ProcessFramePacketWithAddresses(QuicFrame(stream_frame), kSelfAddress,
1645 kPeerAddress);
1646 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1647 EXPECT_EQ(kNewEffectivePeerAddress, connection_.effective_peer_address());
1648
1649 // Process another packet with a different direct peer address and the same
1650 // effective peer address on server side will not start connection migration.
1651 const QuicSocketAddress kNewPeerAddress =
1652 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
1653 connection_.ReturnEffectivePeerAddressForNextPacket(kNewEffectivePeerAddress);
1654 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
1655 // ack_frame is used to complete the migration started by the last packet, we
1656 // need to make sure a new migration does not start after the previous one is
1657 // completed.
1658 QuicAckFrame ack_frame = InitAckFrame(1);
1659 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
1660 ProcessFramePacketWithAddresses(QuicFrame(&ack_frame), kSelfAddress,
1661 kNewPeerAddress);
1662 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1663 EXPECT_EQ(kNewEffectivePeerAddress, connection_.effective_peer_address());
1664
1665 // Process another packet with different direct peer address and different
1666 // effective peer address on server side will start connection migration.
1667 const QuicSocketAddress kNewerEffectivePeerAddress =
1668 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/65432);
1669 const QuicSocketAddress kFinalPeerAddress =
1670 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/34567);
1671 connection_.ReturnEffectivePeerAddressForNextPacket(
1672 kNewerEffectivePeerAddress);
1673 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
1674 ProcessFramePacketWithAddresses(QuicFrame(stream_frame), kSelfAddress,
1675 kFinalPeerAddress);
1676 EXPECT_EQ(kFinalPeerAddress, connection_.peer_address());
1677 EXPECT_EQ(kNewerEffectivePeerAddress, connection_.effective_peer_address());
1678 EXPECT_EQ(PORT_CHANGE, connection_.active_effective_peer_migration_type());
1679
1680 // While the previous migration is ongoing, process another packet with the
1681 // same direct peer address and different effective peer address on server
1682 // side will start a new connection migration.
1683 const QuicSocketAddress kNewestEffectivePeerAddress =
1684 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/65430);
1685 connection_.ReturnEffectivePeerAddressForNextPacket(
1686 kNewestEffectivePeerAddress);
1687 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
1688 EXPECT_CALL(*send_algorithm_, OnConnectionMigration()).Times(1);
1689 ProcessFramePacketWithAddresses(QuicFrame(stream_frame), kSelfAddress,
1690 kFinalPeerAddress);
1691 EXPECT_EQ(kFinalPeerAddress, connection_.peer_address());
1692 EXPECT_EQ(kNewestEffectivePeerAddress, connection_.effective_peer_address());
1693 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
1694 connection_.active_effective_peer_migration_type());
1695}
1696
1697TEST_P(QuicConnectionTest, ReceivePaddedPingAtServer) {
QUICHE teamcd098022019-03-22 18:49:55 -07001698 if (connection_.SupportsMultiplePacketNumberSpaces()) {
1699 return;
1700 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001701 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1702 set_perspective(Perspective::IS_SERVER);
1703 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1704 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1705
1706 // Clear direct_peer_address.
1707 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1708 // Clear effective_peer_address, it is the same as direct_peer_address for
1709 // this test.
1710 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1711 QuicSocketAddress());
1712 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1713
1714 QuicStreamFrame stream_frame(
1715 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false, 0u,
1716 QuicStringPiece());
1717 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1718 ProcessFramePacketWithAddresses(QuicFrame(stream_frame), kSelfAddress,
1719 kPeerAddress);
1720 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1721 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1722
1723 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
1724 EXPECT_CALL(visitor_, OnConnectivityProbeReceived(_, _)).Times(0);
1725
1726 // Process a padded PING or PATH CHALLENGE packet with no peer address change
1727 // on server side will be ignored.
1728 OwningSerializedPacketPointer probing_packet;
1729 if (version().transport_version == QUIC_VERSION_99) {
1730 QuicPathFrameBuffer payload = {
1731 {0xde, 0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xfe}};
1732 probing_packet =
1733 QuicPacketCreatorPeer::SerializePathChallengeConnectivityProbingPacket(
1734 &peer_creator_, &payload);
1735 } else {
1736 probing_packet = QuicPacketCreatorPeer::SerializeConnectivityProbingPacket(
1737 &peer_creator_);
1738 }
1739 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
1740 QuicEncryptedPacket(probing_packet->encrypted_buffer,
1741 probing_packet->encrypted_length),
1742 clock_.Now()));
1743
1744 uint64_t num_probing_received =
1745 connection_.GetStats().num_connectivity_probing_received;
1746 ProcessReceivedPacket(kSelfAddress, kPeerAddress, *received);
1747
1748 EXPECT_EQ(num_probing_received,
1749 connection_.GetStats().num_connectivity_probing_received);
1750 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1751 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1752}
1753
1754TEST_P(QuicConnectionTest, WriteOutOfOrderQueuedPackets) {
1755 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
QUICHE teamcd098022019-03-22 18:49:55 -07001756 if (!IsDefaultTestConfiguration() ||
1757 connection_.SupportsMultiplePacketNumberSpaces()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001758 return;
1759 }
1760
1761 set_perspective(Perspective::IS_CLIENT);
1762
1763 BlockOnNextWrite();
1764
1765 QuicStreamId stream_id = 2;
1766 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
1767
1768 EXPECT_EQ(1u, connection_.NumQueuedPackets());
1769
1770 writer_->SetWritable();
1771 connection_.SendConnectivityProbingPacket(writer_.get(),
1772 connection_.peer_address());
1773
1774 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INTERNAL_ERROR,
1775 "Packet written out of order.",
1776 ConnectionCloseSource::FROM_SELF));
1777 EXPECT_QUIC_BUG(connection_.OnCanWrite(),
1778 "Attempt to write packet:1 after:2");
1779 EXPECT_FALSE(connection_.connected());
1780}
1781
1782TEST_P(QuicConnectionTest, DiscardQueuedPacketsAfterConnectionClose) {
QUICHE teamcd098022019-03-22 18:49:55 -07001783 if (connection_.SupportsMultiplePacketNumberSpaces()) {
1784 return;
1785 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001786 // Regression test for b/74073386.
1787 {
1788 InSequence seq;
1789 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1790 EXPECT_CALL(visitor_, OnConnectionClosed(_, _, _)).Times(1);
1791 }
1792
1793 set_perspective(Perspective::IS_CLIENT);
1794
1795 writer_->SimulateNextPacketTooLarge();
1796
1797 // This packet write should fail, which should cause the connection to close
1798 // after sending a connection close packet, then the failed packet should be
1799 // queued.
1800 connection_.SendStreamDataWithString(/*id=*/2, "foo", 0, NO_FIN);
1801
1802 EXPECT_FALSE(connection_.connected());
1803 EXPECT_EQ(1u, connection_.NumQueuedPackets());
1804
1805 EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
1806 connection_.OnCanWrite();
1807 EXPECT_EQ(1u, connection_.GetStats().packets_discarded);
1808}
1809
1810TEST_P(QuicConnectionTest, ReceiveConnectivityProbingAtServer) {
QUICHE teamcd098022019-03-22 18:49:55 -07001811 if (connection_.SupportsMultiplePacketNumberSpaces()) {
1812 return;
1813 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001814 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1815 set_perspective(Perspective::IS_SERVER);
1816 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1817 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1818
1819 // Clear direct_peer_address.
1820 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1821 // Clear effective_peer_address, it is the same as direct_peer_address for
1822 // this test.
1823 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1824 QuicSocketAddress());
1825 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1826
1827 QuicStreamFrame stream_frame(
1828 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false, 0u,
1829 QuicStringPiece());
1830 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1831 ProcessFramePacketWithAddresses(QuicFrame(stream_frame), kSelfAddress,
1832 kPeerAddress);
1833 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1834 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1835
1836 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
1837 EXPECT_CALL(visitor_, OnConnectivityProbeReceived(_, _)).Times(1);
1838
1839 // Process a padded PING packet from a new peer address on server side
1840 // is effectively receiving a connectivity probing.
1841 const QuicSocketAddress kNewPeerAddress =
1842 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
1843
1844 OwningSerializedPacketPointer probing_packet = ConstructProbingPacket();
1845 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
1846 QuicEncryptedPacket(probing_packet->encrypted_buffer,
1847 probing_packet->encrypted_length),
1848 clock_.Now()));
1849
1850 uint64_t num_probing_received =
1851 connection_.GetStats().num_connectivity_probing_received;
1852 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
1853
1854 EXPECT_EQ(num_probing_received + 1,
1855 connection_.GetStats().num_connectivity_probing_received);
1856 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1857 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1858
1859 // Process another packet with the old peer address on server side will not
1860 // start peer migration.
1861 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
1862 ProcessFramePacketWithAddresses(QuicFrame(stream_frame), kSelfAddress,
1863 kPeerAddress);
1864 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1865 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1866}
1867
1868TEST_P(QuicConnectionTest, ReceiveReorderedConnectivityProbingAtServer) {
QUICHE teamcd098022019-03-22 18:49:55 -07001869 if (connection_.SupportsMultiplePacketNumberSpaces()) {
1870 return;
1871 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001872 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1873 set_perspective(Perspective::IS_SERVER);
1874 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1875 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1876
1877 // Clear direct_peer_address.
1878 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1879 // Clear effective_peer_address, it is the same as direct_peer_address for
1880 // this test.
1881 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1882 QuicSocketAddress());
1883 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1884
1885 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
1886 QuicStreamFrame stream_frame(
1887 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false, 0u,
1888 QuicStringPiece());
1889 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1890 ProcessFramePacketWithAddresses(QuicFrame(stream_frame), kSelfAddress,
1891 kPeerAddress);
1892 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1893 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1894
1895 // Decrease packet number to simulate out-of-order packets.
1896 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 4);
1897
1898 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
1899 EXPECT_CALL(visitor_, OnConnectivityProbeReceived(_, _)).Times(1);
1900
1901 // Process a padded PING packet from a new peer address on server side
1902 // is effectively receiving a connectivity probing, even if a newer packet has
1903 // been received before this one.
1904 const QuicSocketAddress kNewPeerAddress =
1905 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
1906
1907 OwningSerializedPacketPointer probing_packet = ConstructProbingPacket();
1908 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
1909 QuicEncryptedPacket(probing_packet->encrypted_buffer,
1910 probing_packet->encrypted_length),
1911 clock_.Now()));
1912
1913 uint64_t num_probing_received =
1914 connection_.GetStats().num_connectivity_probing_received;
1915 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
1916
1917 EXPECT_EQ(num_probing_received + 1,
1918 connection_.GetStats().num_connectivity_probing_received);
1919 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1920 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1921}
1922
1923TEST_P(QuicConnectionTest, MigrateAfterProbingAtServer) {
QUICHE teamcd098022019-03-22 18:49:55 -07001924 if (connection_.SupportsMultiplePacketNumberSpaces()) {
1925 return;
1926 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001927 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1928 set_perspective(Perspective::IS_SERVER);
1929 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1930 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1931
1932 // Clear direct_peer_address.
1933 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1934 // Clear effective_peer_address, it is the same as direct_peer_address for
1935 // this test.
1936 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1937 QuicSocketAddress());
1938 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1939
1940 QuicStreamFrame stream_frame(
1941 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false, 0u,
1942 QuicStringPiece());
1943 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1944 ProcessFramePacketWithAddresses(QuicFrame(stream_frame), kSelfAddress,
1945 kPeerAddress);
1946 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1947 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1948
1949 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
1950 EXPECT_CALL(visitor_, OnConnectivityProbeReceived(_, _)).Times(1);
1951
1952 // Process a padded PING packet from a new peer address on server side
1953 // is effectively receiving a connectivity probing.
1954 const QuicSocketAddress kNewPeerAddress =
1955 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
1956
1957 OwningSerializedPacketPointer probing_packet = ConstructProbingPacket();
1958 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
1959 QuicEncryptedPacket(probing_packet->encrypted_buffer,
1960 probing_packet->encrypted_length),
1961 clock_.Now()));
1962 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
1963 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1964 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1965
1966 // Process another non-probing packet with the new peer address on server
1967 // side will start peer migration.
1968 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
1969
1970 ProcessFramePacketWithAddresses(QuicFrame(stream_frame), kSelfAddress,
1971 kNewPeerAddress);
1972 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1973 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1974}
1975
1976TEST_P(QuicConnectionTest, ReceivePaddedPingAtClient) {
QUICHE teamcd098022019-03-22 18:49:55 -07001977 if (connection_.SupportsMultiplePacketNumberSpaces()) {
1978 return;
1979 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001980 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1981 set_perspective(Perspective::IS_CLIENT);
1982 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
1983
1984 // Clear direct_peer_address.
1985 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1986 // Clear effective_peer_address, it is the same as direct_peer_address for
1987 // this test.
1988 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1989 QuicSocketAddress());
1990 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1991
1992 QuicStreamFrame stream_frame(
1993 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false, 0u,
1994 QuicStringPiece());
1995 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1996 ProcessFramePacketWithAddresses(QuicFrame(stream_frame), kSelfAddress,
1997 kPeerAddress);
1998 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1999 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2000
2001 // Client takes all padded PING packet as speculative connectivity
2002 // probing packet, and reports to visitor.
2003 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2004 EXPECT_CALL(visitor_, OnConnectivityProbeReceived(_, _)).Times(1);
2005
2006 OwningSerializedPacketPointer probing_packet = ConstructProbingPacket();
2007 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2008 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2009 probing_packet->encrypted_length),
2010 clock_.Now()));
2011 uint64_t num_probing_received =
2012 connection_.GetStats().num_connectivity_probing_received;
2013 ProcessReceivedPacket(kSelfAddress, kPeerAddress, *received);
2014
2015 EXPECT_EQ(num_probing_received,
2016 connection_.GetStats().num_connectivity_probing_received);
2017 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2018 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2019}
2020
2021TEST_P(QuicConnectionTest, ReceiveConnectivityProbingAtClient) {
QUICHE teamcd098022019-03-22 18:49:55 -07002022 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2023 return;
2024 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002025 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2026 set_perspective(Perspective::IS_CLIENT);
2027 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2028
2029 // Clear direct_peer_address.
2030 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2031 // Clear effective_peer_address, it is the same as direct_peer_address for
2032 // this test.
2033 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2034 QuicSocketAddress());
2035 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2036
2037 QuicStreamFrame stream_frame(
2038 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false, 0u,
2039 QuicStringPiece());
2040 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2041 ProcessFramePacketWithAddresses(QuicFrame(stream_frame), kSelfAddress,
2042 kPeerAddress);
2043 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2044 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2045
2046 // Process a padded PING packet with a different self address on client side
2047 // is effectively receiving a connectivity probing.
2048 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2049 EXPECT_CALL(visitor_, OnConnectivityProbeReceived(_, _)).Times(1);
2050
2051 const QuicSocketAddress kNewSelfAddress =
2052 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2053
2054 OwningSerializedPacketPointer probing_packet = ConstructProbingPacket();
2055 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2056 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2057 probing_packet->encrypted_length),
2058 clock_.Now()));
2059 uint64_t num_probing_received =
2060 connection_.GetStats().num_connectivity_probing_received;
2061 ProcessReceivedPacket(kNewSelfAddress, kPeerAddress, *received);
2062
2063 EXPECT_EQ(num_probing_received + 1,
2064 connection_.GetStats().num_connectivity_probing_received);
2065 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2066 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2067}
2068
2069TEST_P(QuicConnectionTest, PeerAddressChangeAtClient) {
QUICHE teamcd098022019-03-22 18:49:55 -07002070 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2071 return;
2072 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002073 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2074 set_perspective(Perspective::IS_CLIENT);
2075 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2076
2077 // Clear direct_peer_address.
2078 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2079 // Clear effective_peer_address, it is the same as direct_peer_address for
2080 // this test.
2081 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2082 QuicSocketAddress());
2083 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2084
2085 QuicStreamFrame stream_frame(
2086 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false, 0u,
2087 QuicStringPiece());
2088 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2089 ProcessFramePacketWithAddresses(QuicFrame(stream_frame), kSelfAddress,
2090 kPeerAddress);
2091 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2092 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2093
2094 // Process another packet with a different peer address on client side will
2095 // only update peer address.
2096 const QuicSocketAddress kNewPeerAddress =
2097 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2098 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2099 ProcessFramePacketWithAddresses(QuicFrame(stream_frame), kSelfAddress,
2100 kNewPeerAddress);
2101 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2102 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2103}
2104
2105TEST_P(QuicConnectionTest, MaxPacketSize) {
QUICHE teamcd098022019-03-22 18:49:55 -07002106 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2107 return;
2108 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002109 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2110 EXPECT_EQ(1350u, connection_.max_packet_length());
2111}
2112
2113TEST_P(QuicConnectionTest, SmallerServerMaxPacketSize) {
QUICHE teamcd098022019-03-22 18:49:55 -07002114 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2115 return;
2116 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002117 TestConnection connection(TestConnectionId(), kPeerAddress, helper_.get(),
2118 alarm_factory_.get(), writer_.get(),
2119 Perspective::IS_SERVER, version());
2120 EXPECT_EQ(Perspective::IS_SERVER, connection.perspective());
2121 EXPECT_EQ(1000u, connection.max_packet_length());
2122}
2123
2124TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSize) {
QUICHE teamcd098022019-03-22 18:49:55 -07002125 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2126 return;
2127 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002128 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2129
2130 set_perspective(Perspective::IS_SERVER);
2131 connection_.SetMaxPacketLength(1000);
2132
2133 QuicPacketHeader header;
2134 header.destination_connection_id = connection_id_;
2135 header.version_flag = true;
2136 header.packet_number = QuicPacketNumber(1);
2137
2138 if (QuicVersionHasLongHeaderLengths(
2139 peer_framer_.version().transport_version)) {
2140 header.long_packet_type = INITIAL;
2141 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
2142 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
2143 }
2144
2145 QuicFrames frames;
2146 QuicPaddingFrame padding;
2147 frames.push_back(QuicFrame(frame1_));
2148 frames.push_back(QuicFrame(padding));
2149 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
2150 char buffer[kMaxPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07002151 size_t encrypted_length =
2152 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12),
2153 *packet, buffer, kMaxPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002154 EXPECT_EQ(kMaxPacketSize, encrypted_length);
2155
2156 framer_.set_version(version());
2157 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2158 connection_.ProcessUdpPacket(
2159 kSelfAddress, kPeerAddress,
2160 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
2161
2162 EXPECT_EQ(kMaxPacketSize, connection_.max_packet_length());
2163}
2164
2165TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSizeWhileWriterLimited) {
QUICHE teamcd098022019-03-22 18:49:55 -07002166 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2167 return;
2168 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002169 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2170
2171 const QuicByteCount lower_max_packet_size = 1240;
2172 writer_->set_max_packet_size(lower_max_packet_size);
2173 set_perspective(Perspective::IS_SERVER);
2174 connection_.SetMaxPacketLength(1000);
2175 EXPECT_EQ(1000u, connection_.max_packet_length());
2176
2177 QuicPacketHeader header;
2178 header.destination_connection_id = connection_id_;
2179 header.version_flag = true;
2180 header.packet_number = QuicPacketNumber(1);
2181
2182 if (QuicVersionHasLongHeaderLengths(
2183 peer_framer_.version().transport_version)) {
2184 header.long_packet_type = INITIAL;
2185 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
2186 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
2187 }
2188
2189 QuicFrames frames;
2190 QuicPaddingFrame padding;
2191 frames.push_back(QuicFrame(frame1_));
2192 frames.push_back(QuicFrame(padding));
2193 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
2194 char buffer[kMaxPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07002195 size_t encrypted_length =
2196 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12),
2197 *packet, buffer, kMaxPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002198 EXPECT_EQ(kMaxPacketSize, encrypted_length);
2199
2200 framer_.set_version(version());
2201 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2202 connection_.ProcessUdpPacket(
2203 kSelfAddress, kPeerAddress,
2204 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
2205
2206 // Here, the limit imposed by the writer is lower than the size of the packet
2207 // received, so the writer max packet size is used.
2208 EXPECT_EQ(lower_max_packet_size, connection_.max_packet_length());
2209}
2210
2211TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriter) {
QUICHE teamcd098022019-03-22 18:49:55 -07002212 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2213 return;
2214 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002215 const QuicByteCount lower_max_packet_size = 1240;
2216 writer_->set_max_packet_size(lower_max_packet_size);
2217
2218 static_assert(lower_max_packet_size < kDefaultMaxPacketSize,
2219 "Default maximum packet size is too low");
2220 connection_.SetMaxPacketLength(kDefaultMaxPacketSize);
2221
2222 EXPECT_EQ(lower_max_packet_size, connection_.max_packet_length());
2223}
2224
2225TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriterForNewConnection) {
QUICHE teamcd098022019-03-22 18:49:55 -07002226 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2227 return;
2228 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002229 const QuicConnectionId connection_id = TestConnectionId(17);
2230 const QuicByteCount lower_max_packet_size = 1240;
2231 writer_->set_max_packet_size(lower_max_packet_size);
2232 TestConnection connection(connection_id, kPeerAddress, helper_.get(),
2233 alarm_factory_.get(), writer_.get(),
2234 Perspective::IS_CLIENT, version());
2235 EXPECT_EQ(Perspective::IS_CLIENT, connection.perspective());
2236 EXPECT_EQ(lower_max_packet_size, connection.max_packet_length());
2237}
2238
2239TEST_P(QuicConnectionTest, PacketsInOrder) {
QUICHE teamcd098022019-03-22 18:49:55 -07002240 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2241 return;
2242 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002243 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2244
2245 ProcessPacket(1);
2246 EXPECT_EQ(QuicPacketNumber(1u), LargestAcked(*outgoing_ack()));
2247 EXPECT_EQ(1u, outgoing_ack()->packets.NumIntervals());
2248
2249 ProcessPacket(2);
2250 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(*outgoing_ack()));
2251 EXPECT_EQ(1u, outgoing_ack()->packets.NumIntervals());
2252
2253 ProcessPacket(3);
2254 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(*outgoing_ack()));
2255 EXPECT_EQ(1u, outgoing_ack()->packets.NumIntervals());
2256}
2257
2258TEST_P(QuicConnectionTest, PacketsOutOfOrder) {
QUICHE teamcd098022019-03-22 18:49:55 -07002259 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2260 return;
2261 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002262 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2263
2264 ProcessPacket(3);
2265 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(*outgoing_ack()));
2266 EXPECT_TRUE(IsMissing(2));
2267 EXPECT_TRUE(IsMissing(1));
2268
2269 ProcessPacket(2);
2270 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(*outgoing_ack()));
2271 EXPECT_FALSE(IsMissing(2));
2272 EXPECT_TRUE(IsMissing(1));
2273
2274 ProcessPacket(1);
2275 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(*outgoing_ack()));
2276 EXPECT_FALSE(IsMissing(2));
2277 EXPECT_FALSE(IsMissing(1));
2278}
2279
2280TEST_P(QuicConnectionTest, DuplicatePacket) {
QUICHE teamcd098022019-03-22 18:49:55 -07002281 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2282 return;
2283 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002284 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2285
2286 ProcessPacket(3);
2287 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(*outgoing_ack()));
2288 EXPECT_TRUE(IsMissing(2));
2289 EXPECT_TRUE(IsMissing(1));
2290
2291 // Send packet 3 again, but do not set the expectation that
2292 // the visitor OnStreamFrame() will be called.
2293 ProcessDataPacket(3);
2294 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(*outgoing_ack()));
2295 EXPECT_TRUE(IsMissing(2));
2296 EXPECT_TRUE(IsMissing(1));
2297}
2298
2299TEST_P(QuicConnectionTest, PacketsOutOfOrderWithAdditionsAndLeastAwaiting) {
QUICHE teamcd098022019-03-22 18:49:55 -07002300 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2301 return;
2302 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002303 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2304
2305 ProcessPacket(3);
2306 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(*outgoing_ack()));
2307 EXPECT_TRUE(IsMissing(2));
2308 EXPECT_TRUE(IsMissing(1));
2309
2310 ProcessPacket(2);
2311 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(*outgoing_ack()));
2312 EXPECT_TRUE(IsMissing(1));
2313
2314 ProcessPacket(5);
2315 EXPECT_EQ(QuicPacketNumber(5u), LargestAcked(*outgoing_ack()));
2316 EXPECT_TRUE(IsMissing(1));
2317 EXPECT_TRUE(IsMissing(4));
2318
2319 // Pretend at this point the client has gotten acks for 2 and 3 and 1 is a
2320 // packet the peer will not retransmit. It indicates this by sending 'least
2321 // awaiting' is 4. The connection should then realize 1 will not be
2322 // retransmitted, and will remove it from the missing list.
2323 QuicAckFrame frame = InitAckFrame(1);
2324 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
2325 ProcessAckPacket(6, &frame);
2326
2327 // Force an ack to be sent.
2328 SendAckPacketToPeer();
2329 EXPECT_TRUE(IsMissing(4));
2330}
2331
2332TEST_P(QuicConnectionTest, RejectPacketTooFarOut) {
QUICHE teamcd098022019-03-22 18:49:55 -07002333 if (GetQuicReloadableFlag(quic_use_uber_received_packet_manager)) {
2334 return;
2335 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002336 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_PACKET_HEADER, _,
2337 ConnectionCloseSource::FROM_SELF));
2338
2339 // Call ProcessDataPacket rather than ProcessPacket, as we should not get a
2340 // packet call to the visitor.
2341 if (GetQuicRestartFlag(quic_enable_accept_random_ipn)) {
2342 ProcessDataPacket(MaxRandomInitialPacketNumber() + 6000);
2343 } else {
2344 ProcessDataPacket(6000);
2345 }
2346 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
2347 nullptr);
2348}
2349
2350TEST_P(QuicConnectionTest, RejectUnencryptedStreamData) {
QUICHE teamcd098022019-03-22 18:49:55 -07002351 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2352 return;
2353 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002354 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
2355 if (!IsDefaultTestConfiguration()) {
2356 return;
2357 }
2358
2359 // Process an unencrypted packet from the non-crypto stream.
2360 frame1_.stream_id = 3;
2361 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2362 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_UNENCRYPTED_STREAM_DATA, _,
2363 ConnectionCloseSource::FROM_SELF));
2364 EXPECT_QUIC_PEER_BUG(ProcessDataPacket(1), "");
2365 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
2366 nullptr);
2367 const std::vector<QuicConnectionCloseFrame>& connection_close_frames =
2368 writer_->connection_close_frames();
2369 EXPECT_EQ(1u, connection_close_frames.size());
2370 EXPECT_EQ(QUIC_UNENCRYPTED_STREAM_DATA,
2371 connection_close_frames[0].error_code);
2372}
2373
2374TEST_P(QuicConnectionTest, OutOfOrderReceiptCausesAckSend) {
QUICHE teamcd098022019-03-22 18:49:55 -07002375 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2376 return;
2377 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002378 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2379
2380 ProcessPacket(3);
2381 if (GetQuicRestartFlag(quic_enable_accept_random_ipn)) {
2382 // Should not cause an ack.
2383 EXPECT_EQ(0u, writer_->packets_write_attempts());
2384 } else {
2385 // Should ack immediately since we have missing packets.
2386 EXPECT_EQ(1u, writer_->packets_write_attempts());
2387 }
2388
2389 ProcessPacket(2);
2390 if (GetQuicRestartFlag(quic_enable_accept_random_ipn)) {
2391 // Should ack immediately, since this fills the last hole.
2392 EXPECT_EQ(1u, writer_->packets_write_attempts());
2393 } else {
2394 // Should ack immediately since we have missing packets.
2395 EXPECT_EQ(2u, writer_->packets_write_attempts());
2396 }
2397
2398 ProcessPacket(1);
2399 // Should ack immediately, since this fills the last hole.
2400 if (GetQuicRestartFlag(quic_enable_accept_random_ipn)) {
2401 EXPECT_EQ(2u, writer_->packets_write_attempts());
2402 } else {
2403 EXPECT_EQ(3u, writer_->packets_write_attempts());
2404 }
2405
2406 ProcessPacket(4);
2407 // Should not cause an ack.
2408 if (GetQuicRestartFlag(quic_enable_accept_random_ipn)) {
2409 EXPECT_EQ(2u, writer_->packets_write_attempts());
2410 } else {
2411 EXPECT_EQ(3u, writer_->packets_write_attempts());
2412 }
2413}
2414
2415TEST_P(QuicConnectionTest, OutOfOrderAckReceiptCausesNoAck) {
QUICHE teamcd098022019-03-22 18:49:55 -07002416 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2417 return;
2418 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002419 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2420
2421 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
2422 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
2423 EXPECT_EQ(2u, writer_->packets_write_attempts());
2424
2425 QuicAckFrame ack1 = InitAckFrame(1);
2426 QuicAckFrame ack2 = InitAckFrame(2);
2427 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2428 ProcessAckPacket(2, &ack2);
2429 // Should ack immediately since we have missing packets.
2430 EXPECT_EQ(2u, writer_->packets_write_attempts());
2431
2432 ProcessAckPacket(1, &ack1);
2433 // Should not ack an ack filling a missing packet.
2434 EXPECT_EQ(2u, writer_->packets_write_attempts());
2435}
2436
2437TEST_P(QuicConnectionTest, AckReceiptCausesAckSend) {
QUICHE teamcd098022019-03-22 18:49:55 -07002438 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2439 return;
2440 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002441 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2442 QuicPacketNumber original, second;
2443
2444 QuicByteCount packet_size =
2445 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &original); // 1st packet.
2446 SendStreamDataToPeer(3, "bar", 3, NO_FIN, &second); // 2nd packet.
2447
2448 QuicAckFrame frame = InitAckFrame({{second, second + 1}});
2449 // First nack triggers early retransmit.
2450 LostPacketVector lost_packets;
2451 lost_packets.push_back(LostPacket(original, kMaxPacketSize));
2452 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
2453 .WillOnce(SetArgPointee<5>(lost_packets));
2454 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2455 QuicPacketNumber retransmission;
2456 // Packet 1 is short header for IETF QUIC because the encryption level
2457 // switched to ENCRYPTION_FORWARD_SECURE in SendStreamDataToPeer.
2458 EXPECT_CALL(
2459 *send_algorithm_,
2460 OnPacketSent(_, _, _,
2461 GetParam().version.transport_version > QUIC_VERSION_43
2462 ? packet_size
2463 : packet_size - kQuicVersionSize,
2464 _))
2465 .WillOnce(SaveArg<2>(&retransmission));
2466
2467 ProcessAckPacket(&frame);
2468
2469 QuicAckFrame frame2 = ConstructAckFrame(retransmission, original);
2470 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2471 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
2472 ProcessAckPacket(&frame2);
2473
2474 // Now if the peer sends an ack which still reports the retransmitted packet
2475 // as missing, that will bundle an ack with data after two acks in a row
2476 // indicate the high water mark needs to be raised.
2477 EXPECT_CALL(*send_algorithm_,
2478 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA));
2479 connection_.SendStreamDataWithString(3, "foo", 6, NO_FIN);
2480 // No ack sent.
2481 EXPECT_EQ(1u, writer_->frame_count());
2482 EXPECT_EQ(1u, writer_->stream_frames().size());
2483
2484 // No more packet loss for the rest of the test.
2485 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
2486 .Times(AnyNumber());
2487 ProcessAckPacket(&frame2);
2488 EXPECT_CALL(*send_algorithm_,
2489 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA));
2490 connection_.SendStreamDataWithString(3, "foo", 9, NO_FIN);
2491 // Ack bundled.
2492 if (GetParam().no_stop_waiting) {
2493 EXPECT_EQ(2u, writer_->frame_count());
2494 } else {
2495 EXPECT_EQ(3u, writer_->frame_count());
2496 }
2497 EXPECT_EQ(1u, writer_->stream_frames().size());
2498 EXPECT_FALSE(writer_->ack_frames().empty());
2499
2500 // But an ack with no missing packets will not send an ack.
2501 AckPacket(original, &frame2);
2502 ProcessAckPacket(&frame2);
2503 ProcessAckPacket(&frame2);
2504}
2505
2506TEST_P(QuicConnectionTest, AckSentEveryNthPacket) {
QUICHE teamcd098022019-03-22 18:49:55 -07002507 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2508 return;
2509 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002510 connection_.set_ack_frequency_before_ack_decimation(3);
2511
2512 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2513 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(39);
2514
2515 // Expect 13 acks, every 3rd packet.
2516 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(13);
2517 // Receives packets 1 - 39.
2518 for (size_t i = 1; i <= 39; ++i) {
2519 ProcessDataPacket(i);
2520 }
2521}
2522
2523TEST_P(QuicConnectionTest, AckDecimationReducesAcks) {
QUICHE teamcd098022019-03-22 18:49:55 -07002524 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2525 return;
2526 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002527 const size_t kMinRttMs = 40;
2528 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
2529 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
2530 QuicTime::Delta::Zero(), QuicTime::Zero());
2531 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
2532
2533 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
2534
2535 // Start ack decimation from 10th packet.
2536 connection_.set_min_received_before_ack_decimation(10);
2537
2538 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2539 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(30);
2540
2541 // Expect 6 acks: 5 acks between packets 1-10, and ack at 20.
2542 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(6);
2543 // Receives packets 1 - 29.
2544 for (size_t i = 1; i <= 29; ++i) {
2545 ProcessDataPacket(i);
2546 }
2547
2548 // We now receive the 30th packet, and so we send an ack.
2549 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2550 ProcessDataPacket(30);
2551}
2552
2553TEST_P(QuicConnectionTest, AckNeedsRetransmittableFrames) {
QUICHE teamcd098022019-03-22 18:49:55 -07002554 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2555 return;
2556 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002557 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2558 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(99);
2559
2560 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(19);
2561 // Receives packets 1 - 39.
2562 for (size_t i = 1; i <= 39; ++i) {
2563 ProcessDataPacket(i);
2564 }
2565 // Receiving Packet 40 causes 20th ack to send. Session is informed and adds
2566 // WINDOW_UPDATE.
2567 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
2568 .WillOnce(Invoke([this]() {
2569 connection_.SendControlFrame(
2570 QuicFrame(new QuicWindowUpdateFrame(1, 0, 0)));
2571 }));
2572 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2573 EXPECT_EQ(0u, writer_->window_update_frames().size());
2574 ProcessDataPacket(40);
2575 EXPECT_EQ(1u, writer_->window_update_frames().size());
2576
2577 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(9);
2578 // Receives packets 41 - 59.
2579 for (size_t i = 41; i <= 59; ++i) {
2580 ProcessDataPacket(i);
2581 }
2582 // Send a packet containing stream frame.
QUICHE team8c1daa22019-03-13 08:33:41 -07002583 SendStreamDataToPeer(
2584 QuicUtils::GetCryptoStreamId(connection_.version().transport_version),
2585 "bar", 0, NO_FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002586
2587 // Session will not be informed until receiving another 20 packets.
2588 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(19);
2589 for (size_t i = 60; i <= 98; ++i) {
2590 ProcessDataPacket(i);
2591 EXPECT_EQ(0u, writer_->window_update_frames().size());
2592 }
2593 // Session does not add a retransmittable frame.
2594 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
2595 .WillOnce(Invoke([this]() {
2596 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
2597 }));
2598 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2599 EXPECT_EQ(0u, writer_->ping_frames().size());
2600 ProcessDataPacket(99);
2601 EXPECT_EQ(0u, writer_->window_update_frames().size());
2602 // A ping frame will be added.
2603 EXPECT_EQ(1u, writer_->ping_frames().size());
2604}
2605
2606TEST_P(QuicConnectionTest, LeastUnackedLower) {
QUICHE teamcd098022019-03-22 18:49:55 -07002607 if (GetParam().version.transport_version > QUIC_VERSION_43 ||
2608 connection_.SupportsMultiplePacketNumberSpaces()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002609 return;
2610 }
2611 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2612
2613 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
2614 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
2615 SendStreamDataToPeer(1, "eep", 6, NO_FIN, nullptr);
2616
2617 // Start out saying the least unacked is 2.
2618 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
2619 ProcessStopWaitingPacket(InitStopWaitingFrame(2));
2620
2621 // Change it to 1, but lower the packet number to fake out-of-order packets.
2622 // This should be fine.
2623 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 1);
2624 // The scheduler will not process out of order acks, but all packet processing
2625 // causes the connection to try to write.
2626 if (!GetParam().no_stop_waiting) {
2627 EXPECT_CALL(visitor_, OnCanWrite());
2628 }
2629 ProcessStopWaitingPacket(InitStopWaitingFrame(1));
2630
2631 // Now claim it's one, but set the ordering so it was sent "after" the first
2632 // one. This should cause a connection error.
2633 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 7);
2634 if (!GetParam().no_stop_waiting) {
2635 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2636 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_STOP_WAITING_DATA, _,
2637 ConnectionCloseSource::FROM_SELF));
2638 }
2639 ProcessStopWaitingPacket(InitStopWaitingFrame(1));
2640}
2641
2642TEST_P(QuicConnectionTest, TooManySentPackets) {
QUICHE teamcd098022019-03-22 18:49:55 -07002643 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2644 return;
2645 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002646 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2647
2648 QuicPacketCount max_tracked_packets = 50;
2649 QuicConnectionPeer::SetMaxTrackedPackets(&connection_, max_tracked_packets);
2650
2651 const int num_packets = max_tracked_packets + 5;
2652
2653 for (int i = 0; i < num_packets; ++i) {
2654 SendStreamDataToPeer(1, "foo", 3 * i, NO_FIN, nullptr);
2655 }
2656
2657 // Ack packet 1, which leaves more than the limit outstanding.
2658 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2659 EXPECT_CALL(visitor_,
2660 OnConnectionClosed(QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS, _,
2661 ConnectionCloseSource::FROM_SELF));
2662
2663 // Nack the first packet and ack the rest, leaving a huge gap.
2664 QuicAckFrame frame1 = ConstructAckFrame(num_packets, 1);
2665 ProcessAckPacket(&frame1);
2666}
2667
2668TEST_P(QuicConnectionTest, LargestObservedLower) {
QUICHE teamcd098022019-03-22 18:49:55 -07002669 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2670 return;
2671 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002672 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2673
2674 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
2675 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
2676 SendStreamDataToPeer(1, "eep", 6, NO_FIN, nullptr);
2677 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2678
2679 // Start out saying the largest observed is 2.
2680 QuicAckFrame frame1 = InitAckFrame(1);
2681 QuicAckFrame frame2 = InitAckFrame(2);
2682 ProcessAckPacket(&frame2);
2683
QUICHE team9929cc42019-03-13 08:17:43 -07002684 if (GetQuicReloadableFlag(quic_tolerate_reneging)) {
2685 EXPECT_CALL(visitor_, OnCanWrite());
2686 } else {
2687 // Now change it to 1, and it should cause a connection error.
2688 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, _,
2689 ConnectionCloseSource::FROM_SELF));
2690 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
2691 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002692 ProcessAckPacket(&frame1);
2693}
2694
2695TEST_P(QuicConnectionTest, AckUnsentData) {
QUICHE teamcd098022019-03-22 18:49:55 -07002696 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2697 return;
2698 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002699 // Ack a packet which has not been sent.
2700 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, _,
2701 ConnectionCloseSource::FROM_SELF));
2702 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2703 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2704 QuicAckFrame frame = InitAckFrame(1);
2705 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
2706 ProcessAckPacket(&frame);
2707}
2708
2709TEST_P(QuicConnectionTest, BasicSending) {
QUICHE teamcd098022019-03-22 18:49:55 -07002710 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2711 return;
2712 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002713 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2714 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2715 ProcessDataPacket(1);
2716 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
2717 QuicPacketNumber last_packet;
2718 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
2719 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
2720 SendAckPacketToPeer(); // Packet 2
2721
2722 if (GetParam().no_stop_waiting) {
2723 // Expect no stop waiting frame is sent.
2724 EXPECT_FALSE(least_unacked().IsInitialized());
2725 } else {
2726 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
2727 }
2728
2729 SendAckPacketToPeer(); // Packet 3
2730 if (GetParam().no_stop_waiting) {
2731 // Expect no stop waiting frame is sent.
2732 EXPECT_FALSE(least_unacked().IsInitialized());
2733 } else {
2734 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
2735 }
2736
2737 SendStreamDataToPeer(1, "bar", 3, NO_FIN, &last_packet); // Packet 4
2738 EXPECT_EQ(QuicPacketNumber(4u), last_packet);
2739 SendAckPacketToPeer(); // Packet 5
2740 if (GetParam().no_stop_waiting) {
2741 // Expect no stop waiting frame is sent.
2742 EXPECT_FALSE(least_unacked().IsInitialized());
2743 } else {
2744 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
2745 }
2746
2747 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2748
2749 // Peer acks up to packet 3.
2750 QuicAckFrame frame = InitAckFrame(3);
2751 ProcessAckPacket(&frame);
2752 SendAckPacketToPeer(); // Packet 6
2753
2754 // As soon as we've acked one, we skip ack packets 2 and 3 and note lack of
2755 // ack for 4.
2756 if (GetParam().no_stop_waiting) {
2757 // Expect no stop waiting frame is sent.
2758 EXPECT_FALSE(least_unacked().IsInitialized());
2759 } else {
2760 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
2761 }
2762
2763 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2764
2765 // Peer acks up to packet 4, the last packet.
2766 QuicAckFrame frame2 = InitAckFrame(6);
2767 ProcessAckPacket(&frame2); // Acks don't instigate acks.
2768
2769 // Verify that we did not send an ack.
2770 EXPECT_EQ(QuicPacketNumber(6u), writer_->header().packet_number);
2771
2772 // So the last ack has not changed.
2773 if (GetParam().no_stop_waiting) {
2774 // Expect no stop waiting frame is sent.
2775 EXPECT_FALSE(least_unacked().IsInitialized());
2776 } else {
2777 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
2778 }
2779
2780 // If we force an ack, we shouldn't change our retransmit state.
2781 SendAckPacketToPeer(); // Packet 7
2782 if (GetParam().no_stop_waiting) {
2783 // Expect no stop waiting frame is sent.
2784 EXPECT_FALSE(least_unacked().IsInitialized());
2785 } else {
2786 EXPECT_EQ(QuicPacketNumber(7u), least_unacked());
2787 }
2788
2789 // But if we send more data it should.
2790 SendStreamDataToPeer(1, "eep", 6, NO_FIN, &last_packet); // Packet 8
2791 EXPECT_EQ(QuicPacketNumber(8u), last_packet);
2792 SendAckPacketToPeer(); // Packet 9
2793 if (GetParam().no_stop_waiting) {
2794 // Expect no stop waiting frame is sent.
2795 EXPECT_FALSE(least_unacked().IsInitialized());
2796 } else {
2797 EXPECT_EQ(QuicPacketNumber(7u), least_unacked());
2798 }
2799}
2800
2801// QuicConnection should record the packet sent-time prior to sending the
2802// packet.
2803TEST_P(QuicConnectionTest, RecordSentTimeBeforePacketSent) {
QUICHE teamcd098022019-03-22 18:49:55 -07002804 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2805 return;
2806 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002807 // We're using a MockClock for the tests, so we have complete control over the
2808 // time.
2809 // Our recorded timestamp for the last packet sent time will be passed in to
2810 // the send_algorithm. Make sure that it is set to the correct value.
2811 QuicTime actual_recorded_send_time = QuicTime::Zero();
2812 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2813 .WillOnce(SaveArg<0>(&actual_recorded_send_time));
2814
2815 // First send without any pause and check the result.
2816 QuicTime expected_recorded_send_time = clock_.Now();
2817 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
2818 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
2819 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
2820 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
2821
2822 // Now pause during the write, and check the results.
2823 actual_recorded_send_time = QuicTime::Zero();
2824 const QuicTime::Delta write_pause_time_delta =
2825 QuicTime::Delta::FromMilliseconds(5000);
2826 SetWritePauseTimeDelta(write_pause_time_delta);
2827 expected_recorded_send_time = clock_.Now();
2828
2829 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2830 .WillOnce(SaveArg<0>(&actual_recorded_send_time));
2831 connection_.SendStreamDataWithString(2, "baz", 0, NO_FIN);
2832 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
2833 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
2834 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
2835}
2836
2837TEST_P(QuicConnectionTest, FramePacking) {
QUICHE teamcd098022019-03-22 18:49:55 -07002838 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2839 return;
2840 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002841 // Send two stream frames in 1 packet by queueing them.
2842 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2843 {
2844 QuicConnection::ScopedPacketFlusher flusher(&connection_,
2845 QuicConnection::SEND_ACK);
2846 connection_.SendStreamData3();
2847 connection_.SendStreamData5();
2848 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2849 }
2850 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2851 EXPECT_FALSE(connection_.HasQueuedData());
2852
2853 // Parse the last packet and ensure it's an ack and two stream frames from
2854 // two different streams.
2855 if (GetParam().no_stop_waiting) {
2856 EXPECT_EQ(2u, writer_->frame_count());
2857 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
2858 } else {
2859 EXPECT_EQ(2u, writer_->frame_count());
2860 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
2861 }
2862
2863 EXPECT_TRUE(writer_->ack_frames().empty());
2864
2865 ASSERT_EQ(2u, writer_->stream_frames().size());
2866 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
2867 writer_->stream_frames()[0]->stream_id);
2868 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
2869 writer_->stream_frames()[1]->stream_id);
2870}
2871
2872TEST_P(QuicConnectionTest, FramePackingNonCryptoThenCrypto) {
QUICHE teamcd098022019-03-22 18:49:55 -07002873 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2874 return;
2875 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002876 // Send two stream frames (one non-crypto, then one crypto) in 2 packets by
2877 // queueing them.
2878 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2879 {
2880 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
2881 QuicConnection::ScopedPacketFlusher flusher(&connection_,
2882 QuicConnection::SEND_ACK);
2883 connection_.SendStreamData3();
2884 connection_.SendCryptoStreamData();
2885 }
2886 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2887 EXPECT_FALSE(connection_.HasQueuedData());
2888
2889 // Parse the last packet and ensure it's the crypto stream frame.
2890 EXPECT_EQ(2u, writer_->frame_count());
2891 ASSERT_EQ(1u, writer_->padding_frames().size());
QUICHE teamea740082019-03-11 17:58:43 -07002892 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002893 ASSERT_EQ(1u, writer_->stream_frames().size());
2894 EXPECT_EQ(QuicUtils::GetCryptoStreamId(connection_.transport_version()),
2895 writer_->stream_frames()[0]->stream_id);
2896 } else {
2897 EXPECT_EQ(1u, writer_->crypto_frames().size());
2898 }
2899}
2900
2901TEST_P(QuicConnectionTest, FramePackingCryptoThenNonCrypto) {
QUICHE teamcd098022019-03-22 18:49:55 -07002902 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2903 return;
2904 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002905 // Send two stream frames (one crypto, then one non-crypto) in 2 packets by
2906 // queueing them.
2907 {
2908 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2909 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
2910 QuicConnection::ScopedPacketFlusher flusher(&connection_,
2911 QuicConnection::SEND_ACK);
2912 connection_.SendCryptoStreamData();
2913 connection_.SendStreamData3();
2914 }
2915 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2916 EXPECT_FALSE(connection_.HasQueuedData());
2917
2918 // Parse the last packet and ensure it's the stream frame from stream 3.
2919 EXPECT_EQ(1u, writer_->frame_count());
2920 ASSERT_EQ(1u, writer_->stream_frames().size());
2921 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
2922 writer_->stream_frames()[0]->stream_id);
2923}
2924
2925TEST_P(QuicConnectionTest, FramePackingAckResponse) {
QUICHE teamcd098022019-03-22 18:49:55 -07002926 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2927 return;
2928 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002929 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2930 // Process a data packet to queue up a pending ack.
2931 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2932 ProcessDataPacket(1);
2933 QuicPacketNumber last_packet;
QUICHE team8c1daa22019-03-13 08:33:41 -07002934 SendStreamDataToPeer(
2935 QuicUtils::GetCryptoStreamId(connection_.version().transport_version),
2936 "foo", 0, NO_FIN, &last_packet);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002937 // Verify ack is bundled with outging packet.
2938 EXPECT_FALSE(writer_->ack_frames().empty());
2939
2940 EXPECT_CALL(visitor_, OnCanWrite())
2941 .WillOnce(DoAll(IgnoreResult(InvokeWithoutArgs(
2942 &connection_, &TestConnection::SendStreamData3)),
2943 IgnoreResult(InvokeWithoutArgs(
2944 &connection_, &TestConnection::SendStreamData5))));
2945
2946 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2947
2948 // Process a data packet to cause the visitor's OnCanWrite to be invoked.
2949 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
QUICHE team8c1daa22019-03-13 08:33:41 -07002950 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
2951 QuicMakeUnique<TaggingEncrypter>(0x01));
2952 connection_.SetDecrypter(ENCRYPTION_FORWARD_SECURE,
2953 QuicMakeUnique<StrictTaggingDecrypter>(0x01));
2954 ProcessDataPacketAtLevel(2, false, ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002955
2956 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2957 EXPECT_FALSE(connection_.HasQueuedData());
2958
2959 // Parse the last packet and ensure it's an ack and two stream frames from
2960 // two different streams.
2961 if (GetParam().no_stop_waiting) {
2962 EXPECT_EQ(3u, writer_->frame_count());
2963 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
2964 } else {
2965 EXPECT_EQ(4u, writer_->frame_count());
2966 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
2967 }
2968 EXPECT_FALSE(writer_->ack_frames().empty());
2969 ASSERT_EQ(2u, writer_->stream_frames().size());
2970 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
2971 writer_->stream_frames()[0]->stream_id);
2972 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
2973 writer_->stream_frames()[1]->stream_id);
2974}
2975
2976TEST_P(QuicConnectionTest, FramePackingSendv) {
QUICHE teamcd098022019-03-22 18:49:55 -07002977 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2978 return;
2979 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002980 // Send data in 1 packet by writing multiple blocks in a single iovector
2981 // using writev.
2982 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2983
2984 char data[] = "ABCDEF";
2985 struct iovec iov[2];
2986 iov[0].iov_base = data;
2987 iov[0].iov_len = 4;
2988 iov[1].iov_base = data + 4;
2989 iov[1].iov_len = 2;
2990 connection_.SaveAndSendStreamData(
2991 QuicUtils::GetCryptoStreamId(connection_.transport_version()), iov, 2, 6,
2992 0, NO_FIN);
2993
2994 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2995 EXPECT_FALSE(connection_.HasQueuedData());
2996
2997 // Parse the last packet and ensure multiple iovector blocks have
2998 // been packed into a single stream frame from one stream.
2999 EXPECT_EQ(2u, writer_->frame_count());
3000 EXPECT_EQ(1u, writer_->stream_frames().size());
3001 EXPECT_EQ(1u, writer_->padding_frames().size());
3002 QuicStreamFrame* frame = writer_->stream_frames()[0].get();
3003 EXPECT_EQ(QuicUtils::GetCryptoStreamId(connection_.transport_version()),
3004 frame->stream_id);
3005 EXPECT_EQ("ABCDEF", QuicStringPiece(frame->data_buffer, frame->data_length));
3006}
3007
3008TEST_P(QuicConnectionTest, FramePackingSendvQueued) {
QUICHE teamcd098022019-03-22 18:49:55 -07003009 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3010 return;
3011 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003012 // Try to send two stream frames in 1 packet by using writev.
3013 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3014
3015 BlockOnNextWrite();
3016 char data[] = "ABCDEF";
3017 struct iovec iov[2];
3018 iov[0].iov_base = data;
3019 iov[0].iov_len = 4;
3020 iov[1].iov_base = data + 4;
3021 iov[1].iov_len = 2;
3022 connection_.SaveAndSendStreamData(
3023 QuicUtils::GetCryptoStreamId(connection_.transport_version()), iov, 2, 6,
3024 0, NO_FIN);
3025
3026 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3027 EXPECT_TRUE(connection_.HasQueuedData());
3028
3029 // Unblock the writes and actually send.
3030 writer_->SetWritable();
3031 connection_.OnCanWrite();
3032 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3033
3034 // Parse the last packet and ensure it's one stream frame from one stream.
3035 EXPECT_EQ(2u, writer_->frame_count());
3036 EXPECT_EQ(1u, writer_->stream_frames().size());
3037 EXPECT_EQ(1u, writer_->padding_frames().size());
3038 EXPECT_EQ(QuicUtils::GetCryptoStreamId(connection_.transport_version()),
3039 writer_->stream_frames()[0]->stream_id);
3040}
3041
3042TEST_P(QuicConnectionTest, SendingZeroBytes) {
QUICHE teamcd098022019-03-22 18:49:55 -07003043 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3044 return;
3045 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003046 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3047 // Send a zero byte write with a fin using writev.
3048 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3049 connection_.SaveAndSendStreamData(
3050 QuicUtils::GetHeadersStreamId(connection_.transport_version()), nullptr,
3051 0, 0, 0, FIN);
3052
3053 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3054 EXPECT_FALSE(connection_.HasQueuedData());
3055
3056 // Parse the last packet and ensure it's one stream frame from one stream.
3057 EXPECT_EQ(1u, writer_->frame_count());
3058 EXPECT_EQ(1u, writer_->stream_frames().size());
3059 EXPECT_EQ(QuicUtils::GetHeadersStreamId(connection_.transport_version()),
3060 writer_->stream_frames()[0]->stream_id);
3061 EXPECT_TRUE(writer_->stream_frames()[0]->fin);
3062}
3063
3064TEST_P(QuicConnectionTest, LargeSendWithPendingAck) {
QUICHE teamcd098022019-03-22 18:49:55 -07003065 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3066 return;
3067 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003068 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3069 // Set the ack alarm by processing a ping frame.
3070 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3071
3072 // Processs a PING frame.
3073 ProcessFramePacket(QuicFrame(QuicPingFrame()));
3074 // Ensure that this has caused the ACK alarm to be set.
3075 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
3076 EXPECT_TRUE(ack_alarm->IsSet());
3077
3078 // Send data and ensure the ack is bundled.
3079 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(8);
3080 size_t len = 10000;
3081 std::unique_ptr<char[]> data_array(new char[len]);
3082 memset(data_array.get(), '?', len);
3083 struct iovec iov;
3084 iov.iov_base = data_array.get();
3085 iov.iov_len = len;
3086 QuicConsumedData consumed = connection_.SaveAndSendStreamData(
3087 QuicUtils::GetHeadersStreamId(connection_.transport_version()), &iov, 1,
3088 len, 0, FIN);
3089 EXPECT_EQ(len, consumed.bytes_consumed);
3090 EXPECT_TRUE(consumed.fin_consumed);
3091 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3092 EXPECT_FALSE(connection_.HasQueuedData());
3093
3094 // Parse the last packet and ensure it's one stream frame with a fin.
3095 EXPECT_EQ(1u, writer_->frame_count());
3096 EXPECT_EQ(1u, writer_->stream_frames().size());
3097 EXPECT_EQ(QuicUtils::GetHeadersStreamId(connection_.transport_version()),
3098 writer_->stream_frames()[0]->stream_id);
3099 EXPECT_TRUE(writer_->stream_frames()[0]->fin);
3100 // Ensure the ack alarm was cancelled when the ack was sent.
3101 EXPECT_FALSE(ack_alarm->IsSet());
3102}
3103
3104TEST_P(QuicConnectionTest, OnCanWrite) {
QUICHE teamcd098022019-03-22 18:49:55 -07003105 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3106 return;
3107 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003108 // Visitor's OnCanWrite will send data, but will have more pending writes.
3109 EXPECT_CALL(visitor_, OnCanWrite())
3110 .WillOnce(DoAll(IgnoreResult(InvokeWithoutArgs(
3111 &connection_, &TestConnection::SendStreamData3)),
3112 IgnoreResult(InvokeWithoutArgs(
3113 &connection_, &TestConnection::SendStreamData5))));
3114 {
3115 InSequence seq;
3116 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillOnce(Return(true));
3117 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
3118 .WillRepeatedly(Return(false));
3119 }
3120
3121 EXPECT_CALL(*send_algorithm_, CanSend(_))
3122 .WillRepeatedly(testing::Return(true));
3123
3124 connection_.OnCanWrite();
3125
3126 // Parse the last packet and ensure it's the two stream frames from
3127 // two different streams.
3128 EXPECT_EQ(2u, writer_->frame_count());
3129 EXPECT_EQ(2u, writer_->stream_frames().size());
3130 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3131 writer_->stream_frames()[0]->stream_id);
3132 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3133 writer_->stream_frames()[1]->stream_id);
3134}
3135
3136TEST_P(QuicConnectionTest, RetransmitOnNack) {
QUICHE teamcd098022019-03-22 18:49:55 -07003137 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3138 return;
3139 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003140 QuicPacketNumber last_packet;
3141 QuicByteCount second_packet_size;
3142 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet); // Packet 1
3143 second_packet_size =
3144 SendStreamDataToPeer(3, "foos", 3, NO_FIN, &last_packet); // Packet 2
3145 SendStreamDataToPeer(3, "fooos", 7, NO_FIN, &last_packet); // Packet 3
3146
3147 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3148
3149 // Don't lose a packet on an ack, and nothing is retransmitted.
3150 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3151 QuicAckFrame ack_one = InitAckFrame(1);
3152 ProcessAckPacket(&ack_one);
3153
3154 // Lose a packet and ensure it triggers retransmission.
3155 QuicAckFrame nack_two = ConstructAckFrame(3, 2);
3156 LostPacketVector lost_packets;
3157 lost_packets.push_back(LostPacket(QuicPacketNumber(2), kMaxPacketSize));
3158 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3159 .WillOnce(SetArgPointee<5>(lost_packets));
3160 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3161 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3162 EXPECT_FALSE(QuicPacketCreatorPeer::SendVersionInPacket(creator_));
3163 ProcessAckPacket(&nack_two);
3164}
3165
3166TEST_P(QuicConnectionTest, DoNotSendQueuedPacketForResetStream) {
QUICHE teamcd098022019-03-22 18:49:55 -07003167 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3168 return;
3169 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003170 // Block the connection to queue the packet.
3171 BlockOnNextWrite();
3172
3173 QuicStreamId stream_id = 2;
3174 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
3175
3176 // Now that there is a queued packet, reset the stream.
3177 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
3178
3179 // Unblock the connection and verify that only the RST_STREAM is sent.
3180 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3181 writer_->SetWritable();
3182 connection_.OnCanWrite();
3183 if (!connection_.session_decides_what_to_write()) {
3184 // OnCanWrite will cause RST_STREAM be sent again.
3185 connection_.SendControlFrame(QuicFrame(new QuicRstStreamFrame(
3186 1, stream_id, QUIC_ERROR_PROCESSING_STREAM, 14)));
3187 }
3188 EXPECT_EQ(1u, writer_->frame_count());
3189 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3190}
3191
3192TEST_P(QuicConnectionTest, SendQueuedPacketForQuicRstStreamNoError) {
QUICHE teamcd098022019-03-22 18:49:55 -07003193 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3194 return;
3195 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003196 // Block the connection to queue the packet.
3197 BlockOnNextWrite();
3198
3199 QuicStreamId stream_id = 2;
3200 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
3201
3202 // Now that there is a queued packet, reset the stream.
3203 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 3);
3204
3205 // Unblock the connection and verify that the RST_STREAM is sent and the data
3206 // packet is sent.
3207 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(2));
3208 writer_->SetWritable();
3209 connection_.OnCanWrite();
3210 if (!connection_.session_decides_what_to_write()) {
3211 // OnCanWrite will cause RST_STREAM be sent again.
3212 connection_.SendControlFrame(QuicFrame(
3213 new QuicRstStreamFrame(1, stream_id, QUIC_STREAM_NO_ERROR, 14)));
3214 }
3215 EXPECT_EQ(1u, writer_->frame_count());
3216 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3217}
3218
3219TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnNack) {
QUICHE teamcd098022019-03-22 18:49:55 -07003220 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3221 return;
3222 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003223 QuicStreamId stream_id = 2;
3224 QuicPacketNumber last_packet;
3225 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3226 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3227 SendStreamDataToPeer(stream_id, "fooos", 7, NO_FIN, &last_packet);
3228
3229 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3230 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 12);
3231
3232 // Lose a packet and ensure it does not trigger retransmission.
3233 QuicAckFrame nack_two = ConstructAckFrame(last_packet, last_packet - 1);
3234 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3235 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3236 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3237 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3238 ProcessAckPacket(&nack_two);
3239}
3240
3241TEST_P(QuicConnectionTest, RetransmitForQuicRstStreamNoErrorOnNack) {
QUICHE teamcd098022019-03-22 18:49:55 -07003242 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3243 return;
3244 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003245 QuicStreamId stream_id = 2;
3246 QuicPacketNumber last_packet;
3247 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3248 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3249 SendStreamDataToPeer(stream_id, "fooos", 7, NO_FIN, &last_packet);
3250
3251 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3252 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 12);
3253
3254 // Lose a packet, ensure it triggers retransmission.
3255 QuicAckFrame nack_two = ConstructAckFrame(last_packet, last_packet - 1);
3256 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3257 LostPacketVector lost_packets;
3258 lost_packets.push_back(LostPacket(last_packet - 1, kMaxPacketSize));
3259 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3260 .WillOnce(SetArgPointee<5>(lost_packets));
3261 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3262 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
3263 ProcessAckPacket(&nack_two);
3264}
3265
3266TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnRTO) {
QUICHE teamcd098022019-03-22 18:49:55 -07003267 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3268 return;
3269 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003270 QuicStreamId stream_id = 2;
3271 QuicPacketNumber last_packet;
3272 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3273
3274 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3275 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
3276
3277 // Fire the RTO and verify that the RST_STREAM is resent, not stream data.
3278 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3279 clock_.AdvanceTime(DefaultRetransmissionTime());
3280 connection_.GetRetransmissionAlarm()->Fire();
3281 EXPECT_EQ(1u, writer_->frame_count());
3282 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3283 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
3284}
3285
3286// Ensure that if the only data in flight is non-retransmittable, the
3287// retransmission alarm is not set.
3288TEST_P(QuicConnectionTest, CancelRetransmissionAlarmAfterResetStream) {
QUICHE teamcd098022019-03-22 18:49:55 -07003289 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3290 return;
3291 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003292 QuicStreamId stream_id = 2;
3293 QuicPacketNumber last_data_packet;
3294 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
3295
3296 // Cancel the stream.
3297 const QuicPacketNumber rst_packet = last_data_packet + 1;
3298 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, rst_packet, _, _)).Times(1);
3299 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
3300
3301 // Ack the RST_STREAM frame (since it's retransmittable), but not the data
3302 // packet, which is no longer retransmittable since the stream was cancelled.
3303 QuicAckFrame nack_stream_data =
3304 ConstructAckFrame(rst_packet, last_data_packet);
3305 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3306 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3307 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3308 ProcessAckPacket(&nack_stream_data);
3309
3310 // Ensure that the data is still in flight, but the retransmission alarm is no
3311 // longer set.
3312 EXPECT_GT(QuicSentPacketManagerPeer::GetBytesInFlight(manager_), 0u);
3313 if (GetQuicReloadableFlag(quic_optimize_inflight_check)) {
3314 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3315 // Firing the alarm should remove all bytes_in_flight.
3316 connection_.GetRetransmissionAlarm()->Fire();
3317 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
3318 }
3319 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3320}
3321
3322TEST_P(QuicConnectionTest, RetransmitForQuicRstStreamNoErrorOnRTO) {
QUICHE teamcd098022019-03-22 18:49:55 -07003323 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3324 return;
3325 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003326 connection_.SetMaxTailLossProbes(0);
3327
3328 QuicStreamId stream_id = 2;
3329 QuicPacketNumber last_packet;
3330 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3331
3332 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3333 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 3);
3334
3335 // Fire the RTO and verify that the RST_STREAM is resent, the stream data
3336 // is sent.
3337 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(2));
3338 clock_.AdvanceTime(DefaultRetransmissionTime());
3339 connection_.GetRetransmissionAlarm()->Fire();
3340 EXPECT_EQ(1u, writer_->frame_count());
3341 ASSERT_EQ(1u, writer_->rst_stream_frames().size());
3342 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
3343}
3344
3345TEST_P(QuicConnectionTest, DoNotSendPendingRetransmissionForResetStream) {
QUICHE teamcd098022019-03-22 18:49:55 -07003346 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3347 return;
3348 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003349 QuicStreamId stream_id = 2;
3350 QuicPacketNumber last_packet;
3351 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3352 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3353 BlockOnNextWrite();
3354 connection_.SendStreamDataWithString(stream_id, "fooos", 7, NO_FIN);
3355
3356 // Lose a packet which will trigger a pending retransmission.
3357 QuicAckFrame ack = ConstructAckFrame(last_packet, last_packet - 1);
3358 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3359 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3360 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3361 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3362 ProcessAckPacket(&ack);
3363
3364 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 12);
3365
3366 // Unblock the connection and verify that the RST_STREAM is sent but not the
3367 // second data packet nor a retransmit.
3368 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3369 writer_->SetWritable();
3370 connection_.OnCanWrite();
3371 if (!connection_.session_decides_what_to_write()) {
3372 // OnCanWrite will cause this RST_STREAM_FRAME be sent again.
3373 connection_.SendControlFrame(QuicFrame(new QuicRstStreamFrame(
3374 1, stream_id, QUIC_ERROR_PROCESSING_STREAM, 14)));
3375 }
3376 EXPECT_EQ(1u, writer_->frame_count());
3377 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3378 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
3379}
3380
3381TEST_P(QuicConnectionTest, SendPendingRetransmissionForQuicRstStreamNoError) {
QUICHE teamcd098022019-03-22 18:49:55 -07003382 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3383 return;
3384 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003385 QuicStreamId stream_id = 2;
3386 QuicPacketNumber last_packet;
3387 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3388 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3389 BlockOnNextWrite();
3390 connection_.SendStreamDataWithString(stream_id, "fooos", 7, NO_FIN);
3391
3392 // Lose a packet which will trigger a pending retransmission.
3393 QuicAckFrame ack = ConstructAckFrame(last_packet, last_packet - 1);
3394 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3395 LostPacketVector lost_packets;
3396 lost_packets.push_back(LostPacket(last_packet - 1, kMaxPacketSize));
3397 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3398 .WillOnce(SetArgPointee<5>(lost_packets));
3399 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3400 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3401 ProcessAckPacket(&ack);
3402
3403 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 12);
3404
3405 // Unblock the connection and verify that the RST_STREAM is sent and the
3406 // second data packet or a retransmit is sent.
3407 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(2));
3408 writer_->SetWritable();
3409 connection_.OnCanWrite();
3410 // The RST_STREAM_FRAME is sent after queued packets and pending
3411 // retransmission.
3412 connection_.SendControlFrame(QuicFrame(
3413 new QuicRstStreamFrame(1, stream_id, QUIC_STREAM_NO_ERROR, 14)));
3414 EXPECT_EQ(1u, writer_->frame_count());
3415 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3416}
3417
3418TEST_P(QuicConnectionTest, RetransmitAckedPacket) {
QUICHE teamcd098022019-03-22 18:49:55 -07003419 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3420 return;
3421 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003422 QuicPacketNumber last_packet;
3423 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
3424 SendStreamDataToPeer(1, "foos", 3, NO_FIN, &last_packet); // Packet 2
3425 SendStreamDataToPeer(1, "fooos", 7, NO_FIN, &last_packet); // Packet 3
3426
3427 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3428
3429 // Instigate a loss with an ack.
3430 QuicAckFrame nack_two = ConstructAckFrame(3, 2);
3431 // The first nack should trigger a fast retransmission, but we'll be
3432 // write blocked, so the packet will be queued.
3433 BlockOnNextWrite();
3434
3435 LostPacketVector lost_packets;
3436 lost_packets.push_back(LostPacket(QuicPacketNumber(2), kMaxPacketSize));
3437 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3438 .WillOnce(SetArgPointee<5>(lost_packets));
3439 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3440 ProcessAckPacket(&nack_two);
3441 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3442
3443 // Now, ack the previous transmission.
3444 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3445 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(false, _, _, _, _));
3446 QuicAckFrame ack_all = InitAckFrame(3);
3447 ProcessAckPacket(&ack_all);
3448
3449 // Unblock the socket and attempt to send the queued packets. We will always
3450 // send the retransmission.
3451 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _))
3452 .Times(1);
3453
3454 writer_->SetWritable();
3455 connection_.OnCanWrite();
3456
3457 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3458 // We do not store retransmittable frames of this retransmission.
3459 EXPECT_FALSE(QuicConnectionPeer::HasRetransmittableFrames(&connection_, 4));
3460}
3461
3462TEST_P(QuicConnectionTest, RetransmitNackedLargestObserved) {
QUICHE teamcd098022019-03-22 18:49:55 -07003463 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3464 return;
3465 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003466 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3467 QuicPacketNumber original, second;
3468
3469 QuicByteCount packet_size =
3470 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &original); // 1st packet.
3471 SendStreamDataToPeer(3, "bar", 3, NO_FIN, &second); // 2nd packet.
3472
3473 QuicAckFrame frame = InitAckFrame({{second, second + 1}});
3474 // The first nack should retransmit the largest observed packet.
3475 LostPacketVector lost_packets;
3476 lost_packets.push_back(LostPacket(original, kMaxPacketSize));
3477 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3478 .WillOnce(SetArgPointee<5>(lost_packets));
3479 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3480 // Packet 1 is short header for IETF QUIC because the encryption level
3481 // switched to ENCRYPTION_FORWARD_SECURE in SendStreamDataToPeer.
3482 EXPECT_CALL(
3483 *send_algorithm_,
3484 OnPacketSent(_, _, _,
3485 GetParam().version.transport_version > QUIC_VERSION_43
3486 ? packet_size
3487 : packet_size - kQuicVersionSize,
3488 _));
3489 ProcessAckPacket(&frame);
3490}
3491
3492TEST_P(QuicConnectionTest, QueueAfterTwoRTOs) {
QUICHE teamcd098022019-03-22 18:49:55 -07003493 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3494 return;
3495 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003496 connection_.SetMaxTailLossProbes(0);
3497
3498 for (int i = 0; i < 10; ++i) {
3499 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3500 connection_.SendStreamDataWithString(3, "foo", i * 3, NO_FIN);
3501 }
3502
3503 // Block the writer and ensure they're queued.
3504 BlockOnNextWrite();
3505 clock_.AdvanceTime(DefaultRetransmissionTime());
3506 // Only one packet should be retransmitted.
3507 connection_.GetRetransmissionAlarm()->Fire();
3508 EXPECT_TRUE(connection_.HasQueuedData());
3509
3510 // Unblock the writer.
3511 writer_->SetWritable();
3512 clock_.AdvanceTime(QuicTime::Delta::FromMicroseconds(
3513 2 * DefaultRetransmissionTime().ToMicroseconds()));
3514 // Retransmit already retransmitted packets event though the packet number
3515 // greater than the largest observed.
3516 if (connection_.session_decides_what_to_write()) {
3517 // 2 RTOs + 1 TLP.
3518 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
3519 } else {
3520 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3521 }
3522 connection_.GetRetransmissionAlarm()->Fire();
3523 connection_.OnCanWrite();
3524}
3525
3526TEST_P(QuicConnectionTest, WriteBlockedBufferedThenSent) {
QUICHE teamcd098022019-03-22 18:49:55 -07003527 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3528 return;
3529 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003530 BlockOnNextWrite();
3531 writer_->set_is_write_blocked_data_buffered(true);
3532 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3533 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3534 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3535
3536 writer_->SetWritable();
3537 connection_.OnCanWrite();
3538 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3539}
3540
3541TEST_P(QuicConnectionTest, WriteBlockedThenSent) {
QUICHE teamcd098022019-03-22 18:49:55 -07003542 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3543 return;
3544 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003545 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3546 BlockOnNextWrite();
3547 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3548 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3549 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3550
3551 // The second packet should also be queued, in order to ensure packets are
3552 // never sent out of order.
3553 writer_->SetWritable();
3554 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3555 EXPECT_EQ(2u, connection_.NumQueuedPackets());
3556
3557 // Now both are sent in order when we unblock.
3558 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3559 connection_.OnCanWrite();
3560 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3561}
3562
3563TEST_P(QuicConnectionTest, RetransmitWriteBlockedAckedOriginalThenSent) {
QUICHE teamcd098022019-03-22 18:49:55 -07003564 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3565 return;
3566 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003567 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3568 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
3569 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3570
3571 BlockOnNextWrite();
3572 writer_->set_is_write_blocked_data_buffered(true);
3573 // Simulate the retransmission alarm firing.
3574 clock_.AdvanceTime(DefaultRetransmissionTime());
3575 connection_.GetRetransmissionAlarm()->Fire();
3576
3577 // Ack the sent packet before the callback returns, which happens in
3578 // rare circumstances with write blocked sockets.
3579 QuicAckFrame ack = InitAckFrame(1);
3580 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3581 ProcessAckPacket(&ack);
3582
3583 writer_->SetWritable();
3584 connection_.OnCanWrite();
3585 // There is now a pending packet, but with no retransmittable frames.
3586 if (GetQuicReloadableFlag(quic_optimize_inflight_check)) {
3587 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3588 // Firing the alarm should remove all bytes_in_flight.
3589 connection_.GetRetransmissionAlarm()->Fire();
3590 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
3591 }
3592 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3593 EXPECT_FALSE(QuicConnectionPeer::HasRetransmittableFrames(&connection_, 2));
3594}
3595
3596TEST_P(QuicConnectionTest, AlarmsWhenWriteBlocked) {
QUICHE teamcd098022019-03-22 18:49:55 -07003597 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3598 return;
3599 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003600 // Block the connection.
3601 BlockOnNextWrite();
3602 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
3603 EXPECT_EQ(1u, writer_->packets_write_attempts());
3604 EXPECT_TRUE(writer_->IsWriteBlocked());
3605
3606 // Set the send alarm. Fire the alarm and ensure it doesn't attempt to write.
3607 connection_.GetSendAlarm()->Set(clock_.ApproximateNow());
3608 connection_.GetSendAlarm()->Fire();
3609 EXPECT_TRUE(writer_->IsWriteBlocked());
3610 EXPECT_EQ(1u, writer_->packets_write_attempts());
3611}
3612
3613TEST_P(QuicConnectionTest, NoSendAlarmAfterProcessPacketWhenWriteBlocked) {
QUICHE teamcd098022019-03-22 18:49:55 -07003614 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3615 return;
3616 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003617 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3618
3619 // Block the connection.
3620 BlockOnNextWrite();
3621 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
3622 EXPECT_TRUE(writer_->IsWriteBlocked());
3623 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3624 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
3625
3626 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3627 // Process packet number 1. Can not call ProcessPacket or ProcessDataPacket
3628 // here, because they will fire the alarm after QuicConnection::ProcessPacket
3629 // is returned.
3630 const uint64_t received_packet_num = 1;
3631 const bool has_stop_waiting = false;
QUICHE team6987b4a2019-03-15 16:23:04 -07003632 const EncryptionLevel level = ENCRYPTION_INITIAL;
QUICHE team8c1daa22019-03-13 08:33:41 -07003633 std::unique_ptr<QuicPacket> packet(ConstructDataPacket(
QUICHE team6987b4a2019-03-15 16:23:04 -07003634 received_packet_num, has_stop_waiting, ENCRYPTION_INITIAL));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003635 char buffer[kMaxPacketSize];
3636 size_t encrypted_length =
3637 peer_framer_.EncryptPayload(level, QuicPacketNumber(received_packet_num),
3638 *packet, buffer, kMaxPacketSize);
3639 connection_.ProcessUdpPacket(
3640 kSelfAddress, kPeerAddress,
3641 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
3642
3643 EXPECT_TRUE(writer_->IsWriteBlocked());
3644 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
3645}
3646
3647TEST_P(QuicConnectionTest, AddToWriteBlockedListIfWriterBlockedWhenProcessing) {
QUICHE teamcd098022019-03-22 18:49:55 -07003648 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3649 return;
3650 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003651 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3652 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
3653
3654 // Simulate the case where a shared writer gets blocked by another connection.
3655 writer_->SetWriteBlocked();
3656
3657 // Process an ACK, make sure the connection calls visitor_->OnWriteBlocked().
3658 QuicAckFrame ack1 = InitAckFrame(1);
3659 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
3660 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
3661 ProcessAckPacket(1, &ack1);
3662}
3663
3664TEST_P(QuicConnectionTest, DoNotAddToWriteBlockedListAfterDisconnect) {
QUICHE teamcd098022019-03-22 18:49:55 -07003665 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3666 return;
3667 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003668 writer_->SetBatchMode(true);
3669 EXPECT_TRUE(connection_.connected());
3670 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, _,
3671 ConnectionCloseSource::FROM_SELF));
3672
3673 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
3674
3675 {
3676 QuicConnection::ScopedPacketFlusher flusher(&connection_,
3677 QuicConnection::NO_ACK);
3678 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
3679 ConnectionCloseBehavior::SILENT_CLOSE);
3680
3681 EXPECT_FALSE(connection_.connected());
3682 writer_->SetWriteBlocked();
3683 }
3684}
3685
3686TEST_P(QuicConnectionTest, AddToWriteBlockedListIfBlockedOnFlushPackets) {
QUICHE teamcd098022019-03-22 18:49:55 -07003687 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3688 return;
3689 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003690 writer_->SetBatchMode(true);
3691 writer_->BlockOnNextFlush();
3692
3693 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
3694 {
3695 QuicConnection::ScopedPacketFlusher flusher(&connection_,
3696 QuicConnection::NO_ACK);
3697 // flusher's destructor will call connection_.FlushPackets, which should add
3698 // the connection to the write blocked list.
3699 }
3700}
3701
3702TEST_P(QuicConnectionTest, NoLimitPacketsPerNack) {
QUICHE teamcd098022019-03-22 18:49:55 -07003703 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3704 return;
3705 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003706 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3707 int offset = 0;
3708 // Send packets 1 to 15.
3709 for (int i = 0; i < 15; ++i) {
3710 SendStreamDataToPeer(1, "foo", offset, NO_FIN, nullptr);
3711 offset += 3;
3712 }
3713
3714 // Ack 15, nack 1-14.
3715
3716 QuicAckFrame nack =
3717 InitAckFrame({{QuicPacketNumber(15), QuicPacketNumber(16)}});
3718
3719 // 14 packets have been NACK'd and lost.
3720 LostPacketVector lost_packets;
3721 for (int i = 1; i < 15; ++i) {
3722 lost_packets.push_back(LostPacket(QuicPacketNumber(i), kMaxPacketSize));
3723 }
3724 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3725 .WillOnce(SetArgPointee<5>(lost_packets));
3726 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3727 if (connection_.session_decides_what_to_write()) {
3728 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3729 } else {
3730 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(14);
3731 }
3732 ProcessAckPacket(&nack);
3733}
3734
3735// Test sending multiple acks from the connection to the session.
3736TEST_P(QuicConnectionTest, MultipleAcks) {
QUICHE teamcd098022019-03-22 18:49:55 -07003737 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3738 return;
3739 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003740 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3741 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3742 ProcessDataPacket(1);
3743 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
3744 QuicPacketNumber last_packet;
3745 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
3746 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
3747 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet); // Packet 2
3748 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
3749 SendAckPacketToPeer(); // Packet 3
3750 SendStreamDataToPeer(5, "foo", 0, NO_FIN, &last_packet); // Packet 4
3751 EXPECT_EQ(QuicPacketNumber(4u), last_packet);
3752 SendStreamDataToPeer(1, "foo", 3, NO_FIN, &last_packet); // Packet 5
3753 EXPECT_EQ(QuicPacketNumber(5u), last_packet);
3754 SendStreamDataToPeer(3, "foo", 3, NO_FIN, &last_packet); // Packet 6
3755 EXPECT_EQ(QuicPacketNumber(6u), last_packet);
3756
3757 // Client will ack packets 1, 2, [!3], 4, 5.
3758 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3759 QuicAckFrame frame1 = ConstructAckFrame(5, 3);
3760 ProcessAckPacket(&frame1);
3761
3762 // Now the client implicitly acks 3, and explicitly acks 6.
3763 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3764 QuicAckFrame frame2 = InitAckFrame(6);
3765 ProcessAckPacket(&frame2);
3766}
3767
3768TEST_P(QuicConnectionTest, DontLatchUnackedPacket) {
QUICHE teamcd098022019-03-22 18:49:55 -07003769 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3770 return;
3771 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003772 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3773 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3774 ProcessDataPacket(1);
3775 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
3776 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr); // Packet 1;
3777 // From now on, we send acks, so the send algorithm won't mark them pending.
3778 SendAckPacketToPeer(); // Packet 2
3779
3780 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3781 QuicAckFrame frame = InitAckFrame(1);
3782 ProcessAckPacket(&frame);
3783
3784 // Verify that our internal state has least-unacked as 2, because we're still
3785 // waiting for a potential ack for 2.
3786
3787 EXPECT_EQ(QuicPacketNumber(2u), stop_waiting()->least_unacked);
3788
3789 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3790 frame = InitAckFrame(2);
3791 ProcessAckPacket(&frame);
3792 EXPECT_EQ(QuicPacketNumber(3u), stop_waiting()->least_unacked);
3793
3794 // When we send an ack, we make sure our least-unacked makes sense. In this
3795 // case since we're not waiting on an ack for 2 and all packets are acked, we
3796 // set it to 3.
3797 SendAckPacketToPeer(); // Packet 3
3798 // Least_unacked remains at 3 until another ack is received.
3799 EXPECT_EQ(QuicPacketNumber(3u), stop_waiting()->least_unacked);
3800 if (GetParam().no_stop_waiting) {
3801 // Expect no stop waiting frame is sent.
3802 EXPECT_FALSE(least_unacked().IsInitialized());
3803 } else {
3804 // Check that the outgoing ack had its packet number as least_unacked.
3805 EXPECT_EQ(QuicPacketNumber(3u), least_unacked());
3806 }
3807
3808 // Ack the ack, which updates the rtt and raises the least unacked.
3809 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3810 frame = InitAckFrame(3);
3811 ProcessAckPacket(&frame);
3812
3813 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr); // Packet 4
3814 EXPECT_EQ(QuicPacketNumber(4u), stop_waiting()->least_unacked);
3815 SendAckPacketToPeer(); // Packet 5
3816 if (GetParam().no_stop_waiting) {
3817 // Expect no stop waiting frame is sent.
3818 EXPECT_FALSE(least_unacked().IsInitialized());
3819 } else {
3820 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
3821 }
3822
3823 // Send two data packets at the end, and ensure if the last one is acked,
3824 // the least unacked is raised above the ack packets.
3825 SendStreamDataToPeer(1, "bar", 6, NO_FIN, nullptr); // Packet 6
3826 SendStreamDataToPeer(1, "bar", 9, NO_FIN, nullptr); // Packet 7
3827
3828 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3829 frame = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(5)},
3830 {QuicPacketNumber(7), QuicPacketNumber(8)}});
3831 ProcessAckPacket(&frame);
3832
3833 EXPECT_EQ(QuicPacketNumber(6u), stop_waiting()->least_unacked);
3834}
3835
3836TEST_P(QuicConnectionTest, TLP) {
QUICHE teamcd098022019-03-22 18:49:55 -07003837 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3838 return;
3839 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003840 connection_.SetMaxTailLossProbes(1);
3841
3842 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
3843 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
3844 QuicTime retransmission_time =
3845 connection_.GetRetransmissionAlarm()->deadline();
3846 EXPECT_NE(QuicTime::Zero(), retransmission_time);
3847
3848 EXPECT_EQ(QuicPacketNumber(1u), writer_->header().packet_number);
3849 // Simulate the retransmission alarm firing and sending a tlp,
3850 // so send algorithm's OnRetransmissionTimeout is not called.
3851 clock_.AdvanceTime(retransmission_time - clock_.Now());
3852 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
3853 connection_.GetRetransmissionAlarm()->Fire();
3854 EXPECT_EQ(QuicPacketNumber(2u), writer_->header().packet_number);
3855 // We do not raise the high water mark yet.
3856 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
3857}
3858
3859TEST_P(QuicConnectionTest, RTO) {
QUICHE teamcd098022019-03-22 18:49:55 -07003860 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3861 return;
3862 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003863 connection_.SetMaxTailLossProbes(0);
3864
3865 QuicTime default_retransmission_time =
3866 clock_.ApproximateNow() + DefaultRetransmissionTime();
3867 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
3868 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
3869
3870 EXPECT_EQ(QuicPacketNumber(1u), writer_->header().packet_number);
3871 EXPECT_EQ(default_retransmission_time,
3872 connection_.GetRetransmissionAlarm()->deadline());
3873 // Simulate the retransmission alarm firing.
3874 clock_.AdvanceTime(DefaultRetransmissionTime());
3875 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
3876 connection_.GetRetransmissionAlarm()->Fire();
3877 EXPECT_EQ(QuicPacketNumber(2u), writer_->header().packet_number);
3878 // We do not raise the high water mark yet.
3879 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
3880}
3881
3882TEST_P(QuicConnectionTest, RetransmitWithSameEncryptionLevel) {
QUICHE teamcd098022019-03-22 18:49:55 -07003883 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3884 return;
3885 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003886 use_tagging_decrypter();
3887
3888 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
3889 // the end of the packet. We can test this to check which encrypter was used.
QUICHE team6987b4a2019-03-15 16:23:04 -07003890 connection_.SetEncrypter(ENCRYPTION_INITIAL,
QUICHE teama6ef0a62019-03-07 20:34:33 -05003891 QuicMakeUnique<TaggingEncrypter>(0x01));
3892 SendStreamDataToPeer(
3893 QuicUtils::GetCryptoStreamId(connection_.transport_version()), "foo", 0,
3894 NO_FIN, nullptr);
3895 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
3896
3897 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
3898 QuicMakeUnique<TaggingEncrypter>(0x02));
3899 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
3900 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
3901 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
3902
3903 {
3904 InSequence s;
3905 EXPECT_CALL(*send_algorithm_,
3906 OnPacketSent(_, _, QuicPacketNumber(3), _, _));
3907 EXPECT_CALL(*send_algorithm_,
3908 OnPacketSent(_, _, QuicPacketNumber(4), _, _));
3909 }
3910
3911 // Manually mark both packets for retransmission.
3912 connection_.RetransmitUnackedPackets(ALL_UNACKED_RETRANSMISSION);
3913
QUICHE team6987b4a2019-03-15 16:23:04 -07003914 // Packet should have been sent with ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05003915 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_previous_packet());
3916
3917 // Packet should have been sent with ENCRYPTION_ZERO_RTT.
3918 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
3919}
3920
3921TEST_P(QuicConnectionTest, SendHandshakeMessages) {
QUICHE teamcd098022019-03-22 18:49:55 -07003922 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3923 return;
3924 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003925 use_tagging_decrypter();
3926 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
3927 // the end of the packet. We can test this to check which encrypter was used.
QUICHE team6987b4a2019-03-15 16:23:04 -07003928 connection_.SetEncrypter(ENCRYPTION_INITIAL,
QUICHE teama6ef0a62019-03-07 20:34:33 -05003929 QuicMakeUnique<TaggingEncrypter>(0x01));
3930
3931 // Attempt to send a handshake message and have the socket block.
3932 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
3933 BlockOnNextWrite();
3934 connection_.SendStreamDataWithString(
3935 QuicUtils::GetCryptoStreamId(connection_.transport_version()), "foo", 0,
3936 NO_FIN);
3937 // The packet should be serialized, but not queued.
3938 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3939
3940 // Switch to the new encrypter.
3941 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
3942 QuicMakeUnique<TaggingEncrypter>(0x02));
3943 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
3944
3945 // Now become writeable and flush the packets.
3946 writer_->SetWritable();
3947 EXPECT_CALL(visitor_, OnCanWrite());
3948 connection_.OnCanWrite();
3949 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3950
3951 // Verify that the handshake packet went out at the null encryption.
3952 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
3953}
3954
3955TEST_P(QuicConnectionTest,
3956 DropRetransmitsForNullEncryptedPacketAfterForwardSecure) {
QUICHE teamcd098022019-03-22 18:49:55 -07003957 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3958 return;
3959 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003960 use_tagging_decrypter();
QUICHE team6987b4a2019-03-15 16:23:04 -07003961 connection_.SetEncrypter(ENCRYPTION_INITIAL,
QUICHE teama6ef0a62019-03-07 20:34:33 -05003962 QuicMakeUnique<TaggingEncrypter>(0x01));
3963 QuicPacketNumber packet_number;
3964 connection_.SendCryptoStreamData();
3965
3966 // Simulate the retransmission alarm firing and the socket blocking.
3967 BlockOnNextWrite();
3968 clock_.AdvanceTime(DefaultRetransmissionTime());
3969 connection_.GetRetransmissionAlarm()->Fire();
3970
3971 // Go forward secure.
3972 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
3973 QuicMakeUnique<TaggingEncrypter>(0x02));
3974 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3975 notifier_.NeuterUnencryptedData();
3976 connection_.NeuterUnencryptedPackets();
3977
3978 EXPECT_EQ(QuicTime::Zero(), connection_.GetRetransmissionAlarm()->deadline());
3979 // Unblock the socket and ensure that no packets are sent.
3980 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3981 writer_->SetWritable();
3982 connection_.OnCanWrite();
3983}
3984
3985TEST_P(QuicConnectionTest, RetransmitPacketsWithInitialEncryption) {
QUICHE teamcd098022019-03-22 18:49:55 -07003986 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3987 return;
3988 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003989 use_tagging_decrypter();
QUICHE team6987b4a2019-03-15 16:23:04 -07003990 connection_.SetEncrypter(ENCRYPTION_INITIAL,
QUICHE teama6ef0a62019-03-07 20:34:33 -05003991 QuicMakeUnique<TaggingEncrypter>(0x01));
QUICHE team6987b4a2019-03-15 16:23:04 -07003992 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003993
3994 SendStreamDataToPeer(
3995 QuicUtils::GetCryptoStreamId(connection_.transport_version()), "foo", 0,
3996 NO_FIN, nullptr);
3997
3998 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
3999 QuicMakeUnique<TaggingEncrypter>(0x02));
4000 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4001
4002 SendStreamDataToPeer(2, "bar", 0, NO_FIN, nullptr);
4003 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4004
4005 connection_.RetransmitUnackedPackets(ALL_INITIAL_RETRANSMISSION);
4006}
4007
4008TEST_P(QuicConnectionTest, BufferNonDecryptablePackets) {
QUICHE teamcd098022019-03-22 18:49:55 -07004009 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4010 return;
4011 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004012 // SetFromConfig is always called after construction from InitializeSession.
4013 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4014 QuicConfig config;
4015 connection_.SetFromConfig(config);
4016 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4017 use_tagging_decrypter();
4018
4019 const uint8_t tag = 0x07;
4020 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
4021 QuicMakeUnique<TaggingEncrypter>(tag));
4022
4023 // Process an encrypted packet which can not yet be decrypted which should
4024 // result in the packet being buffered.
4025 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4026
4027 // Transition to the new encryption state and process another encrypted packet
4028 // which should result in the original packet being processed.
4029 connection_.SetDecrypter(ENCRYPTION_ZERO_RTT,
4030 QuicMakeUnique<StrictTaggingDecrypter>(tag));
4031 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4032 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
4033 QuicMakeUnique<TaggingEncrypter>(tag));
4034 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(2);
4035 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4036
4037 // Finally, process a third packet and note that we do not reprocess the
4038 // buffered packet.
4039 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4040 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4041}
4042
4043TEST_P(QuicConnectionTest, TestRetransmitOrder) {
QUICHE teamcd098022019-03-22 18:49:55 -07004044 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4045 return;
4046 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004047 connection_.SetMaxTailLossProbes(0);
4048
4049 QuicByteCount first_packet_size;
4050 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4051 .WillOnce(SaveArg<3>(&first_packet_size));
4052
4053 connection_.SendStreamDataWithString(3, "first_packet", 0, NO_FIN);
4054 QuicByteCount second_packet_size;
4055 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4056 .WillOnce(SaveArg<3>(&second_packet_size));
4057 connection_.SendStreamDataWithString(3, "second_packet", 12, NO_FIN);
4058 EXPECT_NE(first_packet_size, second_packet_size);
4059 // Advance the clock by huge time to make sure packets will be retransmitted.
4060 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
4061 {
4062 InSequence s;
4063 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, first_packet_size, _));
4064 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, second_packet_size, _));
4065 }
4066 connection_.GetRetransmissionAlarm()->Fire();
4067
4068 // Advance again and expect the packets to be sent again in the same order.
4069 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(20));
4070 {
4071 InSequence s;
4072 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, first_packet_size, _));
4073 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, second_packet_size, _));
4074 }
4075 connection_.GetRetransmissionAlarm()->Fire();
4076}
4077
4078TEST_P(QuicConnectionTest, Buffer100NonDecryptablePacketsThenKeyChange) {
QUICHE teamcd098022019-03-22 18:49:55 -07004079 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4080 return;
4081 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004082 // SetFromConfig is always called after construction from InitializeSession.
4083 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4084 QuicConfig config;
4085 config.set_max_undecryptable_packets(100);
4086 connection_.SetFromConfig(config);
4087 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4088 use_tagging_decrypter();
4089
4090 const uint8_t tag = 0x07;
4091 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
4092 QuicMakeUnique<TaggingEncrypter>(tag));
4093
4094 // Process an encrypted packet which can not yet be decrypted which should
4095 // result in the packet being buffered.
4096 for (uint64_t i = 1; i <= 100; ++i) {
4097 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4098 }
4099
4100 // Transition to the new encryption state and process another encrypted packet
4101 // which should result in the original packets being processed.
4102 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
4103 connection_.SetDecrypter(ENCRYPTION_ZERO_RTT,
4104 QuicMakeUnique<StrictTaggingDecrypter>(tag));
4105 EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
4106 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4107 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
4108 QuicMakeUnique<TaggingEncrypter>(tag));
4109
4110 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(100);
4111 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
4112
4113 // Finally, process a third packet and note that we do not reprocess the
4114 // buffered packet.
4115 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4116 ProcessDataPacketAtLevel(102, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4117}
4118
4119TEST_P(QuicConnectionTest, SetRTOAfterWritingToSocket) {
QUICHE teamcd098022019-03-22 18:49:55 -07004120 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4121 return;
4122 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004123 BlockOnNextWrite();
4124 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4125 // Make sure that RTO is not started when the packet is queued.
4126 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4127
4128 // Test that RTO is started once we write to the socket.
4129 writer_->SetWritable();
4130 connection_.OnCanWrite();
4131 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4132}
4133
4134TEST_P(QuicConnectionTest, DelayRTOWithAckReceipt) {
QUICHE teamcd098022019-03-22 18:49:55 -07004135 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4136 return;
4137 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004138 connection_.SetMaxTailLossProbes(0);
4139
4140 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4141 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
4142 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
4143 connection_.SendStreamDataWithString(3, "bar", 0, NO_FIN);
4144 QuicAlarm* retransmission_alarm = connection_.GetRetransmissionAlarm();
4145 EXPECT_TRUE(retransmission_alarm->IsSet());
4146 EXPECT_EQ(clock_.Now() + DefaultRetransmissionTime(),
4147 retransmission_alarm->deadline());
4148
4149 // Advance the time right before the RTO, then receive an ack for the first
4150 // packet to delay the RTO.
4151 clock_.AdvanceTime(DefaultRetransmissionTime());
4152 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4153 QuicAckFrame ack = InitAckFrame(1);
4154 ProcessAckPacket(&ack);
4155 // Now we have an RTT sample of DefaultRetransmissionTime(500ms),
4156 // so the RTO has increased to 2 * SRTT.
4157 EXPECT_TRUE(retransmission_alarm->IsSet());
4158 EXPECT_EQ(retransmission_alarm->deadline(),
4159 clock_.Now() + 2 * DefaultRetransmissionTime());
4160
4161 // Move forward past the original RTO and ensure the RTO is still pending.
4162 clock_.AdvanceTime(2 * DefaultRetransmissionTime());
4163
4164 // Ensure the second packet gets retransmitted when it finally fires.
4165 EXPECT_TRUE(retransmission_alarm->IsSet());
4166 EXPECT_EQ(retransmission_alarm->deadline(), clock_.ApproximateNow());
4167 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4168 // Manually cancel the alarm to simulate a real test.
4169 connection_.GetRetransmissionAlarm()->Fire();
4170
4171 // The new retransmitted packet number should set the RTO to a larger value
4172 // than previously.
4173 EXPECT_TRUE(retransmission_alarm->IsSet());
4174 QuicTime next_rto_time = retransmission_alarm->deadline();
4175 QuicTime expected_rto_time =
4176 connection_.sent_packet_manager().GetRetransmissionTime();
4177 EXPECT_EQ(next_rto_time, expected_rto_time);
4178}
4179
4180TEST_P(QuicConnectionTest, TestQueued) {
QUICHE teamcd098022019-03-22 18:49:55 -07004181 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4182 return;
4183 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004184 connection_.SetMaxTailLossProbes(0);
4185
4186 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4187 BlockOnNextWrite();
4188 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4189 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4190
4191 // Unblock the writes and actually send.
4192 writer_->SetWritable();
4193 connection_.OnCanWrite();
4194 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4195}
4196
4197TEST_P(QuicConnectionTest, InitialTimeout) {
QUICHE teamcd098022019-03-22 18:49:55 -07004198 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4199 return;
4200 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004201 EXPECT_TRUE(connection_.connected());
4202 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4203 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4204
4205 // SetFromConfig sets the initial timeouts before negotiation.
4206 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4207 QuicConfig config;
4208 connection_.SetFromConfig(config);
4209 // Subtract a second from the idle timeout on the client side.
4210 QuicTime default_timeout =
4211 clock_.ApproximateNow() +
4212 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4213 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
4214
4215 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NETWORK_IDLE_TIMEOUT, _,
4216 ConnectionCloseSource::FROM_SELF));
4217 // Simulate the timeout alarm firing.
4218 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1));
4219 connection_.GetTimeoutAlarm()->Fire();
4220
4221 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4222 EXPECT_FALSE(connection_.connected());
4223
4224 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
4225 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4226 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4227 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4228 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4229}
4230
4231TEST_P(QuicConnectionTest, IdleTimeoutAfterFirstSentPacket) {
QUICHE teamcd098022019-03-22 18:49:55 -07004232 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4233 return;
4234 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004235 EXPECT_TRUE(connection_.connected());
4236 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4237 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4238
4239 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4240 QuicConfig config;
4241 connection_.SetFromConfig(config);
4242 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4243 QuicTime initial_ddl =
4244 clock_.ApproximateNow() +
4245 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4246 EXPECT_EQ(initial_ddl, connection_.GetTimeoutAlarm()->deadline());
4247 EXPECT_TRUE(connection_.connected());
4248
4249 // Advance the time and send the first packet to the peer.
4250 clock_.AdvanceTime(QuicTime::Delta::FromMicroseconds(20));
4251 QuicPacketNumber last_packet;
4252 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4253 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4254 // This will be the updated deadline for the connection to idle time out.
4255 QuicTime new_ddl = clock_.ApproximateNow() +
4256 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4257
4258 // Simulate the timeout alarm firing, the connection should not be closed as
4259 // a new packet has been sent.
4260 EXPECT_CALL(visitor_, OnConnectionClosed(_, _, _)).Times(0);
4261 QuicTime::Delta delay = initial_ddl - clock_.ApproximateNow();
4262 clock_.AdvanceTime(delay);
4263 connection_.GetTimeoutAlarm()->Fire();
4264 // Verify the timeout alarm deadline is updated.
4265 EXPECT_TRUE(connection_.connected());
4266 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4267 EXPECT_EQ(new_ddl, connection_.GetTimeoutAlarm()->deadline());
4268
4269 // Simulate the timeout alarm firing again, the connection now should be
4270 // closed.
4271 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NETWORK_IDLE_TIMEOUT, _,
4272 ConnectionCloseSource::FROM_SELF));
4273 clock_.AdvanceTime(new_ddl - clock_.ApproximateNow());
4274 connection_.GetTimeoutAlarm()->Fire();
4275 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4276 EXPECT_FALSE(connection_.connected());
4277
4278 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
4279 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4280 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4281 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4282 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4283}
4284
4285TEST_P(QuicConnectionTest, IdleTimeoutAfterSendTwoPackets) {
QUICHE teamcd098022019-03-22 18:49:55 -07004286 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4287 return;
4288 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004289 EXPECT_TRUE(connection_.connected());
4290 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4291 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4292
4293 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4294 QuicConfig config;
4295 connection_.SetFromConfig(config);
4296 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4297 QuicTime initial_ddl =
4298 clock_.ApproximateNow() +
4299 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4300 EXPECT_EQ(initial_ddl, connection_.GetTimeoutAlarm()->deadline());
4301 EXPECT_TRUE(connection_.connected());
4302
4303 // Immediately send the first packet, this is a rare case but test code will
4304 // hit this issue often as MockClock used for tests doesn't move with code
4305 // execution until manually adjusted.
4306 QuicPacketNumber last_packet;
4307 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4308 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4309
4310 // Advance the time and send the second packet to the peer.
4311 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
4312 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4313 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
4314
4315 if (GetQuicReloadableFlag(
4316 quic_fix_time_of_first_packet_sent_after_receiving)) {
4317 // Simulate the timeout alarm firing, the connection will be closed.
4318 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NETWORK_IDLE_TIMEOUT, _,
4319 ConnectionCloseSource::FROM_SELF));
4320 clock_.AdvanceTime(initial_ddl - clock_.ApproximateNow());
4321 connection_.GetTimeoutAlarm()->Fire();
4322 } else {
4323 // Simulate the timeout alarm firing, the connection will not be closed.
4324 EXPECT_CALL(visitor_, OnConnectionClosed(_, _, _)).Times(0);
4325 clock_.AdvanceTime(initial_ddl - clock_.ApproximateNow());
4326 connection_.GetTimeoutAlarm()->Fire();
4327 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4328 EXPECT_TRUE(connection_.connected());
4329
4330 // Advance another 20ms, and fire the alarm again. The connection will be
4331 // closed.
4332 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NETWORK_IDLE_TIMEOUT, _,
4333 ConnectionCloseSource::FROM_SELF));
4334 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
4335 connection_.GetTimeoutAlarm()->Fire();
4336 }
4337
4338 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4339 EXPECT_FALSE(connection_.connected());
4340
4341 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
4342 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4343 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4344 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4345 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4346}
4347
4348TEST_P(QuicConnectionTest, HandshakeTimeout) {
QUICHE teamcd098022019-03-22 18:49:55 -07004349 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4350 return;
4351 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004352 // Use a shorter handshake timeout than idle timeout for this test.
4353 const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(5);
4354 connection_.SetNetworkTimeouts(timeout, timeout);
4355 EXPECT_TRUE(connection_.connected());
4356 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4357
4358 QuicTime handshake_timeout =
4359 clock_.ApproximateNow() + timeout - QuicTime::Delta::FromSeconds(1);
4360 EXPECT_EQ(handshake_timeout, connection_.GetTimeoutAlarm()->deadline());
4361 EXPECT_TRUE(connection_.connected());
4362
4363 // Send and ack new data 3 seconds later to lengthen the idle timeout.
4364 SendStreamDataToPeer(
4365 QuicUtils::GetHeadersStreamId(connection_.transport_version()), "GET /",
4366 0, FIN, nullptr);
4367 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(3));
4368 QuicAckFrame frame = InitAckFrame(1);
4369 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4370 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4371 ProcessAckPacket(&frame);
4372
4373 // Fire early to verify it wouldn't timeout yet.
4374 connection_.GetTimeoutAlarm()->Fire();
4375 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4376 EXPECT_TRUE(connection_.connected());
4377
4378 clock_.AdvanceTime(timeout - QuicTime::Delta::FromSeconds(2));
4379
4380 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_HANDSHAKE_TIMEOUT, _,
4381 ConnectionCloseSource::FROM_SELF));
4382 // Simulate the timeout alarm firing.
4383 connection_.GetTimeoutAlarm()->Fire();
4384
4385 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4386 EXPECT_FALSE(connection_.connected());
4387
4388 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
4389 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4390 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4391 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4392}
4393
4394TEST_P(QuicConnectionTest, PingAfterSend) {
QUICHE teamcd098022019-03-22 18:49:55 -07004395 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4396 return;
4397 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004398 EXPECT_TRUE(connection_.connected());
4399 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4400 .WillRepeatedly(Return(true));
4401 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4402
4403 // Advance to 5ms, and send a packet to the peer, which will set
4404 // the ping alarm.
4405 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4406 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4407 SendStreamDataToPeer(
4408 QuicUtils::GetHeadersStreamId(connection_.transport_version()), "GET /",
4409 0, FIN, nullptr);
4410 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4411 EXPECT_EQ(clock_.ApproximateNow() + QuicTime::Delta::FromSeconds(15),
4412 connection_.GetPingAlarm()->deadline());
4413
4414 // Now recevie an ACK of the previous packet, which will move the
4415 // ping alarm forward.
4416 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4417 QuicAckFrame frame = InitAckFrame(1);
4418 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4419 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4420 ProcessAckPacket(&frame);
4421 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4422 // The ping timer is set slightly less than 15 seconds in the future, because
4423 // of the 1s ping timer alarm granularity.
4424 EXPECT_EQ(clock_.ApproximateNow() + QuicTime::Delta::FromSeconds(15) -
4425 QuicTime::Delta::FromMilliseconds(5),
4426 connection_.GetPingAlarm()->deadline());
4427
4428 writer_->Reset();
4429 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15));
4430 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
4431 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
4432 }));
4433 connection_.GetPingAlarm()->Fire();
4434 EXPECT_EQ(1u, writer_->frame_count());
4435 ASSERT_EQ(1u, writer_->ping_frames().size());
4436 writer_->Reset();
4437
4438 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4439 .WillRepeatedly(Return(false));
4440 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4441 SendAckPacketToPeer();
4442
4443 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4444}
4445
4446TEST_P(QuicConnectionTest, ReducedPingTimeout) {
QUICHE teamcd098022019-03-22 18:49:55 -07004447 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4448 return;
4449 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004450 EXPECT_TRUE(connection_.connected());
4451 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4452 .WillRepeatedly(Return(true));
4453 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4454
4455 // Use a reduced ping timeout for this connection.
4456 connection_.set_ping_timeout(QuicTime::Delta::FromSeconds(10));
4457
4458 // Advance to 5ms, and send a packet to the peer, which will set
4459 // the ping alarm.
4460 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4461 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4462 SendStreamDataToPeer(
4463 QuicUtils::GetHeadersStreamId(connection_.transport_version()), "GET /",
4464 0, FIN, nullptr);
4465 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4466 EXPECT_EQ(clock_.ApproximateNow() + QuicTime::Delta::FromSeconds(10),
4467 connection_.GetPingAlarm()->deadline());
4468
4469 // Now recevie an ACK of the previous packet, which will move the
4470 // ping alarm forward.
4471 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4472 QuicAckFrame frame = InitAckFrame(1);
4473 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4474 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4475 ProcessAckPacket(&frame);
4476 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4477 // The ping timer is set slightly less than 10 seconds in the future, because
4478 // of the 1s ping timer alarm granularity.
4479 EXPECT_EQ(clock_.ApproximateNow() + QuicTime::Delta::FromSeconds(10) -
4480 QuicTime::Delta::FromMilliseconds(5),
4481 connection_.GetPingAlarm()->deadline());
4482
4483 writer_->Reset();
4484 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
4485 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
4486 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
4487 }));
4488 connection_.GetPingAlarm()->Fire();
4489 EXPECT_EQ(1u, writer_->frame_count());
4490 ASSERT_EQ(1u, writer_->ping_frames().size());
4491 writer_->Reset();
4492
4493 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4494 .WillRepeatedly(Return(false));
4495 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4496 SendAckPacketToPeer();
4497
4498 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4499}
4500
4501// Tests whether sending an MTU discovery packet to peer successfully causes the
4502// maximum packet size to increase.
4503TEST_P(QuicConnectionTest, SendMtuDiscoveryPacket) {
QUICHE teamcd098022019-03-22 18:49:55 -07004504 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4505 return;
4506 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004507 EXPECT_TRUE(connection_.connected());
4508
4509 // Send an MTU probe.
4510 const size_t new_mtu = kDefaultMaxPacketSize + 100;
4511 QuicByteCount mtu_probe_size;
4512 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4513 .WillOnce(SaveArg<3>(&mtu_probe_size));
4514 connection_.SendMtuDiscoveryPacket(new_mtu);
4515 EXPECT_EQ(new_mtu, mtu_probe_size);
4516 EXPECT_EQ(QuicPacketNumber(1u), creator_->packet_number());
4517
4518 // Send more than MTU worth of data. No acknowledgement was received so far,
4519 // so the MTU should be at its old value.
vasilvvc48c8712019-03-11 13:38:16 -07004520 const std::string data(kDefaultMaxPacketSize + 1, '.');
QUICHE teama6ef0a62019-03-07 20:34:33 -05004521 QuicByteCount size_before_mtu_change;
4522 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4523 .Times(2)
4524 .WillOnce(SaveArg<3>(&size_before_mtu_change))
4525 .WillOnce(Return());
4526 connection_.SendStreamDataWithString(3, data, 0, FIN);
4527 EXPECT_EQ(QuicPacketNumber(3u), creator_->packet_number());
4528 EXPECT_EQ(kDefaultMaxPacketSize, size_before_mtu_change);
4529
4530 // Acknowledge all packets so far.
4531 QuicAckFrame probe_ack = InitAckFrame(3);
4532 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4533 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4534 ProcessAckPacket(&probe_ack);
4535 EXPECT_EQ(new_mtu, connection_.max_packet_length());
4536
4537 // Send the same data again. Check that it fits into a single packet now.
4538 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4539 connection_.SendStreamDataWithString(3, data, 0, FIN);
4540 EXPECT_EQ(QuicPacketNumber(4u), creator_->packet_number());
4541}
4542
4543// Tests whether MTU discovery does not happen when it is not explicitly enabled
4544// by the connection options.
4545TEST_P(QuicConnectionTest, MtuDiscoveryDisabled) {
QUICHE teamcd098022019-03-22 18:49:55 -07004546 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4547 return;
4548 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004549 EXPECT_TRUE(connection_.connected());
4550
4551 const QuicPacketCount packets_between_probes_base = 10;
4552 set_packets_between_probes_base(packets_between_probes_base);
4553
4554 const QuicPacketCount number_of_packets = packets_between_probes_base * 2;
4555 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
4556 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
4557 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4558 EXPECT_EQ(0u, connection_.mtu_probe_count());
4559 }
4560}
4561
4562// Tests whether MTU discovery works when the probe gets acknowledged on the
4563// first try.
4564TEST_P(QuicConnectionTest, MtuDiscoveryEnabled) {
QUICHE teamcd098022019-03-22 18:49:55 -07004565 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4566 return;
4567 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004568 EXPECT_TRUE(connection_.connected());
4569
4570 connection_.EnablePathMtuDiscovery(send_algorithm_);
4571
4572 const QuicPacketCount packets_between_probes_base = 5;
4573 set_packets_between_probes_base(packets_between_probes_base);
4574
4575 // Send enough packets so that the next one triggers path MTU discovery.
4576 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
4577 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
4578 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4579 }
4580
4581 // Trigger the probe.
4582 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
4583 nullptr);
4584 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4585 QuicByteCount probe_size;
4586 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4587 .WillOnce(SaveArg<3>(&probe_size));
4588 connection_.GetMtuDiscoveryAlarm()->Fire();
4589 EXPECT_EQ(kMtuDiscoveryTargetPacketSizeHigh, probe_size);
4590
4591 const QuicPacketNumber probe_packet_number =
4592 FirstSendingPacketNumber() + packets_between_probes_base;
4593 ASSERT_EQ(probe_packet_number, creator_->packet_number());
4594
4595 // Acknowledge all packets sent so far.
4596 QuicAckFrame probe_ack = InitAckFrame(probe_packet_number);
4597 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4598 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4599 ProcessAckPacket(&probe_ack);
4600 EXPECT_EQ(kMtuDiscoveryTargetPacketSizeHigh, connection_.max_packet_length());
4601 EXPECT_EQ(0u, connection_.GetBytesInFlight());
4602
4603 // Send more packets, and ensure that none of them sets the alarm.
4604 for (QuicPacketCount i = 0; i < 4 * packets_between_probes_base; i++) {
4605 SendStreamDataToPeer(3, ".", packets_between_probes_base + i, NO_FIN,
4606 nullptr);
4607 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4608 }
4609
4610 EXPECT_EQ(1u, connection_.mtu_probe_count());
4611}
4612
4613// Tests whether MTU discovery works correctly when the probes never get
4614// acknowledged.
4615TEST_P(QuicConnectionTest, MtuDiscoveryFailed) {
QUICHE teamcd098022019-03-22 18:49:55 -07004616 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4617 return;
4618 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004619 EXPECT_TRUE(connection_.connected());
4620
4621 connection_.EnablePathMtuDiscovery(send_algorithm_);
4622
4623 const QuicTime::Delta rtt = QuicTime::Delta::FromMilliseconds(100);
4624
4625 EXPECT_EQ(kPacketsBetweenMtuProbesBase,
4626 QuicConnectionPeer::GetPacketsBetweenMtuProbes(&connection_));
4627 // Lower the number of probes between packets in order to make the test go
4628 // much faster.
4629 const QuicPacketCount packets_between_probes_base = 5;
4630 set_packets_between_probes_base(packets_between_probes_base);
4631
4632 // This tests sends more packets than strictly necessary to make sure that if
4633 // the connection was to send more discovery packets than needed, those would
4634 // get caught as well.
4635 const QuicPacketCount number_of_packets =
4636 packets_between_probes_base * (1 << (kMtuDiscoveryAttempts + 1));
4637 std::vector<QuicPacketNumber> mtu_discovery_packets;
4638 // Called by the first ack.
4639 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4640 // Called on many acks.
4641 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
4642 .Times(AnyNumber());
4643 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
4644 SendStreamDataToPeer(3, "!", i, NO_FIN, nullptr);
4645 clock_.AdvanceTime(rtt);
4646
4647 // Receive an ACK, which marks all data packets as received, and all MTU
4648 // discovery packets as missing.
4649
4650 QuicAckFrame ack;
4651
4652 if (!mtu_discovery_packets.empty()) {
4653 QuicPacketNumber min_packet = *min_element(mtu_discovery_packets.begin(),
4654 mtu_discovery_packets.end());
4655 QuicPacketNumber max_packet = *max_element(mtu_discovery_packets.begin(),
4656 mtu_discovery_packets.end());
4657 ack.packets.AddRange(QuicPacketNumber(1), min_packet);
4658 ack.packets.AddRange(QuicPacketNumber(max_packet + 1),
4659 creator_->packet_number() + 1);
4660 ack.largest_acked = creator_->packet_number();
4661
4662 } else {
4663 ack.packets.AddRange(QuicPacketNumber(1), creator_->packet_number() + 1);
4664 ack.largest_acked = creator_->packet_number();
4665 }
4666
4667 ProcessAckPacket(&ack);
4668
4669 // Trigger MTU probe if it would be scheduled now.
4670 if (!connection_.GetMtuDiscoveryAlarm()->IsSet()) {
4671 continue;
4672 }
4673
4674 // Fire the alarm. The alarm should cause a packet to be sent.
4675 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4676 connection_.GetMtuDiscoveryAlarm()->Fire();
4677 // Record the packet number of the MTU discovery packet in order to
4678 // mark it as NACK'd.
4679 mtu_discovery_packets.push_back(creator_->packet_number());
4680 }
4681
4682 // Ensure the number of packets between probes grows exponentially by checking
4683 // it against the closed-form expression for the packet number.
4684 ASSERT_EQ(kMtuDiscoveryAttempts, mtu_discovery_packets.size());
4685 for (uint64_t i = 0; i < kMtuDiscoveryAttempts; i++) {
4686 // 2^0 + 2^1 + 2^2 + ... + 2^n = 2^(n + 1) - 1
4687 const QuicPacketCount packets_between_probes =
4688 packets_between_probes_base * ((1 << (i + 1)) - 1);
4689 EXPECT_EQ(QuicPacketNumber(packets_between_probes + (i + 1)),
4690 mtu_discovery_packets[i]);
4691 }
4692
4693 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4694 EXPECT_EQ(kDefaultMaxPacketSize, connection_.max_packet_length());
4695 EXPECT_EQ(kMtuDiscoveryAttempts, connection_.mtu_probe_count());
4696}
4697
4698// Tests whether MTU discovery works when the writer has a limit on how large a
4699// packet can be.
4700TEST_P(QuicConnectionTest, MtuDiscoveryWriterLimited) {
QUICHE teamcd098022019-03-22 18:49:55 -07004701 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4702 return;
4703 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004704 EXPECT_TRUE(connection_.connected());
4705
4706 const QuicByteCount mtu_limit = kMtuDiscoveryTargetPacketSizeHigh - 1;
4707 writer_->set_max_packet_size(mtu_limit);
4708 connection_.EnablePathMtuDiscovery(send_algorithm_);
4709
4710 const QuicPacketCount packets_between_probes_base = 5;
4711 set_packets_between_probes_base(packets_between_probes_base);
4712
4713 // Send enough packets so that the next one triggers path MTU discovery.
4714 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
4715 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
4716 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4717 }
4718
4719 // Trigger the probe.
4720 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
4721 nullptr);
4722 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4723 QuicByteCount probe_size;
4724 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4725 .WillOnce(SaveArg<3>(&probe_size));
4726 connection_.GetMtuDiscoveryAlarm()->Fire();
4727 EXPECT_EQ(mtu_limit, probe_size);
4728
4729 const QuicPacketNumber probe_sequence_number =
4730 FirstSendingPacketNumber() + packets_between_probes_base;
4731 ASSERT_EQ(probe_sequence_number, creator_->packet_number());
4732
4733 // Acknowledge all packets sent so far.
4734 QuicAckFrame probe_ack = InitAckFrame(probe_sequence_number);
4735 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4736 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4737 ProcessAckPacket(&probe_ack);
4738 EXPECT_EQ(mtu_limit, connection_.max_packet_length());
4739 EXPECT_EQ(0u, connection_.GetBytesInFlight());
4740
4741 // Send more packets, and ensure that none of them sets the alarm.
4742 for (QuicPacketCount i = 0; i < 4 * packets_between_probes_base; i++) {
4743 SendStreamDataToPeer(3, ".", packets_between_probes_base + i, NO_FIN,
4744 nullptr);
4745 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4746 }
4747
4748 EXPECT_EQ(1u, connection_.mtu_probe_count());
4749}
4750
4751// Tests whether MTU discovery works when the writer returns an error despite
4752// advertising higher packet length.
4753TEST_P(QuicConnectionTest, MtuDiscoveryWriterFailed) {
QUICHE teamcd098022019-03-22 18:49:55 -07004754 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4755 return;
4756 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004757 EXPECT_TRUE(connection_.connected());
4758
4759 const QuicByteCount mtu_limit = kMtuDiscoveryTargetPacketSizeHigh - 1;
4760 const QuicByteCount initial_mtu = connection_.max_packet_length();
4761 EXPECT_LT(initial_mtu, mtu_limit);
4762 writer_->set_max_packet_size(mtu_limit);
4763 connection_.EnablePathMtuDiscovery(send_algorithm_);
4764
4765 const QuicPacketCount packets_between_probes_base = 5;
4766 set_packets_between_probes_base(packets_between_probes_base);
4767
4768 // Send enough packets so that the next one triggers path MTU discovery.
4769 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
4770 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
4771 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4772 }
4773
4774 // Trigger the probe.
4775 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
4776 nullptr);
4777 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4778 writer_->SimulateNextPacketTooLarge();
4779 connection_.GetMtuDiscoveryAlarm()->Fire();
4780 ASSERT_TRUE(connection_.connected());
4781
4782 // Send more data.
4783 QuicPacketNumber probe_number = creator_->packet_number();
4784 QuicPacketCount extra_packets = packets_between_probes_base * 3;
4785 for (QuicPacketCount i = 0; i < extra_packets; i++) {
4786 connection_.EnsureWritableAndSendStreamData5();
4787 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4788 }
4789
4790 // Acknowledge all packets sent so far, except for the lost probe.
4791 QuicAckFrame probe_ack =
4792 ConstructAckFrame(creator_->packet_number(), probe_number);
4793 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4794 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4795 ProcessAckPacket(&probe_ack);
4796 EXPECT_EQ(initial_mtu, connection_.max_packet_length());
4797
4798 // Send more packets, and ensure that none of them sets the alarm.
4799 for (QuicPacketCount i = 0; i < 4 * packets_between_probes_base; i++) {
4800 connection_.EnsureWritableAndSendStreamData5();
4801 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4802 }
4803
4804 EXPECT_EQ(initial_mtu, connection_.max_packet_length());
4805 EXPECT_EQ(1u, connection_.mtu_probe_count());
4806}
4807
4808TEST_P(QuicConnectionTest, NoMtuDiscoveryAfterConnectionClosed) {
QUICHE teamcd098022019-03-22 18:49:55 -07004809 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4810 return;
4811 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004812 EXPECT_TRUE(connection_.connected());
4813
4814 connection_.EnablePathMtuDiscovery(send_algorithm_);
4815
4816 const QuicPacketCount packets_between_probes_base = 10;
4817 set_packets_between_probes_base(packets_between_probes_base);
4818
4819 // Send enough packets so that the next one triggers path MTU discovery.
4820 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
4821 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
4822 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4823 }
4824
4825 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
4826 nullptr);
4827 EXPECT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4828
4829 EXPECT_CALL(visitor_, OnConnectionClosed(_, _, _));
4830 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
4831 ConnectionCloseBehavior::SILENT_CLOSE);
4832 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4833}
4834
4835TEST_P(QuicConnectionTest, TimeoutAfterSend) {
QUICHE teamcd098022019-03-22 18:49:55 -07004836 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4837 return;
4838 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004839 EXPECT_TRUE(connection_.connected());
4840 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4841 QuicConfig config;
4842 connection_.SetFromConfig(config);
4843 EXPECT_FALSE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
4844
4845 const QuicTime::Delta initial_idle_timeout =
4846 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4847 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
4848 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
4849
4850 // When we send a packet, the timeout will change to 5ms +
4851 // kInitialIdleTimeoutSecs.
4852 clock_.AdvanceTime(five_ms);
4853 SendStreamDataToPeer(
4854 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
4855 0, FIN, nullptr);
4856 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
4857
4858 // Now send more data. This will not move the timeout because
4859 // no data has been received since the previous write.
4860 clock_.AdvanceTime(five_ms);
4861 SendStreamDataToPeer(
4862 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
4863 3, FIN, nullptr);
4864 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
4865
4866 // The original alarm will fire. We should not time out because we had a
4867 // network event at t=5ms. The alarm will reregister.
4868 clock_.AdvanceTime(initial_idle_timeout - five_ms - five_ms);
4869 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
4870 connection_.GetTimeoutAlarm()->Fire();
4871 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4872 EXPECT_TRUE(connection_.connected());
4873 EXPECT_EQ(default_timeout + five_ms,
4874 connection_.GetTimeoutAlarm()->deadline());
4875
4876 // This time, we should time out.
4877 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NETWORK_IDLE_TIMEOUT, _,
4878 ConnectionCloseSource::FROM_SELF));
4879 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4880 clock_.AdvanceTime(five_ms);
4881 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
4882 connection_.GetTimeoutAlarm()->Fire();
4883 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4884 EXPECT_FALSE(connection_.connected());
4885}
4886
4887TEST_P(QuicConnectionTest, TimeoutAfterRetransmission) {
QUICHE teamcd098022019-03-22 18:49:55 -07004888 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4889 return;
4890 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004891 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4892 EXPECT_TRUE(connection_.connected());
4893 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4894 QuicConfig config;
4895 connection_.SetFromConfig(config);
4896 EXPECT_FALSE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
4897
4898 const QuicTime start_time = clock_.Now();
4899 const QuicTime::Delta initial_idle_timeout =
4900 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4901 QuicTime default_timeout = clock_.Now() + initial_idle_timeout;
4902
4903 connection_.SetMaxTailLossProbes(0);
4904 const QuicTime default_retransmission_time =
4905 start_time + DefaultRetransmissionTime();
4906
4907 ASSERT_LT(default_retransmission_time, default_timeout);
4908
4909 // When we send a packet, the timeout will change to 5 ms +
4910 // kInitialIdleTimeoutSecs (but it will not reschedule the alarm).
4911 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
4912 const QuicTime send_time = start_time + five_ms;
4913 clock_.AdvanceTime(five_ms);
4914 ASSERT_EQ(send_time, clock_.Now());
4915 SendStreamDataToPeer(
4916 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
4917 0, FIN, nullptr);
4918 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
4919
4920 // Move forward 5 ms and receive a packet, which will move the timeout
4921 // forward 5 ms more (but will not reschedule the alarm).
4922 const QuicTime receive_time = send_time + five_ms;
4923 clock_.AdvanceTime(receive_time - clock_.Now());
4924 ASSERT_EQ(receive_time, clock_.Now());
4925 ProcessPacket(1);
4926
4927 // Now move forward to the retransmission time and retransmit the
4928 // packet, which should move the timeout forward again (but will not
4929 // reschedule the alarm).
4930 EXPECT_EQ(default_retransmission_time + five_ms,
4931 connection_.GetRetransmissionAlarm()->deadline());
4932 // Simulate the retransmission alarm firing.
4933 const QuicTime rto_time = send_time + DefaultRetransmissionTime();
4934 const QuicTime final_timeout = rto_time + initial_idle_timeout;
4935 clock_.AdvanceTime(rto_time - clock_.Now());
4936 ASSERT_EQ(rto_time, clock_.Now());
4937 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _));
4938 connection_.GetRetransmissionAlarm()->Fire();
4939
4940 // Advance to the original timeout and fire the alarm. The connection should
4941 // timeout, and the alarm should be registered based on the time of the
4942 // retransmission.
4943 clock_.AdvanceTime(default_timeout - clock_.Now());
4944 ASSERT_EQ(default_timeout.ToDebuggingValue(),
4945 clock_.Now().ToDebuggingValue());
4946 EXPECT_EQ(default_timeout, clock_.Now());
4947 connection_.GetTimeoutAlarm()->Fire();
4948 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4949 EXPECT_TRUE(connection_.connected());
4950 ASSERT_EQ(final_timeout.ToDebuggingValue(),
4951 connection_.GetTimeoutAlarm()->deadline().ToDebuggingValue());
4952
4953 // This time, we should time out.
4954 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NETWORK_IDLE_TIMEOUT, _,
4955 ConnectionCloseSource::FROM_SELF));
4956 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4957 clock_.AdvanceTime(final_timeout - clock_.Now());
4958 EXPECT_EQ(connection_.GetTimeoutAlarm()->deadline(), clock_.Now());
4959 EXPECT_EQ(final_timeout, clock_.Now());
4960 connection_.GetTimeoutAlarm()->Fire();
4961 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4962 EXPECT_FALSE(connection_.connected());
4963}
4964
4965TEST_P(QuicConnectionTest, NewTimeoutAfterSendSilentClose) {
QUICHE teamcd098022019-03-22 18:49:55 -07004966 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4967 return;
4968 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004969 // Same test as above, but complete a handshake which enables silent close,
4970 // causing no connection close packet to be sent.
4971 EXPECT_TRUE(connection_.connected());
4972 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4973 QuicConfig config;
4974
4975 // Create a handshake message that also enables silent close.
4976 CryptoHandshakeMessage msg;
vasilvvc48c8712019-03-11 13:38:16 -07004977 std::string error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004978 QuicConfig client_config;
4979 client_config.SetInitialStreamFlowControlWindowToSend(
4980 kInitialStreamFlowControlWindowForTest);
4981 client_config.SetInitialSessionFlowControlWindowToSend(
4982 kInitialSessionFlowControlWindowForTest);
4983 client_config.SetIdleNetworkTimeout(
4984 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs),
4985 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs));
4986 client_config.ToHandshakeMessage(&msg);
4987 const QuicErrorCode error =
4988 config.ProcessPeerHello(msg, CLIENT, &error_details);
4989 EXPECT_EQ(QUIC_NO_ERROR, error);
4990
4991 connection_.SetFromConfig(config);
4992 EXPECT_TRUE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
4993
4994 const QuicTime::Delta default_idle_timeout =
4995 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs - 1);
4996 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
4997 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
4998
4999 // When we send a packet, the timeout will change to 5ms +
5000 // kInitialIdleTimeoutSecs.
5001 clock_.AdvanceTime(five_ms);
5002 SendStreamDataToPeer(
5003 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5004 0, FIN, nullptr);
5005 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5006
5007 // Now send more data. This will not move the timeout because
5008 // no data has been received since the previous write.
5009 clock_.AdvanceTime(five_ms);
5010 SendStreamDataToPeer(
5011 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5012 3, FIN, nullptr);
5013 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5014
5015 // The original alarm will fire. We should not time out because we had a
5016 // network event at t=5ms. The alarm will reregister.
5017 clock_.AdvanceTime(default_idle_timeout - five_ms - five_ms);
5018 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
5019 connection_.GetTimeoutAlarm()->Fire();
5020 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5021 EXPECT_TRUE(connection_.connected());
5022 EXPECT_EQ(default_timeout + five_ms,
5023 connection_.GetTimeoutAlarm()->deadline());
5024
5025 // This time, we should time out.
5026 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NETWORK_IDLE_TIMEOUT, _,
5027 ConnectionCloseSource::FROM_SELF));
5028 clock_.AdvanceTime(five_ms);
5029 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5030 connection_.GetTimeoutAlarm()->Fire();
5031 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5032 EXPECT_FALSE(connection_.connected());
5033}
5034
5035TEST_P(QuicConnectionTest, TimeoutAfterSendSilentCloseAndTLP) {
QUICHE teamcd098022019-03-22 18:49:55 -07005036 if (connection_.SupportsMultiplePacketNumberSpaces()) {
5037 return;
5038 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005039 // Same test as above, but complete a handshake which enables silent close,
5040 // but sending TLPs causes the connection close to be sent.
5041 EXPECT_TRUE(connection_.connected());
5042 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5043 QuicConfig config;
5044
5045 // Create a handshake message that also enables silent close.
5046 CryptoHandshakeMessage msg;
vasilvvc48c8712019-03-11 13:38:16 -07005047 std::string error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005048 QuicConfig client_config;
5049 client_config.SetInitialStreamFlowControlWindowToSend(
5050 kInitialStreamFlowControlWindowForTest);
5051 client_config.SetInitialSessionFlowControlWindowToSend(
5052 kInitialSessionFlowControlWindowForTest);
5053 client_config.SetIdleNetworkTimeout(
5054 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs),
5055 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs));
5056 client_config.ToHandshakeMessage(&msg);
5057 const QuicErrorCode error =
5058 config.ProcessPeerHello(msg, CLIENT, &error_details);
5059 EXPECT_EQ(QUIC_NO_ERROR, error);
5060
5061 connection_.SetFromConfig(config);
5062 EXPECT_TRUE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
5063
5064 const QuicTime::Delta default_idle_timeout =
5065 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs - 1);
5066 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5067 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5068
5069 // When we send a packet, the timeout will change to 5ms +
5070 // kInitialIdleTimeoutSecs.
5071 clock_.AdvanceTime(five_ms);
5072 SendStreamDataToPeer(
5073 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5074 0, FIN, nullptr);
5075 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5076
5077 // Retransmit the packet via tail loss probe.
5078 clock_.AdvanceTime(connection_.GetRetransmissionAlarm()->deadline() -
5079 clock_.Now());
5080 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _));
5081 connection_.GetRetransmissionAlarm()->Fire();
5082
5083 // This time, we should time out and send a connection close due to the TLP.
5084 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NETWORK_IDLE_TIMEOUT, _,
5085 ConnectionCloseSource::FROM_SELF));
5086 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5087 clock_.AdvanceTime(connection_.GetTimeoutAlarm()->deadline() -
5088 clock_.ApproximateNow() + five_ms);
5089 connection_.GetTimeoutAlarm()->Fire();
5090 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5091 EXPECT_FALSE(connection_.connected());
5092}
5093
5094TEST_P(QuicConnectionTest, TimeoutAfterSendSilentCloseWithOpenStreams) {
QUICHE teamcd098022019-03-22 18:49:55 -07005095 if (connection_.SupportsMultiplePacketNumberSpaces()) {
5096 return;
5097 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005098 // Same test as above, but complete a handshake which enables silent close,
5099 // but having open streams causes the connection close to be sent.
5100 EXPECT_TRUE(connection_.connected());
5101 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5102 QuicConfig config;
5103
5104 // Create a handshake message that also enables silent close.
5105 CryptoHandshakeMessage msg;
vasilvvc48c8712019-03-11 13:38:16 -07005106 std::string error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005107 QuicConfig client_config;
5108 client_config.SetInitialStreamFlowControlWindowToSend(
5109 kInitialStreamFlowControlWindowForTest);
5110 client_config.SetInitialSessionFlowControlWindowToSend(
5111 kInitialSessionFlowControlWindowForTest);
5112 client_config.SetIdleNetworkTimeout(
5113 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs),
5114 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs));
5115 client_config.ToHandshakeMessage(&msg);
5116 const QuicErrorCode error =
5117 config.ProcessPeerHello(msg, CLIENT, &error_details);
5118 EXPECT_EQ(QUIC_NO_ERROR, error);
5119
5120 connection_.SetFromConfig(config);
5121 EXPECT_TRUE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
5122
5123 const QuicTime::Delta default_idle_timeout =
5124 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs - 1);
5125 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5126 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5127
5128 // When we send a packet, the timeout will change to 5ms +
5129 // kInitialIdleTimeoutSecs.
5130 clock_.AdvanceTime(five_ms);
5131 SendStreamDataToPeer(
5132 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5133 0, FIN, nullptr);
5134 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5135
5136 // Indicate streams are still open.
5137 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
5138 .WillRepeatedly(Return(true));
5139
5140 // This time, we should time out and send a connection close due to the TLP.
5141 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NETWORK_IDLE_TIMEOUT, _,
5142 ConnectionCloseSource::FROM_SELF));
5143 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5144 clock_.AdvanceTime(connection_.GetTimeoutAlarm()->deadline() -
5145 clock_.ApproximateNow() + five_ms);
5146 connection_.GetTimeoutAlarm()->Fire();
5147 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5148 EXPECT_FALSE(connection_.connected());
5149}
5150
5151TEST_P(QuicConnectionTest, TimeoutAfterReceive) {
QUICHE teamcd098022019-03-22 18:49:55 -07005152 if (connection_.SupportsMultiplePacketNumberSpaces()) {
5153 return;
5154 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005155 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5156 EXPECT_TRUE(connection_.connected());
5157 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5158 QuicConfig config;
5159 connection_.SetFromConfig(config);
5160 EXPECT_FALSE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
5161
5162 const QuicTime::Delta initial_idle_timeout =
5163 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5164 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5165 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
5166
5167 connection_.SendStreamDataWithString(
5168 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5169 0, NO_FIN);
5170 connection_.SendStreamDataWithString(
5171 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5172 3, NO_FIN);
5173
5174 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5175 clock_.AdvanceTime(five_ms);
5176
5177 // When we receive a packet, the timeout will change to 5ms +
5178 // kInitialIdleTimeoutSecs.
5179 QuicAckFrame ack = InitAckFrame(2);
5180 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5181 ProcessAckPacket(&ack);
5182
5183 // The original alarm will fire. We should not time out because we had a
5184 // network event at t=5ms. The alarm will reregister.
5185 clock_.AdvanceTime(initial_idle_timeout - five_ms);
5186 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
5187 connection_.GetTimeoutAlarm()->Fire();
5188 EXPECT_TRUE(connection_.connected());
5189 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5190 EXPECT_EQ(default_timeout + five_ms,
5191 connection_.GetTimeoutAlarm()->deadline());
5192
5193 // This time, we should time out.
5194 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NETWORK_IDLE_TIMEOUT, _,
5195 ConnectionCloseSource::FROM_SELF));
5196 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5197 clock_.AdvanceTime(five_ms);
5198 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5199 connection_.GetTimeoutAlarm()->Fire();
5200 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5201 EXPECT_FALSE(connection_.connected());
5202}
5203
5204TEST_P(QuicConnectionTest, TimeoutAfterReceiveNotSendWhenUnacked) {
QUICHE teamcd098022019-03-22 18:49:55 -07005205 if (connection_.SupportsMultiplePacketNumberSpaces()) {
5206 return;
5207 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005208 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5209 EXPECT_TRUE(connection_.connected());
5210 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5211 QuicConfig config;
5212 connection_.SetFromConfig(config);
5213 EXPECT_FALSE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
5214
5215 const QuicTime::Delta initial_idle_timeout =
5216 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5217 connection_.SetNetworkTimeouts(
5218 QuicTime::Delta::Infinite(),
5219 initial_idle_timeout + QuicTime::Delta::FromSeconds(1));
5220 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5221 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
5222
5223 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5224 connection_.SendStreamDataWithString(
5225 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5226 0, NO_FIN);
5227 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5228 connection_.SendStreamDataWithString(
5229 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5230 3, NO_FIN);
5231
5232 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5233
5234 clock_.AdvanceTime(five_ms);
5235
5236 // When we receive a packet, the timeout will change to 5ms +
5237 // kInitialIdleTimeoutSecs.
5238 QuicAckFrame ack = InitAckFrame(2);
5239 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5240 ProcessAckPacket(&ack);
5241
5242 // The original alarm will fire. We should not time out because we had a
5243 // network event at t=5ms. The alarm will reregister.
5244 clock_.AdvanceTime(initial_idle_timeout - five_ms);
5245 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
5246 connection_.GetTimeoutAlarm()->Fire();
5247 EXPECT_TRUE(connection_.connected());
5248 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5249 EXPECT_EQ(default_timeout + five_ms,
5250 connection_.GetTimeoutAlarm()->deadline());
5251
5252 // Now, send packets while advancing the time and verify that the connection
5253 // eventually times out.
5254 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NETWORK_IDLE_TIMEOUT, _,
5255 ConnectionCloseSource::FROM_SELF));
5256 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
5257 for (int i = 0; i < 100 && connection_.connected(); ++i) {
5258 QUIC_LOG(INFO) << "sending data packet";
5259 connection_.SendStreamDataWithString(
5260 GetNthClientInitiatedStreamId(1, connection_.transport_version()),
5261 "foo", 0, NO_FIN);
5262 connection_.GetTimeoutAlarm()->Fire();
5263 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
5264 }
5265 EXPECT_FALSE(connection_.connected());
5266 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5267}
5268
5269TEST_P(QuicConnectionTest, TimeoutAfter5ClientRTOs) {
QUICHE teamcd098022019-03-22 18:49:55 -07005270 if (connection_.SupportsMultiplePacketNumberSpaces()) {
5271 return;
5272 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005273 connection_.SetMaxTailLossProbes(2);
5274 EXPECT_TRUE(connection_.connected());
5275 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5276 QuicConfig config;
5277 QuicTagVector connection_options;
5278 connection_options.push_back(k5RTO);
5279 config.SetConnectionOptionsToSend(connection_options);
5280 connection_.SetFromConfig(config);
5281
5282 // Send stream data.
5283 SendStreamDataToPeer(
5284 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5285 0, FIN, nullptr);
5286
5287 // Fire the retransmission alarm 6 times, twice for TLP and 4 times for RTO.
5288 for (int i = 0; i < 6; ++i) {
5289 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5290 connection_.GetRetransmissionAlarm()->Fire();
5291 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5292 EXPECT_TRUE(connection_.connected());
5293 }
5294
5295 EXPECT_EQ(2u, connection_.sent_packet_manager().GetConsecutiveTlpCount());
5296 EXPECT_EQ(4u, connection_.sent_packet_manager().GetConsecutiveRtoCount());
5297 // This time, we should time out.
5298 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_TOO_MANY_RTOS, _,
5299 ConnectionCloseSource::FROM_SELF));
5300 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5301 connection_.GetRetransmissionAlarm()->Fire();
5302 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5303 EXPECT_FALSE(connection_.connected());
5304}
5305
5306TEST_P(QuicConnectionTest, SendScheduler) {
QUICHE teamcd098022019-03-22 18:49:55 -07005307 if (connection_.SupportsMultiplePacketNumberSpaces()) {
5308 return;
5309 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005310 // Test that if we send a packet without delay, it is not queued.
5311 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
QUICHE team8c1daa22019-03-13 08:33:41 -07005312 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07005313 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005314 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
5315 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
QUICHE team6987b4a2019-03-15 16:23:04 -07005316 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05005317 HAS_RETRANSMITTABLE_DATA, false, false);
5318 EXPECT_EQ(0u, connection_.NumQueuedPackets());
5319}
5320
5321TEST_P(QuicConnectionTest, FailToSendFirstPacket) {
QUICHE teamcd098022019-03-22 18:49:55 -07005322 if (connection_.SupportsMultiplePacketNumberSpaces()) {
5323 return;
5324 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005325 // Test that the connection does not crash when it fails to send the first
5326 // packet at which point self_address_ might be uninitialized.
5327 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
5328 EXPECT_CALL(visitor_, OnConnectionClosed(_, _, _)).Times(1);
QUICHE team8c1daa22019-03-13 08:33:41 -07005329 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07005330 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005331 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
5332 writer_->SetShouldWriteFail();
QUICHE team6987b4a2019-03-15 16:23:04 -07005333 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05005334 HAS_RETRANSMITTABLE_DATA, false, false);
5335}
5336
5337TEST_P(QuicConnectionTest, SendSchedulerEAGAIN) {
QUICHE teamcd098022019-03-22 18:49:55 -07005338 if (connection_.SupportsMultiplePacketNumberSpaces()) {
5339 return;
5340 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005341 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
QUICHE team8c1daa22019-03-13 08:33:41 -07005342 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07005343 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005344 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
5345 BlockOnNextWrite();
5346 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _))
5347 .Times(0);
QUICHE team6987b4a2019-03-15 16:23:04 -07005348 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05005349 HAS_RETRANSMITTABLE_DATA, false, false);
5350 EXPECT_EQ(1u, connection_.NumQueuedPackets());
5351}
5352
5353TEST_P(QuicConnectionTest, TestQueueLimitsOnSendStreamData) {
QUICHE teamcd098022019-03-22 18:49:55 -07005354 if (connection_.SupportsMultiplePacketNumberSpaces()) {
5355 return;
5356 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005357 // All packets carry version info till version is negotiated.
5358 size_t payload_length;
5359 size_t length = GetPacketLengthForOneStream(
5360 connection_.version().transport_version, kIncludeVersion,
5361 !kIncludeDiversificationNonce, PACKET_8BYTE_CONNECTION_ID,
5362 PACKET_0BYTE_CONNECTION_ID,
5363 QuicPacketCreatorPeer::GetPacketNumberLength(creator_),
5364 QuicPacketCreatorPeer::GetRetryTokenLengthLength(creator_),
5365 QuicPacketCreatorPeer::GetLengthLength(creator_), &payload_length);
5366 connection_.SetMaxPacketLength(length);
5367
5368 // Queue the first packet.
5369 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(testing::Return(false));
vasilvvc48c8712019-03-11 13:38:16 -07005370 const std::string payload(payload_length, 'a');
QUICHE teama6ef0a62019-03-07 20:34:33 -05005371 EXPECT_EQ(0u, connection_.SendStreamDataWithString(3, payload, 0, NO_FIN)
5372 .bytes_consumed);
5373 EXPECT_EQ(0u, connection_.NumQueuedPackets());
5374}
5375
5376TEST_P(QuicConnectionTest, LoopThroughSendingPackets) {
QUICHE teamcd098022019-03-22 18:49:55 -07005377 if (connection_.SupportsMultiplePacketNumberSpaces()) {
5378 return;
5379 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005380 // All packets carry version info till version is negotiated.
5381 size_t payload_length;
5382
5383 // Number of packets this test generates. The goal is to have
5384 // kPacketCount packets, each the same size (overhead and payload).
5385 // The payload will vary depending on the overhead (which in turn
5386 // varies per the QUIC packet encoding rules).
5387 const int kPacketCount = 7;
5388
5389 // Get the basic packet size. This assumes, among other things, a
5390 // stream offset of 0.
5391 size_t length = GetPacketLengthForOneStream(
5392 connection_.version().transport_version, kIncludeVersion,
5393 !kIncludeDiversificationNonce, PACKET_8BYTE_CONNECTION_ID,
5394 PACKET_0BYTE_CONNECTION_ID,
5395 QuicPacketCreatorPeer::GetPacketNumberLength(creator_),
5396 QuicPacketCreatorPeer::GetRetryTokenLengthLength(creator_),
5397 QuicPacketCreatorPeer::GetLengthLength(creator_), &payload_length);
5398 // GetPacketLengthForOneStream() assumes a stream offset of 0 in determining
5399 // packet length. The size of the offset field in a stream frame is
5400 // 0 for offset 0, and 2 for non-zero offsets up through 16K (for
5401 // versions other than 99) and 1 for non-zero offsets through 16K
5402 // for version 99. Increase the length by 1 or 2, as apporpriate, so
5403 // that subsequent packets containing subsequent stream frames with
5404 // non-zero offsets will fit within the packet length.
5405 if (connection_.version().transport_version == QUIC_VERSION_99) {
5406 length = length + 1;
5407 } else {
5408 length = length + 2;
5409 }
5410
5411 connection_.SetMaxPacketLength(length);
5412
5413 // Queue the first packet.
5414 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5415 .Times(kPacketCount);
5416
5417 size_t total_payload_length = payload_length * kPacketCount;
5418 // The first frame of the stream is at offset 0. When the offset is
5419 // 0, it is not included in the stream frame. Increase the total
5420 // payload so that the "missing" offset byte in the first packet is
5421 // occupied by a payload byte. The net result is that each of the N
5422 // packets of the test will contain a single stream frame, each of
5423 // which will be the same size (overhead + data).
5424 if (connection_.version().transport_version == QUIC_VERSION_99) {
5425 // Version 99 encodes the offset in 1 byte for the scope of this test.
5426 total_payload_length = total_payload_length + 1;
5427 } else {
5428 // Versions other than 99 encode the offset in 2 bytes for the
5429 // scope of this test.
5430 total_payload_length = total_payload_length + 2;
5431 }
vasilvvc48c8712019-03-11 13:38:16 -07005432 const std::string payload(total_payload_length, 'a');
QUICHE teama6ef0a62019-03-07 20:34:33 -05005433
5434 EXPECT_EQ(payload.size(),
5435 connection_
5436 .SendStreamDataWithString(QuicUtils::GetCryptoStreamId(
5437 connection_.transport_version()),
5438 payload, 0, NO_FIN)
5439 .bytes_consumed);
5440}
5441
5442TEST_P(QuicConnectionTest, LoopThroughSendingPacketsWithTruncation) {
QUICHE teamcd098022019-03-22 18:49:55 -07005443 if (connection_.SupportsMultiplePacketNumberSpaces()) {
5444 return;
5445 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005446 set_perspective(Perspective::IS_SERVER);
5447 if (GetParam().version.transport_version <= QUIC_VERSION_43) {
5448 // For IETF QUIC, encryption level will be switched to FORWARD_SECURE in
5449 // SendStreamDataWithString.
5450 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
5451 }
5452 // Set up a larger payload than will fit in one packet.
vasilvvc48c8712019-03-11 13:38:16 -07005453 const std::string payload(connection_.max_packet_length(), 'a');
QUICHE teama6ef0a62019-03-07 20:34:33 -05005454 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
5455
5456 // Now send some packets with no truncation.
5457 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
5458 EXPECT_EQ(payload.size(),
5459 connection_.SendStreamDataWithString(3, payload, 0, NO_FIN)
5460 .bytes_consumed);
5461 // Track the size of the second packet here. The overhead will be the largest
5462 // we see in this test, due to the non-truncated connection id.
5463 size_t non_truncated_packet_size = writer_->last_packet_size();
5464
5465 // Change to a 0 byte connection id.
5466 QuicConfig config;
5467 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
5468 connection_.SetFromConfig(config);
5469 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
5470 EXPECT_EQ(payload.size(),
5471 connection_.SendStreamDataWithString(3, payload, 1350, NO_FIN)
5472 .bytes_consumed);
5473 if (connection_.transport_version() > QUIC_VERSION_43) {
5474 // Short header packets sent from server omit connection ID already, and
5475 // stream offset size increases from 0 to 2.
5476 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() - 2);
5477 } else {
5478 // Just like above, we save 8 bytes on payload, and 8 on truncation. -2
5479 // because stream offset size is 2 instead of 0.
5480 EXPECT_EQ(non_truncated_packet_size,
5481 writer_->last_packet_size() + 8 * 2 - 2);
5482 }
5483}
5484
5485TEST_P(QuicConnectionTest, SendDelayedAck) {
QUICHE teamcd098022019-03-22 18:49:55 -07005486 if (connection_.SupportsMultiplePacketNumberSpaces()) {
5487 return;
5488 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005489 QuicTime ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
5490 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5491 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5492 const uint8_t tag = 0x07;
5493 connection_.SetDecrypter(ENCRYPTION_ZERO_RTT,
5494 QuicMakeUnique<StrictTaggingDecrypter>(tag));
5495 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
5496 QuicMakeUnique<TaggingEncrypter>(tag));
5497 // Process a packet from the non-crypto stream.
5498 frame1_.stream_id = 3;
5499
5500 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07005501 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005502 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5503 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5504
5505 // Check if delayed ack timer is running for the expected interval.
5506 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5507 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5508 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07005509 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005510 connection_.GetAckAlarm()->Fire();
5511 // Check that ack is sent and that delayed ack alarm is reset.
5512 if (GetParam().no_stop_waiting) {
5513 EXPECT_EQ(1u, writer_->frame_count());
5514 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
5515 } else {
5516 EXPECT_EQ(2u, writer_->frame_count());
5517 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
5518 }
5519 EXPECT_FALSE(writer_->ack_frames().empty());
5520 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5521}
5522
5523TEST_P(QuicConnectionTest, SendDelayedAfterQuiescence) {
QUICHE teamcd098022019-03-22 18:49:55 -07005524 if (connection_.SupportsMultiplePacketNumberSpaces()) {
5525 return;
5526 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005527 QuicConnectionPeer::SetFastAckAfterQuiescence(&connection_, true);
5528
5529 // The beginning of the connection counts as quiescence.
5530 QuicTime ack_time =
5531 clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
5532 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5533 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5534 const uint8_t tag = 0x07;
5535 connection_.SetDecrypter(ENCRYPTION_ZERO_RTT,
5536 QuicMakeUnique<StrictTaggingDecrypter>(tag));
5537 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
5538 QuicMakeUnique<TaggingEncrypter>(tag));
5539 // Process a packet from the non-crypto stream.
5540 frame1_.stream_id = 3;
5541
5542 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07005543 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005544 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5545 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5546
5547 // Check if delayed ack timer is running for the expected interval.
5548 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5549 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5550 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07005551 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005552 connection_.GetAckAlarm()->Fire();
5553 // Check that ack is sent and that delayed ack alarm is reset.
5554 if (GetParam().no_stop_waiting) {
5555 EXPECT_EQ(1u, writer_->frame_count());
5556 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
5557 } else {
5558 EXPECT_EQ(2u, writer_->frame_count());
5559 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
5560 }
5561 EXPECT_FALSE(writer_->ack_frames().empty());
5562 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5563
5564 // Process another packet immedately after sending the ack and expect the
5565 // ack alarm to be set delayed ack time in the future.
5566 ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
5567 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5568 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5569
5570 // Check if delayed ack timer is running for the expected interval.
5571 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5572 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5573 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07005574 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005575 connection_.GetAckAlarm()->Fire();
5576 // Check that ack is sent and that delayed ack alarm is reset.
5577 if (GetParam().no_stop_waiting) {
5578 EXPECT_EQ(1u, writer_->frame_count());
5579 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
5580 } else {
5581 EXPECT_EQ(2u, writer_->frame_count());
5582 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
5583 }
5584 EXPECT_FALSE(writer_->ack_frames().empty());
5585 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5586
5587 // Wait 1 second and enesure the ack alarm is set to 1ms in the future.
5588 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
5589 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
5590 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5591 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5592
5593 // Check if delayed ack timer is running for the expected interval.
5594 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5595 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5596}
5597
5598TEST_P(QuicConnectionTest, SendDelayedAckDecimation) {
QUICHE teamcd098022019-03-22 18:49:55 -07005599 if (connection_.SupportsMultiplePacketNumberSpaces()) {
5600 return;
5601 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005602 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
5603 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION);
5604
5605 const size_t kMinRttMs = 40;
5606 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
5607 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
5608 QuicTime::Delta::Zero(), QuicTime::Zero());
5609 // The ack time should be based on min_rtt/4, since it's less than the
5610 // default delayed ack time.
5611 QuicTime ack_time = clock_.ApproximateNow() +
5612 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
5613 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5614 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5615 const uint8_t tag = 0x07;
5616 connection_.SetDecrypter(ENCRYPTION_ZERO_RTT,
5617 QuicMakeUnique<StrictTaggingDecrypter>(tag));
5618 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
5619 QuicMakeUnique<TaggingEncrypter>(tag));
5620 // Process a packet from the non-crypto stream.
5621 frame1_.stream_id = 3;
5622
5623 // Process all the initial packets in order so there aren't missing packets.
5624 uint64_t kFirstDecimatedPacket = 101;
5625 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
5626 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5627 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5628 }
5629 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5630 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07005631 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005632 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5633 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
5634 ENCRYPTION_ZERO_RTT);
5635
5636 // Check if delayed ack timer is running for the expected interval.
5637 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5638 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5639
5640 // The 10th received packet causes an ack to be sent.
5641 for (int i = 0; i < 9; ++i) {
5642 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5643 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5644 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
5645 ENCRYPTION_ZERO_RTT);
5646 }
5647 // Check that ack is sent and that delayed ack alarm is reset.
5648 if (GetParam().no_stop_waiting) {
5649 EXPECT_EQ(1u, writer_->frame_count());
5650 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
5651 } else {
5652 EXPECT_EQ(2u, writer_->frame_count());
5653 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
5654 }
5655 EXPECT_FALSE(writer_->ack_frames().empty());
5656 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5657}
5658
5659TEST_P(QuicConnectionTest, SendDelayedAckAckDecimationAfterQuiescence) {
QUICHE teamcd098022019-03-22 18:49:55 -07005660 if (connection_.SupportsMultiplePacketNumberSpaces()) {
5661 return;
5662 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005663 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
5664 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION);
5665 QuicConnectionPeer::SetFastAckAfterQuiescence(&connection_, true);
5666
5667 const size_t kMinRttMs = 40;
5668 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
5669 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
5670 QuicTime::Delta::Zero(), QuicTime::Zero());
5671
5672 // The beginning of the connection counts as quiescence.
5673 QuicTime ack_time =
5674 clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
5675 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5676 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5677 const uint8_t tag = 0x07;
5678 connection_.SetDecrypter(ENCRYPTION_ZERO_RTT,
5679 QuicMakeUnique<StrictTaggingDecrypter>(tag));
5680 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
5681 QuicMakeUnique<TaggingEncrypter>(tag));
5682 // Process a packet from the non-crypto stream.
5683 frame1_.stream_id = 3;
5684
5685 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07005686 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005687 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5688 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5689
5690 // Check if delayed ack timer is running for the expected interval.
5691 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5692 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5693 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07005694 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005695 connection_.GetAckAlarm()->Fire();
5696 // Check that ack is sent and that delayed ack alarm is reset.
5697 if (GetParam().no_stop_waiting) {
5698 EXPECT_EQ(1u, writer_->frame_count());
5699 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
5700 } else {
5701 EXPECT_EQ(2u, writer_->frame_count());
5702 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
5703 }
5704 EXPECT_FALSE(writer_->ack_frames().empty());
5705 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5706
5707 // Process another packet immedately after sending the ack and expect the
5708 // ack alarm to be set delayed ack time in the future.
5709 ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
5710 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5711 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5712
5713 // Check if delayed ack timer is running for the expected interval.
5714 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5715 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5716 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07005717 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005718 connection_.GetAckAlarm()->Fire();
5719 // Check that ack is sent and that delayed ack alarm is reset.
5720 if (GetParam().no_stop_waiting) {
5721 EXPECT_EQ(1u, writer_->frame_count());
5722 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
5723 } else {
5724 EXPECT_EQ(2u, writer_->frame_count());
5725 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
5726 }
5727 EXPECT_FALSE(writer_->ack_frames().empty());
5728 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5729
5730 // Wait 1 second and enesure the ack alarm is set to 1ms in the future.
5731 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
5732 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
5733 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5734 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5735
5736 // Check if delayed ack timer is running for the expected interval.
5737 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5738 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5739
5740 // Process enough packets to get into ack decimation behavior.
5741 // The ack time should be based on min_rtt/4, since it's less than the
5742 // default delayed ack time.
5743 ack_time = clock_.ApproximateNow() +
5744 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
5745 uint64_t kFirstDecimatedPacket = 101;
5746 for (unsigned int i = 0; i < kFirstDecimatedPacket - 4; ++i) {
5747 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5748 ProcessDataPacketAtLevel(4 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5749 }
5750 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5751 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07005752 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005753 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5754 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
5755 ENCRYPTION_ZERO_RTT);
5756
5757 // Check if delayed ack timer is running for the expected interval.
5758 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5759 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5760
5761 // The 10th received packet causes an ack to be sent.
5762 for (int i = 0; i < 9; ++i) {
5763 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5764 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5765 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
5766 ENCRYPTION_ZERO_RTT);
5767 }
5768 // Check that ack is sent and that delayed ack alarm is reset.
5769 if (GetParam().no_stop_waiting) {
5770 EXPECT_EQ(1u, writer_->frame_count());
5771 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
5772 } else {
5773 EXPECT_EQ(2u, writer_->frame_count());
5774 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
5775 }
5776 EXPECT_FALSE(writer_->ack_frames().empty());
5777 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5778
5779 // Wait 1 second and enesure the ack alarm is set to 1ms in the future.
5780 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
5781 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
5782 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5783 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 10, !kHasStopWaiting,
5784 ENCRYPTION_ZERO_RTT);
5785
5786 // Check if delayed ack timer is running for the expected interval.
5787 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5788 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5789}
5790
5791TEST_P(QuicConnectionTest, SendDelayedAckDecimationUnlimitedAggregation) {
QUICHE teamcd098022019-03-22 18:49:55 -07005792 if (connection_.SupportsMultiplePacketNumberSpaces()) {
5793 return;
5794 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005795 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
5796 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5797 QuicConfig config;
5798 QuicTagVector connection_options;
5799 connection_options.push_back(kACKD);
5800 // No limit on the number of packets received before sending an ack.
5801 connection_options.push_back(kAKDU);
5802 config.SetConnectionOptionsToSend(connection_options);
5803 connection_.SetFromConfig(config);
5804
5805 const size_t kMinRttMs = 40;
5806 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
5807 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
5808 QuicTime::Delta::Zero(), QuicTime::Zero());
5809 // The ack time should be based on min_rtt/4, since it's less than the
5810 // default delayed ack time.
5811 QuicTime ack_time = clock_.ApproximateNow() +
5812 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
5813 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5814 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5815 const uint8_t tag = 0x07;
5816 connection_.SetDecrypter(ENCRYPTION_ZERO_RTT,
5817 QuicMakeUnique<StrictTaggingDecrypter>(tag));
5818 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
5819 QuicMakeUnique<TaggingEncrypter>(tag));
5820 // Process a packet from the non-crypto stream.
5821 frame1_.stream_id = 3;
5822
5823 // Process all the initial packets in order so there aren't missing packets.
5824 uint64_t kFirstDecimatedPacket = 101;
5825 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
5826 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5827 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5828 }
5829 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5830 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07005831 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005832 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5833 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
5834 ENCRYPTION_ZERO_RTT);
5835
5836 // Check if delayed ack timer is running for the expected interval.
5837 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5838 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5839
5840 // 18 packets will not cause an ack to be sent. 19 will because when
5841 // stop waiting frames are in use, we ack every 20 packets no matter what.
5842 for (int i = 0; i < 18; ++i) {
5843 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5844 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5845 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
5846 ENCRYPTION_ZERO_RTT);
5847 }
5848 // The delayed ack timer should still be set to the expected deadline.
5849 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5850 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5851}
5852
5853TEST_P(QuicConnectionTest, SendDelayedAckDecimationEighthRtt) {
QUICHE teamcd098022019-03-22 18:49:55 -07005854 if (connection_.SupportsMultiplePacketNumberSpaces()) {
5855 return;
5856 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005857 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
5858 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION);
5859 QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
5860
5861 const size_t kMinRttMs = 40;
5862 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
5863 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
5864 QuicTime::Delta::Zero(), QuicTime::Zero());
5865 // The ack time should be based on min_rtt/8, since it's less than the
5866 // default delayed ack time.
5867 QuicTime ack_time = clock_.ApproximateNow() +
5868 QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
5869 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5870 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5871 const uint8_t tag = 0x07;
5872 connection_.SetDecrypter(ENCRYPTION_ZERO_RTT,
5873 QuicMakeUnique<StrictTaggingDecrypter>(tag));
5874 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
5875 QuicMakeUnique<TaggingEncrypter>(tag));
5876 // Process a packet from the non-crypto stream.
5877 frame1_.stream_id = 3;
5878
5879 // Process all the initial packets in order so there aren't missing packets.
5880 uint64_t kFirstDecimatedPacket = 101;
5881 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
5882 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5883 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5884 }
5885 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5886 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07005887 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005888 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5889 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
5890 ENCRYPTION_ZERO_RTT);
5891
5892 // Check if delayed ack timer is running for the expected interval.
5893 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5894 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5895
5896 // The 10th received packet causes an ack to be sent.
5897 for (int i = 0; i < 9; ++i) {
5898 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5899 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5900 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
5901 ENCRYPTION_ZERO_RTT);
5902 }
5903 // Check that ack is sent and that delayed ack alarm is reset.
5904 if (GetParam().no_stop_waiting) {
5905 EXPECT_EQ(1u, writer_->frame_count());
5906 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
5907 } else {
5908 EXPECT_EQ(2u, writer_->frame_count());
5909 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
5910 }
5911 EXPECT_FALSE(writer_->ack_frames().empty());
5912 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5913}
5914
5915TEST_P(QuicConnectionTest, SendDelayedAckDecimationWithReordering) {
QUICHE teamcd098022019-03-22 18:49:55 -07005916 if (connection_.SupportsMultiplePacketNumberSpaces()) {
5917 return;
5918 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005919 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
5920 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
5921
5922 const size_t kMinRttMs = 40;
5923 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
5924 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
5925 QuicTime::Delta::Zero(), QuicTime::Zero());
5926 // The ack time should be based on min_rtt/4, since it's less than the
5927 // default delayed ack time.
5928 QuicTime ack_time = clock_.ApproximateNow() +
5929 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
5930 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5931 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5932 const uint8_t tag = 0x07;
5933 connection_.SetDecrypter(ENCRYPTION_ZERO_RTT,
5934 QuicMakeUnique<StrictTaggingDecrypter>(tag));
5935 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
5936 QuicMakeUnique<TaggingEncrypter>(tag));
5937 // Process a packet from the non-crypto stream.
5938 frame1_.stream_id = 3;
5939
5940 // Process all the initial packets in order so there aren't missing packets.
5941 uint64_t kFirstDecimatedPacket = 101;
5942 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
5943 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5944 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5945 }
5946 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5947
5948 // Receive one packet out of order and then the rest in order.
5949 // The loop leaves a one packet gap between acks sent to simulate some loss.
5950 for (int j = 0; j < 3; ++j) {
5951 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
5952 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5953 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 9 + (j * 11),
5954 !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5955 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
5956 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5957 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5958
5959 // The 10th received packet causes an ack to be sent.
5960 writer_->Reset();
5961 for (int i = 0; i < 9; ++i) {
5962 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5963 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5964 // The ACK shouldn't be sent until the 10th packet is processed.
5965 EXPECT_TRUE(writer_->ack_frames().empty());
5966 ProcessDataPacketAtLevel(kFirstDecimatedPacket + i + (j * 11),
5967 !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5968 }
5969 // Check that ack is sent and that delayed ack alarm is reset.
5970 if (GetParam().no_stop_waiting) {
5971 EXPECT_EQ(1u, writer_->frame_count());
5972 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
5973 } else {
5974 EXPECT_EQ(2u, writer_->frame_count());
5975 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
5976 }
5977 EXPECT_FALSE(writer_->ack_frames().empty());
5978 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5979 }
5980}
5981
5982TEST_P(QuicConnectionTest, SendDelayedAckDecimationWithLargeReordering) {
QUICHE teamcd098022019-03-22 18:49:55 -07005983 if (connection_.SupportsMultiplePacketNumberSpaces()) {
5984 return;
5985 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005986 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
5987 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
5988
5989 const size_t kMinRttMs = 40;
5990 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
5991 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
5992 QuicTime::Delta::Zero(), QuicTime::Zero());
5993 // The ack time should be based on min_rtt/4, since it's less than the
5994 // default delayed ack time.
5995 QuicTime ack_time = clock_.ApproximateNow() +
5996 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
5997 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5998 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5999 const uint8_t tag = 0x07;
6000 connection_.SetDecrypter(ENCRYPTION_ZERO_RTT,
6001 QuicMakeUnique<StrictTaggingDecrypter>(tag));
6002 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
6003 QuicMakeUnique<TaggingEncrypter>(tag));
6004 // Process a packet from the non-crypto stream.
6005 frame1_.stream_id = 3;
6006
6007 // Process all the initial packets in order so there aren't missing packets.
6008 uint64_t kFirstDecimatedPacket = 101;
6009 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6010 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6011 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6012 }
6013 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6014 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006015 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006016 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6017 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6018 ENCRYPTION_ZERO_RTT);
6019
6020 // Check if delayed ack timer is running for the expected interval.
6021 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6022 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6023
6024 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6025 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6026 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 19, !kHasStopWaiting,
6027 ENCRYPTION_ZERO_RTT);
6028 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
6029 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6030 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6031
6032 // The 10th received packet causes an ack to be sent.
6033 for (int i = 0; i < 8; ++i) {
6034 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6035 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6036 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6037 ENCRYPTION_ZERO_RTT);
6038 }
6039 // Check that ack is sent and that delayed ack alarm is reset.
6040 if (GetParam().no_stop_waiting) {
6041 EXPECT_EQ(1u, writer_->frame_count());
6042 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6043 } else {
6044 EXPECT_EQ(2u, writer_->frame_count());
6045 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6046 }
6047 EXPECT_FALSE(writer_->ack_frames().empty());
6048 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6049
6050 // The next packet received in order will cause an immediate ack,
6051 // because it fills a hole.
6052 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6053 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6054 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 10, !kHasStopWaiting,
6055 ENCRYPTION_ZERO_RTT);
6056 // Check that ack is sent and that delayed ack alarm is reset.
6057 if (GetParam().no_stop_waiting) {
6058 EXPECT_EQ(1u, writer_->frame_count());
6059 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6060 } else {
6061 EXPECT_EQ(2u, writer_->frame_count());
6062 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6063 }
6064 EXPECT_FALSE(writer_->ack_frames().empty());
6065 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6066}
6067
6068TEST_P(QuicConnectionTest, SendDelayedAckDecimationWithReorderingEighthRtt) {
QUICHE teamcd098022019-03-22 18:49:55 -07006069 if (connection_.SupportsMultiplePacketNumberSpaces()) {
6070 return;
6071 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006072 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6073 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6074 QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
6075
6076 const size_t kMinRttMs = 40;
6077 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6078 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6079 QuicTime::Delta::Zero(), QuicTime::Zero());
6080 // The ack time should be based on min_rtt/8, since it's less than the
6081 // default delayed ack time.
6082 QuicTime ack_time = clock_.ApproximateNow() +
6083 QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
6084 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6085 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6086 const uint8_t tag = 0x07;
6087 connection_.SetDecrypter(ENCRYPTION_ZERO_RTT,
6088 QuicMakeUnique<StrictTaggingDecrypter>(tag));
6089 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
6090 QuicMakeUnique<TaggingEncrypter>(tag));
6091 // Process a packet from the non-crypto stream.
6092 frame1_.stream_id = 3;
6093
6094 // Process all the initial packets in order so there aren't missing packets.
6095 uint64_t kFirstDecimatedPacket = 101;
6096 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6097 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6098 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6099 }
6100 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6101 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006102 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006103 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6104 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6105 ENCRYPTION_ZERO_RTT);
6106
6107 // Check if delayed ack timer is running for the expected interval.
6108 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6109 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6110
6111 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6112 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6113 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 9, !kHasStopWaiting,
6114 ENCRYPTION_ZERO_RTT);
6115 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
6116 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6117 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6118
6119 // The 10th received packet causes an ack to be sent.
6120 for (int i = 0; i < 8; ++i) {
6121 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6122 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6123 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6124 ENCRYPTION_ZERO_RTT);
6125 }
6126 // Check that ack is sent and that delayed ack alarm is reset.
6127 if (GetParam().no_stop_waiting) {
6128 EXPECT_EQ(1u, writer_->frame_count());
6129 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6130 } else {
6131 EXPECT_EQ(2u, writer_->frame_count());
6132 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6133 }
6134 EXPECT_FALSE(writer_->ack_frames().empty());
6135 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6136}
6137
6138TEST_P(QuicConnectionTest,
6139 SendDelayedAckDecimationWithLargeReorderingEighthRtt) {
QUICHE teamcd098022019-03-22 18:49:55 -07006140 if (connection_.SupportsMultiplePacketNumberSpaces()) {
6141 return;
6142 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006143 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6144 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6145 QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
6146
6147 const size_t kMinRttMs = 40;
6148 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6149 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6150 QuicTime::Delta::Zero(), QuicTime::Zero());
6151 // The ack time should be based on min_rtt/8, since it's less than the
6152 // default delayed ack time.
6153 QuicTime ack_time = clock_.ApproximateNow() +
6154 QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
6155 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6156 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6157 const uint8_t tag = 0x07;
6158 connection_.SetDecrypter(ENCRYPTION_ZERO_RTT,
6159 QuicMakeUnique<StrictTaggingDecrypter>(tag));
6160 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
6161 QuicMakeUnique<TaggingEncrypter>(tag));
6162 // Process a packet from the non-crypto stream.
6163 frame1_.stream_id = 3;
6164
6165 // Process all the initial packets in order so there aren't missing packets.
6166 uint64_t kFirstDecimatedPacket = 101;
6167 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6168 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6169 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6170 }
6171 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6172 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006173 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006174 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6175 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6176 ENCRYPTION_ZERO_RTT);
6177
6178 // Check if delayed ack timer is running for the expected interval.
6179 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6180 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6181
6182 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6183 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6184 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 19, !kHasStopWaiting,
6185 ENCRYPTION_ZERO_RTT);
6186 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
6187 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6188 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6189
6190 // The 10th received packet causes an ack to be sent.
6191 for (int i = 0; i < 8; ++i) {
6192 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6193 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6194 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6195 ENCRYPTION_ZERO_RTT);
6196 }
6197 // Check that ack is sent and that delayed ack alarm is reset.
6198 if (GetParam().no_stop_waiting) {
6199 EXPECT_EQ(1u, writer_->frame_count());
6200 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6201 } else {
6202 EXPECT_EQ(2u, writer_->frame_count());
6203 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6204 }
6205 EXPECT_FALSE(writer_->ack_frames().empty());
6206 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6207
6208 // The next packet received in order will cause an immediate ack,
6209 // because it fills a hole.
6210 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6211 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6212 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 10, !kHasStopWaiting,
6213 ENCRYPTION_ZERO_RTT);
6214 // Check that ack is sent and that delayed ack alarm is reset.
6215 if (GetParam().no_stop_waiting) {
6216 EXPECT_EQ(1u, writer_->frame_count());
6217 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6218 } else {
6219 EXPECT_EQ(2u, writer_->frame_count());
6220 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6221 }
6222 EXPECT_FALSE(writer_->ack_frames().empty());
6223 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6224}
6225
6226TEST_P(QuicConnectionTest, SendDelayedAckOnHandshakeConfirmed) {
QUICHE teamcd098022019-03-22 18:49:55 -07006227 if (connection_.SupportsMultiplePacketNumberSpaces()) {
6228 return;
6229 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006230 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6231 ProcessPacket(1);
6232 // Check that ack is sent and that delayed ack alarm is set.
6233 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6234 QuicTime ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6235 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6236
6237 // Completing the handshake as the server does nothing.
6238 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_SERVER);
6239 connection_.OnHandshakeComplete();
6240 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6241 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6242
6243 // Complete the handshake as the client decreases the delayed ack time to 0ms.
6244 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_CLIENT);
6245 connection_.OnHandshakeComplete();
6246 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6247 EXPECT_EQ(clock_.ApproximateNow(), connection_.GetAckAlarm()->deadline());
6248}
6249
6250TEST_P(QuicConnectionTest, SendDelayedAckOnSecondPacket) {
QUICHE teamcd098022019-03-22 18:49:55 -07006251 if (connection_.SupportsMultiplePacketNumberSpaces()) {
6252 return;
6253 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006254 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6255 ProcessPacket(1);
6256 ProcessPacket(2);
6257 // Check that ack is sent and that delayed ack alarm is reset.
6258 if (GetParam().no_stop_waiting) {
6259 EXPECT_EQ(1u, writer_->frame_count());
6260 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6261 } else {
6262 EXPECT_EQ(2u, writer_->frame_count());
6263 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6264 }
6265 EXPECT_FALSE(writer_->ack_frames().empty());
6266 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6267}
6268
6269TEST_P(QuicConnectionTest, NoAckOnOldNacks) {
QUICHE teamcd098022019-03-22 18:49:55 -07006270 if (connection_.SupportsMultiplePacketNumberSpaces()) {
6271 return;
6272 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006273 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6274 // Drop one packet, triggering a sequence of acks.
6275 if (GetQuicRestartFlag(quic_enable_accept_random_ipn)) {
6276 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6277 } else {
6278 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
6279 }
6280 ProcessPacket(2);
6281 size_t frames_per_ack = GetParam().no_stop_waiting ? 1 : 2;
6282 if (!GetQuicRestartFlag(quic_enable_accept_random_ipn)) {
6283 EXPECT_EQ(frames_per_ack, writer_->frame_count());
6284 EXPECT_FALSE(writer_->ack_frames().empty());
6285 writer_->Reset();
6286 }
6287
6288 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
6289 ProcessPacket(3);
6290 EXPECT_EQ(frames_per_ack, writer_->frame_count());
6291 EXPECT_FALSE(writer_->ack_frames().empty());
6292 writer_->Reset();
6293
6294 if (GetQuicRestartFlag(quic_enable_accept_random_ipn)) {
6295 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6296 } else {
6297 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
6298 }
6299 ProcessPacket(4);
6300 if (GetQuicRestartFlag(quic_enable_accept_random_ipn)) {
6301 EXPECT_EQ(0u, writer_->frame_count());
6302 } else {
6303 EXPECT_EQ(frames_per_ack, writer_->frame_count());
6304 EXPECT_FALSE(writer_->ack_frames().empty());
6305 writer_->Reset();
6306 }
6307
6308 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
6309 ProcessPacket(5);
6310 EXPECT_EQ(frames_per_ack, writer_->frame_count());
6311 EXPECT_FALSE(writer_->ack_frames().empty());
6312 writer_->Reset();
6313
6314 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6315 // Now only set the timer on the 6th packet, instead of sending another ack.
6316 ProcessPacket(6);
6317 EXPECT_EQ(0u, writer_->frame_count());
6318 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6319}
6320
6321TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingPacket) {
QUICHE teamcd098022019-03-22 18:49:55 -07006322 if (connection_.SupportsMultiplePacketNumberSpaces()) {
6323 return;
6324 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006325 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
QUICHE team8c1daa22019-03-13 08:33:41 -07006326 EXPECT_CALL(visitor_, OnStreamFrame(_));
6327 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
6328 QuicMakeUnique<TaggingEncrypter>(0x01));
6329 connection_.SetDecrypter(ENCRYPTION_FORWARD_SECURE,
6330 QuicMakeUnique<StrictTaggingDecrypter>(0x01));
6331 ProcessDataPacketAtLevel(1, false, ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006332 connection_.SendStreamDataWithString(
6333 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6334 0, NO_FIN);
6335 // Check that ack is bundled with outgoing data and that delayed ack
6336 // alarm is reset.
6337 if (GetParam().no_stop_waiting) {
6338 EXPECT_EQ(2u, writer_->frame_count());
6339 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6340 } else {
6341 EXPECT_EQ(3u, writer_->frame_count());
6342 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6343 }
6344 EXPECT_FALSE(writer_->ack_frames().empty());
6345 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6346}
6347
6348TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingCryptoPacket) {
QUICHE teamcd098022019-03-22 18:49:55 -07006349 if (connection_.SupportsMultiplePacketNumberSpaces()) {
6350 return;
6351 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006352 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6353 ProcessPacket(1);
6354 connection_.SendStreamDataWithString(
6355 QuicUtils::GetCryptoStreamId(connection_.transport_version()), "foo", 0,
6356 NO_FIN);
6357 // Check that ack is bundled with outgoing crypto data.
6358 if (GetParam().no_stop_waiting) {
6359 EXPECT_EQ(3u, writer_->frame_count());
6360 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6361 } else {
6362 EXPECT_EQ(4u, writer_->frame_count());
6363 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6364 }
6365 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6366}
6367
6368TEST_P(QuicConnectionTest, BlockAndBufferOnFirstCHLOPacketOfTwo) {
QUICHE teamcd098022019-03-22 18:49:55 -07006369 if (connection_.SupportsMultiplePacketNumberSpaces()) {
6370 return;
6371 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006372 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6373 ProcessPacket(1);
6374 BlockOnNextWrite();
6375 writer_->set_is_write_blocked_data_buffered(true);
6376 connection_.SendStreamDataWithString(
6377 QuicUtils::GetCryptoStreamId(connection_.transport_version()), "foo", 0,
6378 NO_FIN);
6379 EXPECT_TRUE(writer_->IsWriteBlocked());
6380 EXPECT_FALSE(connection_.HasQueuedData());
6381 connection_.SendStreamDataWithString(
6382 QuicUtils::GetCryptoStreamId(connection_.transport_version()), "bar", 3,
6383 NO_FIN);
6384 EXPECT_TRUE(writer_->IsWriteBlocked());
6385 EXPECT_TRUE(connection_.HasQueuedData());
6386}
6387
6388TEST_P(QuicConnectionTest, BundleAckForSecondCHLO) {
QUICHE teamcd098022019-03-22 18:49:55 -07006389 if (connection_.SupportsMultiplePacketNumberSpaces()) {
6390 return;
6391 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006392 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6393 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6394 EXPECT_CALL(visitor_, OnCanWrite())
6395 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6396 &connection_, &TestConnection::SendCryptoStreamData)));
6397 // Process a packet from the crypto stream, which is frame1_'s default.
6398 // Receiving the CHLO as packet 2 first will cause the connection to
6399 // immediately send an ack, due to the packet gap.
6400 ProcessPacket(2);
6401 // Check that ack is sent and that delayed ack alarm is reset.
6402 if (GetParam().no_stop_waiting) {
6403 EXPECT_EQ(3u, writer_->frame_count());
6404 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6405 } else {
6406 EXPECT_EQ(4u, writer_->frame_count());
6407 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6408 }
QUICHE teamea740082019-03-11 17:58:43 -07006409 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006410 EXPECT_EQ(1u, writer_->stream_frames().size());
6411 } else {
6412 EXPECT_EQ(1u, writer_->crypto_frames().size());
6413 }
6414 EXPECT_EQ(1u, writer_->padding_frames().size());
6415 ASSERT_FALSE(writer_->ack_frames().empty());
6416 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(writer_->ack_frames().front()));
6417 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6418}
6419
6420TEST_P(QuicConnectionTest, BundleAckForSecondCHLOTwoPacketReject) {
QUICHE teamcd098022019-03-22 18:49:55 -07006421 if (connection_.SupportsMultiplePacketNumberSpaces()) {
6422 return;
6423 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006424 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6425 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6426
6427 // Process two packets from the crypto stream, which is frame1_'s default,
6428 // simulating a 2 packet reject.
6429 {
6430 ProcessPacket(1);
6431 // Send the new CHLO when the REJ is processed.
6432 EXPECT_CALL(visitor_, OnStreamFrame(_))
6433 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6434 &connection_, &TestConnection::SendCryptoStreamData)));
6435 ProcessDataPacket(2);
6436 }
6437 // Check that ack is sent and that delayed ack alarm is reset.
6438 if (GetParam().no_stop_waiting) {
6439 EXPECT_EQ(3u, writer_->frame_count());
6440 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6441 } else {
6442 EXPECT_EQ(4u, writer_->frame_count());
6443 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6444 }
QUICHE teamea740082019-03-11 17:58:43 -07006445 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006446 EXPECT_EQ(1u, writer_->stream_frames().size());
6447 } else {
6448 EXPECT_EQ(1u, writer_->crypto_frames().size());
6449 }
6450 EXPECT_EQ(1u, writer_->padding_frames().size());
6451 ASSERT_FALSE(writer_->ack_frames().empty());
6452 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(writer_->ack_frames().front()));
6453 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6454}
6455
6456TEST_P(QuicConnectionTest, BundleAckWithDataOnIncomingAck) {
QUICHE teamcd098022019-03-22 18:49:55 -07006457 if (connection_.SupportsMultiplePacketNumberSpaces()) {
6458 return;
6459 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006460 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6461 connection_.SendStreamDataWithString(
6462 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6463 0, NO_FIN);
6464 connection_.SendStreamDataWithString(
6465 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6466 3, NO_FIN);
6467 // Ack the second packet, which will retransmit the first packet.
6468 QuicAckFrame ack = ConstructAckFrame(2, 1);
6469 LostPacketVector lost_packets;
6470 lost_packets.push_back(LostPacket(QuicPacketNumber(1), kMaxPacketSize));
6471 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
6472 .WillOnce(SetArgPointee<5>(lost_packets));
6473 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
6474 ProcessAckPacket(&ack);
6475 EXPECT_EQ(1u, writer_->frame_count());
6476 EXPECT_EQ(1u, writer_->stream_frames().size());
6477 writer_->Reset();
6478
6479 // Now ack the retransmission, which will both raise the high water mark
6480 // and see if there is more data to send.
6481 ack = ConstructAckFrame(3, 1);
6482 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
6483 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
6484 ProcessAckPacket(&ack);
6485
6486 // Check that no packet is sent and the ack alarm isn't set.
6487 EXPECT_EQ(0u, writer_->frame_count());
6488 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6489 writer_->Reset();
6490
6491 // Send the same ack, but send both data and an ack together.
6492 ack = ConstructAckFrame(3, 1);
6493 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
6494 EXPECT_CALL(visitor_, OnCanWrite())
6495 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6496 &connection_, &TestConnection::EnsureWritableAndSendStreamData5)));
6497 ProcessAckPacket(&ack);
6498
6499 // Check that ack is bundled with outgoing data and the delayed ack
6500 // alarm is reset.
6501 if (GetParam().no_stop_waiting) {
6502 EXPECT_EQ(2u, writer_->frame_count());
6503 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6504 } else {
6505 EXPECT_EQ(3u, writer_->frame_count());
6506 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6507 }
6508 EXPECT_FALSE(writer_->ack_frames().empty());
6509 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(writer_->ack_frames().front()));
6510 EXPECT_EQ(1u, writer_->stream_frames().size());
6511 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6512}
6513
6514TEST_P(QuicConnectionTest, NoAckSentForClose) {
QUICHE teamcd098022019-03-22 18:49:55 -07006515 if (connection_.SupportsMultiplePacketNumberSpaces()) {
6516 return;
6517 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006518 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6519 ProcessPacket(1);
6520 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, _,
6521 ConnectionCloseSource::FROM_PEER));
6522 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6523 ProcessClosePacket(2);
6524}
6525
6526TEST_P(QuicConnectionTest, SendWhenDisconnected) {
QUICHE teamcd098022019-03-22 18:49:55 -07006527 if (connection_.SupportsMultiplePacketNumberSpaces()) {
6528 return;
6529 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006530 EXPECT_TRUE(connection_.connected());
6531 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, _,
6532 ConnectionCloseSource::FROM_SELF));
6533 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
6534 ConnectionCloseBehavior::SILENT_CLOSE);
6535 EXPECT_FALSE(connection_.connected());
6536 EXPECT_FALSE(connection_.CanWriteStreamData());
QUICHE team8c1daa22019-03-13 08:33:41 -07006537 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07006538 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006539 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6540 .Times(0);
QUICHE team6987b4a2019-03-15 16:23:04 -07006541 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05006542 HAS_RETRANSMITTABLE_DATA, false, false);
6543}
6544
6545TEST_P(QuicConnectionTest, SendConnectivityProbingWhenDisconnected) {
6546 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
QUICHE teamcd098022019-03-22 18:49:55 -07006547 if (!IsDefaultTestConfiguration() ||
6548 connection_.SupportsMultiplePacketNumberSpaces()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006549 return;
6550 }
6551
6552 EXPECT_TRUE(connection_.connected());
6553 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, _,
6554 ConnectionCloseSource::FROM_SELF));
6555 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
6556 ConnectionCloseBehavior::SILENT_CLOSE);
6557 EXPECT_FALSE(connection_.connected());
6558 EXPECT_FALSE(connection_.CanWriteStreamData());
6559
6560 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6561 .Times(0);
6562
6563 EXPECT_QUIC_BUG(connection_.SendConnectivityProbingPacket(
6564 writer_.get(), connection_.peer_address()),
6565 "Not sending connectivity probing packet as connection is "
6566 "disconnected.");
6567}
6568
6569TEST_P(QuicConnectionTest, WriteBlockedAfterClientSendsConnectivityProbe) {
QUICHE teamcd098022019-03-22 18:49:55 -07006570 if (connection_.SupportsMultiplePacketNumberSpaces()) {
6571 return;
6572 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006573 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
6574 TestPacketWriter probing_writer(version(), &clock_);
6575 // Block next write so that sending connectivity probe will encounter a
6576 // blocked write when send a connectivity probe to the peer.
6577 probing_writer.BlockOnNextWrite();
6578 // Connection will not be marked as write blocked as connectivity probe only
6579 // affects the probing_writer which is not the default.
6580 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
6581
6582 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6583 .Times(1);
6584 connection_.SendConnectivityProbingPacket(&probing_writer,
6585 connection_.peer_address());
6586}
6587
6588TEST_P(QuicConnectionTest, WriterBlockedAfterServerSendsConnectivityProbe) {
QUICHE teamcd098022019-03-22 18:49:55 -07006589 if (connection_.SupportsMultiplePacketNumberSpaces()) {
6590 return;
6591 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006592 set_perspective(Perspective::IS_SERVER);
6593 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
6594
6595 // Block next write so that sending connectivity probe will encounter a
6596 // blocked write when send a connectivity probe to the peer.
6597 writer_->BlockOnNextWrite();
6598 // Connection will be marked as write blocked as server uses the default
6599 // writer to send connectivity probes.
6600 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
6601
6602 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6603 .Times(1);
6604 connection_.SendConnectivityProbingPacket(writer_.get(),
6605 connection_.peer_address());
6606}
6607
6608TEST_P(QuicConnectionTest, WriterErrorWhenClientSendsConnectivityProbe) {
QUICHE teamcd098022019-03-22 18:49:55 -07006609 if (connection_.SupportsMultiplePacketNumberSpaces()) {
6610 return;
6611 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006612 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
6613 TestPacketWriter probing_writer(version(), &clock_);
6614 probing_writer.SetShouldWriteFail();
6615
6616 // Connection should not be closed if a connectivity probe is failed to be
6617 // sent.
6618 EXPECT_CALL(visitor_, OnConnectionClosed(_, _, _)).Times(0);
6619
6620 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6621 .Times(0);
6622 connection_.SendConnectivityProbingPacket(&probing_writer,
6623 connection_.peer_address());
6624}
6625
6626TEST_P(QuicConnectionTest, WriterErrorWhenServerSendsConnectivityProbe) {
QUICHE teamcd098022019-03-22 18:49:55 -07006627 if (connection_.SupportsMultiplePacketNumberSpaces()) {
6628 return;
6629 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006630 set_perspective(Perspective::IS_SERVER);
6631 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
6632
6633 writer_->SetShouldWriteFail();
6634 // Connection should not be closed if a connectivity probe is failed to be
6635 // sent.
6636 EXPECT_CALL(visitor_, OnConnectionClosed(_, _, _)).Times(0);
6637
6638 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6639 .Times(0);
6640 connection_.SendConnectivityProbingPacket(writer_.get(),
6641 connection_.peer_address());
6642}
6643
6644TEST_P(QuicConnectionTest, PublicReset) {
QUICHE teamcd098022019-03-22 18:49:55 -07006645 if (GetParam().version.transport_version > QUIC_VERSION_43 ||
6646 connection_.SupportsMultiplePacketNumberSpaces()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006647 return;
6648 }
6649 QuicPublicResetPacket header;
6650 // Public reset packet in only built by server.
6651 header.connection_id = connection_id_;
6652 std::unique_ptr<QuicEncryptedPacket> packet(
6653 framer_.BuildPublicResetPacket(header));
6654 std::unique_ptr<QuicReceivedPacket> received(
6655 ConstructReceivedPacket(*packet, QuicTime::Zero()));
6656 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PUBLIC_RESET, _,
6657 ConnectionCloseSource::FROM_PEER));
6658 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
6659}
6660
6661TEST_P(QuicConnectionTest, IetfStatelessReset) {
QUICHE teamcd098022019-03-22 18:49:55 -07006662 if (GetParam().version.transport_version <= QUIC_VERSION_43 ||
6663 connection_.SupportsMultiplePacketNumberSpaces()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006664 return;
6665 }
6666 const QuicUint128 kTestStatelessResetToken = 1010101;
6667 QuicConfig config;
6668 QuicConfigPeer::SetReceivedStatelessResetToken(&config,
6669 kTestStatelessResetToken);
6670 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6671 connection_.SetFromConfig(config);
6672 std::unique_ptr<QuicEncryptedPacket> packet(
6673 QuicFramer::BuildIetfStatelessResetPacket(connection_id_,
6674 kTestStatelessResetToken));
6675 std::unique_ptr<QuicReceivedPacket> received(
6676 ConstructReceivedPacket(*packet, QuicTime::Zero()));
6677 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PUBLIC_RESET, _,
6678 ConnectionCloseSource::FROM_PEER));
6679 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
6680}
6681
6682TEST_P(QuicConnectionTest, GoAway) {
QUICHE teamcd098022019-03-22 18:49:55 -07006683 if (GetParam().version.transport_version == QUIC_VERSION_99 ||
6684 connection_.SupportsMultiplePacketNumberSpaces()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006685 // GoAway is not available in version 99.
6686 return;
6687 }
6688
6689 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6690
6691 QuicGoAwayFrame goaway;
6692 goaway.last_good_stream_id = 1;
6693 goaway.error_code = QUIC_PEER_GOING_AWAY;
6694 goaway.reason_phrase = "Going away.";
6695 EXPECT_CALL(visitor_, OnGoAway(_));
6696 ProcessGoAwayPacket(&goaway);
6697}
6698
6699TEST_P(QuicConnectionTest, WindowUpdate) {
QUICHE teamcd098022019-03-22 18:49:55 -07006700 if (connection_.SupportsMultiplePacketNumberSpaces()) {
6701 return;
6702 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006703 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6704
6705 QuicWindowUpdateFrame window_update;
6706 window_update.stream_id = 3;
6707 window_update.byte_offset = 1234;
6708 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
6709 ProcessFramePacket(QuicFrame(&window_update));
6710}
6711
6712TEST_P(QuicConnectionTest, Blocked) {
QUICHE teamcd098022019-03-22 18:49:55 -07006713 if (connection_.SupportsMultiplePacketNumberSpaces()) {
6714 return;
6715 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006716 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6717
6718 QuicBlockedFrame blocked;
6719 blocked.stream_id = 3;
6720 EXPECT_CALL(visitor_, OnBlockedFrame(_));
6721 ProcessFramePacket(QuicFrame(&blocked));
6722 EXPECT_EQ(1u, connection_.GetStats().blocked_frames_received);
6723 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
6724}
6725
6726TEST_P(QuicConnectionTest, ZeroBytePacket) {
QUICHE teamcd098022019-03-22 18:49:55 -07006727 if (connection_.SupportsMultiplePacketNumberSpaces()) {
6728 return;
6729 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006730 // Don't close the connection for zero byte packets.
6731 EXPECT_CALL(visitor_, OnConnectionClosed(_, _, _)).Times(0);
6732 QuicReceivedPacket encrypted(nullptr, 0, QuicTime::Zero());
6733 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, encrypted);
6734}
6735
6736TEST_P(QuicConnectionTest, MissingPacketsBeforeLeastUnacked) {
QUICHE teamcd098022019-03-22 18:49:55 -07006737 if (GetParam().version.transport_version > QUIC_VERSION_43 ||
6738 connection_.SupportsMultiplePacketNumberSpaces()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006739 return;
6740 }
6741 // Set the packet number of the ack packet to be least unacked (4).
6742 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 3);
6743 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6744 ProcessStopWaitingPacket(InitStopWaitingFrame(4));
6745 EXPECT_FALSE(outgoing_ack()->packets.Empty());
6746}
6747
6748TEST_P(QuicConnectionTest, ServerSendsVersionNegotiationPacket) {
QUICHE teamcd098022019-03-22 18:49:55 -07006749 if (connection_.SupportsMultiplePacketNumberSpaces()) {
6750 return;
6751 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006752 // Turn off QUIC_VERSION_99.
6753 SetQuicReloadableFlag(quic_enable_version_99, false);
6754 connection_.SetSupportedVersions(CurrentSupportedVersions());
6755 set_perspective(Perspective::IS_SERVER);
6756 if (GetParam().version.transport_version > QUIC_VERSION_43) {
6757 peer_framer_.set_version_for_tests(
6758 ParsedQuicVersion(PROTOCOL_QUIC_CRYPTO, QUIC_VERSION_99));
6759 } else {
6760 peer_framer_.set_version_for_tests(UnsupportedQuicVersion());
6761 }
6762
6763 QuicPacketHeader header;
6764 header.destination_connection_id = connection_id_;
6765 header.version_flag = true;
6766 header.packet_number = QuicPacketNumber(12);
6767
6768 if (QuicVersionHasLongHeaderLengths(
6769 peer_framer_.version().transport_version)) {
6770 header.long_packet_type = INITIAL;
6771 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
6772 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
6773 }
6774
6775 QuicFrames frames;
6776 frames.push_back(QuicFrame(frame1_));
6777 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
6778 char buffer[kMaxPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07006779 size_t encrypted_length =
6780 framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12), *packet,
6781 buffer, kMaxPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006782
6783 framer_.set_version(version());
6784 // Writer's framer's perspective is client, so that it needs to have the right
6785 // version to process either IETF or GQUIC version negotiation packet.
6786 writer_->SetSupportedVersions({version()});
6787 connection_.ProcessUdpPacket(
6788 kSelfAddress, kPeerAddress,
6789 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
6790 EXPECT_TRUE(writer_->version_negotiation_packet() != nullptr);
6791
6792 ParsedQuicVersionVector supported_versions = CurrentSupportedVersions();
6793 ASSERT_EQ(supported_versions.size(),
6794 writer_->version_negotiation_packet()->versions.size());
6795
6796 // We expect all versions in supported_versions to be
6797 // included in the packet.
6798 for (size_t i = 0; i < supported_versions.size(); ++i) {
6799 EXPECT_EQ(supported_versions[i],
6800 writer_->version_negotiation_packet()->versions[i]);
6801 }
6802}
6803
6804TEST_P(QuicConnectionTest, ServerSendsVersionNegotiationPacketSocketBlocked) {
QUICHE teamcd098022019-03-22 18:49:55 -07006805 if (connection_.SupportsMultiplePacketNumberSpaces()) {
6806 return;
6807 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006808 // Turn off QUIC_VERSION_99.
6809 SetQuicReloadableFlag(quic_enable_version_99, false);
6810 connection_.SetSupportedVersions(CurrentSupportedVersions());
6811 set_perspective(Perspective::IS_SERVER);
6812 if (GetParam().version.transport_version > QUIC_VERSION_43) {
6813 peer_framer_.set_version_for_tests(
6814 ParsedQuicVersion(PROTOCOL_QUIC_CRYPTO, QUIC_VERSION_99));
6815 } else {
6816 peer_framer_.set_version_for_tests(UnsupportedQuicVersion());
6817 }
6818
6819 QuicPacketHeader header;
6820 header.destination_connection_id = connection_id_;
6821 header.version_flag = true;
6822 header.packet_number = QuicPacketNumber(12);
6823
6824 if (QuicVersionHasLongHeaderLengths(
6825 peer_framer_.version().transport_version)) {
6826 header.long_packet_type = INITIAL;
6827 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
6828 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
6829 }
6830
6831 QuicFrames frames;
6832 frames.push_back(QuicFrame(frame1_));
6833 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
6834 char buffer[kMaxPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07006835 size_t encrypted_length =
6836 framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12), *packet,
6837 buffer, kMaxPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006838
6839 framer_.set_version(version());
6840 BlockOnNextWrite();
6841 // Writer's framer's perspective is client, so that it needs to have the right
6842 // version to process either IETF or GQUIC version negotiation packet.
6843 writer_->SetSupportedVersions({version()});
6844 connection_.ProcessUdpPacket(
6845 kSelfAddress, kPeerAddress,
6846 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
6847 EXPECT_EQ(0u, writer_->last_packet_size());
6848 EXPECT_TRUE(connection_.HasQueuedData());
6849
6850 writer_->SetWritable();
6851 connection_.OnCanWrite();
6852 EXPECT_TRUE(writer_->version_negotiation_packet() != nullptr);
6853
6854 ParsedQuicVersionVector supported_versions = CurrentSupportedVersions();
6855 ASSERT_EQ(supported_versions.size(),
6856 writer_->version_negotiation_packet()->versions.size());
6857
6858 // We expect all versions in supported_versions to be
6859 // included in the packet.
6860 for (size_t i = 0; i < supported_versions.size(); ++i) {
6861 EXPECT_EQ(supported_versions[i],
6862 writer_->version_negotiation_packet()->versions[i]);
6863 }
6864}
6865
6866TEST_P(QuicConnectionTest,
6867 ServerSendsVersionNegotiationPacketSocketBlockedDataBuffered) {
QUICHE teamcd098022019-03-22 18:49:55 -07006868 if (connection_.SupportsMultiplePacketNumberSpaces()) {
6869 return;
6870 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006871 // Turn off QUIC_VERSION_99.
6872 SetQuicReloadableFlag(quic_enable_version_99, false);
6873 connection_.SetSupportedVersions(CurrentSupportedVersions());
6874 set_perspective(Perspective::IS_SERVER);
6875 if (GetParam().version.transport_version > QUIC_VERSION_43) {
6876 peer_framer_.set_version_for_tests(
6877 ParsedQuicVersion(PROTOCOL_QUIC_CRYPTO, QUIC_VERSION_99));
6878 } else {
6879 peer_framer_.set_version_for_tests(UnsupportedQuicVersion());
6880 }
6881
6882 QuicPacketHeader header;
6883 header.destination_connection_id = connection_id_;
6884 header.version_flag = true;
6885 header.packet_number = QuicPacketNumber(12);
6886
6887 if (QuicVersionHasLongHeaderLengths(
6888 peer_framer_.version().transport_version)) {
6889 header.long_packet_type = INITIAL;
6890 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
6891 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
6892 }
6893
6894 QuicFrames frames;
6895 frames.push_back(QuicFrame(frame1_));
6896 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
6897 char buffer[kMaxPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07006898 size_t encryped_length =
6899 framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12), *packet,
6900 buffer, kMaxPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006901
6902 framer_.set_version(version());
6903 set_perspective(Perspective::IS_SERVER);
6904 BlockOnNextWrite();
6905 writer_->set_is_write_blocked_data_buffered(true);
6906 // Writer's framer's perspective is client, so that it needs to have the right
6907 // version to process either IETF or GQUIC version negotiation packet.
6908 writer_->SetSupportedVersions({version()});
6909 connection_.ProcessUdpPacket(
6910 kSelfAddress, kPeerAddress,
6911 QuicReceivedPacket(buffer, encryped_length, QuicTime::Zero(), false));
6912 EXPECT_EQ(0u, writer_->last_packet_size());
6913 EXPECT_FALSE(connection_.HasQueuedData());
6914}
6915
6916TEST_P(QuicConnectionTest, ClientHandlesVersionNegotiation) {
QUICHE teamcd098022019-03-22 18:49:55 -07006917 if (connection_.SupportsMultiplePacketNumberSpaces()) {
6918 return;
6919 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006920 // Start out with some unsupported version.
6921 QuicConnectionPeer::GetFramer(&connection_)
6922 ->set_version_for_tests(ParsedQuicVersion(
6923 PROTOCOL_UNSUPPORTED,
6924 GetParam().version.transport_version == QUIC_VERSION_99
6925 ? QUIC_VERSION_99
6926 : QUIC_VERSION_UNSUPPORTED));
6927
6928 // Send a version negotiation packet.
6929 std::unique_ptr<QuicEncryptedPacket> encrypted(
6930 peer_framer_.BuildVersionNegotiationPacket(
6931 connection_id_, connection_.transport_version() > QUIC_VERSION_43,
6932 AllSupportedVersions()));
6933 std::unique_ptr<QuicReceivedPacket> received(
6934 ConstructReceivedPacket(*encrypted, QuicTime::Zero()));
6935 if (GetQuicReloadableFlag(quic_no_client_conn_ver_negotiation)) {
6936 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_VERSION, _,
6937 ConnectionCloseSource::FROM_SELF));
6938 }
6939 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
6940 if (GetQuicReloadableFlag(quic_no_client_conn_ver_negotiation)) {
6941 EXPECT_FALSE(connection_.connected());
6942 return;
6943 }
6944
6945 // Now force another packet. The connection should transition into
6946 // NEGOTIATED_VERSION state and tell the packet creator to StopSendingVersion.
6947 QuicPacketHeader header;
6948 header.destination_connection_id = connection_id_;
6949 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
6950 header.packet_number = QuicPacketNumber(12);
6951 header.version_flag = false;
6952 QuicFrames frames;
6953 frames.push_back(QuicFrame(frame1_));
6954 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
6955 char buffer[kMaxPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07006956 size_t encrypted_length =
6957 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12),
6958 *packet, buffer, kMaxPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006959 ASSERT_NE(0u, encrypted_length);
6960 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6961 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6962 connection_.ProcessUdpPacket(
6963 kSelfAddress, kPeerAddress,
6964 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
6965 if (GetParam().version.transport_version > QUIC_VERSION_43) {
6966 // IETF QUIC stops sending version when switch to FORWARD_SECURE.
6967 EXPECT_NE(ENCRYPTION_FORWARD_SECURE, connection_.encryption_level());
6968 ASSERT_TRUE(QuicPacketCreatorPeer::SendVersionInPacket(creator_));
6969 } else {
6970 ASSERT_FALSE(QuicPacketCreatorPeer::SendVersionInPacket(creator_));
6971 }
6972}
6973
6974TEST_P(QuicConnectionTest, BadVersionNegotiation) {
QUICHE teamcd098022019-03-22 18:49:55 -07006975 if (connection_.SupportsMultiplePacketNumberSpaces()) {
6976 return;
6977 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006978 // Send a version negotiation packet with the version the client started with.
6979 // It should be rejected.
6980 EXPECT_CALL(visitor_,
6981 OnConnectionClosed(QUIC_INVALID_VERSION_NEGOTIATION_PACKET, _,
6982 ConnectionCloseSource::FROM_SELF));
6983 std::unique_ptr<QuicEncryptedPacket> encrypted(
6984 framer_.BuildVersionNegotiationPacket(
6985 connection_id_, connection_.transport_version() > QUIC_VERSION_43,
6986 AllSupportedVersions()));
6987 std::unique_ptr<QuicReceivedPacket> received(
6988 ConstructReceivedPacket(*encrypted, QuicTime::Zero()));
6989 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
6990}
6991
6992TEST_P(QuicConnectionTest, CheckSendStats) {
QUICHE teamcd098022019-03-22 18:49:55 -07006993 if (connection_.SupportsMultiplePacketNumberSpaces()) {
6994 return;
6995 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006996 connection_.SetMaxTailLossProbes(0);
6997
6998 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
6999 connection_.SendStreamDataWithString(3, "first", 0, NO_FIN);
7000 size_t first_packet_size = writer_->last_packet_size();
7001
7002 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7003 connection_.SendStreamDataWithString(5, "second", 0, NO_FIN);
7004 size_t second_packet_size = writer_->last_packet_size();
7005
7006 // 2 retransmissions due to rto, 1 due to explicit nack.
7007 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
7008 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
7009
7010 // Retransmit due to RTO.
7011 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
7012 connection_.GetRetransmissionAlarm()->Fire();
7013
7014 // Retransmit due to explicit nacks.
7015 QuicAckFrame nack_three =
7016 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)},
7017 {QuicPacketNumber(4), QuicPacketNumber(5)}});
7018
7019 LostPacketVector lost_packets;
7020 lost_packets.push_back(LostPacket(QuicPacketNumber(1), kMaxPacketSize));
7021 lost_packets.push_back(LostPacket(QuicPacketNumber(3), kMaxPacketSize));
7022 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
7023 .WillOnce(SetArgPointee<5>(lost_packets));
7024 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7025 if (!connection_.session_decides_what_to_write()) {
7026 EXPECT_CALL(visitor_, OnCanWrite());
7027 }
7028 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7029 ProcessAckPacket(&nack_three);
7030
7031 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
7032 .WillOnce(Return(QuicBandwidth::Zero()));
7033
7034 const QuicConnectionStats& stats = connection_.GetStats();
7035 // For IETF QUIC, version is not included as the encryption level switches to
7036 // FORWARD_SECURE in SendStreamDataWithString.
7037 size_t save_on_version =
7038 GetParam().version.transport_version > QUIC_VERSION_43 ? 0
7039 : kQuicVersionSize;
7040 EXPECT_EQ(3 * first_packet_size + 2 * second_packet_size - save_on_version,
7041 stats.bytes_sent);
7042 EXPECT_EQ(5u, stats.packets_sent);
7043 EXPECT_EQ(2 * first_packet_size + second_packet_size - save_on_version,
7044 stats.bytes_retransmitted);
7045 EXPECT_EQ(3u, stats.packets_retransmitted);
7046 EXPECT_EQ(1u, stats.rto_count);
7047 EXPECT_EQ(kDefaultMaxPacketSize, stats.max_packet_size);
7048}
7049
7050TEST_P(QuicConnectionTest, ProcessFramesIfPacketClosedConnection) {
QUICHE teamcd098022019-03-22 18:49:55 -07007051 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7052 return;
7053 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007054 // Construct a packet with stream frame and connection close frame.
7055 QuicPacketHeader header;
7056 header.destination_connection_id = connection_id_;
7057 if (peer_framer_.transport_version() > QUIC_VERSION_43) {
7058 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
7059 }
7060 header.packet_number = QuicPacketNumber(1);
7061 header.version_flag = false;
7062
7063 QuicConnectionCloseFrame qccf;
7064 qccf.error_code = QUIC_PEER_GOING_AWAY;
7065
7066 QuicFrames frames;
7067 frames.push_back(QuicFrame(frame1_));
7068 frames.push_back(QuicFrame(&qccf));
7069 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
7070 EXPECT_TRUE(nullptr != packet);
7071 char buffer[kMaxPacketSize];
7072 size_t encrypted_length = peer_framer_.EncryptPayload(
QUICHE team6987b4a2019-03-15 16:23:04 -07007073 ENCRYPTION_INITIAL, QuicPacketNumber(1), *packet, buffer, kMaxPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007074
7075 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, _,
7076 ConnectionCloseSource::FROM_PEER));
7077 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7078 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7079
7080 connection_.ProcessUdpPacket(
7081 kSelfAddress, kPeerAddress,
7082 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
7083}
7084
7085TEST_P(QuicConnectionTest, SelectMutualVersion) {
QUICHE teamcd098022019-03-22 18:49:55 -07007086 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7087 return;
7088 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007089 connection_.SetSupportedVersions(AllSupportedVersions());
7090 // Set the connection to speak the lowest quic version.
7091 connection_.set_version(QuicVersionMin());
7092 EXPECT_EQ(QuicVersionMin(), connection_.version());
7093
7094 // Pass in available versions which includes a higher mutually supported
7095 // version. The higher mutually supported version should be selected.
7096 ParsedQuicVersionVector supported_versions = AllSupportedVersions();
7097 EXPECT_TRUE(connection_.SelectMutualVersion(supported_versions));
7098 EXPECT_EQ(QuicVersionMax(), connection_.version());
7099
7100 // Expect that the lowest version is selected.
7101 // Ensure the lowest supported version is less than the max, unless they're
7102 // the same.
7103 ParsedQuicVersionVector lowest_version_vector;
7104 lowest_version_vector.push_back(QuicVersionMin());
7105 EXPECT_TRUE(connection_.SelectMutualVersion(lowest_version_vector));
7106 EXPECT_EQ(QuicVersionMin(), connection_.version());
7107
7108 // Shouldn't be able to find a mutually supported version.
7109 ParsedQuicVersionVector unsupported_version;
7110 unsupported_version.push_back(UnsupportedQuicVersion());
7111 EXPECT_FALSE(connection_.SelectMutualVersion(unsupported_version));
7112}
7113
7114TEST_P(QuicConnectionTest, ConnectionCloseWhenWritable) {
QUICHE teamcd098022019-03-22 18:49:55 -07007115 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7116 return;
7117 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007118 EXPECT_FALSE(writer_->IsWriteBlocked());
7119
7120 // Send a packet.
7121 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7122 EXPECT_EQ(0u, connection_.NumQueuedPackets());
7123 EXPECT_EQ(1u, writer_->packets_write_attempts());
7124
7125 TriggerConnectionClose();
7126 EXPECT_EQ(2u, writer_->packets_write_attempts());
7127}
7128
7129TEST_P(QuicConnectionTest, ConnectionCloseGettingWriteBlocked) {
QUICHE teamcd098022019-03-22 18:49:55 -07007130 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7131 return;
7132 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007133 BlockOnNextWrite();
7134 TriggerConnectionClose();
7135 EXPECT_EQ(1u, writer_->packets_write_attempts());
7136 EXPECT_TRUE(writer_->IsWriteBlocked());
7137}
7138
7139TEST_P(QuicConnectionTest, ConnectionCloseWhenWriteBlocked) {
QUICHE teamcd098022019-03-22 18:49:55 -07007140 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7141 return;
7142 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007143 BlockOnNextWrite();
7144 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7145 EXPECT_EQ(1u, connection_.NumQueuedPackets());
7146 EXPECT_EQ(1u, writer_->packets_write_attempts());
7147 EXPECT_TRUE(writer_->IsWriteBlocked());
7148 TriggerConnectionClose();
7149 EXPECT_EQ(1u, writer_->packets_write_attempts());
7150}
7151
7152TEST_P(QuicConnectionTest, OnPacketSentDebugVisitor) {
QUICHE teamcd098022019-03-22 18:49:55 -07007153 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7154 return;
7155 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007156 MockQuicConnectionDebugVisitor debug_visitor;
7157 connection_.set_debug_visitor(&debug_visitor);
7158
7159 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _)).Times(1);
7160 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7161
7162 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _)).Times(1);
7163 connection_.SendConnectivityProbingPacket(writer_.get(),
7164 connection_.peer_address());
7165}
7166
7167TEST_P(QuicConnectionTest, OnPacketHeaderDebugVisitor) {
QUICHE teamcd098022019-03-22 18:49:55 -07007168 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7169 return;
7170 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007171 QuicPacketHeader header;
7172 header.packet_number = QuicPacketNumber(1);
7173 if (GetParam().version.transport_version > QUIC_VERSION_43) {
7174 header.form = IETF_QUIC_LONG_HEADER_PACKET;
7175 }
7176
7177 MockQuicConnectionDebugVisitor debug_visitor;
7178 connection_.set_debug_visitor(&debug_visitor);
7179 EXPECT_CALL(debug_visitor, OnPacketHeader(Ref(header))).Times(1);
7180 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(1);
7181 EXPECT_CALL(debug_visitor, OnSuccessfulVersionNegotiation(_)).Times(1);
7182 connection_.OnPacketHeader(header);
7183}
7184
7185TEST_P(QuicConnectionTest, Pacing) {
QUICHE teamcd098022019-03-22 18:49:55 -07007186 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7187 return;
7188 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007189 TestConnection server(connection_id_, kSelfAddress, helper_.get(),
7190 alarm_factory_.get(), writer_.get(),
7191 Perspective::IS_SERVER, version());
7192 TestConnection client(connection_id_, kPeerAddress, helper_.get(),
7193 alarm_factory_.get(), writer_.get(),
7194 Perspective::IS_CLIENT, version());
7195 EXPECT_FALSE(QuicSentPacketManagerPeer::UsingPacing(
7196 static_cast<const QuicSentPacketManager*>(
7197 &client.sent_packet_manager())));
7198 EXPECT_FALSE(QuicSentPacketManagerPeer::UsingPacing(
7199 static_cast<const QuicSentPacketManager*>(
7200 &server.sent_packet_manager())));
7201}
7202
7203TEST_P(QuicConnectionTest, WindowUpdateInstigateAcks) {
QUICHE teamcd098022019-03-22 18:49:55 -07007204 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7205 return;
7206 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007207 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7208
7209 // Send a WINDOW_UPDATE frame.
7210 QuicWindowUpdateFrame window_update;
7211 window_update.stream_id = 3;
7212 window_update.byte_offset = 1234;
7213 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
7214 ProcessFramePacket(QuicFrame(&window_update));
7215
7216 // Ensure that this has caused the ACK alarm to be set.
7217 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
7218 EXPECT_TRUE(ack_alarm->IsSet());
7219}
7220
7221TEST_P(QuicConnectionTest, BlockedFrameInstigateAcks) {
QUICHE teamcd098022019-03-22 18:49:55 -07007222 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7223 return;
7224 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007225 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7226
7227 // Send a BLOCKED frame.
7228 QuicBlockedFrame blocked;
7229 blocked.stream_id = 3;
7230 EXPECT_CALL(visitor_, OnBlockedFrame(_));
7231 ProcessFramePacket(QuicFrame(&blocked));
7232
7233 // Ensure that this has caused the ACK alarm to be set.
7234 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
7235 EXPECT_TRUE(ack_alarm->IsSet());
7236}
7237
7238TEST_P(QuicConnectionTest, ReevaluateTimeUntilSendOnAck) {
QUICHE teamcd098022019-03-22 18:49:55 -07007239 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7240 return;
7241 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007242 // Enable pacing.
7243 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7244 QuicConfig config;
7245 connection_.SetFromConfig(config);
7246
7247 // Send two packets. One packet is not sufficient because if it gets acked,
7248 // there will be no packets in flight after that and the pacer will always
7249 // allow the next packet in that situation.
7250 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7251 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
7252 connection_.SendStreamDataWithString(
7253 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
7254 0, NO_FIN);
7255 connection_.SendStreamDataWithString(
7256 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "bar",
7257 3, NO_FIN);
7258 connection_.OnCanWrite();
7259
7260 // Schedule the next packet for a few milliseconds in future.
7261 QuicSentPacketManagerPeer::DisablePacerBursts(manager_);
7262 QuicTime scheduled_pacing_time =
7263 clock_.Now() + QuicTime::Delta::FromMilliseconds(5);
7264 QuicSentPacketManagerPeer::SetNextPacedPacketTime(manager_,
7265 scheduled_pacing_time);
7266
7267 // Send a packet and have it be blocked by congestion control.
7268 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(false));
7269 connection_.SendStreamDataWithString(
7270 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "baz",
7271 6, NO_FIN);
7272 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
7273
7274 // Process an ack and the send alarm will be set to the new 5ms delay.
7275 QuicAckFrame ack = InitAckFrame(1);
7276 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
7277 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7278 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
7279 ProcessAckPacket(&ack);
7280 EXPECT_EQ(1u, writer_->frame_count());
7281 EXPECT_EQ(1u, writer_->stream_frames().size());
7282 EXPECT_TRUE(connection_.GetSendAlarm()->IsSet());
7283 EXPECT_EQ(scheduled_pacing_time, connection_.GetSendAlarm()->deadline());
7284 writer_->Reset();
7285}
7286
7287TEST_P(QuicConnectionTest, SendAcksImmediately) {
QUICHE teamcd098022019-03-22 18:49:55 -07007288 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7289 return;
7290 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007291 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7292 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7293 ProcessDataPacket(1);
7294 CongestionBlockWrites();
7295 SendAckPacketToPeer();
7296}
7297
7298TEST_P(QuicConnectionTest, SendPingImmediately) {
QUICHE teamcd098022019-03-22 18:49:55 -07007299 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7300 return;
7301 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007302 MockQuicConnectionDebugVisitor debug_visitor;
7303 connection_.set_debug_visitor(&debug_visitor);
7304
7305 CongestionBlockWrites();
7306 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7307 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _)).Times(1);
7308 EXPECT_CALL(debug_visitor, OnPingSent()).Times(1);
7309 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
7310 EXPECT_FALSE(connection_.HasQueuedData());
7311}
7312
7313TEST_P(QuicConnectionTest, SendBlockedImmediately) {
QUICHE teamcd098022019-03-22 18:49:55 -07007314 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7315 return;
7316 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007317 MockQuicConnectionDebugVisitor debug_visitor;
7318 connection_.set_debug_visitor(&debug_visitor);
7319
7320 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7321 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _)).Times(1);
7322 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7323 connection_.SendControlFrame(QuicFrame(new QuicBlockedFrame(1, 3)));
7324 EXPECT_EQ(1u, connection_.GetStats().blocked_frames_sent);
7325 EXPECT_FALSE(connection_.HasQueuedData());
7326}
7327
7328TEST_P(QuicConnectionTest, SendingUnencryptedStreamDataFails) {
QUICHE teamcd098022019-03-22 18:49:55 -07007329 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7330 return;
7331 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007332 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
7333 if (!IsDefaultTestConfiguration()) {
7334 return;
7335 }
7336
7337 EXPECT_CALL(visitor_,
7338 OnConnectionClosed(QUIC_ATTEMPT_TO_SEND_UNENCRYPTED_STREAM_DATA,
7339 _, ConnectionCloseSource::FROM_SELF));
7340 struct iovec iov;
7341 MakeIOVector("", &iov);
7342 EXPECT_QUIC_BUG(connection_.SaveAndSendStreamData(3, &iov, 1, 0, 0, FIN),
7343 "Cannot send stream data without encryption.");
7344 EXPECT_FALSE(connection_.connected());
7345}
7346
7347TEST_P(QuicConnectionTest, SetRetransmissionAlarmForCryptoPacket) {
QUICHE teamcd098022019-03-22 18:49:55 -07007348 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7349 return;
7350 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007351 EXPECT_TRUE(connection_.connected());
7352 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
7353
7354 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7355 connection_.SendCryptoStreamData();
7356
7357 // Verify retransmission timer is correctly set after crypto packet has been
7358 // sent.
7359 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
7360 QuicTime retransmission_time =
7361 QuicConnectionPeer::GetSentPacketManager(&connection_)
7362 ->GetRetransmissionTime();
7363 EXPECT_NE(retransmission_time, clock_.ApproximateNow());
7364 EXPECT_EQ(retransmission_time,
7365 connection_.GetRetransmissionAlarm()->deadline());
7366
7367 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7368 connection_.GetRetransmissionAlarm()->Fire();
7369}
7370
7371TEST_P(QuicConnectionTest, PathDegradingAlarmForCryptoPacket) {
QUICHE teamcd098022019-03-22 18:49:55 -07007372 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7373 return;
7374 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007375 EXPECT_TRUE(connection_.connected());
7376 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7377 EXPECT_FALSE(connection_.IsPathDegrading());
7378
7379 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7380 connection_.SendCryptoStreamData();
7381
7382 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7383 EXPECT_FALSE(connection_.IsPathDegrading());
7384 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7385 ->GetPathDegradingDelay();
7386 EXPECT_EQ(clock_.ApproximateNow() + delay,
7387 connection_.GetPathDegradingAlarm()->deadline());
7388
7389 // Fire the path degrading alarm, path degrading signal should be sent to
7390 // the visitor.
7391 EXPECT_CALL(visitor_, OnPathDegrading());
7392 clock_.AdvanceTime(delay);
7393 connection_.GetPathDegradingAlarm()->Fire();
7394 EXPECT_TRUE(connection_.IsPathDegrading());
7395 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7396}
7397
7398// Includes regression test for https://b.corp.google.com/issues/69979024.
7399TEST_P(QuicConnectionTest, PathDegradingAlarmForNonCryptoPackets) {
QUICHE teamcd098022019-03-22 18:49:55 -07007400 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7401 return;
7402 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007403 EXPECT_TRUE(connection_.connected());
7404 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7405 EXPECT_FALSE(connection_.IsPathDegrading());
7406
7407 const char data[] = "data";
7408 size_t data_size = strlen(data);
7409 QuicStreamOffset offset = 0;
7410
7411 for (int i = 0; i < 2; ++i) {
7412 // Send a packet. Now there's a retransmittable packet on the wire, so the
7413 // path degrading alarm should be set.
7414 connection_.SendStreamDataWithString(
7415 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
7416 offset, NO_FIN);
7417 offset += data_size;
7418 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7419 // Check the deadline of the path degrading alarm.
7420 QuicTime::Delta delay =
7421 QuicConnectionPeer::GetSentPacketManager(&connection_)
7422 ->GetPathDegradingDelay();
7423 EXPECT_EQ(clock_.ApproximateNow() + delay,
7424 connection_.GetPathDegradingAlarm()->deadline());
7425
7426 // Send a second packet. The path degrading alarm's deadline should remain
7427 // the same.
7428 // Regression test for https://b.corp.google.com/issues/69979024.
7429 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7430 QuicTime prev_deadline = connection_.GetPathDegradingAlarm()->deadline();
7431 connection_.SendStreamDataWithString(
7432 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
7433 offset, NO_FIN);
7434 offset += data_size;
7435 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7436 EXPECT_EQ(prev_deadline, connection_.GetPathDegradingAlarm()->deadline());
7437
7438 // Now receive an ACK of the first packet. This should advance the path
7439 // degrading alarm's deadline since forward progress has been made.
7440 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7441 if (i == 0) {
7442 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7443 }
7444 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7445 QuicAckFrame frame = InitAckFrame(
7446 {{QuicPacketNumber(1u + 2u * i), QuicPacketNumber(2u + 2u * i)}});
7447 ProcessAckPacket(&frame);
7448 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7449 // Check the deadline of the path degrading alarm.
7450 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7451 ->GetPathDegradingDelay();
7452 EXPECT_EQ(clock_.ApproximateNow() + delay,
7453 connection_.GetPathDegradingAlarm()->deadline());
7454
7455 if (i == 0) {
7456 // Now receive an ACK of the second packet. Since there are no more
7457 // retransmittable packets on the wire, this should cancel the path
7458 // degrading alarm.
7459 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7460 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7461 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
7462 ProcessAckPacket(&frame);
7463 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7464 } else {
7465 // Advance time to the path degrading alarm's deadline and simulate
7466 // firing the alarm.
7467 clock_.AdvanceTime(delay);
7468 EXPECT_CALL(visitor_, OnPathDegrading());
7469 connection_.GetPathDegradingAlarm()->Fire();
7470 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7471 }
7472 }
7473 EXPECT_TRUE(connection_.IsPathDegrading());
7474}
7475
7476TEST_P(QuicConnectionTest, RetransmittableOnWireSetsPingAlarm) {
QUICHE teamcd098022019-03-22 18:49:55 -07007477 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7478 return;
7479 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007480 const QuicTime::Delta retransmittable_on_wire_timeout =
7481 QuicTime::Delta::FromMilliseconds(50);
7482 connection_.set_retransmittable_on_wire_timeout(
7483 retransmittable_on_wire_timeout);
7484
7485 EXPECT_TRUE(connection_.connected());
7486 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7487 .WillRepeatedly(Return(true));
7488
7489 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7490 EXPECT_FALSE(connection_.IsPathDegrading());
7491 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
7492
7493 const char data[] = "data";
7494 size_t data_size = strlen(data);
7495 QuicStreamOffset offset = 0;
7496
7497 // Send a packet.
7498 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7499 offset += data_size;
7500 // Now there's a retransmittable packet on the wire, so the path degrading
7501 // alarm should be set.
7502 // The retransmittable-on-wire alarm should not be set.
7503 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7504 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7505 ->GetPathDegradingDelay();
7506 EXPECT_EQ(clock_.ApproximateNow() + delay,
7507 connection_.GetPathDegradingAlarm()->deadline());
7508 ASSERT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
7509 // The ping alarm is set for the ping timeout, not the shorter
7510 // retransmittable_on_wire_timeout.
7511 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7512 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
7513 EXPECT_EQ((clock_.ApproximateNow() + ping_delay),
7514 connection_.GetPingAlarm()->deadline());
7515
7516 // Now receive an ACK of the packet.
7517 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7518 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7519 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7520 QuicAckFrame frame =
7521 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7522 ProcessAckPacket(&frame);
7523 // No more retransmittable packets on the wire, so the path degrading alarm
7524 // should be cancelled, and the ping alarm should be set to the
7525 // retransmittable_on_wire_timeout.
7526 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7527 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7528 EXPECT_EQ(clock_.ApproximateNow() + retransmittable_on_wire_timeout,
7529 connection_.GetPingAlarm()->deadline());
7530
7531 // Simulate firing the ping alarm and sending a PING.
7532 clock_.AdvanceTime(retransmittable_on_wire_timeout);
7533 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
7534 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
7535 }));
7536 connection_.GetPingAlarm()->Fire();
7537
7538 // Now there's a retransmittable packet (PING) on the wire, so the path
7539 // degrading alarm should be set.
7540 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7541 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7542 ->GetPathDegradingDelay();
7543 EXPECT_EQ(clock_.ApproximateNow() + delay,
7544 connection_.GetPathDegradingAlarm()->deadline());
7545}
7546
7547// This test verifies that the connection marks path as degrading and does not
7548// spin timer to detect path degrading when a new packet is sent on the
7549// degraded path.
7550TEST_P(QuicConnectionTest, NoPathDegradingAlarmIfPathIsDegrading) {
QUICHE teamcd098022019-03-22 18:49:55 -07007551 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7552 return;
7553 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007554 EXPECT_TRUE(connection_.connected());
7555 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7556 EXPECT_FALSE(connection_.IsPathDegrading());
7557
7558 const char data[] = "data";
7559 size_t data_size = strlen(data);
7560 QuicStreamOffset offset = 0;
7561
7562 // Send the first packet. Now there's a retransmittable packet on the wire, so
7563 // the path degrading alarm should be set.
7564 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7565 offset += data_size;
7566 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7567 // Check the deadline of the path degrading alarm.
7568 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7569 ->GetPathDegradingDelay();
7570 EXPECT_EQ(clock_.ApproximateNow() + delay,
7571 connection_.GetPathDegradingAlarm()->deadline());
7572
7573 // Send a second packet. The path degrading alarm's deadline should remain
7574 // the same.
7575 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7576 QuicTime prev_deadline = connection_.GetPathDegradingAlarm()->deadline();
7577 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7578 offset += data_size;
7579 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7580 EXPECT_EQ(prev_deadline, connection_.GetPathDegradingAlarm()->deadline());
7581
7582 // Now receive an ACK of the first packet. This should advance the path
7583 // degrading alarm's deadline since forward progress has been made.
7584 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7585 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7586 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7587 QuicAckFrame frame =
7588 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
7589 ProcessAckPacket(&frame);
7590 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7591 // Check the deadline of the path degrading alarm.
7592 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7593 ->GetPathDegradingDelay();
7594 EXPECT_EQ(clock_.ApproximateNow() + delay,
7595 connection_.GetPathDegradingAlarm()->deadline());
7596
7597 // Advance time to the path degrading alarm's deadline and simulate
7598 // firing the path degrading alarm. This path will be considered as
7599 // degrading.
7600 clock_.AdvanceTime(delay);
7601 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
7602 connection_.GetPathDegradingAlarm()->Fire();
7603 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7604 EXPECT_TRUE(connection_.IsPathDegrading());
7605
7606 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7607 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7608 // Send a third packet. The path degrading alarm is no longer set but path
7609 // should still be marked as degrading.
7610 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7611 offset += data_size;
7612 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7613 EXPECT_TRUE(connection_.IsPathDegrading());
7614}
7615
7616// This test verifies that the connection unmarks path as degrarding and spins
7617// the timer to detect future path degrading when forward progress is made
7618// after path has been marked degrading.
7619TEST_P(QuicConnectionTest, UnmarkPathDegradingOnForwardProgress) {
QUICHE teamcd098022019-03-22 18:49:55 -07007620 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7621 return;
7622 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007623 EXPECT_TRUE(connection_.connected());
7624 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7625 EXPECT_FALSE(connection_.IsPathDegrading());
7626
7627 const char data[] = "data";
7628 size_t data_size = strlen(data);
7629 QuicStreamOffset offset = 0;
7630
7631 // Send the first packet. Now there's a retransmittable packet on the wire, so
7632 // the path degrading alarm should be set.
7633 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7634 offset += data_size;
7635 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7636 // Check the deadline of the path degrading alarm.
7637 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7638 ->GetPathDegradingDelay();
7639 EXPECT_EQ(clock_.ApproximateNow() + delay,
7640 connection_.GetPathDegradingAlarm()->deadline());
7641
7642 // Send a second packet. The path degrading alarm's deadline should remain
7643 // the same.
7644 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7645 QuicTime prev_deadline = connection_.GetPathDegradingAlarm()->deadline();
7646 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7647 offset += data_size;
7648 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7649 EXPECT_EQ(prev_deadline, connection_.GetPathDegradingAlarm()->deadline());
7650
7651 // Now receive an ACK of the first packet. This should advance the path
7652 // degrading alarm's deadline since forward progress has been made.
7653 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7654 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7655 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7656 QuicAckFrame frame =
7657 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
7658 ProcessAckPacket(&frame);
7659 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7660 // Check the deadline of the path degrading alarm.
7661 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7662 ->GetPathDegradingDelay();
7663 EXPECT_EQ(clock_.ApproximateNow() + delay,
7664 connection_.GetPathDegradingAlarm()->deadline());
7665
7666 // Advance time to the path degrading alarm's deadline and simulate
7667 // firing the alarm.
7668 clock_.AdvanceTime(delay);
7669 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
7670 connection_.GetPathDegradingAlarm()->Fire();
7671 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7672 EXPECT_TRUE(connection_.IsPathDegrading());
7673
7674 // Send a third packet. The path degrading alarm is no longer set but path
7675 // should still be marked as degrading.
7676 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7677 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7678 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7679 offset += data_size;
7680 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7681 EXPECT_TRUE(connection_.IsPathDegrading());
7682
7683 // Now receive an ACK of the second packet. This should unmark the path as
7684 // degrading. And will set a timer to detect new path degrading.
7685 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7686 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7687 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
7688 ProcessAckPacket(&frame);
7689 EXPECT_FALSE(connection_.IsPathDegrading());
7690 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7691}
7692
7693TEST_P(QuicConnectionTest, NoPathDegradingOnServer) {
QUICHE teamcd098022019-03-22 18:49:55 -07007694 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7695 return;
7696 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007697 set_perspective(Perspective::IS_SERVER);
7698 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
7699
7700 EXPECT_FALSE(connection_.IsPathDegrading());
7701 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7702
7703 // Send data.
7704 const char data[] = "data";
7705 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
7706 EXPECT_FALSE(connection_.IsPathDegrading());
7707 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7708
7709 // Ack data.
7710 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7711 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7712 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7713 QuicAckFrame frame =
7714 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
7715 ProcessAckPacket(&frame);
7716 EXPECT_FALSE(connection_.IsPathDegrading());
7717 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7718}
7719
7720TEST_P(QuicConnectionTest, NoPathDegradingAfterSendingAck) {
QUICHE teamcd098022019-03-22 18:49:55 -07007721 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7722 return;
7723 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007724 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7725 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7726 ProcessDataPacket(1);
7727 SendAckPacketToPeer();
7728 EXPECT_FALSE(connection_.sent_packet_manager().unacked_packets().empty());
7729 EXPECT_FALSE(connection_.sent_packet_manager().HasInFlightPackets());
7730 EXPECT_FALSE(connection_.IsPathDegrading());
7731 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7732}
7733
7734TEST_P(QuicConnectionTest, MultipleCallsToCloseConnection) {
QUICHE teamcd098022019-03-22 18:49:55 -07007735 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7736 return;
7737 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007738 // Verifies that multiple calls to CloseConnection do not
7739 // result in multiple attempts to close the connection - it will be marked as
7740 // disconnected after the first call.
7741 EXPECT_CALL(visitor_, OnConnectionClosed(_, _, _)).Times(1);
7742 connection_.CloseConnection(QUIC_NO_ERROR, "no reason",
7743 ConnectionCloseBehavior::SILENT_CLOSE);
7744 connection_.CloseConnection(QUIC_NO_ERROR, "no reason",
7745 ConnectionCloseBehavior::SILENT_CLOSE);
7746}
7747
7748TEST_P(QuicConnectionTest, ServerReceivesChloOnNonCryptoStream) {
QUICHE teamcd098022019-03-22 18:49:55 -07007749 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7750 return;
7751 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007752 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7753
7754 set_perspective(Perspective::IS_SERVER);
7755 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
7756
7757 CryptoHandshakeMessage message;
7758 CryptoFramer framer;
7759 message.set_tag(kCHLO);
QUICHE team3fe6a8b2019-03-14 09:10:38 -07007760 std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007761 frame1_.stream_id = 10;
7762 frame1_.data_buffer = data->data();
7763 frame1_.data_length = data->length();
7764
7765 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_MAYBE_CORRUPTED_MEMORY, _,
7766 ConnectionCloseSource::FROM_SELF));
7767 ForceProcessFramePacket(QuicFrame(frame1_));
7768}
7769
7770TEST_P(QuicConnectionTest, ClientReceivesRejOnNonCryptoStream) {
QUICHE teamcd098022019-03-22 18:49:55 -07007771 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7772 return;
7773 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007774 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7775
7776 CryptoHandshakeMessage message;
7777 CryptoFramer framer;
7778 message.set_tag(kREJ);
QUICHE team3fe6a8b2019-03-14 09:10:38 -07007779 std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007780 frame1_.stream_id = 10;
7781 frame1_.data_buffer = data->data();
7782 frame1_.data_length = data->length();
7783
7784 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_MAYBE_CORRUPTED_MEMORY, _,
7785 ConnectionCloseSource::FROM_SELF));
7786 ForceProcessFramePacket(QuicFrame(frame1_));
7787}
7788
7789TEST_P(QuicConnectionTest, CloseConnectionOnPacketTooLarge) {
QUICHE teamcd098022019-03-22 18:49:55 -07007790 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7791 return;
7792 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007793 SimulateNextPacketTooLarge();
7794 // A connection close packet is sent
7795 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PACKET_WRITE_ERROR, _,
7796 ConnectionCloseSource::FROM_SELF))
7797 .Times(1);
7798 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7799}
7800
7801TEST_P(QuicConnectionTest, AlwaysGetPacketTooLarge) {
QUICHE teamcd098022019-03-22 18:49:55 -07007802 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7803 return;
7804 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007805 // Test even we always get packet too large, we do not infinitely try to send
7806 // close packet.
7807 AlwaysGetPacketTooLarge();
7808 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PACKET_WRITE_ERROR, _,
7809 ConnectionCloseSource::FROM_SELF))
7810 .Times(1);
7811 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7812}
7813
7814// Verify that if connection has no outstanding data, it notifies the send
7815// algorithm after the write.
7816TEST_P(QuicConnectionTest, SendDataAndBecomeApplicationLimited) {
QUICHE teamcd098022019-03-22 18:49:55 -07007817 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7818 return;
7819 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007820 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
7821 {
7822 InSequence seq;
7823 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7824 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7825 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
7826 .WillRepeatedly(Return(false));
7827 }
7828
7829 connection_.SendStreamData3();
7830}
7831
7832// Verify that the connection does not become app-limited if there is
7833// outstanding data to send after the write.
7834TEST_P(QuicConnectionTest, NotBecomeApplicationLimitedIfMoreDataAvailable) {
QUICHE teamcd098022019-03-22 18:49:55 -07007835 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7836 return;
7837 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007838 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
7839 {
7840 InSequence seq;
7841 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7842 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7843 }
7844
7845 connection_.SendStreamData3();
7846}
7847
7848// Verify that the connection does not become app-limited after blocked write
7849// even if there is outstanding data to send after the write.
7850TEST_P(QuicConnectionTest, NotBecomeApplicationLimitedDueToWriteBlock) {
QUICHE teamcd098022019-03-22 18:49:55 -07007851 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7852 return;
7853 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007854 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
7855 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7856 BlockOnNextWrite();
7857
7858 connection_.SendStreamData3();
7859
7860 // Now unblock the writer, become congestion control blocked,
7861 // and ensure we become app-limited after writing.
7862 writer_->SetWritable();
7863 CongestionBlockWrites();
7864 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(false));
7865 {
7866 InSequence seq;
7867 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7868 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
7869 }
7870 connection_.OnCanWrite();
7871}
7872
7873// Test the mode in which the link is filled up with probing retransmissions if
7874// the connection becomes application-limited.
7875TEST_P(QuicConnectionTest, SendDataWhenApplicationLimited) {
QUICHE teamcd098022019-03-22 18:49:55 -07007876 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7877 return;
7878 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007879 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7880 EXPECT_CALL(*send_algorithm_, ShouldSendProbingPacket())
7881 .WillRepeatedly(Return(true));
7882 {
7883 InSequence seq;
7884 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7885 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7886 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
7887 .WillRepeatedly(Return(false));
7888 }
7889 // Fix congestion window to be 20,000 bytes.
7890 EXPECT_CALL(*send_algorithm_, CanSend(Ge(20000u)))
7891 .WillRepeatedly(Return(false));
7892 EXPECT_CALL(*send_algorithm_, CanSend(Lt(20000u)))
7893 .WillRepeatedly(Return(true));
7894
7895 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
7896 ASSERT_EQ(0u, connection_.GetStats().packets_sent);
7897 connection_.set_fill_up_link_during_probing(true);
7898 connection_.OnHandshakeComplete();
7899 connection_.SendStreamData3();
7900
7901 // We expect a lot of packets from a 20 kbyte window.
7902 EXPECT_GT(connection_.GetStats().packets_sent, 10u);
7903 // Ensure that the packets are padded.
7904 QuicByteCount average_packet_size =
7905 connection_.GetStats().bytes_sent / connection_.GetStats().packets_sent;
7906 EXPECT_GT(average_packet_size, 1000u);
7907
7908 // Acknowledge all packets sent, except for the last one.
7909 QuicAckFrame ack = InitAckFrame(
7910 connection_.sent_packet_manager().GetLargestSentPacket() - 1);
7911 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
7912 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7913
7914 // Ensure that since we no longer have retransmittable bytes in flight, this
7915 // will not cause any responses to be sent.
7916 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
7917 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
7918 ProcessAckPacket(&ack);
7919}
7920
7921TEST_P(QuicConnectionTest, DonotForceSendingAckOnPacketTooLarge) {
QUICHE teamcd098022019-03-22 18:49:55 -07007922 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7923 return;
7924 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007925 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7926 // Send an ack by simulating delayed ack alarm firing.
7927 ProcessPacket(1);
7928 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
7929 EXPECT_TRUE(ack_alarm->IsSet());
7930 connection_.GetAckAlarm()->Fire();
7931 // Simulate data packet causes write error.
7932 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PACKET_WRITE_ERROR, _, _));
7933 SimulateNextPacketTooLarge();
7934 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7935 EXPECT_EQ(1u, writer_->frame_count());
7936 EXPECT_FALSE(writer_->connection_close_frames().empty());
7937 // Ack frame is not bundled in connection close packet.
7938 EXPECT_TRUE(writer_->ack_frames().empty());
7939}
7940
7941TEST_P(QuicConnectionTest, CloseConnectionForStatelessReject) {
QUICHE teamcd098022019-03-22 18:49:55 -07007942 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7943 return;
7944 }
vasilvvc48c8712019-03-11 13:38:16 -07007945 std::string error_details("stateless reject");
QUICHE teama6ef0a62019-03-07 20:34:33 -05007946 EXPECT_CALL(visitor_, OnConnectionClosed(
7947 QUIC_CRYPTO_HANDSHAKE_STATELESS_REJECT,
7948 error_details, ConnectionCloseSource::FROM_PEER));
7949 connection_.set_perspective(Perspective::IS_CLIENT);
7950 connection_.CloseConnection(QUIC_CRYPTO_HANDSHAKE_STATELESS_REJECT,
7951 error_details,
7952 ConnectionCloseBehavior::SILENT_CLOSE);
7953}
7954
7955// Regression test for b/63620844.
7956TEST_P(QuicConnectionTest, FailedToWriteHandshakePacket) {
QUICHE teamcd098022019-03-22 18:49:55 -07007957 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7958 return;
7959 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007960 SimulateNextPacketTooLarge();
7961 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PACKET_WRITE_ERROR, _,
7962 ConnectionCloseSource::FROM_SELF))
7963 .Times(1);
7964 connection_.SendCryptoStreamData();
7965}
7966
7967TEST_P(QuicConnectionTest, MaxPacingRate) {
QUICHE teamcd098022019-03-22 18:49:55 -07007968 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7969 return;
7970 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007971 EXPECT_EQ(0, connection_.MaxPacingRate().ToBytesPerSecond());
7972 connection_.SetMaxPacingRate(QuicBandwidth::FromBytesPerSecond(100));
7973 EXPECT_EQ(100, connection_.MaxPacingRate().ToBytesPerSecond());
7974}
7975
7976TEST_P(QuicConnectionTest, ClientAlwaysSendConnectionId) {
QUICHE teamcd098022019-03-22 18:49:55 -07007977 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7978 return;
7979 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007980 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
7981 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7982 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7983 EXPECT_EQ(CONNECTION_ID_PRESENT,
7984 writer_->last_packet_header().destination_connection_id_included);
7985
7986 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7987 QuicConfig config;
7988 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
7989 connection_.SetFromConfig(config);
7990
7991 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7992 connection_.SendStreamDataWithString(3, "bar", 3, NO_FIN);
7993 // Verify connection id is still sent in the packet.
7994 EXPECT_EQ(CONNECTION_ID_PRESENT,
7995 writer_->last_packet_header().destination_connection_id_included);
7996}
7997
7998TEST_P(QuicConnectionTest, SendProbingRetransmissions) {
QUICHE teamcd098022019-03-22 18:49:55 -07007999 if (connection_.SupportsMultiplePacketNumberSpaces()) {
8000 return;
8001 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008002 MockQuicConnectionDebugVisitor debug_visitor;
8003 connection_.set_debug_visitor(&debug_visitor);
8004
8005 const QuicStreamId stream_id = 2;
8006 QuicPacketNumber last_packet;
8007 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
8008 SendStreamDataToPeer(stream_id, "bar", 3, NO_FIN, &last_packet);
8009 SendStreamDataToPeer(stream_id, "test", 6, NO_FIN, &last_packet);
8010
8011 const QuicByteCount old_bytes_in_flight =
8012 connection_.sent_packet_manager().GetBytesInFlight();
8013
8014 // Allow 9 probing retransmissions to be sent.
8015 {
8016 InSequence seq;
8017 EXPECT_CALL(*send_algorithm_, CanSend(_))
8018 .Times(9 * 2)
8019 .WillRepeatedly(Return(true));
8020 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(Return(false));
8021 }
8022 // Expect them retransmitted in cyclic order (foo, bar, test, foo, bar...).
8023 QuicPacketCount sent_count = 0;
8024 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _))
8025 .WillRepeatedly(Invoke([this, &sent_count](const SerializedPacket&,
8026 QuicPacketNumber,
8027 TransmissionType, QuicTime) {
8028 ASSERT_EQ(1u, writer_->stream_frames().size());
8029 // Identify the frames by stream offset (0, 3, 6, 0, 3...).
8030 EXPECT_EQ(3 * (sent_count % 3), writer_->stream_frames()[0]->offset);
8031 sent_count++;
8032 }));
8033 EXPECT_CALL(*send_algorithm_, ShouldSendProbingPacket())
8034 .WillRepeatedly(Return(true));
8035
8036 connection_.SendProbingRetransmissions();
8037
8038 // Ensure that the in-flight has increased.
8039 const QuicByteCount new_bytes_in_flight =
8040 connection_.sent_packet_manager().GetBytesInFlight();
8041 EXPECT_GT(new_bytes_in_flight, old_bytes_in_flight);
8042}
8043
8044// Ensure that SendProbingRetransmissions() does not retransmit anything when
8045// there are no outstanding packets.
8046TEST_P(QuicConnectionTest,
8047 SendProbingRetransmissionsFailsWhenNothingToRetransmit) {
QUICHE teamcd098022019-03-22 18:49:55 -07008048 if (connection_.SupportsMultiplePacketNumberSpaces()) {
8049 return;
8050 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008051 ASSERT_TRUE(connection_.sent_packet_manager().unacked_packets().empty());
8052
8053 MockQuicConnectionDebugVisitor debug_visitor;
8054 connection_.set_debug_visitor(&debug_visitor);
8055 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _)).Times(0);
8056 EXPECT_CALL(*send_algorithm_, ShouldSendProbingPacket())
8057 .WillRepeatedly(Return(true));
8058
8059 connection_.SendProbingRetransmissions();
8060}
8061
8062TEST_P(QuicConnectionTest, PingAfterLastRetransmittablePacketAcked) {
QUICHE teamcd098022019-03-22 18:49:55 -07008063 if (connection_.SupportsMultiplePacketNumberSpaces()) {
8064 return;
8065 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008066 const QuicTime::Delta retransmittable_on_wire_timeout =
8067 QuicTime::Delta::FromMilliseconds(50);
8068 connection_.set_retransmittable_on_wire_timeout(
8069 retransmittable_on_wire_timeout);
8070
8071 EXPECT_TRUE(connection_.connected());
8072 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8073 .WillRepeatedly(Return(true));
8074
8075 const char data[] = "data";
8076 size_t data_size = strlen(data);
8077 QuicStreamOffset offset = 0;
8078
8079 // Advance 5ms, send a retransmittable packet to the peer.
8080 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8081 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8082 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8083 offset += data_size;
8084 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8085 // The ping alarm is set for the ping timeout, not the shorter
8086 // retransmittable_on_wire_timeout.
8087 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8088 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
8089 EXPECT_EQ((clock_.ApproximateNow() + ping_delay),
8090 connection_.GetPingAlarm()->deadline());
8091
8092 // Advance 5ms, send a second retransmittable packet to the peer.
8093 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8094 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8095 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8096 offset += data_size;
8097 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8098
8099 // Now receive an ACK of the first packet. This should not set the
8100 // retransmittable-on-wire alarm since packet 2 is still on the wire.
8101 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8102 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8103 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8104 QuicAckFrame frame =
8105 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8106 ProcessAckPacket(&frame);
8107 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8108 // The ping alarm is set for the ping timeout, not the shorter
8109 // retransmittable_on_wire_timeout.
8110 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8111 // The ping alarm has a 1 second granularity, and the clock has been advanced
8112 // 10ms since it was originally set.
8113 EXPECT_EQ((clock_.ApproximateNow() + ping_delay -
8114 QuicTime::Delta::FromMilliseconds(10)),
8115 connection_.GetPingAlarm()->deadline());
8116
8117 // Now receive an ACK of the second packet. This should set the
8118 // retransmittable-on-wire alarm now that no retransmittable packets are on
8119 // the wire.
8120 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8121 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8122 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8123 ProcessAckPacket(&frame);
8124 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8125 EXPECT_EQ(clock_.ApproximateNow() + retransmittable_on_wire_timeout,
8126 connection_.GetPingAlarm()->deadline());
8127
8128 // Now receive a duplicate ACK of the second packet. This should not update
8129 // the ping alarm.
8130 QuicTime prev_deadline = connection_.GetPingAlarm()->deadline();
8131 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8132 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8133 ProcessAckPacket(&frame);
8134 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8135 EXPECT_EQ(prev_deadline, connection_.GetPingAlarm()->deadline());
8136
8137 // Now receive a non-ACK packet. This should not update the ping alarm.
8138 prev_deadline = connection_.GetPingAlarm()->deadline();
8139 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8140 ProcessPacket(4);
8141 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8142 EXPECT_EQ(prev_deadline, connection_.GetPingAlarm()->deadline());
8143
8144 // Simulate the alarm firing and check that a PING is sent.
8145 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8146 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
8147 }));
8148 connection_.GetPingAlarm()->Fire();
8149 if (GetParam().no_stop_waiting) {
8150 EXPECT_EQ(2u, writer_->frame_count());
8151 } else {
8152 EXPECT_EQ(3u, writer_->frame_count());
8153 }
8154 ASSERT_EQ(1u, writer_->ping_frames().size());
8155}
8156
8157TEST_P(QuicConnectionTest, NoPingIfRetransmittablePacketSent) {
QUICHE teamcd098022019-03-22 18:49:55 -07008158 if (connection_.SupportsMultiplePacketNumberSpaces()) {
8159 return;
8160 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008161 const QuicTime::Delta retransmittable_on_wire_timeout =
8162 QuicTime::Delta::FromMilliseconds(50);
8163 connection_.set_retransmittable_on_wire_timeout(
8164 retransmittable_on_wire_timeout);
8165
8166 EXPECT_TRUE(connection_.connected());
8167 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8168 .WillRepeatedly(Return(true));
8169
8170 const char data[] = "data";
8171 size_t data_size = strlen(data);
8172 QuicStreamOffset offset = 0;
8173
8174 // Advance 5ms, send a retransmittable packet to the peer.
8175 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8176 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8177 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8178 offset += data_size;
8179 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8180 // The ping alarm is set for the ping timeout, not the shorter
8181 // retransmittable_on_wire_timeout.
8182 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8183 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
8184 EXPECT_EQ((clock_.ApproximateNow() + ping_delay),
8185 connection_.GetPingAlarm()->deadline());
8186
8187 // Now receive an ACK of the first packet. This should set the
8188 // retransmittable-on-wire alarm now that no retransmittable packets are on
8189 // the wire.
8190 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8191 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8192 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8193 QuicAckFrame frame =
8194 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8195 ProcessAckPacket(&frame);
8196 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8197 EXPECT_EQ(clock_.ApproximateNow() + retransmittable_on_wire_timeout,
8198 connection_.GetPingAlarm()->deadline());
8199
8200 // Before the alarm fires, send another retransmittable packet. This should
8201 // cancel the retransmittable-on-wire alarm since now there's a
8202 // retransmittable packet on the wire.
8203 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8204 offset += data_size;
8205 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8206
8207 // Now receive an ACK of the second packet. This should set the
8208 // retransmittable-on-wire alarm now that no retransmittable packets are on
8209 // the wire.
8210 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8211 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8212 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8213 ProcessAckPacket(&frame);
8214 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8215 EXPECT_EQ(clock_.ApproximateNow() + retransmittable_on_wire_timeout,
8216 connection_.GetPingAlarm()->deadline());
8217
8218 // Simulate the alarm firing and check that a PING is sent.
8219 writer_->Reset();
8220 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8221 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
8222 }));
8223 connection_.GetPingAlarm()->Fire();
8224 if (GetParam().no_stop_waiting) {
8225 EXPECT_EQ(2u, writer_->frame_count());
8226 } else {
8227 EXPECT_EQ(3u, writer_->frame_count());
8228 }
8229 ASSERT_EQ(1u, writer_->ping_frames().size());
8230}
8231
8232TEST_P(QuicConnectionTest, OnForwardProgressConfirmed) {
QUICHE teamcd098022019-03-22 18:49:55 -07008233 if (connection_.SupportsMultiplePacketNumberSpaces()) {
8234 return;
8235 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008236 EXPECT_CALL(visitor_, OnForwardProgressConfirmed()).Times(Exactly(0));
8237 EXPECT_TRUE(connection_.connected());
8238
8239 const char data[] = "data";
8240 size_t data_size = strlen(data);
8241 QuicStreamOffset offset = 0;
8242
8243 // Send two packets.
8244 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8245 offset += data_size;
8246 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8247 offset += data_size;
8248
8249 // Ack packet 1. This increases the largest_acked to 1, so
8250 // OnForwardProgressConfirmed() should be called
8251 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8252 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8253 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8254 EXPECT_CALL(visitor_, OnForwardProgressConfirmed());
8255 QuicAckFrame frame =
8256 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8257 ProcessAckPacket(&frame);
8258
8259 // Ack packet 1 again. largest_acked remains at 1, so
8260 // OnForwardProgressConfirmed() should not be called.
8261 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8262 frame = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8263 ProcessAckPacket(&frame);
8264
8265 // Ack packet 2. This increases the largest_acked to 2, so
8266 // OnForwardProgressConfirmed() should be called.
8267 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8268 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8269 EXPECT_CALL(visitor_, OnForwardProgressConfirmed());
8270 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8271 ProcessAckPacket(&frame);
8272}
8273
8274TEST_P(QuicConnectionTest, ValidStatelessResetToken) {
QUICHE teamcd098022019-03-22 18:49:55 -07008275 if (connection_.SupportsMultiplePacketNumberSpaces()) {
8276 return;
8277 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008278 const QuicUint128 kTestToken = 1010101;
8279 const QuicUint128 kWrongTestToken = 1010100;
8280 QuicConfig config;
8281 // No token has been received.
8282 EXPECT_FALSE(connection_.IsValidStatelessResetToken(kTestToken));
8283
8284 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(2);
8285 // Token is different from received token.
8286 QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestToken);
8287 connection_.SetFromConfig(config);
8288 EXPECT_FALSE(connection_.IsValidStatelessResetToken(kWrongTestToken));
8289
8290 QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestToken);
8291 connection_.SetFromConfig(config);
8292 EXPECT_TRUE(connection_.IsValidStatelessResetToken(kTestToken));
8293}
8294
8295TEST_P(QuicConnectionTest, WriteBlockedWithInvalidAck) {
QUICHE teamcd098022019-03-22 18:49:55 -07008296 if (connection_.SupportsMultiplePacketNumberSpaces()) {
8297 return;
8298 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008299 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8300 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, _, _));
8301
8302 BlockOnNextWrite();
8303 connection_.SendStreamDataWithString(5, "foo", 0, FIN);
8304 // This causes connection to be closed because packet 1 has not been sent yet.
8305 QuicAckFrame frame = InitAckFrame(1);
8306 ProcessAckPacket(1, &frame);
8307}
8308
8309TEST_P(QuicConnectionTest, SendMessage) {
QUICHE teamcd098022019-03-22 18:49:55 -07008310 if (connection_.transport_version() <= QUIC_VERSION_44 ||
8311 connection_.SupportsMultiplePacketNumberSpaces()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008312 return;
8313 }
vasilvvc48c8712019-03-11 13:38:16 -07008314 std::string message(connection_.GetLargestMessagePayload() * 2, 'a');
QUICHE teama6ef0a62019-03-07 20:34:33 -05008315 QuicStringPiece message_data(message);
8316 QuicMemSliceStorage storage(nullptr, 0, nullptr, 0);
8317 {
8318 QuicConnection::ScopedPacketFlusher flusher(&connection_,
8319 QuicConnection::SEND_ACK);
8320 connection_.SendStreamData3();
8321 // Send a message which cannot fit into current open packet, and 2 packets
8322 // get sent, one contains stream frame, and the other only contains the
8323 // message frame.
8324 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
8325 EXPECT_EQ(
8326 MESSAGE_STATUS_SUCCESS,
8327 connection_.SendMessage(
8328 1, MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(),
8329 QuicStringPiece(message_data.data(),
8330 connection_.GetLargestMessagePayload()),
8331 &storage)));
8332 }
8333 // Fail to send a message if connection is congestion control blocked.
8334 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(Return(false));
8335 EXPECT_EQ(
8336 MESSAGE_STATUS_BLOCKED,
8337 connection_.SendMessage(
8338 2, MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(),
8339 "message", &storage)));
8340
8341 // Always fail to send a message which cannot fit into one packet.
8342 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8343 EXPECT_EQ(
8344 MESSAGE_STATUS_TOO_LARGE,
8345 connection_.SendMessage(
8346 3,
8347 MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(),
8348 QuicStringPiece(message_data.data(),
8349 connection_.GetLargestMessagePayload() + 1),
8350 &storage)));
8351}
8352
8353// Test to check that the path challenge/path response logic works
8354// correctly. This test is only for version-99
8355TEST_P(QuicConnectionTest, PathChallengeResponse) {
QUICHE teamcd098022019-03-22 18:49:55 -07008356 if (connection_.version().transport_version != QUIC_VERSION_99 ||
8357 connection_.SupportsMultiplePacketNumberSpaces()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008358 return;
8359 }
8360 // First check if we can probe from server to client and back
8361 set_perspective(Perspective::IS_SERVER);
8362 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
8363
8364 // Create and send the probe request (PATH_CHALLENGE frame).
8365 // SendConnectivityProbingPacket ends up calling
8366 // TestPacketWriter::WritePacket() which in turns receives and parses the
8367 // packet by calling framer_.ProcessPacket() -- which in turn calls
8368 // SimpleQuicFramer::OnPathChallengeFrame(). SimpleQuicFramer saves
8369 // the packet in writer_->path_challenge_frames()
8370 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8371 connection_.SendConnectivityProbingPacket(writer_.get(),
8372 connection_.peer_address());
8373 // Save the random contents of the challenge for later comparison to the
8374 // response.
8375 QuicPathFrameBuffer challenge_data =
8376 writer_->path_challenge_frames().front().data_buffer;
8377
8378 // Normally, QuicConnection::OnPathChallengeFrame and OnPaddingFrame would be
8379 // called and it will perform actions to ensure that the rest of the protocol
8380 // is performed (specifically, call UpdatePacketContent to say that this is a
8381 // path challenge so that when QuicConnection::OnPacketComplete is called
8382 // (again, out of the framer), the response is generated). Simulate those
8383 // calls so that the right internal state is set up for generating
8384 // the response.
8385 EXPECT_TRUE(connection_.OnPathChallengeFrame(
8386 writer_->path_challenge_frames().front()));
8387 EXPECT_TRUE(connection_.OnPaddingFrame(writer_->padding_frames().front()));
8388 // Cause the response to be created and sent. Result is that the response
8389 // should be stashed in writer's path_response_frames.
8390 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8391 connection_.SendConnectivityProbingResponsePacket(connection_.peer_address());
8392
8393 // The final check is to ensure that the random data in the response matches
8394 // the random data from the challenge.
8395 EXPECT_EQ(0, memcmp(&challenge_data,
8396 &(writer_->path_response_frames().front().data_buffer),
8397 sizeof(challenge_data)));
8398}
8399
8400// Regression test for b/110259444
8401TEST_P(QuicConnectionTest, DoNotScheduleSpuriousAckAlarm) {
QUICHE teamcd098022019-03-22 18:49:55 -07008402 if (connection_.SupportsMultiplePacketNumberSpaces()) {
8403 return;
8404 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008405 SetQuicReloadableFlag(quic_fix_spurious_ack_alarm, true);
8406 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8407 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
8408 writer_->SetWriteBlocked();
8409
8410 ProcessPacket(1);
8411 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
8412 // Verify ack alarm is set.
8413 EXPECT_TRUE(ack_alarm->IsSet());
8414 // Fire the ack alarm, verify no packet is sent because the writer is blocked.
8415 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8416 connection_.GetAckAlarm()->Fire();
8417
8418 writer_->SetWritable();
8419 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8420 ProcessPacket(2);
8421 // Verify ack alarm is not set.
8422 EXPECT_FALSE(ack_alarm->IsSet());
8423}
8424
8425TEST_P(QuicConnectionTest, DisablePacingOffloadConnectionOptions) {
QUICHE teamcd098022019-03-22 18:49:55 -07008426 if (connection_.SupportsMultiplePacketNumberSpaces()) {
8427 return;
8428 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008429 EXPECT_FALSE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
8430 writer_->set_supports_release_time(true);
8431 QuicConfig config;
8432 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8433 connection_.SetFromConfig(config);
8434 EXPECT_TRUE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
8435
8436 QuicTagVector connection_options;
8437 connection_options.push_back(kNPCO);
8438 config.SetConnectionOptionsToSend(connection_options);
8439 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8440 connection_.SetFromConfig(config);
8441 // Verify pacing offload is disabled.
8442 EXPECT_FALSE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
8443}
8444
8445// Regression test for b/110259444
8446// Get a path response without having issued a path challenge...
8447TEST_P(QuicConnectionTest, OrphanPathResponse) {
QUICHE teamcd098022019-03-22 18:49:55 -07008448 if (connection_.SupportsMultiplePacketNumberSpaces()) {
8449 return;
8450 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008451 QuicPathFrameBuffer data = {{0, 1, 2, 3, 4, 5, 6, 7}};
8452
8453 QuicPathResponseFrame frame(99, data);
8454 EXPECT_TRUE(connection_.OnPathResponseFrame(frame));
8455 // If PATH_RESPONSE was accepted (payload matches the payload saved
8456 // in QuicConnection::transmitted_connectivity_probe_payload_) then
8457 // current_packet_content_ would be set to FIRST_FRAME_IS_PING.
8458 // Since this PATH_RESPONSE does not match, current_packet_content_
8459 // must not be FIRST_FRAME_IS_PING.
8460 EXPECT_NE(QuicConnection::FIRST_FRAME_IS_PING,
8461 QuicConnectionPeer::GetCurrentPacketContent(&connection_));
8462}
8463
8464// Regression test for b/120791670
8465TEST_P(QuicConnectionTest, StopProcessingGQuicPacketInIetfQuicConnection) {
QUICHE teamcd098022019-03-22 18:49:55 -07008466 if (connection_.SupportsMultiplePacketNumberSpaces()) {
8467 return;
8468 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008469 // This test mimics a problematic scenario where an IETF QUIC connection
8470 // receives a Google QUIC packet and continue processing it using Google QUIC
8471 // wire format.
8472 if (version().transport_version <= QUIC_VERSION_43) {
8473 return;
8474 }
8475 set_perspective(Perspective::IS_SERVER);
8476 QuicStreamFrame stream_frame(
8477 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false, 0u,
8478 QuicStringPiece());
8479 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8480 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
8481 ProcessFramePacketWithAddresses(QuicFrame(stream_frame), kSelfAddress,
8482 kPeerAddress);
8483
8484 // Let connection process a Google QUIC packet.
8485 peer_framer_.set_version_for_tests(
8486 ParsedQuicVersion(PROTOCOL_QUIC_CRYPTO, QUIC_VERSION_43));
QUICHE team8c1daa22019-03-13 08:33:41 -07008487 std::unique_ptr<QuicPacket> packet(
QUICHE team6987b4a2019-03-15 16:23:04 -07008488 ConstructDataPacket(2, !kHasStopWaiting, ENCRYPTION_INITIAL));
QUICHE teama6ef0a62019-03-07 20:34:33 -05008489 char buffer[kMaxPacketSize];
8490 size_t encrypted_length = peer_framer_.EncryptPayload(
QUICHE team6987b4a2019-03-15 16:23:04 -07008491 ENCRYPTION_INITIAL, QuicPacketNumber(2), *packet, buffer, kMaxPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008492 // Make sure no stream frame is processed.
8493 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(0);
8494 connection_.ProcessUdpPacket(
8495 kSelfAddress, kPeerAddress,
8496 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
8497
8498 EXPECT_EQ(2u, connection_.GetStats().packets_received);
8499 EXPECT_EQ(1u, connection_.GetStats().packets_processed);
8500}
8501
8502TEST_P(QuicConnectionTest, AcceptPacketNumberZero) {
QUICHE teamcd098022019-03-22 18:49:55 -07008503 if (version().transport_version != QUIC_VERSION_99 ||
8504 connection_.SupportsMultiplePacketNumberSpaces()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008505 return;
8506 }
8507 // Set first_sending_packet_number to be 0 to allow successfully processing
8508 // acks which ack packet number 0.
8509 QuicFramerPeer::SetFirstSendingPacketNumber(writer_->framer()->framer(), 0);
8510 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8511
8512 ProcessPacket(0);
8513 EXPECT_EQ(QuicPacketNumber(0), LargestAcked(*outgoing_ack()));
8514 EXPECT_EQ(1u, outgoing_ack()->packets.NumIntervals());
8515
8516 ProcessPacket(1);
8517 EXPECT_EQ(QuicPacketNumber(1), LargestAcked(*outgoing_ack()));
8518 EXPECT_EQ(1u, outgoing_ack()->packets.NumIntervals());
8519
8520 ProcessPacket(2);
8521 EXPECT_EQ(QuicPacketNumber(2), LargestAcked(*outgoing_ack()));
8522 EXPECT_EQ(1u, outgoing_ack()->packets.NumIntervals());
8523}
8524
QUICHE teamcd098022019-03-22 18:49:55 -07008525TEST_P(QuicConnectionTest, MultiplePacketNumberSpacesBasicSending) {
8526 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8527 return;
8528 }
8529 use_tagging_decrypter();
8530 connection_.SetEncrypter(ENCRYPTION_INITIAL,
8531 QuicMakeUnique<TaggingEncrypter>(0x01));
8532
8533 connection_.SendCryptoStreamData();
8534 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8535 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
8536 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8537 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8538 QuicAckFrame frame1 = InitAckFrame(1);
8539 // Received ACK for packet 1.
8540 ProcessFramePacketAtLevel(30, QuicFrame(&frame1), ENCRYPTION_INITIAL);
8541
8542 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(4);
8543 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
8544 NO_FIN);
8545 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 4,
8546 NO_FIN);
8547 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
8548 8, NO_FIN);
8549 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
8550 12, FIN);
8551 // Received ACK for packets 2, 4, 5.
8552 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
8553 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8554 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8555 QuicAckFrame frame2 =
8556 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)},
8557 {QuicPacketNumber(4), QuicPacketNumber(6)}});
8558 // Make sure although the same packet number is used, but they are in
8559 // different packet number spaces.
8560 ProcessFramePacketAtLevel(30, QuicFrame(&frame2), ENCRYPTION_FORWARD_SECURE);
8561}
8562
8563TEST_P(QuicConnectionTest, PeerAcksPacketsInWrongPacketNumberSpace) {
8564 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8565 return;
8566 }
8567 use_tagging_decrypter();
8568 connection_.SetEncrypter(ENCRYPTION_INITIAL,
8569 QuicMakeUnique<TaggingEncrypter>(0x01));
8570
8571 connection_.SendCryptoStreamData();
8572 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8573 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
8574 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8575 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8576 QuicAckFrame frame1 = InitAckFrame(1);
8577 // Received ACK for packet 1.
8578 ProcessFramePacketAtLevel(30, QuicFrame(&frame1), ENCRYPTION_INITIAL);
8579
8580 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
8581 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
8582 NO_FIN);
8583 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 4,
8584 NO_FIN);
8585
8586 // Received ACK for packets 2 and 3 in wrong packet number space.
8587 QuicAckFrame invalid_ack =
8588 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(4)}});
8589 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, _,
8590 ConnectionCloseSource::FROM_SELF));
8591 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8592 ProcessFramePacketAtLevel(300, QuicFrame(&invalid_ack), ENCRYPTION_INITIAL);
8593}
8594
8595TEST_P(QuicConnectionTest, MultiplePacketNumberSpacesBasicReceiving) {
8596 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8597 return;
8598 }
8599 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8600 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
8601 use_tagging_decrypter();
8602 // Receives packet 1000 in initial data.
8603 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_INITIAL);
8604 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
8605 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
8606 QuicMakeUnique<TaggingEncrypter>(0x02));
8607 connection_.SetDecrypter(ENCRYPTION_ZERO_RTT,
8608 QuicMakeUnique<StrictTaggingDecrypter>(0x02));
8609 connection_.SetEncrypter(ENCRYPTION_INITIAL,
8610 QuicMakeUnique<TaggingEncrypter>(0x02));
8611 // Receives packet 1000 in application data.
8612 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
8613 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
8614 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
8615 NO_FIN);
8616 // Verify application data ACK gets bundled with outgoing data.
8617 EXPECT_EQ(2u, writer_->frame_count());
8618 // Make sure ACK alarm is still set because initial data is not ACKed.
8619 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
8620 // Receive packet 1001 in application data.
8621 ProcessDataPacketAtLevel(1001, false, ENCRYPTION_ZERO_RTT);
8622 clock_.AdvanceTime(DefaultRetransmissionTime());
8623 // Simulates ACK alarm fires and verify two ACKs are flushed.
8624 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
8625 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
8626 QuicMakeUnique<TaggingEncrypter>(0x02));
8627 connection_.GetAckAlarm()->Fire();
8628 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
8629 // Receives more packets in application data.
8630 ProcessDataPacketAtLevel(1002, false, ENCRYPTION_ZERO_RTT);
8631 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
8632
8633 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
8634 QuicMakeUnique<TaggingEncrypter>(0x02));
8635 connection_.SetDecrypter(ENCRYPTION_FORWARD_SECURE,
8636 QuicMakeUnique<StrictTaggingDecrypter>(0x02));
8637 // Verify zero rtt and forward secure packets get acked in the same packet.
8638 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8639 ProcessDataPacketAtLevel(1003, false, ENCRYPTION_FORWARD_SECURE);
8640 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
8641}
8642
QUICHE teama6ef0a62019-03-07 20:34:33 -05008643} // namespace
8644} // namespace test
8645} // namespace quic