Fix nullptr crash in OnEmbed
[chromium-blink-merge.git] / net / quic / quic_connection_test.cc
blobf3d59620f2a80ab123b04a603ad0b60083a2b298
1 // 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.
5 #include "net/quic/quic_connection.h"
7 #include <ostream>
9 #include "base/basictypes.h"
10 #include "base/bind.h"
11 #include "base/memory/scoped_ptr.h"
12 #include "base/stl_util.h"
13 #include "net/base/net_errors.h"
14 #include "net/quic/congestion_control/loss_detection_interface.h"
15 #include "net/quic/congestion_control/send_algorithm_interface.h"
16 #include "net/quic/crypto/null_encrypter.h"
17 #include "net/quic/crypto/quic_decrypter.h"
18 #include "net/quic/crypto/quic_encrypter.h"
19 #include "net/quic/quic_ack_notifier.h"
20 #include "net/quic/quic_flags.h"
21 #include "net/quic/quic_protocol.h"
22 #include "net/quic/quic_utils.h"
23 #include "net/quic/test_tools/mock_clock.h"
24 #include "net/quic/test_tools/mock_random.h"
25 #include "net/quic/test_tools/quic_config_peer.h"
26 #include "net/quic/test_tools/quic_connection_peer.h"
27 #include "net/quic/test_tools/quic_framer_peer.h"
28 #include "net/quic/test_tools/quic_packet_creator_peer.h"
29 #include "net/quic/test_tools/quic_packet_generator_peer.h"
30 #include "net/quic/test_tools/quic_sent_packet_manager_peer.h"
31 #include "net/quic/test_tools/quic_test_utils.h"
32 #include "net/quic/test_tools/simple_quic_framer.h"
33 #include "net/test/gtest_util.h"
34 #include "testing/gmock/include/gmock/gmock.h"
35 #include "testing/gtest/include/gtest/gtest.h"
37 using base::StringPiece;
38 using std::map;
39 using std::ostream;
40 using std::string;
41 using std::vector;
42 using testing::AnyNumber;
43 using testing::AtLeast;
44 using testing::Contains;
45 using testing::DoAll;
46 using testing::InSequence;
47 using testing::InvokeWithoutArgs;
48 using testing::NiceMock;
49 using testing::Ref;
50 using testing::Return;
51 using testing::SaveArg;
52 using testing::StrictMock;
53 using testing::_;
55 namespace net {
56 namespace test {
57 namespace {
59 const char data1[] = "foo";
60 const char data2[] = "bar";
62 const bool kFin = true;
63 const bool kEntropyFlag = true;
65 const QuicPacketEntropyHash kTestEntropyHash = 76;
67 const int kDefaultRetransmissionTimeMs = 500;
69 // TaggingEncrypter appends kTagSize bytes of |tag| to the end of each message.
70 class TaggingEncrypter : public QuicEncrypter {
71 public:
72 explicit TaggingEncrypter(uint8 tag)
73 : tag_(tag) {
76 ~TaggingEncrypter() override {}
78 // QuicEncrypter interface.
79 bool SetKey(StringPiece key) override { return true; }
81 bool SetNoncePrefix(StringPiece nonce_prefix) override { return true; }
83 bool EncryptPacket(QuicPacketSequenceNumber sequence_number,
84 StringPiece associated_data,
85 StringPiece plaintext,
86 char* output,
87 size_t* output_length,
88 size_t max_output_length) override {
89 const size_t len = plaintext.size() + kTagSize;
90 if (max_output_length < len) {
91 return false;
93 memcpy(output, plaintext.data(), plaintext.size());
94 output += plaintext.size();
95 memset(output, tag_, kTagSize);
96 *output_length = len;
97 return true;
100 size_t GetKeySize() const override { return 0; }
101 size_t GetNoncePrefixSize() const override { return 0; }
103 size_t GetMaxPlaintextSize(size_t ciphertext_size) const override {
104 return ciphertext_size - kTagSize;
107 size_t GetCiphertextSize(size_t plaintext_size) const override {
108 return plaintext_size + kTagSize;
111 StringPiece GetKey() const override { return StringPiece(); }
113 StringPiece GetNoncePrefix() const override { return StringPiece(); }
115 private:
116 enum {
117 kTagSize = 12,
120 const uint8 tag_;
122 DISALLOW_COPY_AND_ASSIGN(TaggingEncrypter);
125 // TaggingDecrypter ensures that the final kTagSize bytes of the message all
126 // have the same value and then removes them.
127 class TaggingDecrypter : public QuicDecrypter {
128 public:
129 ~TaggingDecrypter() override {}
131 // QuicDecrypter interface
132 bool SetKey(StringPiece key) override { return true; }
134 bool SetNoncePrefix(StringPiece nonce_prefix) override { return true; }
136 bool DecryptPacket(QuicPacketSequenceNumber sequence_number,
137 const StringPiece& associated_data,
138 const StringPiece& ciphertext,
139 char* output,
140 size_t* output_length,
141 size_t max_output_length) override {
142 if (ciphertext.size() < kTagSize) {
143 return false;
145 if (!CheckTag(ciphertext, GetTag(ciphertext))) {
146 return false;
148 *output_length = ciphertext.size() - kTagSize;
149 memcpy(output, ciphertext.data(), *output_length);
150 return true;
153 StringPiece GetKey() const override { return StringPiece(); }
154 StringPiece GetNoncePrefix() const override { return StringPiece(); }
155 const char* cipher_name() const override { return "Tagging"; }
156 // Use a distinct value starting with 0xFFFFFF, which is never used by TLS.
157 uint32 cipher_id() const override { return 0xFFFFFFF0; }
159 protected:
160 virtual uint8 GetTag(StringPiece ciphertext) {
161 return ciphertext.data()[ciphertext.size()-1];
164 private:
165 enum {
166 kTagSize = 12,
169 bool CheckTag(StringPiece ciphertext, uint8 tag) {
170 for (size_t i = ciphertext.size() - kTagSize; i < ciphertext.size(); i++) {
171 if (ciphertext.data()[i] != tag) {
172 return false;
176 return true;
180 // StringTaggingDecrypter ensures that the final kTagSize bytes of the message
181 // match the expected value.
182 class StrictTaggingDecrypter : public TaggingDecrypter {
183 public:
184 explicit StrictTaggingDecrypter(uint8 tag) : tag_(tag) {}
185 ~StrictTaggingDecrypter() override {}
187 // TaggingQuicDecrypter
188 uint8 GetTag(StringPiece ciphertext) override { return tag_; }
190 const char* cipher_name() const override { return "StrictTagging"; }
191 // Use a distinct value starting with 0xFFFFFF, which is never used by TLS.
192 uint32 cipher_id() const override { return 0xFFFFFFF1; }
194 private:
195 const uint8 tag_;
198 class TestConnectionHelper : public QuicConnectionHelperInterface {
199 public:
200 class TestAlarm : public QuicAlarm {
201 public:
202 explicit TestAlarm(QuicAlarm::Delegate* delegate)
203 : QuicAlarm(delegate) {
206 void SetImpl() override {}
207 void CancelImpl() override {}
208 using QuicAlarm::Fire;
211 TestConnectionHelper(MockClock* clock, MockRandom* random_generator)
212 : clock_(clock),
213 random_generator_(random_generator) {
214 clock_->AdvanceTime(QuicTime::Delta::FromSeconds(1));
217 // QuicConnectionHelperInterface
218 const QuicClock* GetClock() const override { return clock_; }
220 QuicRandom* GetRandomGenerator() override { return random_generator_; }
222 QuicAlarm* CreateAlarm(QuicAlarm::Delegate* delegate) override {
223 return new TestAlarm(delegate);
226 private:
227 MockClock* clock_;
228 MockRandom* random_generator_;
230 DISALLOW_COPY_AND_ASSIGN(TestConnectionHelper);
233 class TestPacketWriter : public QuicPacketWriter {
234 public:
235 TestPacketWriter(QuicVersion version, MockClock *clock)
236 : version_(version),
237 framer_(SupportedVersions(version_)),
238 last_packet_size_(0),
239 write_blocked_(false),
240 block_on_next_write_(false),
241 is_write_blocked_data_buffered_(false),
242 final_bytes_of_last_packet_(0),
243 final_bytes_of_previous_packet_(0),
244 use_tagging_decrypter_(false),
245 packets_write_attempts_(0),
246 clock_(clock),
247 write_pause_time_delta_(QuicTime::Delta::Zero()) {
250 // QuicPacketWriter interface
251 WriteResult WritePacket(const char* buffer,
252 size_t buf_len,
253 const IPAddressNumber& self_address,
254 const IPEndPoint& peer_address) override {
255 QuicEncryptedPacket packet(buffer, buf_len);
256 ++packets_write_attempts_;
258 if (packet.length() >= sizeof(final_bytes_of_last_packet_)) {
259 final_bytes_of_previous_packet_ = final_bytes_of_last_packet_;
260 memcpy(&final_bytes_of_last_packet_, packet.data() + packet.length() - 4,
261 sizeof(final_bytes_of_last_packet_));
264 if (use_tagging_decrypter_) {
265 framer_.framer()->SetDecrypter(ENCRYPTION_NONE, new TaggingDecrypter);
267 EXPECT_TRUE(framer_.ProcessPacket(packet));
268 if (block_on_next_write_) {
269 write_blocked_ = true;
270 block_on_next_write_ = false;
272 if (IsWriteBlocked()) {
273 return WriteResult(WRITE_STATUS_BLOCKED, -1);
275 last_packet_size_ = packet.length();
277 if (!write_pause_time_delta_.IsZero()) {
278 clock_->AdvanceTime(write_pause_time_delta_);
280 return WriteResult(WRITE_STATUS_OK, last_packet_size_);
283 bool IsWriteBlockedDataBuffered() const override {
284 return is_write_blocked_data_buffered_;
287 bool IsWriteBlocked() const override { return write_blocked_; }
289 void SetWritable() override { write_blocked_ = false; }
291 void BlockOnNextWrite() { block_on_next_write_ = true; }
293 // Sets the amount of time that the writer should before the actual write.
294 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
295 write_pause_time_delta_ = delta;
298 const QuicPacketHeader& header() { return framer_.header(); }
300 size_t frame_count() const { return framer_.num_frames(); }
302 const vector<QuicAckFrame>& ack_frames() const {
303 return framer_.ack_frames();
306 const vector<QuicStopWaitingFrame>& stop_waiting_frames() const {
307 return framer_.stop_waiting_frames();
310 const vector<QuicConnectionCloseFrame>& connection_close_frames() const {
311 return framer_.connection_close_frames();
314 const vector<QuicRstStreamFrame>& rst_stream_frames() const {
315 return framer_.rst_stream_frames();
318 const vector<QuicStreamFrame>& stream_frames() const {
319 return framer_.stream_frames();
322 const vector<QuicPingFrame>& ping_frames() const {
323 return framer_.ping_frames();
326 size_t last_packet_size() {
327 return last_packet_size_;
330 const QuicVersionNegotiationPacket* version_negotiation_packet() {
331 return framer_.version_negotiation_packet();
334 void set_is_write_blocked_data_buffered(bool buffered) {
335 is_write_blocked_data_buffered_ = buffered;
338 void set_perspective(Perspective perspective) {
339 // We invert perspective here, because the framer needs to parse packets
340 // we send.
341 perspective = perspective == Perspective::IS_CLIENT
342 ? Perspective::IS_SERVER
343 : Perspective::IS_CLIENT;
344 QuicFramerPeer::SetPerspective(framer_.framer(), perspective);
347 // final_bytes_of_last_packet_ returns the last four bytes of the previous
348 // packet as a little-endian, uint32. This is intended to be used with a
349 // TaggingEncrypter so that tests can determine which encrypter was used for
350 // a given packet.
351 uint32 final_bytes_of_last_packet() { return final_bytes_of_last_packet_; }
353 // Returns the final bytes of the second to last packet.
354 uint32 final_bytes_of_previous_packet() {
355 return final_bytes_of_previous_packet_;
358 void use_tagging_decrypter() {
359 use_tagging_decrypter_ = true;
362 uint32 packets_write_attempts() { return packets_write_attempts_; }
364 void Reset() { framer_.Reset(); }
366 void SetSupportedVersions(const QuicVersionVector& versions) {
367 framer_.SetSupportedVersions(versions);
370 private:
371 QuicVersion version_;
372 SimpleQuicFramer framer_;
373 size_t last_packet_size_;
374 bool write_blocked_;
375 bool block_on_next_write_;
376 bool is_write_blocked_data_buffered_;
377 uint32 final_bytes_of_last_packet_;
378 uint32 final_bytes_of_previous_packet_;
379 bool use_tagging_decrypter_;
380 uint32 packets_write_attempts_;
381 MockClock *clock_;
382 // If non-zero, the clock will pause during WritePacket for this amount of
383 // time.
384 QuicTime::Delta write_pause_time_delta_;
386 DISALLOW_COPY_AND_ASSIGN(TestPacketWriter);
389 class TestConnection : public QuicConnection {
390 public:
391 TestConnection(QuicConnectionId connection_id,
392 IPEndPoint address,
393 TestConnectionHelper* helper,
394 const PacketWriterFactory& factory,
395 Perspective perspective,
396 QuicVersion version)
397 : QuicConnection(connection_id,
398 address,
399 helper,
400 factory,
401 /* owns_writer= */ false,
402 perspective,
403 /* is_secure= */ false,
404 SupportedVersions(version)) {
405 // Disable tail loss probes for most tests.
406 QuicSentPacketManagerPeer::SetMaxTailLossProbes(
407 QuicConnectionPeer::GetSentPacketManager(this), 0);
408 writer()->set_perspective(perspective);
411 void SendAck() {
412 QuicConnectionPeer::SendAck(this);
415 void SetSendAlgorithm(SendAlgorithmInterface* send_algorithm) {
416 QuicConnectionPeer::SetSendAlgorithm(this, send_algorithm);
419 void SetLossAlgorithm(LossDetectionInterface* loss_algorithm) {
420 QuicSentPacketManagerPeer::SetLossAlgorithm(
421 QuicConnectionPeer::GetSentPacketManager(this), loss_algorithm);
424 void SendPacket(EncryptionLevel level,
425 QuicPacketSequenceNumber sequence_number,
426 QuicPacket* packet,
427 QuicPacketEntropyHash entropy_hash,
428 HasRetransmittableData retransmittable,
429 bool has_ack,
430 bool has_pending_frames) {
431 RetransmittableFrames* retransmittable_frames =
432 retransmittable == HAS_RETRANSMITTABLE_DATA
433 ? new RetransmittableFrames(ENCRYPTION_NONE)
434 : nullptr;
435 char buffer[kMaxPacketSize];
436 QuicEncryptedPacket* encrypted =
437 QuicConnectionPeer::GetFramer(this)->EncryptPayload(
438 ENCRYPTION_NONE, sequence_number, *packet, buffer, kMaxPacketSize);
439 delete packet;
440 OnSerializedPacket(SerializedPacket(
441 sequence_number, PACKET_6BYTE_SEQUENCE_NUMBER, encrypted, entropy_hash,
442 retransmittable_frames, has_ack, has_pending_frames));
445 QuicConsumedData SendStreamDataWithString(
446 QuicStreamId id,
447 StringPiece data,
448 QuicStreamOffset offset,
449 bool fin,
450 QuicAckNotifier::DelegateInterface* delegate) {
451 return SendStreamDataWithStringHelper(id, data, offset, fin,
452 MAY_FEC_PROTECT, delegate);
455 QuicConsumedData SendStreamDataWithStringWithFec(
456 QuicStreamId id,
457 StringPiece data,
458 QuicStreamOffset offset,
459 bool fin,
460 QuicAckNotifier::DelegateInterface* delegate) {
461 return SendStreamDataWithStringHelper(id, data, offset, fin,
462 MUST_FEC_PROTECT, delegate);
465 QuicConsumedData SendStreamDataWithStringHelper(
466 QuicStreamId id,
467 StringPiece data,
468 QuicStreamOffset offset,
469 bool fin,
470 FecProtection fec_protection,
471 QuicAckNotifier::DelegateInterface* delegate) {
472 struct iovec iov;
473 QuicIOVector data_iov(MakeIOVector(data, &iov));
474 return QuicConnection::SendStreamData(id, data_iov, offset, fin,
475 fec_protection, delegate);
478 QuicConsumedData SendStreamData3() {
479 return SendStreamDataWithString(kClientDataStreamId1, "food", 0, !kFin,
480 nullptr);
483 QuicConsumedData SendStreamData3WithFec() {
484 return SendStreamDataWithStringWithFec(kClientDataStreamId1, "food", 0,
485 !kFin, nullptr);
488 QuicConsumedData SendStreamData5() {
489 return SendStreamDataWithString(kClientDataStreamId2, "food2", 0, !kFin,
490 nullptr);
493 QuicConsumedData SendStreamData5WithFec() {
494 return SendStreamDataWithStringWithFec(kClientDataStreamId2, "food2", 0,
495 !kFin, nullptr);
497 // Ensures the connection can write stream data before writing.
498 QuicConsumedData EnsureWritableAndSendStreamData5() {
499 EXPECT_TRUE(CanWriteStreamData());
500 return SendStreamData5();
503 // The crypto stream has special semantics so that it is not blocked by a
504 // congestion window limitation, and also so that it gets put into a separate
505 // packet (so that it is easier to reason about a crypto frame not being
506 // split needlessly across packet boundaries). As a result, we have separate
507 // tests for some cases for this stream.
508 QuicConsumedData SendCryptoStreamData() {
509 return SendStreamDataWithString(kCryptoStreamId, "chlo", 0, !kFin, nullptr);
512 void set_version(QuicVersion version) {
513 QuicConnectionPeer::GetFramer(this)->set_version(version);
516 void SetSupportedVersions(const QuicVersionVector& versions) {
517 QuicConnectionPeer::GetFramer(this)->SetSupportedVersions(versions);
518 writer()->SetSupportedVersions(versions);
521 void set_perspective(Perspective perspective) {
522 writer()->set_perspective(perspective);
523 QuicConnectionPeer::SetPerspective(this, perspective);
526 // Enable path MTU discovery. Assumes that the test is performed from the
527 // client perspective and the higher value of MTU target is used.
528 void EnablePathMtuDiscovery(MockSendAlgorithm* send_algorithm) {
529 ASSERT_EQ(Perspective::IS_CLIENT, perspective());
531 FLAGS_quic_do_path_mtu_discovery = true;
533 QuicConfig config;
534 QuicTagVector connection_options;
535 connection_options.push_back(kMTUH);
536 config.SetConnectionOptionsToSend(connection_options);
537 EXPECT_CALL(*send_algorithm, SetFromConfig(_, _));
538 SetFromConfig(config);
540 // Normally, the pacing would be disabled in the test, but calling
541 // SetFromConfig enables it. Set nearly-infinite bandwidth to make the
542 // pacing algorithm work.
543 EXPECT_CALL(*send_algorithm, PacingRate())
544 .WillRepeatedly(Return(QuicBandwidth::FromKBytesPerSecond(10000)));
547 TestConnectionHelper::TestAlarm* GetAckAlarm() {
548 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
549 QuicConnectionPeer::GetAckAlarm(this));
552 TestConnectionHelper::TestAlarm* GetPingAlarm() {
553 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
554 QuicConnectionPeer::GetPingAlarm(this));
557 TestConnectionHelper::TestAlarm* GetFecAlarm() {
558 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
559 QuicConnectionPeer::GetFecAlarm(this));
562 TestConnectionHelper::TestAlarm* GetResumeWritesAlarm() {
563 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
564 QuicConnectionPeer::GetResumeWritesAlarm(this));
567 TestConnectionHelper::TestAlarm* GetRetransmissionAlarm() {
568 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
569 QuicConnectionPeer::GetRetransmissionAlarm(this));
572 TestConnectionHelper::TestAlarm* GetSendAlarm() {
573 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
574 QuicConnectionPeer::GetSendAlarm(this));
577 TestConnectionHelper::TestAlarm* GetTimeoutAlarm() {
578 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
579 QuicConnectionPeer::GetTimeoutAlarm(this));
582 TestConnectionHelper::TestAlarm* GetMtuDiscoveryAlarm() {
583 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
584 QuicConnectionPeer::GetMtuDiscoveryAlarm(this));
587 using QuicConnection::SelectMutualVersion;
589 private:
590 TestPacketWriter* writer() {
591 return static_cast<TestPacketWriter*>(QuicConnection::writer());
594 DISALLOW_COPY_AND_ASSIGN(TestConnection);
597 // Used for testing packets revived from FEC packets.
598 class FecQuicConnectionDebugVisitor
599 : public QuicConnectionDebugVisitor {
600 public:
601 void OnRevivedPacket(const QuicPacketHeader& header,
602 StringPiece data) override {
603 revived_header_ = header;
606 // Public accessor method.
607 QuicPacketHeader revived_header() const {
608 return revived_header_;
611 private:
612 QuicPacketHeader revived_header_;
615 class MockPacketWriterFactory : public QuicConnection::PacketWriterFactory {
616 public:
617 explicit MockPacketWriterFactory(QuicPacketWriter* writer) {
618 ON_CALL(*this, Create(_)).WillByDefault(Return(writer));
620 ~MockPacketWriterFactory() override {}
622 MOCK_CONST_METHOD1(Create, QuicPacketWriter*(QuicConnection* connection));
625 // Run tests with combinations of {QuicVersion, fec_send_policy}.
626 struct TestParams {
627 TestParams(QuicVersion version, FecSendPolicy fec_send_policy)
628 : version(version), fec_send_policy(fec_send_policy) {}
630 friend ostream& operator<<(ostream& os, const TestParams& p) {
631 os << "{ client_version: " << QuicVersionToString(p.version)
632 << " fec_send_policy: " << p.fec_send_policy << " }";
633 return os;
636 QuicVersion version;
637 FecSendPolicy fec_send_policy;
640 // Constructs various test permutations.
641 vector<TestParams> GetTestParams() {
642 vector<TestParams> params;
643 QuicVersionVector all_supported_versions = QuicSupportedVersions();
644 for (size_t i = 0; i < all_supported_versions.size(); ++i) {
645 params.push_back(TestParams(all_supported_versions[i], FEC_ANY_TRIGGER));
646 params.push_back(TestParams(all_supported_versions[i], FEC_ALARM_TRIGGER));
648 return params;
651 class QuicConnectionTest : public ::testing::TestWithParam<TestParams> {
652 protected:
653 QuicConnectionTest()
654 : connection_id_(42),
655 framer_(SupportedVersions(version()),
656 QuicTime::Zero(),
657 Perspective::IS_CLIENT),
658 peer_creator_(connection_id_, &framer_, &random_generator_),
659 send_algorithm_(new StrictMock<MockSendAlgorithm>),
660 loss_algorithm_(new MockLossAlgorithm()),
661 helper_(new TestConnectionHelper(&clock_, &random_generator_)),
662 writer_(new TestPacketWriter(version(), &clock_)),
663 factory_(writer_.get()),
664 connection_(connection_id_,
665 IPEndPoint(),
666 helper_.get(),
667 factory_,
668 Perspective::IS_CLIENT,
669 version()),
670 creator_(QuicConnectionPeer::GetPacketCreator(&connection_)),
671 generator_(QuicConnectionPeer::GetPacketGenerator(&connection_)),
672 manager_(QuicConnectionPeer::GetSentPacketManager(&connection_)),
673 frame1_(1, false, 0, StringPiece(data1)),
674 frame2_(1, false, 3, StringPiece(data2)),
675 sequence_number_length_(PACKET_6BYTE_SEQUENCE_NUMBER),
676 connection_id_length_(PACKET_8BYTE_CONNECTION_ID) {
677 connection_.set_visitor(&visitor_);
678 connection_.SetSendAlgorithm(send_algorithm_);
679 connection_.SetLossAlgorithm(loss_algorithm_);
680 framer_.set_received_entropy_calculator(&entropy_calculator_);
681 generator_->set_fec_send_policy(GetParam().fec_send_policy);
682 EXPECT_CALL(*send_algorithm_, TimeUntilSend(_, _, _))
683 .WillRepeatedly(Return(QuicTime::Delta::Zero()));
684 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
685 .Times(AnyNumber());
686 EXPECT_CALL(*send_algorithm_, RetransmissionDelay())
687 .WillRepeatedly(Return(QuicTime::Delta::Zero()));
688 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
689 .WillRepeatedly(Return(kDefaultTCPMSS));
690 EXPECT_CALL(*send_algorithm_, PacingRate())
691 .WillRepeatedly(Return(QuicBandwidth::Zero()));
692 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
693 .WillByDefault(Return(true));
694 EXPECT_CALL(*send_algorithm_, HasReliableBandwidthEstimate())
695 .Times(AnyNumber());
696 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
697 .Times(AnyNumber())
698 .WillRepeatedly(Return(QuicBandwidth::Zero()));
699 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
700 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
701 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).Times(AnyNumber());
702 EXPECT_CALL(visitor_, HasPendingHandshake()).Times(AnyNumber());
703 EXPECT_CALL(visitor_, OnCanWrite()).Times(AnyNumber());
704 EXPECT_CALL(visitor_, HasOpenDynamicStreams())
705 .WillRepeatedly(Return(false));
706 EXPECT_CALL(visitor_, OnCongestionWindowChange(_)).Times(AnyNumber());
708 EXPECT_CALL(*loss_algorithm_, GetLossTimeout())
709 .WillRepeatedly(Return(QuicTime::Zero()));
710 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
711 .WillRepeatedly(Return(SequenceNumberSet()));
714 QuicVersion version() { return GetParam().version; }
716 QuicAckFrame* outgoing_ack() {
717 QuicConnectionPeer::PopulateAckFrame(&connection_, &ack_);
718 return &ack_;
721 QuicStopWaitingFrame* stop_waiting() {
722 QuicConnectionPeer::PopulateStopWaitingFrame(&connection_, &stop_waiting_);
723 return &stop_waiting_;
726 QuicPacketSequenceNumber least_unacked() {
727 if (writer_->stop_waiting_frames().empty()) {
728 return 0;
730 return writer_->stop_waiting_frames()[0].least_unacked;
733 void use_tagging_decrypter() {
734 writer_->use_tagging_decrypter();
737 void ProcessPacket(QuicPacketSequenceNumber number) {
738 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
739 ProcessDataPacket(number, 0, !kEntropyFlag);
742 QuicPacketEntropyHash ProcessFramePacket(QuicFrame frame) {
743 QuicFrames frames;
744 frames.push_back(QuicFrame(frame));
745 QuicPacketCreatorPeer::SetSendVersionInPacket(
746 &peer_creator_, connection_.perspective() == Perspective::IS_SERVER);
748 char buffer[kMaxPacketSize];
749 SerializedPacket serialized_packet =
750 peer_creator_.SerializeAllFrames(frames, buffer, kMaxPacketSize);
751 scoped_ptr<QuicEncryptedPacket> encrypted(serialized_packet.packet);
752 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
753 return serialized_packet.entropy_hash;
756 size_t ProcessDataPacket(QuicPacketSequenceNumber number,
757 QuicFecGroupNumber fec_group,
758 bool entropy_flag) {
759 return ProcessDataPacketAtLevel(number, fec_group, entropy_flag,
760 ENCRYPTION_NONE);
763 size_t ProcessDataPacketAtLevel(QuicPacketSequenceNumber number,
764 QuicFecGroupNumber fec_group,
765 bool entropy_flag,
766 EncryptionLevel level) {
767 scoped_ptr<QuicPacket> packet(ConstructDataPacket(number, fec_group,
768 entropy_flag));
769 char buffer[kMaxPacketSize];
770 scoped_ptr<QuicEncryptedPacket> encrypted(
771 framer_.EncryptPayload(level, number, *packet, buffer, kMaxPacketSize));
772 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
773 return encrypted->length();
776 void ProcessClosePacket(QuicPacketSequenceNumber number,
777 QuicFecGroupNumber fec_group) {
778 scoped_ptr<QuicPacket> packet(ConstructClosePacket(number, fec_group));
779 char buffer[kMaxPacketSize];
780 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPayload(
781 ENCRYPTION_NONE, number, *packet, buffer, kMaxPacketSize));
782 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
785 size_t ProcessFecProtectedPacket(QuicPacketSequenceNumber number,
786 bool expect_revival, bool entropy_flag) {
787 if (expect_revival) {
788 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
790 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1).RetiresOnSaturation();
791 return ProcessDataPacket(number, 1, entropy_flag);
794 // Processes an FEC packet that covers the packets that would have been
795 // received.
796 size_t ProcessFecPacket(QuicPacketSequenceNumber number,
797 QuicPacketSequenceNumber min_protected_packet,
798 bool expect_revival,
799 bool entropy_flag,
800 QuicPacket* packet) {
801 if (expect_revival) {
802 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
805 // Construct the decrypted data packet so we can compute the correct
806 // redundancy. If |packet| has been provided then use that, otherwise
807 // construct a default data packet.
808 scoped_ptr<QuicPacket> data_packet;
809 if (packet) {
810 data_packet.reset(packet);
811 } else {
812 data_packet.reset(ConstructDataPacket(number, 1, !kEntropyFlag));
815 QuicPacketHeader header;
816 header.public_header.connection_id = connection_id_;
817 header.public_header.sequence_number_length = sequence_number_length_;
818 header.public_header.connection_id_length = connection_id_length_;
819 header.packet_sequence_number = number;
820 header.entropy_flag = entropy_flag;
821 header.fec_flag = true;
822 header.is_in_fec_group = IN_FEC_GROUP;
823 header.fec_group = min_protected_packet;
824 QuicFecData fec_data;
825 fec_data.fec_group = header.fec_group;
827 // Since all data packets in this test have the same payload, the
828 // redundancy is either equal to that payload or the xor of that payload
829 // with itself, depending on the number of packets.
830 if (((number - min_protected_packet) % 2) == 0) {
831 for (size_t i = GetStartOfFecProtectedData(
832 header.public_header.connection_id_length,
833 header.public_header.version_flag,
834 header.public_header.sequence_number_length);
835 i < data_packet->length(); ++i) {
836 data_packet->mutable_data()[i] ^= data_packet->data()[i];
839 fec_data.redundancy = data_packet->FecProtectedData();
841 scoped_ptr<QuicPacket> fec_packet(framer_.BuildFecPacket(header, fec_data));
842 char buffer[kMaxPacketSize];
843 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPayload(
844 ENCRYPTION_NONE, number, *fec_packet, buffer, kMaxPacketSize));
846 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
847 return encrypted->length();
850 QuicByteCount SendStreamDataToPeer(QuicStreamId id,
851 StringPiece data,
852 QuicStreamOffset offset,
853 bool fin,
854 QuicPacketSequenceNumber* last_packet) {
855 QuicByteCount packet_size;
856 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
857 .WillOnce(DoAll(SaveArg<3>(&packet_size), Return(true)));
858 connection_.SendStreamDataWithString(id, data, offset, fin, nullptr);
859 if (last_packet != nullptr) {
860 *last_packet = creator_->sequence_number();
862 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
863 .Times(AnyNumber());
864 return packet_size;
867 void SendAckPacketToPeer() {
868 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
869 connection_.SendAck();
870 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
871 .Times(AnyNumber());
874 void ProcessAckPacket(QuicPacketSequenceNumber packet_number,
875 QuicAckFrame* frame) {
876 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, packet_number - 1);
877 ProcessFramePacket(QuicFrame(frame));
880 QuicPacketEntropyHash ProcessAckPacket(QuicAckFrame* frame) {
881 return ProcessFramePacket(QuicFrame(frame));
884 QuicPacketEntropyHash ProcessStopWaitingPacket(QuicStopWaitingFrame* frame) {
885 return ProcessFramePacket(QuicFrame(frame));
888 QuicPacketEntropyHash ProcessGoAwayPacket(QuicGoAwayFrame* frame) {
889 return ProcessFramePacket(QuicFrame(frame));
892 bool IsMissing(QuicPacketSequenceNumber number) {
893 return IsAwaitingPacket(*outgoing_ack(), number);
896 QuicPacket* ConstructPacket(QuicPacketHeader header, QuicFrames frames) {
897 QuicPacket* packet = BuildUnsizedDataPacket(&framer_, header, frames);
898 EXPECT_NE(nullptr, packet);
899 return packet;
902 QuicPacket* ConstructDataPacket(QuicPacketSequenceNumber number,
903 QuicFecGroupNumber fec_group,
904 bool entropy_flag) {
905 QuicPacketHeader header;
906 header.public_header.connection_id = connection_id_;
907 header.public_header.sequence_number_length = sequence_number_length_;
908 header.public_header.connection_id_length = connection_id_length_;
909 header.entropy_flag = entropy_flag;
910 header.packet_sequence_number = number;
911 header.is_in_fec_group = fec_group == 0u ? NOT_IN_FEC_GROUP : IN_FEC_GROUP;
912 header.fec_group = fec_group;
914 QuicFrames frames;
915 frames.push_back(QuicFrame(&frame1_));
916 return ConstructPacket(header, frames);
919 QuicPacket* ConstructClosePacket(QuicPacketSequenceNumber number,
920 QuicFecGroupNumber fec_group) {
921 QuicPacketHeader header;
922 header.public_header.connection_id = connection_id_;
923 header.packet_sequence_number = number;
924 header.is_in_fec_group = fec_group == 0u ? NOT_IN_FEC_GROUP : IN_FEC_GROUP;
925 header.fec_group = fec_group;
927 QuicConnectionCloseFrame qccf;
928 qccf.error_code = QUIC_PEER_GOING_AWAY;
930 QuicFrames frames;
931 frames.push_back(QuicFrame(&qccf));
932 return ConstructPacket(header, frames);
935 QuicTime::Delta DefaultRetransmissionTime() {
936 return QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
939 QuicTime::Delta DefaultDelayedAckTime() {
940 return QuicTime::Delta::FromMilliseconds(kMaxDelayedAckTimeMs);
943 // Initialize a frame acknowledging all packets up to largest_observed.
944 const QuicAckFrame InitAckFrame(QuicPacketSequenceNumber largest_observed) {
945 QuicAckFrame frame(MakeAckFrame(largest_observed));
946 if (largest_observed > 0) {
947 frame.entropy_hash =
948 QuicConnectionPeer::GetSentEntropyHash(&connection_,
949 largest_observed);
951 return frame;
954 const QuicStopWaitingFrame InitStopWaitingFrame(
955 QuicPacketSequenceNumber least_unacked) {
956 QuicStopWaitingFrame frame;
957 frame.least_unacked = least_unacked;
958 return frame;
961 // Explicitly nack a packet.
962 void NackPacket(QuicPacketSequenceNumber missing, QuicAckFrame* frame) {
963 frame->missing_packets.insert(missing);
964 frame->entropy_hash ^=
965 QuicConnectionPeer::PacketEntropy(&connection_, missing);
968 // Undo nacking a packet within the frame.
969 void AckPacket(QuicPacketSequenceNumber arrived, QuicAckFrame* frame) {
970 EXPECT_THAT(frame->missing_packets, Contains(arrived));
971 frame->missing_packets.erase(arrived);
972 frame->entropy_hash ^=
973 QuicConnectionPeer::PacketEntropy(&connection_, arrived);
976 void TriggerConnectionClose() {
977 // Send an erroneous packet to close the connection.
978 EXPECT_CALL(visitor_,
979 OnConnectionClosed(QUIC_INVALID_PACKET_HEADER, false));
980 // Call ProcessDataPacket rather than ProcessPacket, as we should not get a
981 // packet call to the visitor.
982 ProcessDataPacket(6000, 0, !kEntropyFlag);
983 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
984 nullptr);
987 void BlockOnNextWrite() {
988 writer_->BlockOnNextWrite();
989 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
992 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
993 writer_->SetWritePauseTimeDelta(delta);
996 void CongestionBlockWrites() {
997 EXPECT_CALL(*send_algorithm_,
998 TimeUntilSend(_, _, _)).WillRepeatedly(
999 testing::Return(QuicTime::Delta::FromSeconds(1)));
1002 void CongestionUnblockWrites() {
1003 EXPECT_CALL(*send_algorithm_,
1004 TimeUntilSend(_, _, _)).WillRepeatedly(
1005 testing::Return(QuicTime::Delta::Zero()));
1008 QuicConnectionId connection_id_;
1009 QuicFramer framer_;
1010 QuicPacketCreator peer_creator_;
1011 MockEntropyCalculator entropy_calculator_;
1013 MockSendAlgorithm* send_algorithm_;
1014 MockLossAlgorithm* loss_algorithm_;
1015 MockClock clock_;
1016 MockRandom random_generator_;
1017 scoped_ptr<TestConnectionHelper> helper_;
1018 scoped_ptr<TestPacketWriter> writer_;
1019 NiceMock<MockPacketWriterFactory> factory_;
1020 TestConnection connection_;
1021 QuicPacketCreator* creator_;
1022 QuicPacketGenerator* generator_;
1023 QuicSentPacketManager* manager_;
1024 StrictMock<MockConnectionVisitor> visitor_;
1026 QuicStreamFrame frame1_;
1027 QuicStreamFrame frame2_;
1028 QuicAckFrame ack_;
1029 QuicStopWaitingFrame stop_waiting_;
1030 QuicSequenceNumberLength sequence_number_length_;
1031 QuicConnectionIdLength connection_id_length_;
1033 private:
1034 DISALLOW_COPY_AND_ASSIGN(QuicConnectionTest);
1037 // Run all end to end tests with all supported versions.
1038 INSTANTIATE_TEST_CASE_P(SupportedVersion,
1039 QuicConnectionTest,
1040 ::testing::ValuesIn(GetTestParams()));
1042 TEST_P(QuicConnectionTest, MaxPacketSize) {
1043 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
1044 EXPECT_EQ(1350u, connection_.max_packet_length());
1047 TEST_P(QuicConnectionTest, SmallerServerMaxPacketSize) {
1048 QuicConnectionId connection_id = 42;
1049 TestConnection connection(connection_id, IPEndPoint(), helper_.get(),
1050 factory_, Perspective::IS_SERVER, version());
1051 EXPECT_EQ(Perspective::IS_SERVER, connection.perspective());
1052 EXPECT_EQ(1000u, connection.max_packet_length());
1055 TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSize) {
1056 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1058 connection_.set_perspective(Perspective::IS_SERVER);
1059 connection_.set_max_packet_length(1000);
1061 QuicPacketHeader header;
1062 header.public_header.connection_id = connection_id_;
1063 header.public_header.version_flag = true;
1064 header.packet_sequence_number = 1;
1066 QuicFrames frames;
1067 QuicPaddingFrame padding;
1068 frames.push_back(QuicFrame(&frame1_));
1069 frames.push_back(QuicFrame(&padding));
1070 scoped_ptr<QuicPacket> packet(ConstructPacket(header, frames));
1071 char buffer[kMaxPacketSize];
1072 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPayload(
1073 ENCRYPTION_NONE, 12, *packet, buffer, kMaxPacketSize));
1074 EXPECT_EQ(kMaxPacketSize, encrypted->length());
1076 framer_.set_version(version());
1077 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
1078 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
1080 EXPECT_EQ(kMaxPacketSize, connection_.max_packet_length());
1083 TEST_P(QuicConnectionTest, PacketsInOrder) {
1084 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1086 ProcessPacket(1);
1087 EXPECT_EQ(1u, outgoing_ack()->largest_observed);
1088 EXPECT_EQ(0u, outgoing_ack()->missing_packets.size());
1090 ProcessPacket(2);
1091 EXPECT_EQ(2u, outgoing_ack()->largest_observed);
1092 EXPECT_EQ(0u, outgoing_ack()->missing_packets.size());
1094 ProcessPacket(3);
1095 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1096 EXPECT_EQ(0u, outgoing_ack()->missing_packets.size());
1099 TEST_P(QuicConnectionTest, PacketsOutOfOrder) {
1100 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1102 ProcessPacket(3);
1103 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1104 EXPECT_TRUE(IsMissing(2));
1105 EXPECT_TRUE(IsMissing(1));
1107 ProcessPacket(2);
1108 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1109 EXPECT_FALSE(IsMissing(2));
1110 EXPECT_TRUE(IsMissing(1));
1112 ProcessPacket(1);
1113 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1114 EXPECT_FALSE(IsMissing(2));
1115 EXPECT_FALSE(IsMissing(1));
1118 TEST_P(QuicConnectionTest, DuplicatePacket) {
1119 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1121 ProcessPacket(3);
1122 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1123 EXPECT_TRUE(IsMissing(2));
1124 EXPECT_TRUE(IsMissing(1));
1126 // Send packet 3 again, but do not set the expectation that
1127 // the visitor OnStreamFrame() will be called.
1128 ProcessDataPacket(3, 0, !kEntropyFlag);
1129 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1130 EXPECT_TRUE(IsMissing(2));
1131 EXPECT_TRUE(IsMissing(1));
1134 TEST_P(QuicConnectionTest, PacketsOutOfOrderWithAdditionsAndLeastAwaiting) {
1135 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1137 ProcessPacket(3);
1138 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1139 EXPECT_TRUE(IsMissing(2));
1140 EXPECT_TRUE(IsMissing(1));
1142 ProcessPacket(2);
1143 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1144 EXPECT_TRUE(IsMissing(1));
1146 ProcessPacket(5);
1147 EXPECT_EQ(5u, outgoing_ack()->largest_observed);
1148 EXPECT_TRUE(IsMissing(1));
1149 EXPECT_TRUE(IsMissing(4));
1151 // Pretend at this point the client has gotten acks for 2 and 3 and 1 is a
1152 // packet the peer will not retransmit. It indicates this by sending 'least
1153 // awaiting' is 4. The connection should then realize 1 will not be
1154 // retransmitted, and will remove it from the missing list.
1155 QuicAckFrame frame = InitAckFrame(1);
1156 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _));
1157 ProcessAckPacket(6, &frame);
1159 // Force an ack to be sent.
1160 SendAckPacketToPeer();
1161 EXPECT_TRUE(IsMissing(4));
1164 TEST_P(QuicConnectionTest, RejectPacketTooFarOut) {
1165 EXPECT_CALL(visitor_,
1166 OnConnectionClosed(QUIC_INVALID_PACKET_HEADER, false));
1167 // Call ProcessDataPacket rather than ProcessPacket, as we should not get a
1168 // packet call to the visitor.
1169 ProcessDataPacket(6000, 0, !kEntropyFlag);
1170 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1171 nullptr);
1174 TEST_P(QuicConnectionTest, RejectUnencryptedStreamData) {
1175 // Process an unencrypted packet from the non-crypto stream.
1176 frame1_.stream_id = 3;
1177 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1178 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_UNENCRYPTED_STREAM_DATA,
1179 false));
1180 ProcessDataPacket(1, 0, !kEntropyFlag);
1181 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1182 nullptr);
1183 const vector<QuicConnectionCloseFrame>& connection_close_frames =
1184 writer_->connection_close_frames();
1185 EXPECT_EQ(1u, connection_close_frames.size());
1186 EXPECT_EQ(QUIC_UNENCRYPTED_STREAM_DATA,
1187 connection_close_frames[0].error_code);
1190 TEST_P(QuicConnectionTest, TruncatedAck) {
1191 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1192 QuicPacketSequenceNumber num_packets = 256 * 2 + 1;
1193 for (QuicPacketSequenceNumber i = 0; i < num_packets; ++i) {
1194 SendStreamDataToPeer(3, "foo", i * 3, !kFin, nullptr);
1197 QuicAckFrame frame = InitAckFrame(num_packets);
1198 SequenceNumberSet lost_packets;
1199 // Create an ack with 256 nacks, none adjacent to one another.
1200 for (QuicPacketSequenceNumber i = 1; i <= 256; ++i) {
1201 NackPacket(i * 2, &frame);
1202 if (i < 256) { // Last packet is nacked, but not lost.
1203 lost_packets.insert(i * 2);
1206 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1207 .WillOnce(Return(lost_packets));
1208 EXPECT_CALL(entropy_calculator_, EntropyHash(511))
1209 .WillOnce(Return(static_cast<QuicPacketEntropyHash>(0)));
1210 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1211 ProcessAckPacket(&frame);
1213 // A truncated ack will not have the true largest observed.
1214 EXPECT_GT(num_packets, manager_->largest_observed());
1216 AckPacket(192, &frame);
1218 // Removing one missing packet allows us to ack 192 and one more range, but
1219 // 192 has already been declared lost, so it doesn't register as an ack.
1220 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1221 .WillOnce(Return(SequenceNumberSet()));
1222 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1223 ProcessAckPacket(&frame);
1224 EXPECT_EQ(num_packets, manager_->largest_observed());
1227 TEST_P(QuicConnectionTest, AckReceiptCausesAckSendBadEntropy) {
1228 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1230 ProcessPacket(1);
1231 // Delay sending, then queue up an ack.
1232 EXPECT_CALL(*send_algorithm_,
1233 TimeUntilSend(_, _, _)).WillOnce(
1234 testing::Return(QuicTime::Delta::FromMicroseconds(1)));
1235 QuicConnectionPeer::SendAck(&connection_);
1237 // Process an ack with a least unacked of the received ack.
1238 // This causes an ack to be sent when TimeUntilSend returns 0.
1239 EXPECT_CALL(*send_algorithm_,
1240 TimeUntilSend(_, _, _)).WillRepeatedly(
1241 testing::Return(QuicTime::Delta::Zero()));
1242 // Skip a packet and then record an ack.
1243 QuicAckFrame frame = InitAckFrame(0);
1244 ProcessAckPacket(3, &frame);
1247 TEST_P(QuicConnectionTest, OutOfOrderReceiptCausesAckSend) {
1248 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1250 ProcessPacket(3);
1251 // Should ack immediately since we have missing packets.
1252 EXPECT_EQ(1u, writer_->packets_write_attempts());
1254 ProcessPacket(2);
1255 // Should ack immediately since we have missing packets.
1256 EXPECT_EQ(2u, writer_->packets_write_attempts());
1258 ProcessPacket(1);
1259 // Should ack immediately, since this fills the last hole.
1260 EXPECT_EQ(3u, writer_->packets_write_attempts());
1262 ProcessPacket(4);
1263 // Should not cause an ack.
1264 EXPECT_EQ(3u, writer_->packets_write_attempts());
1267 TEST_P(QuicConnectionTest, OutOfOrderAckReceiptCausesNoAck) {
1268 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1270 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr);
1271 SendStreamDataToPeer(1, "bar", 3, !kFin, nullptr);
1272 EXPECT_EQ(2u, writer_->packets_write_attempts());
1274 QuicAckFrame ack1 = InitAckFrame(1);
1275 QuicAckFrame ack2 = InitAckFrame(2);
1276 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1277 ProcessAckPacket(2, &ack2);
1278 // Should ack immediately since we have missing packets.
1279 EXPECT_EQ(2u, writer_->packets_write_attempts());
1281 ProcessAckPacket(1, &ack1);
1282 // Should not ack an ack filling a missing packet.
1283 EXPECT_EQ(2u, writer_->packets_write_attempts());
1286 TEST_P(QuicConnectionTest, AckReceiptCausesAckSend) {
1287 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1289 QuicPacketSequenceNumber original;
1290 QuicByteCount packet_size;
1291 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1292 .WillOnce(DoAll(SaveArg<2>(&original), SaveArg<3>(&packet_size),
1293 Return(true)));
1294 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
1295 QuicAckFrame frame = InitAckFrame(original);
1296 NackPacket(original, &frame);
1297 // First nack triggers early retransmit.
1298 SequenceNumberSet lost_packets;
1299 lost_packets.insert(1);
1300 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1301 .WillOnce(Return(lost_packets));
1302 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1303 QuicPacketSequenceNumber retransmission;
1304 EXPECT_CALL(*send_algorithm_,
1305 OnPacketSent(_, _, _, packet_size - kQuicVersionSize, _))
1306 .WillOnce(DoAll(SaveArg<2>(&retransmission), Return(true)));
1308 ProcessAckPacket(&frame);
1310 QuicAckFrame frame2 = InitAckFrame(retransmission);
1311 NackPacket(original, &frame2);
1312 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1313 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1314 .WillOnce(Return(SequenceNumberSet()));
1315 ProcessAckPacket(&frame2);
1317 // Now if the peer sends an ack which still reports the retransmitted packet
1318 // as missing, that will bundle an ack with data after two acks in a row
1319 // indicate the high water mark needs to be raised.
1320 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _,
1321 HAS_RETRANSMITTABLE_DATA));
1322 connection_.SendStreamDataWithString(3, "foo", 3, !kFin, nullptr);
1323 // No ack sent.
1324 EXPECT_EQ(1u, writer_->frame_count());
1325 EXPECT_EQ(1u, writer_->stream_frames().size());
1327 // No more packet loss for the rest of the test.
1328 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1329 .WillRepeatedly(Return(SequenceNumberSet()));
1330 ProcessAckPacket(&frame2);
1331 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _,
1332 HAS_RETRANSMITTABLE_DATA));
1333 connection_.SendStreamDataWithString(3, "foo", 3, !kFin, nullptr);
1334 // Ack bundled.
1335 EXPECT_EQ(3u, writer_->frame_count());
1336 EXPECT_EQ(1u, writer_->stream_frames().size());
1337 EXPECT_FALSE(writer_->ack_frames().empty());
1339 // But an ack with no missing packets will not send an ack.
1340 AckPacket(original, &frame2);
1341 ProcessAckPacket(&frame2);
1342 ProcessAckPacket(&frame2);
1345 TEST_P(QuicConnectionTest, 20AcksCausesAckSend) {
1346 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1348 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr);
1350 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
1351 // But an ack with no missing packets will not send an ack.
1352 QuicAckFrame frame = InitAckFrame(1);
1353 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1354 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1355 .WillRepeatedly(Return(SequenceNumberSet()));
1356 for (int i = 0; i < 20; ++i) {
1357 EXPECT_FALSE(ack_alarm->IsSet());
1358 ProcessAckPacket(&frame);
1360 EXPECT_TRUE(ack_alarm->IsSet());
1363 TEST_P(QuicConnectionTest, LeastUnackedLower) {
1364 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1366 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr);
1367 SendStreamDataToPeer(1, "bar", 3, !kFin, nullptr);
1368 SendStreamDataToPeer(1, "eep", 6, !kFin, nullptr);
1370 // Start out saying the least unacked is 2.
1371 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 5);
1372 QuicStopWaitingFrame frame = InitStopWaitingFrame(2);
1373 ProcessStopWaitingPacket(&frame);
1375 // Change it to 1, but lower the sequence number to fake out-of-order packets.
1376 // This should be fine.
1377 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 1);
1378 // The scheduler will not process out of order acks, but all packet processing
1379 // causes the connection to try to write.
1380 EXPECT_CALL(visitor_, OnCanWrite());
1381 QuicStopWaitingFrame frame2 = InitStopWaitingFrame(1);
1382 ProcessStopWaitingPacket(&frame2);
1384 // Now claim it's one, but set the ordering so it was sent "after" the first
1385 // one. This should cause a connection error.
1386 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
1387 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 7);
1388 EXPECT_CALL(visitor_,
1389 OnConnectionClosed(QUIC_INVALID_STOP_WAITING_DATA, false));
1390 QuicStopWaitingFrame frame3 = InitStopWaitingFrame(1);
1391 ProcessStopWaitingPacket(&frame3);
1394 TEST_P(QuicConnectionTest, TooManySentPackets) {
1395 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1397 const int num_packets = kMaxTrackedPackets + 100;
1398 for (int i = 0; i < num_packets; ++i) {
1399 SendStreamDataToPeer(1, "foo", 3 * i, !kFin, nullptr);
1402 // Ack packet 1, which leaves more than the limit outstanding.
1403 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1404 EXPECT_CALL(visitor_, OnConnectionClosed(
1405 QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS, false));
1406 // We're receive buffer limited, so the connection won't try to write more.
1407 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
1409 // Nack the first packet and ack the rest, leaving a huge gap.
1410 QuicAckFrame frame1 = InitAckFrame(num_packets);
1411 NackPacket(1, &frame1);
1412 ProcessAckPacket(&frame1);
1415 TEST_P(QuicConnectionTest, TooManyReceivedPackets) {
1416 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1417 EXPECT_CALL(visitor_, OnConnectionClosed(
1418 QUIC_TOO_MANY_OUTSTANDING_RECEIVED_PACKETS, false));
1420 // Miss 99 of every 100 packets for 5500 packets.
1421 for (QuicPacketSequenceNumber i = 1; i < kMaxTrackedPackets + 500; i += 100) {
1422 ProcessPacket(i);
1423 if (!connection_.connected()) {
1424 break;
1429 TEST_P(QuicConnectionTest, LargestObservedLower) {
1430 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1432 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr);
1433 SendStreamDataToPeer(1, "bar", 3, !kFin, nullptr);
1434 SendStreamDataToPeer(1, "eep", 6, !kFin, nullptr);
1435 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1437 // Start out saying the largest observed is 2.
1438 QuicAckFrame frame1 = InitAckFrame(1);
1439 QuicAckFrame frame2 = InitAckFrame(2);
1440 ProcessAckPacket(&frame2);
1442 // Now change it to 1, and it should cause a connection error.
1443 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, false));
1444 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
1445 ProcessAckPacket(&frame1);
1448 TEST_P(QuicConnectionTest, AckUnsentData) {
1449 // Ack a packet which has not been sent.
1450 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, false));
1451 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1452 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
1453 QuicAckFrame frame(MakeAckFrame(1));
1454 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
1455 ProcessAckPacket(&frame);
1458 TEST_P(QuicConnectionTest, AckAll) {
1459 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1460 ProcessPacket(1);
1462 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 1);
1463 QuicAckFrame frame1 = InitAckFrame(0);
1464 ProcessAckPacket(&frame1);
1467 TEST_P(QuicConnectionTest, SendingDifferentSequenceNumberLengthsBandwidth) {
1468 QuicPacketSequenceNumber last_packet;
1469 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet);
1470 EXPECT_EQ(1u, last_packet);
1471 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1472 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1473 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1474 writer_->header().public_header.sequence_number_length);
1476 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
1477 Return(kMaxPacketSize * 256));
1479 SendStreamDataToPeer(1, "bar", 3, !kFin, &last_packet);
1480 EXPECT_EQ(2u, last_packet);
1481 EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER,
1482 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1483 // The 1 packet lag is due to the sequence number length being recalculated in
1484 // QuicConnection after a packet is sent.
1485 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1486 writer_->header().public_header.sequence_number_length);
1488 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
1489 Return(kMaxPacketSize * 256 * 256));
1491 SendStreamDataToPeer(1, "foo", 6, !kFin, &last_packet);
1492 EXPECT_EQ(3u, last_packet);
1493 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1494 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1495 EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER,
1496 writer_->header().public_header.sequence_number_length);
1498 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
1499 Return(kMaxPacketSize * 256 * 256 * 256));
1501 SendStreamDataToPeer(1, "bar", 9, !kFin, &last_packet);
1502 EXPECT_EQ(4u, last_packet);
1503 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1504 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1505 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1506 writer_->header().public_header.sequence_number_length);
1508 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
1509 Return(kMaxPacketSize * 256 * 256 * 256 * 256));
1511 SendStreamDataToPeer(1, "foo", 12, !kFin, &last_packet);
1512 EXPECT_EQ(5u, last_packet);
1513 EXPECT_EQ(PACKET_6BYTE_SEQUENCE_NUMBER,
1514 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1515 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1516 writer_->header().public_header.sequence_number_length);
1519 // TODO(ianswett): Re-enable this test by finding a good way to test different
1520 // sequence number lengths without sending packets with giant gaps.
1521 TEST_P(QuicConnectionTest,
1522 DISABLED_SendingDifferentSequenceNumberLengthsUnackedDelta) {
1523 QuicPacketSequenceNumber last_packet;
1524 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet);
1525 EXPECT_EQ(1u, last_packet);
1526 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1527 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1528 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1529 writer_->header().public_header.sequence_number_length);
1531 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 100);
1533 SendStreamDataToPeer(1, "bar", 3, !kFin, &last_packet);
1534 EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER,
1535 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1536 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1537 writer_->header().public_header.sequence_number_length);
1539 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 100 * 256);
1541 SendStreamDataToPeer(1, "foo", 6, !kFin, &last_packet);
1542 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1543 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1544 EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER,
1545 writer_->header().public_header.sequence_number_length);
1547 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 100 * 256 * 256);
1549 SendStreamDataToPeer(1, "bar", 9, !kFin, &last_packet);
1550 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1551 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1552 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1553 writer_->header().public_header.sequence_number_length);
1555 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_,
1556 100 * 256 * 256 * 256);
1558 SendStreamDataToPeer(1, "foo", 12, !kFin, &last_packet);
1559 EXPECT_EQ(PACKET_6BYTE_SEQUENCE_NUMBER,
1560 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1561 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1562 writer_->header().public_header.sequence_number_length);
1565 TEST_P(QuicConnectionTest, BasicSending) {
1566 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1567 QuicPacketSequenceNumber last_packet;
1568 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet); // Packet 1
1569 EXPECT_EQ(1u, last_packet);
1570 SendAckPacketToPeer(); // Packet 2
1572 EXPECT_EQ(1u, least_unacked());
1574 SendAckPacketToPeer(); // Packet 3
1575 EXPECT_EQ(1u, least_unacked());
1577 SendStreamDataToPeer(1, "bar", 3, !kFin, &last_packet); // Packet 4
1578 EXPECT_EQ(4u, last_packet);
1579 SendAckPacketToPeer(); // Packet 5
1580 EXPECT_EQ(1u, least_unacked());
1582 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1584 // Peer acks up to packet 3.
1585 QuicAckFrame frame = InitAckFrame(3);
1586 ProcessAckPacket(&frame);
1587 SendAckPacketToPeer(); // Packet 6
1589 // As soon as we've acked one, we skip ack packets 2 and 3 and note lack of
1590 // ack for 4.
1591 EXPECT_EQ(4u, least_unacked());
1593 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1595 // Peer acks up to packet 4, the last packet.
1596 QuicAckFrame frame2 = InitAckFrame(6);
1597 ProcessAckPacket(&frame2); // Acks don't instigate acks.
1599 // Verify that we did not send an ack.
1600 EXPECT_EQ(6u, writer_->header().packet_sequence_number);
1602 // So the last ack has not changed.
1603 EXPECT_EQ(4u, least_unacked());
1605 // If we force an ack, we shouldn't change our retransmit state.
1606 SendAckPacketToPeer(); // Packet 7
1607 EXPECT_EQ(7u, least_unacked());
1609 // But if we send more data it should.
1610 SendStreamDataToPeer(1, "eep", 6, !kFin, &last_packet); // Packet 8
1611 EXPECT_EQ(8u, last_packet);
1612 SendAckPacketToPeer(); // Packet 9
1613 EXPECT_EQ(7u, least_unacked());
1616 // QuicConnection should record the the packet sent-time prior to sending the
1617 // packet.
1618 TEST_P(QuicConnectionTest, RecordSentTimeBeforePacketSent) {
1619 // We're using a MockClock for the tests, so we have complete control over the
1620 // time.
1621 // Our recorded timestamp for the last packet sent time will be passed in to
1622 // the send_algorithm. Make sure that it is set to the correct value.
1623 QuicTime actual_recorded_send_time = QuicTime::Zero();
1624 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1625 .WillOnce(DoAll(SaveArg<0>(&actual_recorded_send_time), Return(true)));
1627 // First send without any pause and check the result.
1628 QuicTime expected_recorded_send_time = clock_.Now();
1629 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
1630 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
1631 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
1632 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
1634 // Now pause during the write, and check the results.
1635 actual_recorded_send_time = QuicTime::Zero();
1636 const QuicTime::Delta write_pause_time_delta =
1637 QuicTime::Delta::FromMilliseconds(5000);
1638 SetWritePauseTimeDelta(write_pause_time_delta);
1639 expected_recorded_send_time = clock_.Now();
1641 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1642 .WillOnce(DoAll(SaveArg<0>(&actual_recorded_send_time), Return(true)));
1643 connection_.SendStreamDataWithString(2, "baz", 0, !kFin, nullptr);
1644 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
1645 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
1646 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
1649 TEST_P(QuicConnectionTest, FECSending) {
1650 // All packets carry version info till version is negotiated.
1651 size_t payload_length;
1652 // GetPacketLengthForOneStream() assumes a stream offset of 0 in determining
1653 // packet length. The size of the offset field in a stream frame is 0 for
1654 // offset 0, and 2 for non-zero offsets up through 64K. Increase
1655 // max_packet_length by 2 so that subsequent packets containing subsequent
1656 // stream frames with non-zero offets will fit within the packet length.
1657 size_t length = 2 + GetPacketLengthForOneStream(
1658 connection_.version(), kIncludeVersion,
1659 PACKET_8BYTE_CONNECTION_ID, PACKET_1BYTE_SEQUENCE_NUMBER,
1660 IN_FEC_GROUP, &payload_length);
1661 connection_.set_max_packet_length(length);
1663 if (generator_->fec_send_policy() == FEC_ALARM_TRIGGER) {
1664 // Send 4 protected data packets. FEC packet is not sent.
1665 EXPECT_CALL(*send_algorithm_,
1666 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(4);
1667 } else {
1668 // Send 4 protected data packets, which should also trigger 1 FEC packet.
1669 EXPECT_CALL(*send_algorithm_,
1670 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(5);
1672 // The first stream frame will have 2 fewer overhead bytes than the other 3.
1673 const string payload(payload_length * 4 + 2, 'a');
1674 connection_.SendStreamDataWithStringWithFec(1, payload, 0, !kFin, nullptr);
1675 // Expect the FEC group to be closed after SendStreamDataWithString.
1676 EXPECT_FALSE(creator_->IsFecGroupOpen());
1677 EXPECT_FALSE(creator_->IsFecProtected());
1680 TEST_P(QuicConnectionTest, FECQueueing) {
1681 // All packets carry version info till version is negotiated.
1682 size_t payload_length;
1683 size_t length = GetPacketLengthForOneStream(
1684 connection_.version(), kIncludeVersion,
1685 PACKET_8BYTE_CONNECTION_ID, PACKET_1BYTE_SEQUENCE_NUMBER,
1686 IN_FEC_GROUP, &payload_length);
1687 connection_.set_max_packet_length(length);
1688 EXPECT_TRUE(creator_->IsFecEnabled());
1690 EXPECT_EQ(0u, connection_.NumQueuedPackets());
1691 BlockOnNextWrite();
1692 const string payload(payload_length, 'a');
1693 connection_.SendStreamDataWithStringWithFec(1, payload, 0, !kFin, nullptr);
1694 EXPECT_FALSE(creator_->IsFecGroupOpen());
1695 EXPECT_FALSE(creator_->IsFecProtected());
1696 if (generator_->fec_send_policy() == FEC_ALARM_TRIGGER) {
1697 // Expect the first data packet to be queued and not the FEC packet.
1698 EXPECT_EQ(1u, connection_.NumQueuedPackets());
1699 } else {
1700 // Expect the first data packet and the fec packet to be queued.
1701 EXPECT_EQ(2u, connection_.NumQueuedPackets());
1705 TEST_P(QuicConnectionTest, FECAlarmStoppedWhenFECPacketSent) {
1706 EXPECT_TRUE(creator_->IsFecEnabled());
1707 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1708 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1710 creator_->set_max_packets_per_fec_group(2);
1712 // 1 Data packet. FEC alarm should be set.
1713 EXPECT_CALL(*send_algorithm_,
1714 OnPacketSent(_, _, 1u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1715 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, true, nullptr);
1716 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1718 if (generator_->fec_send_policy() == FEC_ALARM_TRIGGER) {
1719 // If FEC send policy is FEC_ALARM_TRIGGER, FEC packet is not sent.
1720 // FEC alarm should not be set.
1721 EXPECT_CALL(*send_algorithm_,
1722 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1723 } else {
1724 // Second data packet triggers FEC packet out. FEC alarm should not be set.
1725 EXPECT_CALL(*send_algorithm_,
1726 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(2);
1728 connection_.SendStreamDataWithStringWithFec(5, "foo", 0, true, nullptr);
1729 if (generator_->fec_send_policy() == FEC_ANY_TRIGGER) {
1730 EXPECT_TRUE(writer_->header().fec_flag);
1732 EXPECT_FALSE(creator_->IsFecGroupOpen());
1733 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1736 TEST_P(QuicConnectionTest, FECAlarmStoppedOnConnectionClose) {
1737 EXPECT_TRUE(creator_->IsFecEnabled());
1738 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1739 creator_->set_max_packets_per_fec_group(100);
1741 // 1 Data packet. FEC alarm should be set.
1742 EXPECT_CALL(*send_algorithm_,
1743 OnPacketSent(_, _, 1u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1744 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, kFin, nullptr);
1745 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1747 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NO_ERROR, false));
1748 // Closing connection should stop the FEC alarm.
1749 connection_.CloseConnection(QUIC_NO_ERROR, /*from_peer=*/false);
1750 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1753 TEST_P(QuicConnectionTest, RemoveFECFromInflightOnRetransmissionTimeout) {
1754 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1755 EXPECT_TRUE(creator_->IsFecEnabled());
1756 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1757 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1759 // 1 Data packet. FEC alarm should be set.
1760 EXPECT_CALL(*send_algorithm_,
1761 OnPacketSent(_, _, 1u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1762 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, !kFin, nullptr);
1763 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1764 size_t protected_packet =
1765 QuicSentPacketManagerPeer::GetBytesInFlight(manager_);
1767 // Force FEC timeout to send FEC packet out.
1768 EXPECT_CALL(*send_algorithm_,
1769 OnPacketSent(_, _, 2u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1770 connection_.GetFecAlarm()->Fire();
1771 EXPECT_TRUE(writer_->header().fec_flag);
1773 size_t fec_packet = protected_packet;
1774 EXPECT_EQ(protected_packet + fec_packet,
1775 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1776 clock_.AdvanceTime(DefaultRetransmissionTime());
1778 // On RTO, both data and FEC packets are removed from inflight, only the data
1779 // packet is retransmitted, and this retransmission (but not FEC) gets added
1780 // back into the inflight.
1781 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
1782 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1783 connection_.GetRetransmissionAlarm()->Fire();
1785 // The retransmission of packet 1 will be 3 bytes smaller than packet 1, since
1786 // the first transmission will have 1 byte for FEC group number and 2 bytes of
1787 // stream frame size, which are absent in the retransmission.
1788 size_t retransmitted_packet = protected_packet - 3;
1789 EXPECT_EQ(protected_packet + retransmitted_packet,
1790 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1791 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1793 // Receive ack for the retransmission. No data should be outstanding.
1794 QuicAckFrame ack = InitAckFrame(3);
1795 NackPacket(1, &ack);
1796 NackPacket(2, &ack);
1797 SequenceNumberSet lost_packets;
1798 lost_packets.insert(1);
1799 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1800 .WillOnce(Return(lost_packets));
1801 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1802 ProcessAckPacket(&ack);
1804 // Ensure the alarm is not set since all packets have been acked or abandoned.
1805 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
1806 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1809 TEST_P(QuicConnectionTest, RemoveFECFromInflightOnLossRetransmission) {
1810 EXPECT_TRUE(creator_->IsFecEnabled());
1811 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1813 // 1 FEC-protected data packet. FEC alarm should be set.
1814 EXPECT_CALL(*send_algorithm_,
1815 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1816 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, kFin, nullptr);
1817 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1818 size_t protected_packet =
1819 QuicSentPacketManagerPeer::GetBytesInFlight(manager_);
1821 // Force FEC timeout to send FEC packet out.
1822 EXPECT_CALL(*send_algorithm_,
1823 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1824 connection_.GetFecAlarm()->Fire();
1825 EXPECT_TRUE(writer_->header().fec_flag);
1826 size_t fec_packet = protected_packet;
1827 EXPECT_EQ(protected_packet + fec_packet,
1828 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1830 // Send more data to trigger NACKs. Note that all data starts at stream offset
1831 // 0 to ensure the same packet size, for ease of testing.
1832 EXPECT_CALL(*send_algorithm_,
1833 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(4);
1834 connection_.SendStreamDataWithString(5, "foo", 0, kFin, nullptr);
1835 connection_.SendStreamDataWithString(7, "foo", 0, kFin, nullptr);
1836 connection_.SendStreamDataWithString(9, "foo", 0, kFin, nullptr);
1837 connection_.SendStreamDataWithString(11, "foo", 0, kFin, nullptr);
1839 // An unprotected packet will be 3 bytes smaller than an FEC-protected packet,
1840 // since the protected packet will have 1 byte for FEC group number and
1841 // 2 bytes of stream frame size, which are absent in the unprotected packet.
1842 size_t unprotected_packet = protected_packet - 3;
1843 EXPECT_EQ(protected_packet + fec_packet + 4 * unprotected_packet,
1844 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1845 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1847 // Ack data packets, and NACK FEC packet and one data packet. Triggers
1848 // NACK-based loss detection of both packets, but only data packet is
1849 // retransmitted and considered oustanding.
1850 QuicAckFrame ack = InitAckFrame(6);
1851 NackPacket(2, &ack);
1852 NackPacket(3, &ack);
1853 SequenceNumberSet lost_packets;
1854 lost_packets.insert(2);
1855 lost_packets.insert(3);
1856 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1857 .WillOnce(Return(lost_packets));
1858 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1859 EXPECT_CALL(*send_algorithm_,
1860 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1861 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1862 ProcessAckPacket(&ack);
1863 // On receiving this ack from the server, the client will no longer send
1864 // version number in subsequent packets, including in this retransmission.
1865 size_t unprotected_packet_no_version = unprotected_packet - 4;
1866 EXPECT_EQ(unprotected_packet_no_version,
1867 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1869 // Receive ack for the retransmission. No data should be outstanding.
1870 QuicAckFrame ack2 = InitAckFrame(7);
1871 NackPacket(2, &ack2);
1872 NackPacket(3, &ack2);
1873 SequenceNumberSet lost_packets2;
1874 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1875 .WillOnce(Return(lost_packets2));
1876 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1877 ProcessAckPacket(&ack2);
1878 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1881 TEST_P(QuicConnectionTest, FECRemainsInflightOnTLPOfEarlierData) {
1882 // This test checks if TLP is sent correctly when a data and an FEC packet
1883 // are outstanding. TLP should be sent for the data packet when the
1884 // retransmission alarm fires.
1885 // Turn on TLP for this test.
1886 QuicSentPacketManagerPeer::SetMaxTailLossProbes(manager_, 1);
1887 EXPECT_TRUE(creator_->IsFecEnabled());
1888 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1889 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1891 // 1 Data packet. FEC alarm should be set.
1892 EXPECT_CALL(*send_algorithm_,
1893 OnPacketSent(_, _, 1u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1894 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, kFin, nullptr);
1895 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1896 size_t protected_packet =
1897 QuicSentPacketManagerPeer::GetBytesInFlight(manager_);
1898 EXPECT_LT(0u, protected_packet);
1900 // Force FEC timeout to send FEC packet out.
1901 EXPECT_CALL(*send_algorithm_,
1902 OnPacketSent(_, _, 2u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1903 connection_.GetFecAlarm()->Fire();
1904 EXPECT_TRUE(writer_->header().fec_flag);
1905 size_t fec_packet = protected_packet;
1906 EXPECT_EQ(protected_packet + fec_packet,
1907 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1909 // TLP alarm should be set.
1910 QuicTime retransmission_time =
1911 connection_.GetRetransmissionAlarm()->deadline();
1912 EXPECT_NE(QuicTime::Zero(), retransmission_time);
1913 // Simulate the retransmission alarm firing and sending a TLP, so send
1914 // algorithm's OnRetransmissionTimeout is not called.
1915 clock_.AdvanceTime(retransmission_time.Subtract(clock_.Now()));
1916 EXPECT_CALL(*send_algorithm_,
1917 OnPacketSent(_, _, 3u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1918 connection_.GetRetransmissionAlarm()->Fire();
1919 // The TLP retransmission of packet 1 will be 3 bytes smaller than packet 1,
1920 // since packet 1 will have 1 byte for FEC group number and 2 bytes of stream
1921 // frame size, which are absent in the the TLP retransmission.
1922 size_t tlp_packet = protected_packet - 3;
1923 EXPECT_EQ(protected_packet + fec_packet + tlp_packet,
1924 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1927 TEST_P(QuicConnectionTest, FECRemainsInflightOnTLPOfLaterData) {
1928 // Tests if TLP is sent correctly when data packet 1 and an FEC packet are
1929 // sent followed by data packet 2, and data packet 1 is acked. TLP should be
1930 // sent for data packet 2 when the retransmission alarm fires. Turn on TLP for
1931 // this test.
1932 QuicSentPacketManagerPeer::SetMaxTailLossProbes(manager_, 1);
1933 EXPECT_TRUE(creator_->IsFecEnabled());
1934 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1935 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1937 // 1 Data packet. FEC alarm should be set.
1938 EXPECT_CALL(*send_algorithm_,
1939 OnPacketSent(_, _, 1u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1940 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, kFin, nullptr);
1941 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1942 size_t protected_packet =
1943 QuicSentPacketManagerPeer::GetBytesInFlight(manager_);
1944 EXPECT_LT(0u, protected_packet);
1946 // Force FEC timeout to send FEC packet out.
1947 EXPECT_CALL(*send_algorithm_,
1948 OnPacketSent(_, _, 2u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1949 connection_.GetFecAlarm()->Fire();
1950 EXPECT_TRUE(writer_->header().fec_flag);
1951 // Protected data packet and FEC packet oustanding.
1952 size_t fec_packet = protected_packet;
1953 EXPECT_EQ(protected_packet + fec_packet,
1954 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1956 // Send 1 unprotected data packet. No FEC alarm should be set.
1957 EXPECT_CALL(*send_algorithm_,
1958 OnPacketSent(_, _, 3u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1959 connection_.SendStreamDataWithString(5, "foo", 0, kFin, nullptr);
1960 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1961 // Protected data packet, FEC packet, and unprotected data packet oustanding.
1962 // An unprotected packet will be 3 bytes smaller than an FEC-protected packet,
1963 // since the protected packet will have 1 byte for FEC group number and
1964 // 2 bytes of stream frame size, which are absent in the unprotected packet.
1965 size_t unprotected_packet = protected_packet - 3;
1966 EXPECT_EQ(protected_packet + fec_packet + unprotected_packet,
1967 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1969 // Receive ack for first data packet. FEC and second data packet are still
1970 // outstanding.
1971 QuicAckFrame ack = InitAckFrame(1);
1972 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1973 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1974 ProcessAckPacket(&ack);
1975 // FEC packet and unprotected data packet oustanding.
1976 EXPECT_EQ(fec_packet + unprotected_packet,
1977 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1979 // TLP alarm should be set.
1980 QuicTime retransmission_time =
1981 connection_.GetRetransmissionAlarm()->deadline();
1982 EXPECT_NE(QuicTime::Zero(), retransmission_time);
1983 // Simulate the retransmission alarm firing and sending a TLP, so send
1984 // algorithm's OnRetransmissionTimeout is not called.
1985 clock_.AdvanceTime(retransmission_time.Subtract(clock_.Now()));
1986 EXPECT_CALL(*send_algorithm_,
1987 OnPacketSent(_, _, 4u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1988 connection_.GetRetransmissionAlarm()->Fire();
1990 // Having received an ack from the server, the client will no longer send
1991 // version number in subsequent packets, including in this retransmission.
1992 size_t tlp_packet_no_version = unprotected_packet - 4;
1993 EXPECT_EQ(fec_packet + unprotected_packet + tlp_packet_no_version,
1994 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1997 TEST_P(QuicConnectionTest, NoTLPForFECPacket) {
1998 // Turn on TLP for this test.
1999 QuicSentPacketManagerPeer::SetMaxTailLossProbes(manager_, 1);
2000 EXPECT_TRUE(creator_->IsFecEnabled());
2001 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2003 // Send 1 FEC-protected data packet. FEC alarm should be set.
2004 EXPECT_CALL(*send_algorithm_,
2005 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
2006 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, !kFin, nullptr);
2007 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
2008 // Force FEC timeout to send FEC packet out.
2009 EXPECT_CALL(*send_algorithm_,
2010 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
2011 connection_.GetFecAlarm()->Fire();
2012 EXPECT_TRUE(writer_->header().fec_flag);
2014 // Ack data packet, but not FEC packet.
2015 QuicAckFrame ack = InitAckFrame(1);
2016 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2017 ProcessAckPacket(&ack);
2019 // No TLP alarm for FEC, but retransmission alarm should be set for an RTO.
2020 EXPECT_LT(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
2021 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2022 QuicTime rto_time = connection_.GetRetransmissionAlarm()->deadline();
2023 EXPECT_NE(QuicTime::Zero(), rto_time);
2025 // Simulate the retransmission alarm firing. FEC packet is no longer
2026 // outstanding.
2027 clock_.AdvanceTime(rto_time.Subtract(clock_.Now()));
2028 connection_.GetRetransmissionAlarm()->Fire();
2030 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
2031 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
2034 TEST_P(QuicConnectionTest, FramePacking) {
2035 CongestionBlockWrites();
2037 // Send an ack and two stream frames in 1 packet by queueing them.
2038 connection_.SendAck();
2039 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
2040 IgnoreResult(InvokeWithoutArgs(&connection_,
2041 &TestConnection::SendStreamData3)),
2042 IgnoreResult(InvokeWithoutArgs(&connection_,
2043 &TestConnection::SendStreamData5))));
2045 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2046 CongestionUnblockWrites();
2047 connection_.GetSendAlarm()->Fire();
2048 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2049 EXPECT_FALSE(connection_.HasQueuedData());
2051 // Parse the last packet and ensure it's an ack and two stream frames from
2052 // two different streams.
2053 EXPECT_EQ(4u, writer_->frame_count());
2054 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
2055 EXPECT_FALSE(writer_->ack_frames().empty());
2056 ASSERT_EQ(2u, writer_->stream_frames().size());
2057 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id);
2058 EXPECT_EQ(kClientDataStreamId2, writer_->stream_frames()[1].stream_id);
2061 TEST_P(QuicConnectionTest, FramePackingNonCryptoThenCrypto) {
2062 CongestionBlockWrites();
2064 // Send an ack and two stream frames (one non-crypto, then one crypto) in 2
2065 // packets by queueing them.
2066 connection_.SendAck();
2067 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
2068 IgnoreResult(InvokeWithoutArgs(&connection_,
2069 &TestConnection::SendStreamData3)),
2070 IgnoreResult(InvokeWithoutArgs(&connection_,
2071 &TestConnection::SendCryptoStreamData))));
2073 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
2074 CongestionUnblockWrites();
2075 connection_.GetSendAlarm()->Fire();
2076 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2077 EXPECT_FALSE(connection_.HasQueuedData());
2079 // Parse the last packet and ensure it's the crypto stream frame.
2080 EXPECT_EQ(1u, writer_->frame_count());
2081 ASSERT_EQ(1u, writer_->stream_frames().size());
2082 EXPECT_EQ(kCryptoStreamId, writer_->stream_frames()[0].stream_id);
2085 TEST_P(QuicConnectionTest, FramePackingCryptoThenNonCrypto) {
2086 CongestionBlockWrites();
2088 // Send an ack and two stream frames (one crypto, then one non-crypto) in 2
2089 // packets by queueing them.
2090 connection_.SendAck();
2091 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
2092 IgnoreResult(InvokeWithoutArgs(&connection_,
2093 &TestConnection::SendCryptoStreamData)),
2094 IgnoreResult(InvokeWithoutArgs(&connection_,
2095 &TestConnection::SendStreamData3))));
2097 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
2098 CongestionUnblockWrites();
2099 connection_.GetSendAlarm()->Fire();
2100 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2101 EXPECT_FALSE(connection_.HasQueuedData());
2103 // Parse the last packet and ensure it's the stream frame from stream 3.
2104 EXPECT_EQ(1u, writer_->frame_count());
2105 ASSERT_EQ(1u, writer_->stream_frames().size());
2106 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id);
2109 TEST_P(QuicConnectionTest, FramePackingFEC) {
2110 EXPECT_TRUE(creator_->IsFecEnabled());
2112 CongestionBlockWrites();
2114 // Queue an ack and two stream frames. Ack gets flushed when FEC is turned on
2115 // for sending protected data; two stream frames are packed in 1 packet.
2116 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
2117 IgnoreResult(InvokeWithoutArgs(
2118 &connection_, &TestConnection::SendStreamData3WithFec)),
2119 IgnoreResult(InvokeWithoutArgs(
2120 &connection_, &TestConnection::SendStreamData5WithFec))));
2121 connection_.SendAck();
2123 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
2124 CongestionUnblockWrites();
2125 connection_.GetSendAlarm()->Fire();
2126 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2127 EXPECT_FALSE(connection_.HasQueuedData());
2129 // Parse the last packet and ensure it's in an fec group.
2130 EXPECT_EQ(2u, writer_->header().fec_group);
2131 EXPECT_EQ(2u, writer_->frame_count());
2133 // FEC alarm should be set.
2134 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
2137 TEST_P(QuicConnectionTest, FramePackingAckResponse) {
2138 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2139 // Process a data packet to queue up a pending ack.
2140 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2141 ProcessDataPacket(1, 1, kEntropyFlag);
2143 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
2144 IgnoreResult(InvokeWithoutArgs(&connection_,
2145 &TestConnection::SendStreamData3)),
2146 IgnoreResult(InvokeWithoutArgs(&connection_,
2147 &TestConnection::SendStreamData5))));
2149 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2151 // Process an ack to cause the visitor's OnCanWrite to be invoked.
2152 QuicAckFrame ack_one = InitAckFrame(0);
2153 ProcessAckPacket(3, &ack_one);
2155 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2156 EXPECT_FALSE(connection_.HasQueuedData());
2158 // Parse the last packet and ensure it's an ack and two stream frames from
2159 // two different streams.
2160 EXPECT_EQ(4u, writer_->frame_count());
2161 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
2162 EXPECT_FALSE(writer_->ack_frames().empty());
2163 ASSERT_EQ(2u, writer_->stream_frames().size());
2164 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id);
2165 EXPECT_EQ(kClientDataStreamId2, writer_->stream_frames()[1].stream_id);
2168 TEST_P(QuicConnectionTest, FramePackingSendv) {
2169 // Send data in 1 packet by writing multiple blocks in a single iovector
2170 // using writev.
2171 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2173 char data[] = "ABCD";
2174 struct iovec iov[2];
2175 iov[0].iov_base = data;
2176 iov[0].iov_len = 2;
2177 iov[1].iov_base = data + 2;
2178 iov[1].iov_len = 2;
2179 connection_.SendStreamData(1, QuicIOVector(iov, 2, 4), 0, !kFin,
2180 MAY_FEC_PROTECT, nullptr);
2182 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2183 EXPECT_FALSE(connection_.HasQueuedData());
2185 // Parse the last packet and ensure multiple iovector blocks have
2186 // been packed into a single stream frame from one stream.
2187 EXPECT_EQ(1u, writer_->frame_count());
2188 EXPECT_EQ(1u, writer_->stream_frames().size());
2189 QuicStreamFrame frame = writer_->stream_frames()[0];
2190 EXPECT_EQ(1u, frame.stream_id);
2191 EXPECT_EQ("ABCD", frame.data);
2194 TEST_P(QuicConnectionTest, FramePackingSendvQueued) {
2195 // Try to send two stream frames in 1 packet by using writev.
2196 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2198 BlockOnNextWrite();
2199 char data[] = "ABCD";
2200 struct iovec iov[2];
2201 iov[0].iov_base = data;
2202 iov[0].iov_len = 2;
2203 iov[1].iov_base = data + 2;
2204 iov[1].iov_len = 2;
2205 connection_.SendStreamData(1, QuicIOVector(iov, 2, 4), 0, !kFin,
2206 MAY_FEC_PROTECT, nullptr);
2208 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2209 EXPECT_TRUE(connection_.HasQueuedData());
2211 // Unblock the writes and actually send.
2212 writer_->SetWritable();
2213 connection_.OnCanWrite();
2214 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2216 // Parse the last packet and ensure it's one stream frame from one stream.
2217 EXPECT_EQ(1u, writer_->frame_count());
2218 EXPECT_EQ(1u, writer_->stream_frames().size());
2219 EXPECT_EQ(1u, writer_->stream_frames()[0].stream_id);
2222 TEST_P(QuicConnectionTest, SendingZeroBytes) {
2223 // Send a zero byte write with a fin using writev.
2224 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2225 QuicIOVector empty_iov(nullptr, 0, 0);
2226 connection_.SendStreamData(1, empty_iov, 0, kFin, MAY_FEC_PROTECT, nullptr);
2228 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2229 EXPECT_FALSE(connection_.HasQueuedData());
2231 // Parse the last packet and ensure it's one stream frame from one stream.
2232 EXPECT_EQ(1u, writer_->frame_count());
2233 EXPECT_EQ(1u, writer_->stream_frames().size());
2234 EXPECT_EQ(1u, writer_->stream_frames()[0].stream_id);
2235 EXPECT_TRUE(writer_->stream_frames()[0].fin);
2238 TEST_P(QuicConnectionTest, OnCanWrite) {
2239 // Visitor's OnCanWrite will send data, but will have more pending writes.
2240 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
2241 IgnoreResult(InvokeWithoutArgs(&connection_,
2242 &TestConnection::SendStreamData3)),
2243 IgnoreResult(InvokeWithoutArgs(&connection_,
2244 &TestConnection::SendStreamData5))));
2245 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillOnce(Return(true));
2246 EXPECT_CALL(*send_algorithm_,
2247 TimeUntilSend(_, _, _)).WillRepeatedly(
2248 testing::Return(QuicTime::Delta::Zero()));
2250 connection_.OnCanWrite();
2252 // Parse the last packet and ensure it's the two stream frames from
2253 // two different streams.
2254 EXPECT_EQ(2u, writer_->frame_count());
2255 EXPECT_EQ(2u, writer_->stream_frames().size());
2256 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id);
2257 EXPECT_EQ(kClientDataStreamId2, writer_->stream_frames()[1].stream_id);
2260 TEST_P(QuicConnectionTest, RetransmitOnNack) {
2261 QuicPacketSequenceNumber last_packet;
2262 QuicByteCount second_packet_size;
2263 SendStreamDataToPeer(3, "foo", 0, !kFin, &last_packet); // Packet 1
2264 second_packet_size =
2265 SendStreamDataToPeer(3, "foos", 3, !kFin, &last_packet); // Packet 2
2266 SendStreamDataToPeer(3, "fooos", 7, !kFin, &last_packet); // Packet 3
2268 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2270 // Don't lose a packet on an ack, and nothing is retransmitted.
2271 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2272 QuicAckFrame ack_one = InitAckFrame(1);
2273 ProcessAckPacket(&ack_one);
2275 // Lose a packet and ensure it triggers retransmission.
2276 QuicAckFrame nack_two = InitAckFrame(3);
2277 NackPacket(2, &nack_two);
2278 SequenceNumberSet lost_packets;
2279 lost_packets.insert(2);
2280 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2281 .WillOnce(Return(lost_packets));
2282 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2283 EXPECT_CALL(*send_algorithm_,
2284 OnPacketSent(_, _, _, second_packet_size - kQuicVersionSize, _)).
2285 Times(1);
2286 ProcessAckPacket(&nack_two);
2289 TEST_P(QuicConnectionTest, DoNotSendQueuedPacketForResetStream) {
2290 // Block the connection to queue the packet.
2291 BlockOnNextWrite();
2293 QuicStreamId stream_id = 2;
2294 connection_.SendStreamDataWithString(stream_id, "foo", 0, !kFin, nullptr);
2296 // Now that there is a queued packet, reset the stream.
2297 connection_.SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 14);
2299 // Unblock the connection and verify that only the RST_STREAM is sent.
2300 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2301 writer_->SetWritable();
2302 connection_.OnCanWrite();
2303 EXPECT_EQ(1u, writer_->frame_count());
2304 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
2307 TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnNack) {
2308 QuicStreamId stream_id = 2;
2309 QuicPacketSequenceNumber last_packet;
2310 SendStreamDataToPeer(stream_id, "foo", 0, !kFin, &last_packet);
2311 SendStreamDataToPeer(stream_id, "foos", 3, !kFin, &last_packet);
2312 SendStreamDataToPeer(stream_id, "fooos", 7, !kFin, &last_packet);
2314 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2315 connection_.SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 14);
2317 // Lose a packet and ensure it does not trigger retransmission.
2318 QuicAckFrame nack_two = InitAckFrame(last_packet);
2319 NackPacket(last_packet - 1, &nack_two);
2320 SequenceNumberSet lost_packets;
2321 lost_packets.insert(last_packet - 1);
2322 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2323 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2324 .WillOnce(Return(lost_packets));
2325 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2326 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
2327 ProcessAckPacket(&nack_two);
2330 TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnRTO) {
2331 QuicStreamId stream_id = 2;
2332 QuicPacketSequenceNumber last_packet;
2333 SendStreamDataToPeer(stream_id, "foo", 0, !kFin, &last_packet);
2335 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2336 connection_.SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 14);
2338 // Fire the RTO and verify that the RST_STREAM is resent, not stream data.
2339 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2340 clock_.AdvanceTime(DefaultRetransmissionTime());
2341 connection_.GetRetransmissionAlarm()->Fire();
2342 EXPECT_EQ(1u, writer_->frame_count());
2343 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
2344 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
2347 TEST_P(QuicConnectionTest, DoNotSendPendingRetransmissionForResetStream) {
2348 QuicStreamId stream_id = 2;
2349 QuicPacketSequenceNumber last_packet;
2350 SendStreamDataToPeer(stream_id, "foo", 0, !kFin, &last_packet);
2351 SendStreamDataToPeer(stream_id, "foos", 3, !kFin, &last_packet);
2352 BlockOnNextWrite();
2353 connection_.SendStreamDataWithString(stream_id, "fooos", 7, !kFin, nullptr);
2355 // Lose a packet which will trigger a pending retransmission.
2356 QuicAckFrame ack = InitAckFrame(last_packet);
2357 NackPacket(last_packet - 1, &ack);
2358 SequenceNumberSet lost_packets;
2359 lost_packets.insert(last_packet - 1);
2360 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2361 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2362 .WillOnce(Return(lost_packets));
2363 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2364 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
2365 ProcessAckPacket(&ack);
2367 connection_.SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 14);
2369 // Unblock the connection and verify that the RST_STREAM is sent but not the
2370 // second data packet nor a retransmit.
2371 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2372 writer_->SetWritable();
2373 connection_.OnCanWrite();
2374 EXPECT_EQ(1u, writer_->frame_count());
2375 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
2376 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
2379 TEST_P(QuicConnectionTest, DiscardRetransmit) {
2380 QuicPacketSequenceNumber last_packet;
2381 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet); // Packet 1
2382 SendStreamDataToPeer(1, "foos", 3, !kFin, &last_packet); // Packet 2
2383 SendStreamDataToPeer(1, "fooos", 7, !kFin, &last_packet); // Packet 3
2385 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2387 // Instigate a loss with an ack.
2388 QuicAckFrame nack_two = InitAckFrame(3);
2389 NackPacket(2, &nack_two);
2390 // The first nack should trigger a fast retransmission, but we'll be
2391 // write blocked, so the packet will be queued.
2392 BlockOnNextWrite();
2393 SequenceNumberSet lost_packets;
2394 lost_packets.insert(2);
2395 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2396 .WillOnce(Return(lost_packets));
2397 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2398 ProcessAckPacket(&nack_two);
2399 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2401 // Now, ack the previous transmission.
2402 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2403 .WillOnce(Return(SequenceNumberSet()));
2404 QuicAckFrame ack_all = InitAckFrame(3);
2405 ProcessAckPacket(&ack_all);
2407 // Unblock the socket and attempt to send the queued packets. However,
2408 // since the previous transmission has been acked, we will not
2409 // send the retransmission.
2410 EXPECT_CALL(*send_algorithm_,
2411 OnPacketSent(_, _, _, _, _)).Times(0);
2413 writer_->SetWritable();
2414 connection_.OnCanWrite();
2416 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2419 TEST_P(QuicConnectionTest, RetransmitNackedLargestObserved) {
2420 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2421 QuicPacketSequenceNumber largest_observed;
2422 QuicByteCount packet_size;
2423 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2424 .WillOnce(DoAll(SaveArg<2>(&largest_observed), SaveArg<3>(&packet_size),
2425 Return(true)));
2426 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
2428 QuicAckFrame frame = InitAckFrame(1);
2429 NackPacket(largest_observed, &frame);
2430 // The first nack should retransmit the largest observed packet.
2431 SequenceNumberSet lost_packets;
2432 lost_packets.insert(1);
2433 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2434 .WillOnce(Return(lost_packets));
2435 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2436 EXPECT_CALL(*send_algorithm_,
2437 OnPacketSent(_, _, _, packet_size - kQuicVersionSize, _));
2438 ProcessAckPacket(&frame);
2441 TEST_P(QuicConnectionTest, QueueAfterTwoRTOs) {
2442 for (int i = 0; i < 10; ++i) {
2443 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2444 connection_.SendStreamDataWithString(3, "foo", i * 3, !kFin, nullptr);
2447 // Block the writer and ensure they're queued.
2448 BlockOnNextWrite();
2449 clock_.AdvanceTime(DefaultRetransmissionTime());
2450 // Only one packet should be retransmitted.
2451 connection_.GetRetransmissionAlarm()->Fire();
2452 EXPECT_TRUE(connection_.HasQueuedData());
2454 // Unblock the writer.
2455 writer_->SetWritable();
2456 clock_.AdvanceTime(QuicTime::Delta::FromMicroseconds(
2457 2 * DefaultRetransmissionTime().ToMicroseconds()));
2458 // Retransmit already retransmitted packets event though the sequence number
2459 // greater than the largest observed.
2460 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
2461 connection_.GetRetransmissionAlarm()->Fire();
2462 connection_.OnCanWrite();
2465 TEST_P(QuicConnectionTest, WriteBlockedThenSent) {
2466 BlockOnNextWrite();
2467 writer_->set_is_write_blocked_data_buffered(true);
2468 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2469 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
2470 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2472 writer_->SetWritable();
2473 connection_.OnCanWrite();
2474 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2477 TEST_P(QuicConnectionTest, RetransmitWriteBlockedAckedOriginalThenSent) {
2478 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2479 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
2480 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2482 BlockOnNextWrite();
2483 writer_->set_is_write_blocked_data_buffered(true);
2484 // Simulate the retransmission alarm firing.
2485 clock_.AdvanceTime(DefaultRetransmissionTime());
2486 connection_.GetRetransmissionAlarm()->Fire();
2488 // Ack the sent packet before the callback returns, which happens in
2489 // rare circumstances with write blocked sockets.
2490 QuicAckFrame ack = InitAckFrame(1);
2491 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2492 ProcessAckPacket(&ack);
2494 writer_->SetWritable();
2495 connection_.OnCanWrite();
2496 // There is now a pending packet, but with no retransmittable frames.
2497 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2498 EXPECT_FALSE(connection_.sent_packet_manager().HasRetransmittableFrames(2));
2501 TEST_P(QuicConnectionTest, AlarmsWhenWriteBlocked) {
2502 // Block the connection.
2503 BlockOnNextWrite();
2504 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
2505 EXPECT_EQ(1u, writer_->packets_write_attempts());
2506 EXPECT_TRUE(writer_->IsWriteBlocked());
2508 // Set the send and resumption alarms. Fire the alarms and ensure they don't
2509 // attempt to write.
2510 connection_.GetResumeWritesAlarm()->Set(clock_.ApproximateNow());
2511 connection_.GetSendAlarm()->Set(clock_.ApproximateNow());
2512 connection_.GetResumeWritesAlarm()->Fire();
2513 connection_.GetSendAlarm()->Fire();
2514 EXPECT_TRUE(writer_->IsWriteBlocked());
2515 EXPECT_EQ(1u, writer_->packets_write_attempts());
2518 TEST_P(QuicConnectionTest, NoLimitPacketsPerNack) {
2519 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2520 int offset = 0;
2521 // Send packets 1 to 15.
2522 for (int i = 0; i < 15; ++i) {
2523 SendStreamDataToPeer(1, "foo", offset, !kFin, nullptr);
2524 offset += 3;
2527 // Ack 15, nack 1-14.
2528 SequenceNumberSet lost_packets;
2529 QuicAckFrame nack = InitAckFrame(15);
2530 for (int i = 1; i < 15; ++i) {
2531 NackPacket(i, &nack);
2532 lost_packets.insert(i);
2535 // 14 packets have been NACK'd and lost. In TCP cubic, PRR limits
2536 // the retransmission rate in the case of burst losses.
2537 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2538 .WillOnce(Return(lost_packets));
2539 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2540 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(14);
2541 ProcessAckPacket(&nack);
2544 // Test sending multiple acks from the connection to the session.
2545 TEST_P(QuicConnectionTest, MultipleAcks) {
2546 QuicPacketSequenceNumber last_packet;
2547 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet); // Packet 1
2548 EXPECT_EQ(1u, last_packet);
2549 SendStreamDataToPeer(3, "foo", 0, !kFin, &last_packet); // Packet 2
2550 EXPECT_EQ(2u, last_packet);
2551 SendAckPacketToPeer(); // Packet 3
2552 SendStreamDataToPeer(5, "foo", 0, !kFin, &last_packet); // Packet 4
2553 EXPECT_EQ(4u, last_packet);
2554 SendStreamDataToPeer(1, "foo", 3, !kFin, &last_packet); // Packet 5
2555 EXPECT_EQ(5u, last_packet);
2556 SendStreamDataToPeer(3, "foo", 3, !kFin, &last_packet); // Packet 6
2557 EXPECT_EQ(6u, last_packet);
2559 // Client will ack packets 1, 2, [!3], 4, 5.
2560 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2561 QuicAckFrame frame1 = InitAckFrame(5);
2562 NackPacket(3, &frame1);
2563 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2564 ProcessAckPacket(&frame1);
2566 // Now the client implicitly acks 3, and explicitly acks 6.
2567 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2568 QuicAckFrame frame2 = InitAckFrame(6);
2569 ProcessAckPacket(&frame2);
2572 TEST_P(QuicConnectionTest, DontLatchUnackedPacket) {
2573 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr); // Packet 1;
2574 // From now on, we send acks, so the send algorithm won't mark them pending.
2575 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2576 .WillByDefault(Return(false));
2577 SendAckPacketToPeer(); // Packet 2
2579 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2580 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2581 QuicAckFrame frame = InitAckFrame(1);
2582 ProcessAckPacket(&frame);
2584 // Verify that our internal state has least-unacked as 2, because we're still
2585 // waiting for a potential ack for 2.
2587 EXPECT_EQ(2u, stop_waiting()->least_unacked);
2589 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2590 frame = InitAckFrame(2);
2591 ProcessAckPacket(&frame);
2592 EXPECT_EQ(3u, stop_waiting()->least_unacked);
2594 // When we send an ack, we make sure our least-unacked makes sense. In this
2595 // case since we're not waiting on an ack for 2 and all packets are acked, we
2596 // set it to 3.
2597 SendAckPacketToPeer(); // Packet 3
2598 // Least_unacked remains at 3 until another ack is received.
2599 EXPECT_EQ(3u, stop_waiting()->least_unacked);
2600 // Check that the outgoing ack had its sequence number as least_unacked.
2601 EXPECT_EQ(3u, least_unacked());
2603 // Ack the ack, which updates the rtt and raises the least unacked.
2604 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2605 frame = InitAckFrame(3);
2606 ProcessAckPacket(&frame);
2608 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2609 .WillByDefault(Return(true));
2610 SendStreamDataToPeer(1, "bar", 3, false, nullptr); // Packet 4
2611 EXPECT_EQ(4u, stop_waiting()->least_unacked);
2612 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2613 .WillByDefault(Return(false));
2614 SendAckPacketToPeer(); // Packet 5
2615 EXPECT_EQ(4u, least_unacked());
2617 // Send two data packets at the end, and ensure if the last one is acked,
2618 // the least unacked is raised above the ack packets.
2619 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2620 .WillByDefault(Return(true));
2621 SendStreamDataToPeer(1, "bar", 6, false, nullptr); // Packet 6
2622 SendStreamDataToPeer(1, "bar", 9, false, nullptr); // Packet 7
2624 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2625 frame = InitAckFrame(7);
2626 NackPacket(5, &frame);
2627 NackPacket(6, &frame);
2628 ProcessAckPacket(&frame);
2630 EXPECT_EQ(6u, stop_waiting()->least_unacked);
2633 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterFecPacket) {
2634 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2636 // Don't send missing packet 1.
2637 ProcessFecPacket(2, 1, true, !kEntropyFlag, nullptr);
2638 // Entropy flag should be false, so entropy should be 0.
2639 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2642 TEST_P(QuicConnectionTest, ReviveMissingPacketWithVaryingSeqNumLengths) {
2643 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2645 // Set up a debug visitor to the connection.
2646 scoped_ptr<FecQuicConnectionDebugVisitor> fec_visitor(
2647 new FecQuicConnectionDebugVisitor());
2648 connection_.set_debug_visitor(fec_visitor.get());
2650 QuicPacketSequenceNumber fec_packet = 0;
2651 QuicSequenceNumberLength lengths[] = {PACKET_6BYTE_SEQUENCE_NUMBER,
2652 PACKET_4BYTE_SEQUENCE_NUMBER,
2653 PACKET_2BYTE_SEQUENCE_NUMBER,
2654 PACKET_1BYTE_SEQUENCE_NUMBER};
2655 // For each sequence number length size, revive a packet and check sequence
2656 // number length in the revived packet.
2657 for (size_t i = 0; i < arraysize(lengths); ++i) {
2658 // Set sequence_number_length_ (for data and FEC packets).
2659 sequence_number_length_ = lengths[i];
2660 fec_packet += 2;
2661 // Don't send missing packet, but send fec packet right after it.
2662 ProcessFecPacket(fec_packet, fec_packet - 1, true, !kEntropyFlag, nullptr);
2663 // Sequence number length in the revived header should be the same as
2664 // in the original data/fec packet headers.
2665 EXPECT_EQ(sequence_number_length_, fec_visitor->revived_header().
2666 public_header.sequence_number_length);
2670 TEST_P(QuicConnectionTest, ReviveMissingPacketWithVaryingConnectionIdLengths) {
2671 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2673 // Set up a debug visitor to the connection.
2674 scoped_ptr<FecQuicConnectionDebugVisitor> fec_visitor(
2675 new FecQuicConnectionDebugVisitor());
2676 connection_.set_debug_visitor(fec_visitor.get());
2678 QuicPacketSequenceNumber fec_packet = 0;
2679 QuicConnectionIdLength lengths[] = {PACKET_8BYTE_CONNECTION_ID,
2680 PACKET_4BYTE_CONNECTION_ID,
2681 PACKET_1BYTE_CONNECTION_ID,
2682 PACKET_0BYTE_CONNECTION_ID};
2683 // For each connection id length size, revive a packet and check connection
2684 // id length in the revived packet.
2685 for (size_t i = 0; i < arraysize(lengths); ++i) {
2686 // Set connection id length (for data and FEC packets).
2687 connection_id_length_ = lengths[i];
2688 fec_packet += 2;
2689 // Don't send missing packet, but send fec packet right after it.
2690 ProcessFecPacket(fec_packet, fec_packet - 1, true, !kEntropyFlag, nullptr);
2691 // Connection id length in the revived header should be the same as
2692 // in the original data/fec packet headers.
2693 EXPECT_EQ(connection_id_length_,
2694 fec_visitor->revived_header().public_header.connection_id_length);
2698 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPacketThenFecPacket) {
2699 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2701 ProcessFecProtectedPacket(1, false, kEntropyFlag);
2702 // Don't send missing packet 2.
2703 ProcessFecPacket(3, 1, true, !kEntropyFlag, nullptr);
2704 // Entropy flag should be true, so entropy should not be 0.
2705 EXPECT_NE(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2708 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPacketsThenFecPacket) {
2709 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2711 ProcessFecProtectedPacket(1, false, !kEntropyFlag);
2712 // Don't send missing packet 2.
2713 ProcessFecProtectedPacket(3, false, !kEntropyFlag);
2714 ProcessFecPacket(4, 1, true, kEntropyFlag, nullptr);
2715 // Ensure QUIC no longer revives entropy for lost packets.
2716 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2717 EXPECT_NE(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 4));
2720 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPacket) {
2721 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2723 // Don't send missing packet 1.
2724 ProcessFecPacket(3, 1, false, !kEntropyFlag, nullptr);
2725 // Out of order.
2726 ProcessFecProtectedPacket(2, true, !kEntropyFlag);
2727 // Entropy flag should be false, so entropy should be 0.
2728 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2731 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPackets) {
2732 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2734 ProcessFecProtectedPacket(1, false, !kEntropyFlag);
2735 // Don't send missing packet 2.
2736 ProcessFecPacket(6, 1, false, kEntropyFlag, nullptr);
2737 ProcessFecProtectedPacket(3, false, kEntropyFlag);
2738 ProcessFecProtectedPacket(4, false, kEntropyFlag);
2739 ProcessFecProtectedPacket(5, true, !kEntropyFlag);
2740 // Ensure entropy is not revived for the missing packet.
2741 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2742 EXPECT_NE(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 3));
2745 TEST_P(QuicConnectionTest, TLP) {
2746 QuicSentPacketManagerPeer::SetMaxTailLossProbes(manager_, 1);
2748 SendStreamDataToPeer(3, "foo", 0, !kFin, nullptr);
2749 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2750 QuicTime retransmission_time =
2751 connection_.GetRetransmissionAlarm()->deadline();
2752 EXPECT_NE(QuicTime::Zero(), retransmission_time);
2754 EXPECT_EQ(1u, writer_->header().packet_sequence_number);
2755 // Simulate the retransmission alarm firing and sending a tlp,
2756 // so send algorithm's OnRetransmissionTimeout is not called.
2757 clock_.AdvanceTime(retransmission_time.Subtract(clock_.Now()));
2758 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 2u, _, _));
2759 connection_.GetRetransmissionAlarm()->Fire();
2760 EXPECT_EQ(2u, writer_->header().packet_sequence_number);
2761 // We do not raise the high water mark yet.
2762 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2765 TEST_P(QuicConnectionTest, RTO) {
2766 QuicTime default_retransmission_time = clock_.ApproximateNow().Add(
2767 DefaultRetransmissionTime());
2768 SendStreamDataToPeer(3, "foo", 0, !kFin, nullptr);
2769 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2771 EXPECT_EQ(1u, writer_->header().packet_sequence_number);
2772 EXPECT_EQ(default_retransmission_time,
2773 connection_.GetRetransmissionAlarm()->deadline());
2774 // Simulate the retransmission alarm firing.
2775 clock_.AdvanceTime(DefaultRetransmissionTime());
2776 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 2u, _, _));
2777 connection_.GetRetransmissionAlarm()->Fire();
2778 EXPECT_EQ(2u, writer_->header().packet_sequence_number);
2779 // We do not raise the high water mark yet.
2780 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2783 TEST_P(QuicConnectionTest, RTOWithSameEncryptionLevel) {
2784 QuicTime default_retransmission_time = clock_.ApproximateNow().Add(
2785 DefaultRetransmissionTime());
2786 use_tagging_decrypter();
2788 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
2789 // the end of the packet. We can test this to check which encrypter was used.
2790 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2791 SendStreamDataToPeer(3, "foo", 0, !kFin, nullptr);
2792 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
2794 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2795 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2796 SendStreamDataToPeer(3, "foo", 0, !kFin, nullptr);
2797 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2799 EXPECT_EQ(default_retransmission_time,
2800 connection_.GetRetransmissionAlarm()->deadline());
2802 InSequence s;
2803 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 3, _, _));
2804 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 4, _, _));
2807 // Simulate the retransmission alarm firing.
2808 clock_.AdvanceTime(DefaultRetransmissionTime());
2809 connection_.GetRetransmissionAlarm()->Fire();
2811 // Packet should have been sent with ENCRYPTION_NONE.
2812 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_previous_packet());
2814 // Packet should have been sent with ENCRYPTION_INITIAL.
2815 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2818 TEST_P(QuicConnectionTest, SendHandshakeMessages) {
2819 use_tagging_decrypter();
2820 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
2821 // the end of the packet. We can test this to check which encrypter was used.
2822 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2824 // Attempt to send a handshake message and have the socket block.
2825 EXPECT_CALL(*send_algorithm_,
2826 TimeUntilSend(_, _, _)).WillRepeatedly(
2827 testing::Return(QuicTime::Delta::Zero()));
2828 BlockOnNextWrite();
2829 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
2830 // The packet should be serialized, but not queued.
2831 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2833 // Switch to the new encrypter.
2834 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2835 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2837 // Now become writeable and flush the packets.
2838 writer_->SetWritable();
2839 EXPECT_CALL(visitor_, OnCanWrite());
2840 connection_.OnCanWrite();
2841 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2843 // Verify that the handshake packet went out at the null encryption.
2844 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
2847 TEST_P(QuicConnectionTest,
2848 DropRetransmitsForNullEncryptedPacketAfterForwardSecure) {
2849 use_tagging_decrypter();
2850 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2851 QuicPacketSequenceNumber sequence_number;
2852 SendStreamDataToPeer(3, "foo", 0, !kFin, &sequence_number);
2854 // Simulate the retransmission alarm firing and the socket blocking.
2855 BlockOnNextWrite();
2856 clock_.AdvanceTime(DefaultRetransmissionTime());
2857 connection_.GetRetransmissionAlarm()->Fire();
2859 // Go forward secure.
2860 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
2861 new TaggingEncrypter(0x02));
2862 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2863 connection_.NeuterUnencryptedPackets();
2865 EXPECT_EQ(QuicTime::Zero(),
2866 connection_.GetRetransmissionAlarm()->deadline());
2867 // Unblock the socket and ensure that no packets are sent.
2868 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
2869 writer_->SetWritable();
2870 connection_.OnCanWrite();
2873 TEST_P(QuicConnectionTest, RetransmitPacketsWithInitialEncryption) {
2874 use_tagging_decrypter();
2875 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2876 connection_.SetDefaultEncryptionLevel(ENCRYPTION_NONE);
2878 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr);
2880 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2881 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2883 SendStreamDataToPeer(2, "bar", 0, !kFin, nullptr);
2884 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2886 connection_.RetransmitUnackedPackets(ALL_INITIAL_RETRANSMISSION);
2889 TEST_P(QuicConnectionTest, DelayForwardSecureEncryptionUntilClientIsReady) {
2890 // A TaggingEncrypter puts kTagSize copies of the given byte (0x02 here) at
2891 // the end of the packet. We can test this to check which encrypter was used.
2892 use_tagging_decrypter();
2893 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2894 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2895 SendAckPacketToPeer();
2896 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2898 // Set a forward-secure encrypter but do not make it the default, and verify
2899 // that it is not yet used.
2900 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
2901 new TaggingEncrypter(0x03));
2902 SendAckPacketToPeer();
2903 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2905 // Now simulate receipt of a forward-secure packet and verify that the
2906 // forward-secure encrypter is now used.
2907 connection_.OnDecryptedPacket(ENCRYPTION_FORWARD_SECURE);
2908 SendAckPacketToPeer();
2909 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
2912 TEST_P(QuicConnectionTest, DelayForwardSecureEncryptionUntilManyPacketSent) {
2913 // Set a congestion window of 10 packets.
2914 QuicPacketCount congestion_window = 10;
2915 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
2916 Return(congestion_window * kDefaultMaxPacketSize));
2918 // A TaggingEncrypter puts kTagSize copies of the given byte (0x02 here) at
2919 // the end of the packet. We can test this to check which encrypter was used.
2920 use_tagging_decrypter();
2921 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2922 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2923 SendAckPacketToPeer();
2924 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2926 // Set a forward-secure encrypter but do not make it the default, and
2927 // verify that it is not yet used.
2928 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
2929 new TaggingEncrypter(0x03));
2930 SendAckPacketToPeer();
2931 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2933 // Now send a packet "Far enough" after the encrypter was set and verify that
2934 // the forward-secure encrypter is now used.
2935 for (uint64 i = 0; i < 3 * congestion_window - 1; ++i) {
2936 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2937 SendAckPacketToPeer();
2939 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
2942 TEST_P(QuicConnectionTest, BufferNonDecryptablePackets) {
2943 // SetFromConfig is always called after construction from InitializeSession.
2944 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
2945 QuicConfig config;
2946 connection_.SetFromConfig(config);
2947 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2948 use_tagging_decrypter();
2950 const uint8 tag = 0x07;
2951 framer_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
2953 // Process an encrypted packet which can not yet be decrypted which should
2954 // result in the packet being buffered.
2955 ProcessDataPacketAtLevel(1, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2957 // Transition to the new encryption state and process another encrypted packet
2958 // which should result in the original packet being processed.
2959 connection_.SetDecrypter(ENCRYPTION_INITIAL, new StrictTaggingDecrypter(tag));
2960 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2961 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
2962 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(2);
2963 ProcessDataPacketAtLevel(2, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2965 // Finally, process a third packet and note that we do not reprocess the
2966 // buffered packet.
2967 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2968 ProcessDataPacketAtLevel(3, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2971 TEST_P(QuicConnectionTest, Buffer100NonDecryptablePackets) {
2972 // SetFromConfig is always called after construction from InitializeSession.
2973 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
2974 QuicConfig config;
2975 config.set_max_undecryptable_packets(100);
2976 connection_.SetFromConfig(config);
2977 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2978 use_tagging_decrypter();
2980 const uint8 tag = 0x07;
2981 framer_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
2983 // Process an encrypted packet which can not yet be decrypted which should
2984 // result in the packet being buffered.
2985 for (QuicPacketSequenceNumber i = 1; i <= 100; ++i) {
2986 ProcessDataPacketAtLevel(i, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2989 // Transition to the new encryption state and process another encrypted packet
2990 // which should result in the original packets being processed.
2991 connection_.SetDecrypter(ENCRYPTION_INITIAL, new StrictTaggingDecrypter(tag));
2992 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2993 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
2994 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(101);
2995 ProcessDataPacketAtLevel(101, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2997 // Finally, process a third packet and note that we do not reprocess the
2998 // buffered packet.
2999 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3000 ProcessDataPacketAtLevel(102, 0, kEntropyFlag, ENCRYPTION_INITIAL);
3003 TEST_P(QuicConnectionTest, TestRetransmitOrder) {
3004 QuicByteCount first_packet_size;
3005 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).WillOnce(
3006 DoAll(SaveArg<3>(&first_packet_size), Return(true)));
3008 connection_.SendStreamDataWithString(3, "first_packet", 0, !kFin, nullptr);
3009 QuicByteCount second_packet_size;
3010 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).WillOnce(
3011 DoAll(SaveArg<3>(&second_packet_size), Return(true)));
3012 connection_.SendStreamDataWithString(3, "second_packet", 12, !kFin, nullptr);
3013 EXPECT_NE(first_packet_size, second_packet_size);
3014 // Advance the clock by huge time to make sure packets will be retransmitted.
3015 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
3017 InSequence s;
3018 EXPECT_CALL(*send_algorithm_,
3019 OnPacketSent(_, _, _, first_packet_size, _));
3020 EXPECT_CALL(*send_algorithm_,
3021 OnPacketSent(_, _, _, second_packet_size, _));
3023 connection_.GetRetransmissionAlarm()->Fire();
3025 // Advance again and expect the packets to be sent again in the same order.
3026 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(20));
3028 InSequence s;
3029 EXPECT_CALL(*send_algorithm_,
3030 OnPacketSent(_, _, _, first_packet_size, _));
3031 EXPECT_CALL(*send_algorithm_,
3032 OnPacketSent(_, _, _, second_packet_size, _));
3034 connection_.GetRetransmissionAlarm()->Fire();
3037 TEST_P(QuicConnectionTest, SetRTOAfterWritingToSocket) {
3038 BlockOnNextWrite();
3039 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
3040 // Make sure that RTO is not started when the packet is queued.
3041 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3043 // Test that RTO is started once we write to the socket.
3044 writer_->SetWritable();
3045 connection_.OnCanWrite();
3046 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3049 TEST_P(QuicConnectionTest, DelayRTOWithAckReceipt) {
3050 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3051 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3052 .Times(2);
3053 connection_.SendStreamDataWithString(2, "foo", 0, !kFin, nullptr);
3054 connection_.SendStreamDataWithString(3, "bar", 0, !kFin, nullptr);
3055 QuicAlarm* retransmission_alarm = connection_.GetRetransmissionAlarm();
3056 EXPECT_TRUE(retransmission_alarm->IsSet());
3057 EXPECT_EQ(clock_.Now().Add(DefaultRetransmissionTime()),
3058 retransmission_alarm->deadline());
3060 // Advance the time right before the RTO, then receive an ack for the first
3061 // packet to delay the RTO.
3062 clock_.AdvanceTime(DefaultRetransmissionTime());
3063 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3064 QuicAckFrame ack = InitAckFrame(1);
3065 ProcessAckPacket(&ack);
3066 EXPECT_TRUE(retransmission_alarm->IsSet());
3067 EXPECT_GT(retransmission_alarm->deadline(), clock_.Now());
3069 // Move forward past the original RTO and ensure the RTO is still pending.
3070 clock_.AdvanceTime(DefaultRetransmissionTime().Multiply(2));
3072 // Ensure the second packet gets retransmitted when it finally fires.
3073 EXPECT_TRUE(retransmission_alarm->IsSet());
3074 EXPECT_LT(retransmission_alarm->deadline(), clock_.ApproximateNow());
3075 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3076 // Manually cancel the alarm to simulate a real test.
3077 connection_.GetRetransmissionAlarm()->Fire();
3079 // The new retransmitted sequence number should set the RTO to a larger value
3080 // than previously.
3081 EXPECT_TRUE(retransmission_alarm->IsSet());
3082 QuicTime next_rto_time = retransmission_alarm->deadline();
3083 QuicTime expected_rto_time =
3084 connection_.sent_packet_manager().GetRetransmissionTime();
3085 EXPECT_EQ(next_rto_time, expected_rto_time);
3088 TEST_P(QuicConnectionTest, TestQueued) {
3089 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3090 BlockOnNextWrite();
3091 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
3092 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3094 // Unblock the writes and actually send.
3095 writer_->SetWritable();
3096 connection_.OnCanWrite();
3097 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3100 TEST_P(QuicConnectionTest, CloseFecGroup) {
3101 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3102 // Don't send missing packet 1.
3103 // Don't send missing packet 2.
3104 ProcessFecProtectedPacket(3, false, !kEntropyFlag);
3105 // Don't send missing FEC packet 3.
3106 ASSERT_EQ(1u, connection_.NumFecGroups());
3108 // Now send non-fec protected ack packet and close the group.
3109 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 4);
3110 QuicStopWaitingFrame frame = InitStopWaitingFrame(5);
3111 ProcessStopWaitingPacket(&frame);
3112 ASSERT_EQ(0u, connection_.NumFecGroups());
3115 TEST_P(QuicConnectionTest, InitialTimeout) {
3116 EXPECT_TRUE(connection_.connected());
3117 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
3118 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3120 // SetFromConfig sets the initial timeouts before negotiation.
3121 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3122 QuicConfig config;
3123 connection_.SetFromConfig(config);
3124 // Subtract a second from the idle timeout on the client side.
3125 QuicTime default_timeout = clock_.ApproximateNow().Add(
3126 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1));
3127 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
3129 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_CONNECTION_TIMED_OUT, false));
3130 // Simulate the timeout alarm firing.
3131 clock_.AdvanceTime(
3132 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1));
3133 connection_.GetTimeoutAlarm()->Fire();
3135 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3136 EXPECT_FALSE(connection_.connected());
3138 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3139 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
3140 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
3141 EXPECT_FALSE(connection_.GetResumeWritesAlarm()->IsSet());
3142 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3143 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
3144 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
3147 TEST_P(QuicConnectionTest, OverallTimeout) {
3148 // Use a shorter overall connection timeout than idle timeout for this test.
3149 const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(5);
3150 connection_.SetNetworkTimeouts(timeout, timeout);
3151 EXPECT_TRUE(connection_.connected());
3152 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
3154 QuicTime overall_timeout = clock_.ApproximateNow().Add(timeout).Subtract(
3155 QuicTime::Delta::FromSeconds(1));
3156 EXPECT_EQ(overall_timeout, connection_.GetTimeoutAlarm()->deadline());
3157 EXPECT_TRUE(connection_.connected());
3159 // Send and ack new data 3 seconds later to lengthen the idle timeout.
3160 SendStreamDataToPeer(1, "GET /", 0, kFin, nullptr);
3161 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(3));
3162 QuicAckFrame frame = InitAckFrame(1);
3163 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3164 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3165 ProcessAckPacket(&frame);
3167 // Fire early to verify it wouldn't timeout yet.
3168 connection_.GetTimeoutAlarm()->Fire();
3169 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
3170 EXPECT_TRUE(connection_.connected());
3172 clock_.AdvanceTime(timeout.Subtract(QuicTime::Delta::FromSeconds(2)));
3174 EXPECT_CALL(visitor_,
3175 OnConnectionClosed(QUIC_CONNECTION_OVERALL_TIMED_OUT, false));
3176 // Simulate the timeout alarm firing.
3177 connection_.GetTimeoutAlarm()->Fire();
3179 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3180 EXPECT_FALSE(connection_.connected());
3182 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3183 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
3184 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
3185 EXPECT_FALSE(connection_.GetResumeWritesAlarm()->IsSet());
3186 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3187 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
3190 TEST_P(QuicConnectionTest, PingAfterSend) {
3191 EXPECT_TRUE(connection_.connected());
3192 EXPECT_CALL(visitor_, HasOpenDynamicStreams()).WillRepeatedly(Return(true));
3193 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
3195 // Advance to 5ms, and send a packet to the peer, which will set
3196 // the ping alarm.
3197 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
3198 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3199 SendStreamDataToPeer(1, "GET /", 0, kFin, nullptr);
3200 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
3201 EXPECT_EQ(clock_.ApproximateNow().Add(QuicTime::Delta::FromSeconds(15)),
3202 connection_.GetPingAlarm()->deadline());
3204 // Now recevie and ACK of the previous packet, which will move the
3205 // ping alarm forward.
3206 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
3207 QuicAckFrame frame = InitAckFrame(1);
3208 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3209 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3210 ProcessAckPacket(&frame);
3211 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
3212 // The ping timer is set slightly less than 15 seconds in the future, because
3213 // of the 1s ping timer alarm granularity.
3214 EXPECT_EQ(clock_.ApproximateNow().Add(QuicTime::Delta::FromSeconds(15))
3215 .Subtract(QuicTime::Delta::FromMilliseconds(5)),
3216 connection_.GetPingAlarm()->deadline());
3218 writer_->Reset();
3219 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15));
3220 connection_.GetPingAlarm()->Fire();
3221 EXPECT_EQ(1u, writer_->frame_count());
3222 ASSERT_EQ(1u, writer_->ping_frames().size());
3223 writer_->Reset();
3225 EXPECT_CALL(visitor_, HasOpenDynamicStreams()).WillRepeatedly(Return(false));
3226 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
3227 SendAckPacketToPeer();
3229 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
3232 // Tests whether sending an MTU discovery packet to peer successfully causes the
3233 // maximum packet size to increase.
3234 TEST_P(QuicConnectionTest, SendMtuDiscoveryPacket) {
3235 EXPECT_TRUE(connection_.connected());
3237 // Send an MTU probe.
3238 const size_t new_mtu = kDefaultMaxPacketSize + 100;
3239 QuicByteCount mtu_probe_size;
3240 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3241 .WillOnce(DoAll(SaveArg<3>(&mtu_probe_size), Return(true)));
3242 connection_.SendMtuDiscoveryPacket(new_mtu);
3243 EXPECT_EQ(new_mtu, mtu_probe_size);
3244 EXPECT_EQ(1u, creator_->sequence_number());
3246 // Send more than MTU worth of data. No acknowledgement was received so far,
3247 // so the MTU should be at its old value.
3248 const string data(kDefaultMaxPacketSize + 1, '.');
3249 QuicByteCount size_before_mtu_change;
3250 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3251 .WillOnce(DoAll(SaveArg<3>(&size_before_mtu_change), Return(true)))
3252 .WillOnce(Return(true));
3253 connection_.SendStreamDataWithString(3, data, 0, kFin, nullptr);
3254 EXPECT_EQ(3u, creator_->sequence_number());
3255 EXPECT_EQ(kDefaultMaxPacketSize, size_before_mtu_change);
3257 // Acknowledge all packets so far.
3258 QuicAckFrame probe_ack = InitAckFrame(3);
3259 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3260 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3261 ProcessAckPacket(&probe_ack);
3262 EXPECT_EQ(new_mtu, connection_.max_packet_length());
3264 // Send the same data again. Check that it fits into a single packet now.
3265 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3266 connection_.SendStreamDataWithString(3, data, 0, kFin, nullptr);
3267 EXPECT_EQ(4u, creator_->sequence_number());
3270 // Tests whether MTU discovery does not happen when it is not explicitly enabled
3271 // by the connection options.
3272 TEST_P(QuicConnectionTest, MtuDiscoveryDisabled) {
3273 EXPECT_TRUE(connection_.connected());
3275 // Restore the current value FLAGS_quic_do_path_mtu_discovery after the test.
3276 ValueRestore<bool> old_flag(&FLAGS_quic_do_path_mtu_discovery, true);
3278 const QuicPacketCount number_of_packets = kPacketsBetweenMtuProbesBase * 2;
3279 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
3280 SendStreamDataToPeer(3, ".", i, /*fin=*/false, nullptr);
3281 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
3282 EXPECT_EQ(0u, connection_.mtu_probe_count());
3286 // Tests whether MTU discovery works when the probe gets acknowledged on the
3287 // first try.
3288 TEST_P(QuicConnectionTest, MtuDiscoveryEnabled) {
3289 EXPECT_TRUE(connection_.connected());
3291 // Restore the current value FLAGS_quic_do_path_mtu_discovery after the test.
3292 ValueRestore<bool> old_flag(&FLAGS_quic_do_path_mtu_discovery, true);
3293 connection_.EnablePathMtuDiscovery(send_algorithm_);
3295 // Send enough packets so that the next one triggers path MTU discovery.
3296 for (QuicPacketCount i = 0; i < kPacketsBetweenMtuProbesBase - 1; i++) {
3297 SendStreamDataToPeer(3, ".", i, /*fin=*/false, nullptr);
3298 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
3301 // Trigger the probe.
3302 SendStreamDataToPeer(3, "!", kPacketsBetweenMtuProbesBase,
3303 /*fin=*/false, nullptr);
3304 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
3305 QuicByteCount probe_size;
3306 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3307 .WillOnce(DoAll(SaveArg<3>(&probe_size), Return(true)));
3308 connection_.GetMtuDiscoveryAlarm()->Fire();
3309 EXPECT_EQ(kMtuDiscoveryTargetPacketSizeHigh, probe_size);
3311 const QuicPacketCount probe_sequence_number =
3312 kPacketsBetweenMtuProbesBase + 1;
3313 ASSERT_EQ(probe_sequence_number, creator_->sequence_number());
3315 // Acknowledge all packets sent so far.
3316 QuicAckFrame probe_ack = InitAckFrame(probe_sequence_number);
3317 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3318 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3319 ProcessAckPacket(&probe_ack);
3320 EXPECT_EQ(kMtuDiscoveryTargetPacketSizeHigh, connection_.max_packet_length());
3321 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
3323 // Send more packets, and ensure that none of them sets the alarm.
3324 for (QuicPacketCount i = 0; i < 4 * kPacketsBetweenMtuProbesBase; i++) {
3325 SendStreamDataToPeer(3, ".", i, /*fin=*/false, nullptr);
3326 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
3329 EXPECT_EQ(1u, connection_.mtu_probe_count());
3332 // Tests whether MTU discovery works correctly when the probes never get
3333 // acknowledged.
3334 TEST_P(QuicConnectionTest, MtuDiscoveryFailed) {
3335 EXPECT_TRUE(connection_.connected());
3337 // Restore the current value FLAGS_quic_do_path_mtu_discovery after the test.
3338 ValueRestore<bool> old_flag(&FLAGS_quic_do_path_mtu_discovery, true);
3339 connection_.EnablePathMtuDiscovery(send_algorithm_);
3341 const QuicTime::Delta rtt = QuicTime::Delta::FromMilliseconds(100);
3343 EXPECT_EQ(kPacketsBetweenMtuProbesBase,
3344 QuicConnectionPeer::GetPacketsBetweenMtuProbes(&connection_));
3345 // Lower the number of probes between packets in order to make the test go
3346 // much faster.
3347 const QuicPacketCount packets_between_probes_base = 10;
3348 QuicConnectionPeer::SetPacketsBetweenMtuProbes(&connection_,
3349 packets_between_probes_base);
3350 QuicConnectionPeer::SetNextMtuProbeAt(&connection_,
3351 packets_between_probes_base);
3353 // This tests sends more packets than strictly necessary to make sure that if
3354 // the connection was to send more discovery packets than needed, those would
3355 // get caught as well.
3356 const QuicPacketCount number_of_packets =
3357 packets_between_probes_base * (1 << (kMtuDiscoveryAttempts + 1));
3358 vector<QuicPacketSequenceNumber> mtu_discovery_packets;
3359 // Called by the first ack.
3360 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3361 // Called on many acks.
3362 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _))
3363 .Times(AnyNumber());
3364 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
3365 SendStreamDataToPeer(3, "!", i, /*fin=*/false, nullptr);
3366 clock_.AdvanceTime(rtt);
3368 // Receive an ACK, which marks all data packets as received, and all MTU
3369 // discovery packets as missing.
3370 QuicAckFrame ack = InitAckFrame(creator_->sequence_number());
3371 for (QuicPacketSequenceNumber& packet : mtu_discovery_packets) {
3372 NackPacket(packet, &ack);
3374 ProcessAckPacket(&ack);
3376 // Trigger MTU probe if it would be scheduled now.
3377 if (!connection_.GetMtuDiscoveryAlarm()->IsSet()) {
3378 continue;
3381 // Fire the alarm. The alarm should cause a packet to be sent.
3382 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3383 .WillOnce(Return(true));
3384 connection_.GetMtuDiscoveryAlarm()->Fire();
3385 // Record the sequence number of the MTU discovery packet in order to
3386 // mark it as NACK'd.
3387 mtu_discovery_packets.push_back(creator_->sequence_number());
3390 // Ensure the number of packets between probes grows exponentially by checking
3391 // it against the closed-form expression for the sequence number.
3392 ASSERT_EQ(kMtuDiscoveryAttempts, mtu_discovery_packets.size());
3393 for (QuicPacketSequenceNumber i = 0; i < kMtuDiscoveryAttempts; i++) {
3394 // 2^0 + 2^1 + 2^2 + ... + 2^n = 2^(n + 1) - 1
3395 const QuicPacketCount packets_between_probes =
3396 packets_between_probes_base * ((1 << (i + 1)) - 1);
3397 EXPECT_EQ(packets_between_probes + (i + 1), mtu_discovery_packets[i]);
3400 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
3401 EXPECT_EQ(kDefaultMaxPacketSize, connection_.max_packet_length());
3402 EXPECT_EQ(kMtuDiscoveryAttempts, connection_.mtu_probe_count());
3405 TEST_P(QuicConnectionTest, NoMtuDiscoveryAfterConnectionClosed) {
3406 EXPECT_TRUE(connection_.connected());
3408 // Restore the current value FLAGS_quic_do_path_mtu_discovery after the test.
3409 ValueRestore<bool> old_flag(&FLAGS_quic_do_path_mtu_discovery, true);
3410 connection_.EnablePathMtuDiscovery(send_algorithm_);
3412 // Send enough packets so that the next one triggers path MTU discovery.
3413 for (QuicPacketCount i = 0; i < kPacketsBetweenMtuProbesBase - 1; i++) {
3414 SendStreamDataToPeer(3, ".", i, /*fin=*/false, nullptr);
3415 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
3418 SendStreamDataToPeer(3, "!", kPacketsBetweenMtuProbesBase,
3419 /*fin=*/false, nullptr);
3420 EXPECT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
3422 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
3423 connection_.CloseConnection(QUIC_INTERNAL_ERROR, /*from_peer=*/false);
3424 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
3427 TEST_P(QuicConnectionTest, TimeoutAfterSend) {
3428 EXPECT_TRUE(connection_.connected());
3429 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3430 QuicConfig config;
3431 connection_.SetFromConfig(config);
3432 EXPECT_FALSE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
3434 const QuicTime::Delta initial_idle_timeout =
3435 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
3436 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
3437 QuicTime default_timeout = clock_.ApproximateNow().Add(initial_idle_timeout);
3439 // When we send a packet, the timeout will change to 5ms +
3440 // kInitialIdleTimeoutSecs.
3441 clock_.AdvanceTime(five_ms);
3443 // Send an ack so we don't set the retransmission alarm.
3444 SendAckPacketToPeer();
3445 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
3447 // The original alarm will fire. We should not time out because we had a
3448 // network event at t=5ms. The alarm will reregister.
3449 clock_.AdvanceTime(initial_idle_timeout.Subtract(five_ms));
3450 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
3451 connection_.GetTimeoutAlarm()->Fire();
3452 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
3453 EXPECT_TRUE(connection_.connected());
3454 EXPECT_EQ(default_timeout.Add(five_ms),
3455 connection_.GetTimeoutAlarm()->deadline());
3457 // This time, we should time out.
3458 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_CONNECTION_TIMED_OUT, false));
3459 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3460 clock_.AdvanceTime(five_ms);
3461 EXPECT_EQ(default_timeout.Add(five_ms), clock_.ApproximateNow());
3462 connection_.GetTimeoutAlarm()->Fire();
3463 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3464 EXPECT_FALSE(connection_.connected());
3467 TEST_P(QuicConnectionTest, TimeoutAfterSendSilentClose) {
3468 // Same test as above, but complete a handshake which enables silent close,
3469 // causing no connection close packet to be sent.
3470 EXPECT_TRUE(connection_.connected());
3471 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3472 QuicConfig config;
3474 // Create a handshake message that also enables silent close.
3475 CryptoHandshakeMessage msg;
3476 string error_details;
3477 QuicConfig client_config;
3478 client_config.SetInitialStreamFlowControlWindowToSend(
3479 kInitialStreamFlowControlWindowForTest);
3480 client_config.SetInitialSessionFlowControlWindowToSend(
3481 kInitialSessionFlowControlWindowForTest);
3482 client_config.SetIdleConnectionStateLifetime(
3483 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs),
3484 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs));
3485 client_config.ToHandshakeMessage(&msg);
3486 const QuicErrorCode error =
3487 config.ProcessPeerHello(msg, CLIENT, &error_details);
3488 EXPECT_EQ(QUIC_NO_ERROR, error);
3490 connection_.SetFromConfig(config);
3491 EXPECT_TRUE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
3493 const QuicTime::Delta default_idle_timeout =
3494 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs - 1);
3495 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
3496 QuicTime default_timeout = clock_.ApproximateNow().Add(default_idle_timeout);
3498 // When we send a packet, the timeout will change to 5ms +
3499 // kInitialIdleTimeoutSecs.
3500 clock_.AdvanceTime(five_ms);
3502 // Send an ack so we don't set the retransmission alarm.
3503 SendAckPacketToPeer();
3504 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
3506 // The original alarm will fire. We should not time out because we had a
3507 // network event at t=5ms. The alarm will reregister.
3508 clock_.AdvanceTime(default_idle_timeout.Subtract(five_ms));
3509 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
3510 connection_.GetTimeoutAlarm()->Fire();
3511 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
3512 EXPECT_TRUE(connection_.connected());
3513 EXPECT_EQ(default_timeout.Add(five_ms),
3514 connection_.GetTimeoutAlarm()->deadline());
3516 // This time, we should time out.
3517 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_CONNECTION_TIMED_OUT, false));
3518 clock_.AdvanceTime(five_ms);
3519 EXPECT_EQ(default_timeout.Add(five_ms), clock_.ApproximateNow());
3520 connection_.GetTimeoutAlarm()->Fire();
3521 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3522 EXPECT_FALSE(connection_.connected());
3525 TEST_P(QuicConnectionTest, SendScheduler) {
3526 // Test that if we send a packet without delay, it is not queued.
3527 QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
3528 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3529 connection_.SendPacket(ENCRYPTION_NONE, 1, packet, kTestEntropyHash,
3530 HAS_RETRANSMITTABLE_DATA, false, false);
3531 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3534 TEST_P(QuicConnectionTest, SendSchedulerEAGAIN) {
3535 QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
3536 BlockOnNextWrite();
3537 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 1, _, _)).Times(0);
3538 connection_.SendPacket(ENCRYPTION_NONE, 1, packet, kTestEntropyHash,
3539 HAS_RETRANSMITTABLE_DATA, false, false);
3540 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3543 TEST_P(QuicConnectionTest, TestQueueLimitsOnSendStreamData) {
3544 // All packets carry version info till version is negotiated.
3545 size_t payload_length;
3546 size_t length = GetPacketLengthForOneStream(
3547 connection_.version(), kIncludeVersion,
3548 PACKET_8BYTE_CONNECTION_ID, PACKET_1BYTE_SEQUENCE_NUMBER,
3549 NOT_IN_FEC_GROUP, &payload_length);
3550 connection_.set_max_packet_length(length);
3552 // Queue the first packet.
3553 EXPECT_CALL(*send_algorithm_,
3554 TimeUntilSend(_, _, _)).WillOnce(
3555 testing::Return(QuicTime::Delta::FromMicroseconds(10)));
3556 const string payload(payload_length, 'a');
3557 EXPECT_EQ(0u, connection_.SendStreamDataWithString(3, payload, 0, !kFin,
3558 nullptr).bytes_consumed);
3559 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3562 TEST_P(QuicConnectionTest, LoopThroughSendingPackets) {
3563 // All packets carry version info till version is negotiated.
3564 size_t payload_length;
3565 // GetPacketLengthForOneStream() assumes a stream offset of 0 in determining
3566 // packet length. The size of the offset field in a stream frame is 0 for
3567 // offset 0, and 2 for non-zero offsets up through 16K. Increase
3568 // max_packet_length by 2 so that subsequent packets containing subsequent
3569 // stream frames with non-zero offets will fit within the packet length.
3570 size_t length = 2 + GetPacketLengthForOneStream(
3571 connection_.version(), kIncludeVersion,
3572 PACKET_8BYTE_CONNECTION_ID, PACKET_1BYTE_SEQUENCE_NUMBER,
3573 NOT_IN_FEC_GROUP, &payload_length);
3574 connection_.set_max_packet_length(length);
3576 // Queue the first packet.
3577 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(7);
3578 // The first stream frame will have 2 fewer overhead bytes than the other six.
3579 const string payload(payload_length * 7 + 2, 'a');
3580 EXPECT_EQ(payload.size(),
3581 connection_.SendStreamDataWithString(1, payload, 0, !kFin, nullptr)
3582 .bytes_consumed);
3585 TEST_P(QuicConnectionTest, LoopThroughSendingPacketsWithTruncation) {
3586 // Set up a larger payload than will fit in one packet.
3587 const string payload(connection_.max_packet_length(), 'a');
3588 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
3590 // Now send some packets with no truncation.
3591 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3592 EXPECT_EQ(payload.size(),
3593 connection_.SendStreamDataWithString(
3594 3, payload, 0, !kFin, nullptr).bytes_consumed);
3595 // Track the size of the second packet here. The overhead will be the largest
3596 // we see in this test, due to the non-truncated connection id.
3597 size_t non_truncated_packet_size = writer_->last_packet_size();
3599 // Change to a 4 byte connection id.
3600 QuicConfig config;
3601 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 4);
3602 connection_.SetFromConfig(config);
3603 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3604 EXPECT_EQ(payload.size(),
3605 connection_.SendStreamDataWithString(
3606 3, payload, 0, !kFin, nullptr).bytes_consumed);
3607 // Verify that we have 8 fewer bytes than in the non-truncated case. The
3608 // first packet got 4 bytes of extra payload due to the truncation, and the
3609 // headers here are also 4 byte smaller.
3610 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() + 8);
3612 // Change to a 1 byte connection id.
3613 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 1);
3614 connection_.SetFromConfig(config);
3615 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3616 EXPECT_EQ(payload.size(),
3617 connection_.SendStreamDataWithString(
3618 3, payload, 0, !kFin, nullptr).bytes_consumed);
3619 // Just like above, we save 7 bytes on payload, and 7 on truncation.
3620 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() + 7 * 2);
3622 // Change to a 0 byte connection id.
3623 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
3624 connection_.SetFromConfig(config);
3625 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3626 EXPECT_EQ(payload.size(),
3627 connection_.SendStreamDataWithString(
3628 3, payload, 0, !kFin, nullptr).bytes_consumed);
3629 // Just like above, we save 8 bytes on payload, and 8 on truncation.
3630 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() + 8 * 2);
3633 TEST_P(QuicConnectionTest, SendDelayedAck) {
3634 QuicTime ack_time = clock_.ApproximateNow().Add(DefaultDelayedAckTime());
3635 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3636 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3637 const uint8 tag = 0x07;
3638 connection_.SetDecrypter(ENCRYPTION_INITIAL, new StrictTaggingDecrypter(tag));
3639 framer_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
3640 // Process a packet from the non-crypto stream.
3641 frame1_.stream_id = 3;
3643 // The same as ProcessPacket(1) except that ENCRYPTION_INITIAL is used
3644 // instead of ENCRYPTION_NONE.
3645 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3646 ProcessDataPacketAtLevel(1, 0, !kEntropyFlag, ENCRYPTION_INITIAL);
3648 // Check if delayed ack timer is running for the expected interval.
3649 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3650 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
3651 // Simulate delayed ack alarm firing.
3652 connection_.GetAckAlarm()->Fire();
3653 // Check that ack is sent and that delayed ack alarm is reset.
3654 EXPECT_EQ(2u, writer_->frame_count());
3655 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3656 EXPECT_FALSE(writer_->ack_frames().empty());
3657 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3660 TEST_P(QuicConnectionTest, SendDelayedAckOnHandshakeConfirmed) {
3661 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3662 ProcessPacket(1);
3663 // Check that ack is sent and that delayed ack alarm is set.
3664 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3665 QuicTime ack_time = clock_.ApproximateNow().Add(DefaultDelayedAckTime());
3666 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
3668 // Completing the handshake as the server does nothing.
3669 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_SERVER);
3670 connection_.OnHandshakeComplete();
3671 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3672 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
3674 // Complete the handshake as the client decreases the delayed ack time to 0ms.
3675 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_CLIENT);
3676 connection_.OnHandshakeComplete();
3677 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3678 EXPECT_EQ(clock_.ApproximateNow(), connection_.GetAckAlarm()->deadline());
3681 TEST_P(QuicConnectionTest, SendDelayedAckOnSecondPacket) {
3682 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3683 ProcessPacket(1);
3684 ProcessPacket(2);
3685 // Check that ack is sent and that delayed ack alarm is reset.
3686 EXPECT_EQ(2u, writer_->frame_count());
3687 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3688 EXPECT_FALSE(writer_->ack_frames().empty());
3689 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3692 TEST_P(QuicConnectionTest, NoAckOnOldNacks) {
3693 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3694 // Drop one packet, triggering a sequence of acks.
3695 ProcessPacket(2);
3696 size_t frames_per_ack = 2;
3697 EXPECT_EQ(frames_per_ack, writer_->frame_count());
3698 EXPECT_FALSE(writer_->ack_frames().empty());
3699 writer_->Reset();
3700 ProcessPacket(3);
3701 EXPECT_EQ(frames_per_ack, writer_->frame_count());
3702 EXPECT_FALSE(writer_->ack_frames().empty());
3703 writer_->Reset();
3704 ProcessPacket(4);
3705 EXPECT_EQ(frames_per_ack, writer_->frame_count());
3706 EXPECT_FALSE(writer_->ack_frames().empty());
3707 writer_->Reset();
3708 ProcessPacket(5);
3709 EXPECT_EQ(frames_per_ack, writer_->frame_count());
3710 EXPECT_FALSE(writer_->ack_frames().empty());
3711 writer_->Reset();
3712 // Now only set the timer on the 6th packet, instead of sending another ack.
3713 ProcessPacket(6);
3714 EXPECT_EQ(0u, writer_->frame_count());
3715 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3718 TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingPacket) {
3719 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3720 ProcessPacket(1);
3721 connection_.SendStreamDataWithString(kClientDataStreamId1, "foo", 0, !kFin,
3722 nullptr);
3723 // Check that ack is bundled with outgoing data and that delayed ack
3724 // alarm is reset.
3725 EXPECT_EQ(3u, writer_->frame_count());
3726 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3727 EXPECT_FALSE(writer_->ack_frames().empty());
3728 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3731 TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingCryptoPacket) {
3732 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3733 ProcessPacket(1);
3734 connection_.SendStreamDataWithString(kCryptoStreamId, "foo", 0, !kFin,
3735 nullptr);
3736 // Check that ack is bundled with outgoing crypto data.
3737 EXPECT_EQ(3u, writer_->frame_count());
3738 EXPECT_FALSE(writer_->ack_frames().empty());
3739 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3742 TEST_P(QuicConnectionTest, BlockAndBufferOnFirstCHLOPacketOfTwo) {
3743 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3744 ProcessPacket(1);
3745 BlockOnNextWrite();
3746 writer_->set_is_write_blocked_data_buffered(true);
3747 connection_.SendStreamDataWithString(kCryptoStreamId, "foo", 0, !kFin,
3748 nullptr);
3749 EXPECT_TRUE(writer_->IsWriteBlocked());
3750 EXPECT_FALSE(connection_.HasQueuedData());
3751 connection_.SendStreamDataWithString(kCryptoStreamId, "bar", 3, !kFin,
3752 nullptr);
3753 EXPECT_TRUE(writer_->IsWriteBlocked());
3754 EXPECT_TRUE(connection_.HasQueuedData());
3757 TEST_P(QuicConnectionTest, BundleAckForSecondCHLO) {
3758 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3759 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3760 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(
3761 IgnoreResult(InvokeWithoutArgs(&connection_,
3762 &TestConnection::SendCryptoStreamData)));
3763 // Process a packet from the crypto stream, which is frame1_'s default.
3764 // Receiving the CHLO as packet 2 first will cause the connection to
3765 // immediately send an ack, due to the packet gap.
3766 ProcessPacket(2);
3767 // Check that ack is sent and that delayed ack alarm is reset.
3768 EXPECT_EQ(3u, writer_->frame_count());
3769 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3770 EXPECT_EQ(1u, writer_->stream_frames().size());
3771 EXPECT_FALSE(writer_->ack_frames().empty());
3772 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3775 TEST_P(QuicConnectionTest, BundleAckWithDataOnIncomingAck) {
3776 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3777 connection_.SendStreamDataWithString(kClientDataStreamId1, "foo", 0, !kFin,
3778 nullptr);
3779 connection_.SendStreamDataWithString(kClientDataStreamId1, "foo", 3, !kFin,
3780 nullptr);
3781 // Ack the second packet, which will retransmit the first packet.
3782 QuicAckFrame ack = InitAckFrame(2);
3783 NackPacket(1, &ack);
3784 SequenceNumberSet lost_packets;
3785 lost_packets.insert(1);
3786 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3787 .WillOnce(Return(lost_packets));
3788 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3789 ProcessAckPacket(&ack);
3790 EXPECT_EQ(1u, writer_->frame_count());
3791 EXPECT_EQ(1u, writer_->stream_frames().size());
3792 writer_->Reset();
3794 // Now ack the retransmission, which will both raise the high water mark
3795 // and see if there is more data to send.
3796 ack = InitAckFrame(3);
3797 NackPacket(1, &ack);
3798 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3799 .WillOnce(Return(SequenceNumberSet()));
3800 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3801 ProcessAckPacket(&ack);
3803 // Check that no packet is sent and the ack alarm isn't set.
3804 EXPECT_EQ(0u, writer_->frame_count());
3805 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3806 writer_->Reset();
3808 // Send the same ack, but send both data and an ack together.
3809 ack = InitAckFrame(3);
3810 NackPacket(1, &ack);
3811 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3812 .WillOnce(Return(SequenceNumberSet()));
3813 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(
3814 IgnoreResult(InvokeWithoutArgs(
3815 &connection_,
3816 &TestConnection::EnsureWritableAndSendStreamData5)));
3817 ProcessAckPacket(&ack);
3819 // Check that ack is bundled with outgoing data and the delayed ack
3820 // alarm is reset.
3821 EXPECT_EQ(3u, writer_->frame_count());
3822 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3823 EXPECT_FALSE(writer_->ack_frames().empty());
3824 EXPECT_EQ(1u, writer_->stream_frames().size());
3825 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3828 TEST_P(QuicConnectionTest, NoAckSentForClose) {
3829 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3830 ProcessPacket(1);
3831 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, true));
3832 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3833 ProcessClosePacket(2, 0);
3836 TEST_P(QuicConnectionTest, SendWhenDisconnected) {
3837 EXPECT_TRUE(connection_.connected());
3838 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, false));
3839 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, false);
3840 EXPECT_FALSE(connection_.connected());
3841 EXPECT_FALSE(connection_.CanWriteStreamData());
3842 QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
3843 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 1, _, _)).Times(0);
3844 connection_.SendPacket(ENCRYPTION_NONE, 1, packet, kTestEntropyHash,
3845 HAS_RETRANSMITTABLE_DATA, false, false);
3848 TEST_P(QuicConnectionTest, PublicReset) {
3849 QuicPublicResetPacket header;
3850 header.public_header.connection_id = connection_id_;
3851 header.public_header.reset_flag = true;
3852 header.public_header.version_flag = false;
3853 header.rejected_sequence_number = 10101;
3854 scoped_ptr<QuicEncryptedPacket> packet(
3855 framer_.BuildPublicResetPacket(header));
3856 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PUBLIC_RESET, true));
3857 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *packet);
3860 TEST_P(QuicConnectionTest, GoAway) {
3861 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3863 QuicGoAwayFrame goaway;
3864 goaway.last_good_stream_id = 1;
3865 goaway.error_code = QUIC_PEER_GOING_AWAY;
3866 goaway.reason_phrase = "Going away.";
3867 EXPECT_CALL(visitor_, OnGoAway(_));
3868 ProcessGoAwayPacket(&goaway);
3871 TEST_P(QuicConnectionTest, WindowUpdate) {
3872 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3874 QuicWindowUpdateFrame window_update;
3875 window_update.stream_id = 3;
3876 window_update.byte_offset = 1234;
3877 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
3878 ProcessFramePacket(QuicFrame(&window_update));
3881 TEST_P(QuicConnectionTest, Blocked) {
3882 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3884 QuicBlockedFrame blocked;
3885 blocked.stream_id = 3;
3886 EXPECT_CALL(visitor_, OnBlockedFrame(_));
3887 ProcessFramePacket(QuicFrame(&blocked));
3890 TEST_P(QuicConnectionTest, ZeroBytePacket) {
3891 // Don't close the connection for zero byte packets.
3892 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
3893 QuicEncryptedPacket encrypted(nullptr, 0);
3894 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), encrypted);
3897 TEST_P(QuicConnectionTest, MissingPacketsBeforeLeastUnacked) {
3898 // Set the sequence number of the ack packet to be least unacked (4).
3899 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 3);
3900 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3901 QuicStopWaitingFrame frame = InitStopWaitingFrame(4);
3902 ProcessStopWaitingPacket(&frame);
3903 EXPECT_TRUE(outgoing_ack()->missing_packets.empty());
3906 TEST_P(QuicConnectionTest, ReceivedEntropyHashCalculation) {
3907 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AtLeast(1));
3908 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3909 ProcessDataPacket(1, 1, kEntropyFlag);
3910 ProcessDataPacket(4, 1, kEntropyFlag);
3911 ProcessDataPacket(3, 1, !kEntropyFlag);
3912 ProcessDataPacket(7, 1, kEntropyFlag);
3913 EXPECT_EQ(146u, outgoing_ack()->entropy_hash);
3916 TEST_P(QuicConnectionTest, ReceivedEntropyHashCalculationHalfFEC) {
3917 // FEC packets should not change the entropy hash calculation.
3918 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AtLeast(1));
3919 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3920 ProcessDataPacket(1, 1, kEntropyFlag);
3921 ProcessFecPacket(4, 1, false, kEntropyFlag, nullptr);
3922 ProcessDataPacket(3, 3, !kEntropyFlag);
3923 ProcessFecPacket(7, 3, false, kEntropyFlag, nullptr);
3924 EXPECT_EQ(146u, outgoing_ack()->entropy_hash);
3927 TEST_P(QuicConnectionTest, UpdateEntropyForReceivedPackets) {
3928 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AtLeast(1));
3929 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3930 ProcessDataPacket(1, 1, kEntropyFlag);
3931 ProcessDataPacket(5, 1, kEntropyFlag);
3932 ProcessDataPacket(4, 1, !kEntropyFlag);
3933 EXPECT_EQ(34u, outgoing_ack()->entropy_hash);
3934 // Make 4th packet my least unacked, and update entropy for 2, 3 packets.
3935 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 5);
3936 QuicPacketEntropyHash six_packet_entropy_hash = 0;
3937 QuicPacketEntropyHash random_entropy_hash = 129u;
3938 QuicStopWaitingFrame frame = InitStopWaitingFrame(4);
3939 frame.entropy_hash = random_entropy_hash;
3940 if (ProcessStopWaitingPacket(&frame)) {
3941 six_packet_entropy_hash = 1 << 6;
3944 EXPECT_EQ((random_entropy_hash + (1 << 5) + six_packet_entropy_hash),
3945 outgoing_ack()->entropy_hash);
3948 TEST_P(QuicConnectionTest, UpdateEntropyHashUptoCurrentPacket) {
3949 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AtLeast(1));
3950 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3951 ProcessDataPacket(1, 1, kEntropyFlag);
3952 ProcessDataPacket(5, 1, !kEntropyFlag);
3953 ProcessDataPacket(22, 1, kEntropyFlag);
3954 EXPECT_EQ(66u, outgoing_ack()->entropy_hash);
3955 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 22);
3956 QuicPacketEntropyHash random_entropy_hash = 85u;
3957 // Current packet is the least unacked packet.
3958 QuicPacketEntropyHash ack_entropy_hash;
3959 QuicStopWaitingFrame frame = InitStopWaitingFrame(23);
3960 frame.entropy_hash = random_entropy_hash;
3961 ack_entropy_hash = ProcessStopWaitingPacket(&frame);
3962 EXPECT_EQ((random_entropy_hash + ack_entropy_hash),
3963 outgoing_ack()->entropy_hash);
3964 ProcessDataPacket(25, 1, kEntropyFlag);
3965 EXPECT_EQ((random_entropy_hash + ack_entropy_hash + (1 << (25 % 8))),
3966 outgoing_ack()->entropy_hash);
3969 TEST_P(QuicConnectionTest, EntropyCalculationForTruncatedAck) {
3970 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AtLeast(1));
3971 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3972 QuicPacketEntropyHash entropy[51];
3973 entropy[0] = 0;
3974 for (int i = 1; i < 51; ++i) {
3975 bool should_send = i % 10 != 1;
3976 bool entropy_flag = (i & (i - 1)) != 0;
3977 if (!should_send) {
3978 entropy[i] = entropy[i - 1];
3979 continue;
3981 if (entropy_flag) {
3982 entropy[i] = entropy[i - 1] ^ (1 << (i % 8));
3983 } else {
3984 entropy[i] = entropy[i - 1];
3986 ProcessDataPacket(i, 1, entropy_flag);
3988 for (int i = 1; i < 50; ++i) {
3989 EXPECT_EQ(entropy[i], QuicConnectionPeer::ReceivedEntropyHash(
3990 &connection_, i));
3994 TEST_P(QuicConnectionTest, ServerSendsVersionNegotiationPacket) {
3995 connection_.SetSupportedVersions(QuicSupportedVersions());
3996 framer_.set_version_for_tests(QUIC_VERSION_UNSUPPORTED);
3998 QuicPacketHeader header;
3999 header.public_header.connection_id = connection_id_;
4000 header.public_header.version_flag = true;
4001 header.packet_sequence_number = 12;
4003 QuicFrames frames;
4004 frames.push_back(QuicFrame(&frame1_));
4005 scoped_ptr<QuicPacket> packet(ConstructPacket(header, frames));
4006 char buffer[kMaxPacketSize];
4007 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPayload(
4008 ENCRYPTION_NONE, 12, *packet, buffer, kMaxPacketSize));
4010 framer_.set_version(version());
4011 connection_.set_perspective(Perspective::IS_SERVER);
4012 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
4013 EXPECT_TRUE(writer_->version_negotiation_packet() != nullptr);
4015 size_t num_versions = arraysize(kSupportedQuicVersions);
4016 ASSERT_EQ(num_versions,
4017 writer_->version_negotiation_packet()->versions.size());
4019 // We expect all versions in kSupportedQuicVersions to be
4020 // included in the packet.
4021 for (size_t i = 0; i < num_versions; ++i) {
4022 EXPECT_EQ(kSupportedQuicVersions[i],
4023 writer_->version_negotiation_packet()->versions[i]);
4027 TEST_P(QuicConnectionTest, ServerSendsVersionNegotiationPacketSocketBlocked) {
4028 connection_.SetSupportedVersions(QuicSupportedVersions());
4029 framer_.set_version_for_tests(QUIC_VERSION_UNSUPPORTED);
4031 QuicPacketHeader header;
4032 header.public_header.connection_id = connection_id_;
4033 header.public_header.version_flag = true;
4034 header.packet_sequence_number = 12;
4036 QuicFrames frames;
4037 frames.push_back(QuicFrame(&frame1_));
4038 scoped_ptr<QuicPacket> packet(ConstructPacket(header, frames));
4039 char buffer[kMaxPacketSize];
4040 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPayload(
4041 ENCRYPTION_NONE, 12, *packet, buffer, kMaxPacketSize));
4043 framer_.set_version(version());
4044 connection_.set_perspective(Perspective::IS_SERVER);
4045 BlockOnNextWrite();
4046 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
4047 EXPECT_EQ(0u, writer_->last_packet_size());
4048 EXPECT_TRUE(connection_.HasQueuedData());
4050 writer_->SetWritable();
4051 connection_.OnCanWrite();
4052 EXPECT_TRUE(writer_->version_negotiation_packet() != nullptr);
4054 size_t num_versions = arraysize(kSupportedQuicVersions);
4055 ASSERT_EQ(num_versions,
4056 writer_->version_negotiation_packet()->versions.size());
4058 // We expect all versions in kSupportedQuicVersions to be
4059 // included in the packet.
4060 for (size_t i = 0; i < num_versions; ++i) {
4061 EXPECT_EQ(kSupportedQuicVersions[i],
4062 writer_->version_negotiation_packet()->versions[i]);
4066 TEST_P(QuicConnectionTest,
4067 ServerSendsVersionNegotiationPacketSocketBlockedDataBuffered) {
4068 connection_.SetSupportedVersions(QuicSupportedVersions());
4069 framer_.set_version_for_tests(QUIC_VERSION_UNSUPPORTED);
4071 QuicPacketHeader header;
4072 header.public_header.connection_id = connection_id_;
4073 header.public_header.version_flag = true;
4074 header.packet_sequence_number = 12;
4076 QuicFrames frames;
4077 frames.push_back(QuicFrame(&frame1_));
4078 scoped_ptr<QuicPacket> packet(ConstructPacket(header, frames));
4079 char buffer[kMaxPacketSize];
4080 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPayload(
4081 ENCRYPTION_NONE, 12, *packet, buffer, kMaxPacketSize));
4083 framer_.set_version(version());
4084 connection_.set_perspective(Perspective::IS_SERVER);
4085 BlockOnNextWrite();
4086 writer_->set_is_write_blocked_data_buffered(true);
4087 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
4088 EXPECT_EQ(0u, writer_->last_packet_size());
4089 EXPECT_FALSE(connection_.HasQueuedData());
4092 TEST_P(QuicConnectionTest, ClientHandlesVersionNegotiation) {
4093 // Start out with some unsupported version.
4094 QuicConnectionPeer::GetFramer(&connection_)->set_version_for_tests(
4095 QUIC_VERSION_UNSUPPORTED);
4097 QuicPacketHeader header;
4098 header.public_header.connection_id = connection_id_;
4099 header.public_header.version_flag = true;
4100 header.packet_sequence_number = 12;
4102 QuicVersionVector supported_versions;
4103 for (size_t i = 0; i < arraysize(kSupportedQuicVersions); ++i) {
4104 supported_versions.push_back(kSupportedQuicVersions[i]);
4107 // Send a version negotiation packet.
4108 scoped_ptr<QuicEncryptedPacket> encrypted(
4109 framer_.BuildVersionNegotiationPacket(
4110 header.public_header, supported_versions));
4111 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
4113 // Now force another packet. The connection should transition into
4114 // NEGOTIATED_VERSION state and tell the packet creator to StopSendingVersion.
4115 header.public_header.version_flag = false;
4116 QuicFrames frames;
4117 frames.push_back(QuicFrame(&frame1_));
4118 scoped_ptr<QuicPacket> packet(ConstructPacket(header, frames));
4119 char buffer[kMaxPacketSize];
4120 encrypted.reset(framer_.EncryptPayload(ENCRYPTION_NONE, 12, *packet, buffer,
4121 kMaxPacketSize));
4122 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4123 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4124 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
4126 ASSERT_FALSE(QuicPacketCreatorPeer::SendVersionInPacket(creator_));
4129 TEST_P(QuicConnectionTest, BadVersionNegotiation) {
4130 QuicPacketHeader header;
4131 header.public_header.connection_id = connection_id_;
4132 header.public_header.version_flag = true;
4133 header.packet_sequence_number = 12;
4135 QuicVersionVector supported_versions;
4136 for (size_t i = 0; i < arraysize(kSupportedQuicVersions); ++i) {
4137 supported_versions.push_back(kSupportedQuicVersions[i]);
4140 // Send a version negotiation packet with the version the client started with.
4141 // It should be rejected.
4142 EXPECT_CALL(visitor_,
4143 OnConnectionClosed(QUIC_INVALID_VERSION_NEGOTIATION_PACKET,
4144 false));
4145 scoped_ptr<QuicEncryptedPacket> encrypted(
4146 framer_.BuildVersionNegotiationPacket(
4147 header.public_header, supported_versions));
4148 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
4151 TEST_P(QuicConnectionTest, CheckSendStats) {
4152 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4153 connection_.SendStreamDataWithString(3, "first", 0, !kFin, nullptr);
4154 size_t first_packet_size = writer_->last_packet_size();
4156 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4157 connection_.SendStreamDataWithString(5, "second", 0, !kFin, nullptr);
4158 size_t second_packet_size = writer_->last_packet_size();
4160 // 2 retransmissions due to rto, 1 due to explicit nack.
4161 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
4162 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
4164 // Retransmit due to RTO.
4165 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
4166 connection_.GetRetransmissionAlarm()->Fire();
4168 // Retransmit due to explicit nacks.
4169 QuicAckFrame nack_three = InitAckFrame(4);
4170 NackPacket(3, &nack_three);
4171 NackPacket(1, &nack_three);
4172 SequenceNumberSet lost_packets;
4173 lost_packets.insert(1);
4174 lost_packets.insert(3);
4175 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4176 .WillOnce(Return(lost_packets));
4177 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4178 EXPECT_CALL(visitor_, OnCanWrite());
4179 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4180 ProcessAckPacket(&nack_three);
4182 EXPECT_CALL(*send_algorithm_, BandwidthEstimate()).WillOnce(
4183 Return(QuicBandwidth::Zero()));
4185 const QuicConnectionStats& stats = connection_.GetStats();
4186 EXPECT_EQ(3 * first_packet_size + 2 * second_packet_size - kQuicVersionSize,
4187 stats.bytes_sent);
4188 EXPECT_EQ(5u, stats.packets_sent);
4189 EXPECT_EQ(2 * first_packet_size + second_packet_size - kQuicVersionSize,
4190 stats.bytes_retransmitted);
4191 EXPECT_EQ(3u, stats.packets_retransmitted);
4192 EXPECT_EQ(1u, stats.rto_count);
4193 EXPECT_EQ(kDefaultMaxPacketSize, stats.max_packet_size);
4196 TEST_P(QuicConnectionTest, CheckReceiveStats) {
4197 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4199 size_t received_bytes = 0;
4200 received_bytes += ProcessFecProtectedPacket(1, false, !kEntropyFlag);
4201 received_bytes += ProcessFecProtectedPacket(3, false, !kEntropyFlag);
4202 // Should be counted against dropped packets.
4203 received_bytes += ProcessDataPacket(3, 1, !kEntropyFlag);
4204 received_bytes += ProcessFecPacket(4, 1, true, !kEntropyFlag, nullptr);
4206 EXPECT_CALL(*send_algorithm_, BandwidthEstimate()).WillOnce(
4207 Return(QuicBandwidth::Zero()));
4209 const QuicConnectionStats& stats = connection_.GetStats();
4210 EXPECT_EQ(received_bytes, stats.bytes_received);
4211 EXPECT_EQ(4u, stats.packets_received);
4213 EXPECT_EQ(1u, stats.packets_revived);
4214 EXPECT_EQ(1u, stats.packets_dropped);
4217 TEST_P(QuicConnectionTest, TestFecGroupLimits) {
4218 // Create and return a group for 1.
4219 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 1) != nullptr);
4221 // Create and return a group for 2.
4222 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 2) != nullptr);
4224 // Create and return a group for 4. This should remove 1 but not 2.
4225 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 4) != nullptr);
4226 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 1) == nullptr);
4227 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 2) != nullptr);
4229 // Create and return a group for 3. This will kill off 2.
4230 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 3) != nullptr);
4231 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 2) == nullptr);
4233 // Verify that adding 5 kills off 3, despite 4 being created before 3.
4234 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 5) != nullptr);
4235 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 4) != nullptr);
4236 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 3) == nullptr);
4239 TEST_P(QuicConnectionTest, ProcessFramesIfPacketClosedConnection) {
4240 // Construct a packet with stream frame and connection close frame.
4241 QuicPacketHeader header;
4242 header.public_header.connection_id = connection_id_;
4243 header.packet_sequence_number = 1;
4244 header.public_header.version_flag = false;
4246 QuicConnectionCloseFrame qccf;
4247 qccf.error_code = QUIC_PEER_GOING_AWAY;
4249 QuicFrames frames;
4250 frames.push_back(QuicFrame(&frame1_));
4251 frames.push_back(QuicFrame(&qccf));
4252 scoped_ptr<QuicPacket> packet(ConstructPacket(header, frames));
4253 EXPECT_TRUE(nullptr != packet.get());
4254 char buffer[kMaxPacketSize];
4255 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPayload(
4256 ENCRYPTION_NONE, 1, *packet, buffer, kMaxPacketSize));
4258 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, true));
4259 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4260 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4262 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
4265 TEST_P(QuicConnectionTest, SelectMutualVersion) {
4266 connection_.SetSupportedVersions(QuicSupportedVersions());
4267 // Set the connection to speak the lowest quic version.
4268 connection_.set_version(QuicVersionMin());
4269 EXPECT_EQ(QuicVersionMin(), connection_.version());
4271 // Pass in available versions which includes a higher mutually supported
4272 // version. The higher mutually supported version should be selected.
4273 QuicVersionVector supported_versions;
4274 for (size_t i = 0; i < arraysize(kSupportedQuicVersions); ++i) {
4275 supported_versions.push_back(kSupportedQuicVersions[i]);
4277 EXPECT_TRUE(connection_.SelectMutualVersion(supported_versions));
4278 EXPECT_EQ(QuicVersionMax(), connection_.version());
4280 // Expect that the lowest version is selected.
4281 // Ensure the lowest supported version is less than the max, unless they're
4282 // the same.
4283 EXPECT_LE(QuicVersionMin(), QuicVersionMax());
4284 QuicVersionVector lowest_version_vector;
4285 lowest_version_vector.push_back(QuicVersionMin());
4286 EXPECT_TRUE(connection_.SelectMutualVersion(lowest_version_vector));
4287 EXPECT_EQ(QuicVersionMin(), connection_.version());
4289 // Shouldn't be able to find a mutually supported version.
4290 QuicVersionVector unsupported_version;
4291 unsupported_version.push_back(QUIC_VERSION_UNSUPPORTED);
4292 EXPECT_FALSE(connection_.SelectMutualVersion(unsupported_version));
4295 TEST_P(QuicConnectionTest, ConnectionCloseWhenWritable) {
4296 EXPECT_FALSE(writer_->IsWriteBlocked());
4298 // Send a packet.
4299 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
4300 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4301 EXPECT_EQ(1u, writer_->packets_write_attempts());
4303 TriggerConnectionClose();
4304 EXPECT_EQ(2u, writer_->packets_write_attempts());
4307 TEST_P(QuicConnectionTest, ConnectionCloseGettingWriteBlocked) {
4308 BlockOnNextWrite();
4309 TriggerConnectionClose();
4310 EXPECT_EQ(1u, writer_->packets_write_attempts());
4311 EXPECT_TRUE(writer_->IsWriteBlocked());
4314 TEST_P(QuicConnectionTest, ConnectionCloseWhenWriteBlocked) {
4315 BlockOnNextWrite();
4316 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
4317 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4318 EXPECT_EQ(1u, writer_->packets_write_attempts());
4319 EXPECT_TRUE(writer_->IsWriteBlocked());
4320 TriggerConnectionClose();
4321 EXPECT_EQ(1u, writer_->packets_write_attempts());
4324 TEST_P(QuicConnectionTest, AckNotifierTriggerCallback) {
4325 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4327 // Create a delegate which we expect to be called.
4328 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4329 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(1);
4331 // Send some data, which will register the delegate to be notified.
4332 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
4334 // Process an ACK from the server which should trigger the callback.
4335 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4336 QuicAckFrame frame = InitAckFrame(1);
4337 ProcessAckPacket(&frame);
4340 TEST_P(QuicConnectionTest, AckNotifierFailToTriggerCallback) {
4341 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4343 // Create a delegate which we don't expect to be called.
4344 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4345 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(0);
4347 // Send some data, which will register the delegate to be notified. This will
4348 // not be ACKed and so the delegate should never be called.
4349 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
4351 // Send some other data which we will ACK.
4352 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
4353 connection_.SendStreamDataWithString(1, "bar", 0, !kFin, nullptr);
4355 // Now we receive ACK for packets 2 and 3, but importantly missing packet 1
4356 // which we registered to be notified about.
4357 QuicAckFrame frame = InitAckFrame(3);
4358 NackPacket(1, &frame);
4359 SequenceNumberSet lost_packets;
4360 lost_packets.insert(1);
4361 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4362 .WillOnce(Return(lost_packets));
4363 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4364 ProcessAckPacket(&frame);
4367 TEST_P(QuicConnectionTest, AckNotifierCallbackAfterRetransmission) {
4368 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4370 // Create a delegate which we expect to be called.
4371 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4372 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(1);
4374 // Send four packets, and register to be notified on ACK of packet 2.
4375 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
4376 connection_.SendStreamDataWithString(3, "bar", 0, !kFin, delegate.get());
4377 connection_.SendStreamDataWithString(3, "baz", 0, !kFin, nullptr);
4378 connection_.SendStreamDataWithString(3, "qux", 0, !kFin, nullptr);
4380 // Now we receive ACK for packets 1, 3, and 4 and lose 2.
4381 QuicAckFrame frame = InitAckFrame(4);
4382 NackPacket(2, &frame);
4383 SequenceNumberSet lost_packets;
4384 lost_packets.insert(2);
4385 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4386 .WillOnce(Return(lost_packets));
4387 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4388 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4389 ProcessAckPacket(&frame);
4391 // Now we get an ACK for packet 5 (retransmitted packet 2), which should
4392 // trigger the callback.
4393 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4394 .WillRepeatedly(Return(SequenceNumberSet()));
4395 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4396 QuicAckFrame second_ack_frame = InitAckFrame(5);
4397 ProcessAckPacket(&second_ack_frame);
4400 // AckNotifierCallback is triggered by the ack of a packet that timed
4401 // out and was retransmitted, even though the retransmission has a
4402 // different sequence number.
4403 TEST_P(QuicConnectionTest, AckNotifierCallbackForAckAfterRTO) {
4404 InSequence s;
4406 // Create a delegate which we expect to be called.
4407 scoped_refptr<MockAckNotifierDelegate> delegate(
4408 new StrictMock<MockAckNotifierDelegate>);
4410 QuicTime default_retransmission_time = clock_.ApproximateNow().Add(
4411 DefaultRetransmissionTime());
4412 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, delegate.get());
4413 EXPECT_EQ(1u, stop_waiting()->least_unacked);
4415 EXPECT_EQ(1u, writer_->header().packet_sequence_number);
4416 EXPECT_EQ(default_retransmission_time,
4417 connection_.GetRetransmissionAlarm()->deadline());
4418 // Simulate the retransmission alarm firing.
4419 clock_.AdvanceTime(DefaultRetransmissionTime());
4420 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 2u, _, _));
4421 connection_.GetRetransmissionAlarm()->Fire();
4422 EXPECT_EQ(2u, writer_->header().packet_sequence_number);
4423 // We do not raise the high water mark yet.
4424 EXPECT_EQ(1u, stop_waiting()->least_unacked);
4426 // Ack the original packet, which will revert the RTO.
4427 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4428 EXPECT_CALL(*delegate, OnAckNotification(1, _, _));
4429 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4430 QuicAckFrame ack_frame = InitAckFrame(1);
4431 ProcessAckPacket(&ack_frame);
4433 // Delegate is not notified again when the retransmit is acked.
4434 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4435 QuicAckFrame second_ack_frame = InitAckFrame(2);
4436 ProcessAckPacket(&second_ack_frame);
4439 // AckNotifierCallback is triggered by the ack of a packet that was
4440 // previously nacked, even though the retransmission has a different
4441 // sequence number.
4442 TEST_P(QuicConnectionTest, AckNotifierCallbackForAckOfNackedPacket) {
4443 InSequence s;
4445 // Create a delegate which we expect to be called.
4446 scoped_refptr<MockAckNotifierDelegate> delegate(
4447 new StrictMock<MockAckNotifierDelegate>);
4449 // Send four packets, and register to be notified on ACK of packet 2.
4450 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
4451 connection_.SendStreamDataWithString(3, "bar", 0, !kFin, delegate.get());
4452 connection_.SendStreamDataWithString(3, "baz", 0, !kFin, nullptr);
4453 connection_.SendStreamDataWithString(3, "qux", 0, !kFin, nullptr);
4455 // Now we receive ACK for packets 1, 3, and 4 and lose 2.
4456 QuicAckFrame frame = InitAckFrame(4);
4457 NackPacket(2, &frame);
4458 SequenceNumberSet lost_packets;
4459 lost_packets.insert(2);
4460 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4461 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4462 .WillOnce(Return(lost_packets));
4463 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4464 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4465 ProcessAckPacket(&frame);
4467 // Now we get an ACK for packet 2, which was previously nacked.
4468 SequenceNumberSet no_lost_packets;
4469 EXPECT_CALL(*delegate.get(), OnAckNotification(1, _, _));
4470 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4471 .WillOnce(Return(no_lost_packets));
4472 QuicAckFrame second_ack_frame = InitAckFrame(4);
4473 ProcessAckPacket(&second_ack_frame);
4475 // Verify that the delegate is not notified again when the
4476 // retransmit is acked.
4477 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4478 .WillOnce(Return(no_lost_packets));
4479 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4480 QuicAckFrame third_ack_frame = InitAckFrame(5);
4481 ProcessAckPacket(&third_ack_frame);
4484 TEST_P(QuicConnectionTest, AckNotifierFECTriggerCallback) {
4485 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4487 // Create a delegate which we expect to be called.
4488 scoped_refptr<MockAckNotifierDelegate> delegate(
4489 new MockAckNotifierDelegate);
4490 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(1);
4492 // Send some data, which will register the delegate to be notified.
4493 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
4494 connection_.SendStreamDataWithString(2, "bar", 0, !kFin, nullptr);
4496 // Process an ACK from the server with a revived packet, which should trigger
4497 // the callback.
4498 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4499 QuicAckFrame frame = InitAckFrame(2);
4500 NackPacket(1, &frame);
4501 frame.revived_packets.insert(1);
4502 ProcessAckPacket(&frame);
4503 // If the ack is processed again, the notifier should not be called again.
4504 ProcessAckPacket(&frame);
4507 TEST_P(QuicConnectionTest, AckNotifierCallbackAfterFECRecovery) {
4508 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4509 EXPECT_CALL(visitor_, OnCanWrite());
4511 // Create a delegate which we expect to be called.
4512 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4513 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(1);
4515 // Expect ACKs for 1 packet.
4516 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4518 // Send one packet, and register to be notified on ACK.
4519 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
4521 // Ack packet gets dropped, but we receive an FEC packet that covers it.
4522 // Should recover the Ack packet and trigger the notification callback.
4523 QuicFrames frames;
4525 QuicAckFrame ack_frame = InitAckFrame(1);
4526 frames.push_back(QuicFrame(&ack_frame));
4528 // Dummy stream frame to satisfy expectations set elsewhere.
4529 frames.push_back(QuicFrame(&frame1_));
4531 QuicPacketHeader ack_header;
4532 ack_header.public_header.connection_id = connection_id_;
4533 ack_header.public_header.reset_flag = false;
4534 ack_header.public_header.version_flag = false;
4535 ack_header.entropy_flag = !kEntropyFlag;
4536 ack_header.fec_flag = true;
4537 ack_header.packet_sequence_number = 1;
4538 ack_header.is_in_fec_group = IN_FEC_GROUP;
4539 ack_header.fec_group = 1;
4541 QuicPacket* packet = BuildUnsizedDataPacket(&framer_, ack_header, frames);
4543 // Take the packet which contains the ACK frame, and construct and deliver an
4544 // FEC packet which allows the ACK packet to be recovered.
4545 ProcessFecPacket(2, 1, true, !kEntropyFlag, packet);
4548 TEST_P(QuicConnectionTest, NetworkChangeVisitorCwndCallbackChangesFecState) {
4549 size_t max_packets_per_fec_group = creator_->max_packets_per_fec_group();
4551 QuicSentPacketManager::NetworkChangeVisitor* visitor =
4552 QuicSentPacketManagerPeer::GetNetworkChangeVisitor(manager_);
4553 EXPECT_TRUE(visitor);
4555 // Increase FEC group size by increasing congestion window to a large number.
4556 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
4557 Return(1000 * kDefaultTCPMSS));
4558 visitor->OnCongestionWindowChange();
4559 EXPECT_LT(max_packets_per_fec_group, creator_->max_packets_per_fec_group());
4562 TEST_P(QuicConnectionTest, NetworkChangeVisitorConfigCallbackChangesFecState) {
4563 QuicSentPacketManager::NetworkChangeVisitor* visitor =
4564 QuicSentPacketManagerPeer::GetNetworkChangeVisitor(manager_);
4565 EXPECT_TRUE(visitor);
4566 EXPECT_EQ(QuicTime::Delta::Zero(),
4567 QuicPacketGeneratorPeer::GetFecTimeout(generator_));
4569 // Verify that sending a config with a new initial rtt changes fec timeout.
4570 // Create and process a config with a non-zero initial RTT.
4571 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4572 QuicConfig config;
4573 config.SetInitialRoundTripTimeUsToSend(300000);
4574 connection_.SetFromConfig(config);
4575 EXPECT_LT(QuicTime::Delta::Zero(),
4576 QuicPacketGeneratorPeer::GetFecTimeout(generator_));
4579 TEST_P(QuicConnectionTest, NetworkChangeVisitorRttCallbackChangesFecState) {
4580 // Verify that sending a config with a new initial rtt changes fec timeout.
4581 QuicSentPacketManager::NetworkChangeVisitor* visitor =
4582 QuicSentPacketManagerPeer::GetNetworkChangeVisitor(manager_);
4583 EXPECT_TRUE(visitor);
4584 EXPECT_EQ(QuicTime::Delta::Zero(),
4585 QuicPacketGeneratorPeer::GetFecTimeout(generator_));
4587 // Increase FEC timeout by increasing RTT.
4588 RttStats* rtt_stats = QuicSentPacketManagerPeer::GetRttStats(manager_);
4589 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(300),
4590 QuicTime::Delta::Zero(), QuicTime::Zero());
4591 visitor->OnRttChange();
4592 EXPECT_LT(QuicTime::Delta::Zero(),
4593 QuicPacketGeneratorPeer::GetFecTimeout(generator_));
4596 TEST_P(QuicConnectionTest, OnPacketHeaderDebugVisitor) {
4597 QuicPacketHeader header;
4599 scoped_ptr<MockQuicConnectionDebugVisitor> debug_visitor(
4600 new MockQuicConnectionDebugVisitor());
4601 connection_.set_debug_visitor(debug_visitor.get());
4602 EXPECT_CALL(*debug_visitor, OnPacketHeader(Ref(header))).Times(1);
4603 connection_.OnPacketHeader(header);
4606 TEST_P(QuicConnectionTest, Pacing) {
4607 TestConnection server(connection_id_, IPEndPoint(), helper_.get(), factory_,
4608 Perspective::IS_SERVER, version());
4609 TestConnection client(connection_id_, IPEndPoint(), helper_.get(), factory_,
4610 Perspective::IS_CLIENT, version());
4611 EXPECT_FALSE(client.sent_packet_manager().using_pacing());
4612 EXPECT_FALSE(server.sent_packet_manager().using_pacing());
4615 TEST_P(QuicConnectionTest, ControlFramesInstigateAcks) {
4616 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4618 // Send a WINDOW_UPDATE frame.
4619 QuicWindowUpdateFrame window_update;
4620 window_update.stream_id = 3;
4621 window_update.byte_offset = 1234;
4622 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
4623 ProcessFramePacket(QuicFrame(&window_update));
4625 // Ensure that this has caused the ACK alarm to be set.
4626 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
4627 EXPECT_TRUE(ack_alarm->IsSet());
4629 // Cancel alarm, and try again with BLOCKED frame.
4630 ack_alarm->Cancel();
4631 QuicBlockedFrame blocked;
4632 blocked.stream_id = 3;
4633 EXPECT_CALL(visitor_, OnBlockedFrame(_));
4634 ProcessFramePacket(QuicFrame(&blocked));
4635 EXPECT_TRUE(ack_alarm->IsSet());
4638 TEST_P(QuicConnectionTest, NoDataNoFin) {
4639 // Make sure that a call to SendStreamWithData, with no data and no FIN, does
4640 // not result in a QuicAckNotifier being used-after-free (fail under ASAN).
4641 // Regression test for b/18594622
4642 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4643 EXPECT_DFATAL(
4644 connection_.SendStreamDataWithString(3, "", 0, !kFin, delegate.get()),
4645 "Attempt to send empty stream frame");
4648 TEST_P(QuicConnectionTest, FecSendPolicyReceivedConnectionOption) {
4649 // Test sending SetReceivedConnectionOptions when FEC send policy is
4650 // FEC_ANY_TRIGGER.
4651 if (GetParam().fec_send_policy == FEC_ALARM_TRIGGER) {
4652 return;
4654 connection_.set_perspective(Perspective::IS_SERVER);
4656 // Test ReceivedConnectionOptions.
4657 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4658 QuicConfig config;
4659 QuicTagVector copt;
4660 copt.push_back(kFSPA);
4661 QuicConfigPeer::SetReceivedConnectionOptions(&config, copt);
4662 EXPECT_EQ(FEC_ANY_TRIGGER, generator_->fec_send_policy());
4663 connection_.SetFromConfig(config);
4664 EXPECT_EQ(FEC_ALARM_TRIGGER, generator_->fec_send_policy());
4667 // TODO(rtenneti): Delete this code after the 0.25 RTT FEC experiment.
4668 TEST_P(QuicConnectionTest, FecRTTMultiplierReceivedConnectionOption) {
4669 connection_.set_perspective(Perspective::IS_SERVER);
4671 // Test ReceivedConnectionOptions.
4672 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4673 QuicConfig config;
4674 QuicTagVector copt;
4675 copt.push_back(kFRTT);
4676 QuicConfigPeer::SetReceivedConnectionOptions(&config, copt);
4677 float rtt_multiplier_for_fec_timeout =
4678 generator_->rtt_multiplier_for_fec_timeout();
4679 connection_.SetFromConfig(config);
4680 // New RTT multiplier is half of the old RTT multiplier.
4681 EXPECT_EQ(rtt_multiplier_for_fec_timeout,
4682 generator_->rtt_multiplier_for_fec_timeout() * 2);
4685 TEST_P(QuicConnectionTest, DoNotSendGoAwayTwice) {
4686 EXPECT_FALSE(connection_.goaway_sent());
4687 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4688 connection_.SendGoAway(QUIC_PEER_GOING_AWAY, kHeadersStreamId, "Going Away.");
4689 EXPECT_TRUE(connection_.goaway_sent());
4690 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4691 connection_.SendGoAway(QUIC_PEER_GOING_AWAY, kHeadersStreamId, "Going Away.");
4694 } // namespace
4695 } // namespace test
4696 } // namespace net