Delete unused downloads page asset.
[chromium-blink-merge.git] / net / quic / quic_connection_test.cc
blob42cd54f2ebe78530a8b5fd6d8981f84fb69aab91
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(QuicPacketNumber packet_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(QuicPacketNumber packet_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 QuicPacketNumber packet_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, packet_number, *packet, buffer, kMaxPacketSize);
439 delete packet;
440 OnSerializedPacket(SerializedPacket(
441 packet_number, PACKET_6BYTE_PACKET_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 packet_number_length_(PACKET_6BYTE_PACKET_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(PacketNumberSet()));
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 QuicPacketNumber 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(QuicPacketNumber 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(QuicPacketNumber number,
757 QuicFecGroupNumber fec_group,
758 bool entropy_flag) {
759 return ProcessDataPacketAtLevel(number, fec_group, entropy_flag,
760 ENCRYPTION_NONE);
763 size_t ProcessDataPacketAtLevel(QuicPacketNumber 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(QuicPacketNumber 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(QuicPacketNumber number,
786 bool expect_revival,
787 bool entropy_flag) {
788 if (expect_revival) {
789 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
791 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1).RetiresOnSaturation();
792 return ProcessDataPacket(number, 1, entropy_flag);
795 // Processes an FEC packet that covers the packets that would have been
796 // received.
797 size_t ProcessFecPacket(QuicPacketNumber number,
798 QuicPacketNumber min_protected_packet,
799 bool expect_revival,
800 bool entropy_flag,
801 QuicPacket* packet) {
802 if (expect_revival) {
803 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
806 // Construct the decrypted data packet so we can compute the correct
807 // redundancy. If |packet| has been provided then use that, otherwise
808 // construct a default data packet.
809 scoped_ptr<QuicPacket> data_packet;
810 if (packet) {
811 data_packet.reset(packet);
812 } else {
813 data_packet.reset(ConstructDataPacket(number, 1, !kEntropyFlag));
816 QuicPacketHeader header;
817 header.public_header.connection_id = connection_id_;
818 header.public_header.packet_number_length = packet_number_length_;
819 header.public_header.connection_id_length = connection_id_length_;
820 header.packet_packet_number = number;
821 header.entropy_flag = entropy_flag;
822 header.fec_flag = true;
823 header.is_in_fec_group = IN_FEC_GROUP;
824 header.fec_group = min_protected_packet;
825 QuicFecData fec_data;
826 fec_data.fec_group = header.fec_group;
828 // Since all data packets in this test have the same payload, the
829 // redundancy is either equal to that payload or the xor of that payload
830 // with itself, depending on the number of packets.
831 if (((number - min_protected_packet) % 2) == 0) {
832 for (size_t i = GetStartOfFecProtectedData(
833 header.public_header.connection_id_length,
834 header.public_header.version_flag,
835 header.public_header.packet_number_length);
836 i < data_packet->length(); ++i) {
837 data_packet->mutable_data()[i] ^= data_packet->data()[i];
840 fec_data.redundancy = data_packet->FecProtectedData();
842 scoped_ptr<QuicPacket> fec_packet(framer_.BuildFecPacket(header, fec_data));
843 char buffer[kMaxPacketSize];
844 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPayload(
845 ENCRYPTION_NONE, number, *fec_packet, buffer, kMaxPacketSize));
847 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
848 return encrypted->length();
851 QuicByteCount SendStreamDataToPeer(QuicStreamId id,
852 StringPiece data,
853 QuicStreamOffset offset,
854 bool fin,
855 QuicPacketNumber* last_packet) {
856 QuicByteCount packet_size;
857 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
858 .WillOnce(DoAll(SaveArg<3>(&packet_size), Return(true)));
859 connection_.SendStreamDataWithString(id, data, offset, fin, nullptr);
860 if (last_packet != nullptr) {
861 *last_packet = creator_->packet_number();
863 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
864 .Times(AnyNumber());
865 return packet_size;
868 void SendAckPacketToPeer() {
869 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
870 connection_.SendAck();
871 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
872 .Times(AnyNumber());
875 void ProcessAckPacket(QuicPacketNumber packet_number, QuicAckFrame* frame) {
876 QuicPacketCreatorPeer::SetPacketNumber(&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(QuicPacketNumber 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(QuicPacketNumber number,
903 QuicFecGroupNumber fec_group,
904 bool entropy_flag) {
905 QuicPacketHeader header;
906 header.public_header.connection_id = connection_id_;
907 header.public_header.packet_number_length = packet_number_length_;
908 header.public_header.connection_id_length = connection_id_length_;
909 header.entropy_flag = entropy_flag;
910 header.packet_packet_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(QuicPacketNumber number,
920 QuicFecGroupNumber fec_group) {
921 QuicPacketHeader header;
922 header.public_header.connection_id = connection_id_;
923 header.packet_packet_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(QuicPacketNumber 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 QuicPacketNumber least_unacked) {
956 QuicStopWaitingFrame frame;
957 frame.least_unacked = least_unacked;
958 return frame;
961 // Explicitly nack a packet.
962 void NackPacket(QuicPacketNumber 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(QuicPacketNumber 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 QuicPacketNumberLength packet_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_packet_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 QuicPacketNumber num_packets = 256 * 2 + 1;
1193 for (QuicPacketNumber i = 0; i < num_packets; ++i) {
1194 SendStreamDataToPeer(3, "foo", i * 3, !kFin, nullptr);
1197 QuicAckFrame frame = InitAckFrame(num_packets);
1198 PacketNumberSet lost_packets;
1199 // Create an ack with 256 nacks, none adjacent to one another.
1200 for (QuicPacketNumber 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(PacketNumberSet()));
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 QuicPacketNumber 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 PacketNumberSet 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 QuicPacketNumber 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(PacketNumberSet()));
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(PacketNumberSet()));
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(PacketNumberSet()));
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::SetPacketNumber(&peer_creator_, 5);
1372 QuicStopWaitingFrame frame = InitStopWaitingFrame(2);
1373 ProcessStopWaitingPacket(&frame);
1375 // Change it to 1, but lower the packet number to fake out-of-order packets.
1376 // This should be fine.
1377 QuicPacketCreatorPeer::SetPacketNumber(&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::SetPacketNumber(&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 (QuicPacketNumber 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::SetPacketNumber(&peer_creator_, 1);
1463 QuicAckFrame frame1 = InitAckFrame(0);
1464 ProcessAckPacket(&frame1);
1467 TEST_P(QuicConnectionTest, SendingDifferentSequenceNumberLengthsBandwidth) {
1468 QuicPacketNumber last_packet;
1469 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet);
1470 EXPECT_EQ(1u, last_packet);
1471 EXPECT_EQ(PACKET_1BYTE_PACKET_NUMBER,
1472 QuicPacketCreatorPeer::NextPacketNumberLength(creator_));
1473 EXPECT_EQ(PACKET_1BYTE_PACKET_NUMBER,
1474 writer_->header().public_header.packet_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_PACKET_NUMBER,
1482 QuicPacketCreatorPeer::NextPacketNumberLength(creator_));
1483 // The 1 packet lag is due to the packet number length being recalculated in
1484 // QuicConnection after a packet is sent.
1485 EXPECT_EQ(PACKET_1BYTE_PACKET_NUMBER,
1486 writer_->header().public_header.packet_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_PACKET_NUMBER,
1494 QuicPacketCreatorPeer::NextPacketNumberLength(creator_));
1495 EXPECT_EQ(PACKET_2BYTE_PACKET_NUMBER,
1496 writer_->header().public_header.packet_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_PACKET_NUMBER,
1504 QuicPacketCreatorPeer::NextPacketNumberLength(creator_));
1505 EXPECT_EQ(PACKET_4BYTE_PACKET_NUMBER,
1506 writer_->header().public_header.packet_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_PACKET_NUMBER,
1514 QuicPacketCreatorPeer::NextPacketNumberLength(creator_));
1515 EXPECT_EQ(PACKET_4BYTE_PACKET_NUMBER,
1516 writer_->header().public_header.packet_number_length);
1519 // TODO(ianswett): Re-enable this test by finding a good way to test different
1520 // packet number lengths without sending packets with giant gaps.
1521 TEST_P(QuicConnectionTest,
1522 DISABLED_SendingDifferentSequenceNumberLengthsUnackedDelta) {
1523 QuicPacketNumber last_packet;
1524 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet);
1525 EXPECT_EQ(1u, last_packet);
1526 EXPECT_EQ(PACKET_1BYTE_PACKET_NUMBER,
1527 QuicPacketCreatorPeer::NextPacketNumberLength(creator_));
1528 EXPECT_EQ(PACKET_1BYTE_PACKET_NUMBER,
1529 writer_->header().public_header.packet_number_length);
1531 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 100);
1533 SendStreamDataToPeer(1, "bar", 3, !kFin, &last_packet);
1534 EXPECT_EQ(PACKET_2BYTE_PACKET_NUMBER,
1535 QuicPacketCreatorPeer::NextPacketNumberLength(creator_));
1536 EXPECT_EQ(PACKET_1BYTE_PACKET_NUMBER,
1537 writer_->header().public_header.packet_number_length);
1539 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 100 * 256);
1541 SendStreamDataToPeer(1, "foo", 6, !kFin, &last_packet);
1542 EXPECT_EQ(PACKET_4BYTE_PACKET_NUMBER,
1543 QuicPacketCreatorPeer::NextPacketNumberLength(creator_));
1544 EXPECT_EQ(PACKET_2BYTE_PACKET_NUMBER,
1545 writer_->header().public_header.packet_number_length);
1547 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 100 * 256 * 256);
1549 SendStreamDataToPeer(1, "bar", 9, !kFin, &last_packet);
1550 EXPECT_EQ(PACKET_4BYTE_PACKET_NUMBER,
1551 QuicPacketCreatorPeer::NextPacketNumberLength(creator_));
1552 EXPECT_EQ(PACKET_4BYTE_PACKET_NUMBER,
1553 writer_->header().public_header.packet_number_length);
1555 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 100 * 256 * 256 * 256);
1557 SendStreamDataToPeer(1, "foo", 12, !kFin, &last_packet);
1558 EXPECT_EQ(PACKET_6BYTE_PACKET_NUMBER,
1559 QuicPacketCreatorPeer::NextPacketNumberLength(creator_));
1560 EXPECT_EQ(PACKET_4BYTE_PACKET_NUMBER,
1561 writer_->header().public_header.packet_number_length);
1564 TEST_P(QuicConnectionTest, BasicSending) {
1565 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1566 QuicPacketNumber last_packet;
1567 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet); // Packet 1
1568 EXPECT_EQ(1u, last_packet);
1569 SendAckPacketToPeer(); // Packet 2
1571 EXPECT_EQ(1u, least_unacked());
1573 SendAckPacketToPeer(); // Packet 3
1574 EXPECT_EQ(1u, least_unacked());
1576 SendStreamDataToPeer(1, "bar", 3, !kFin, &last_packet); // Packet 4
1577 EXPECT_EQ(4u, last_packet);
1578 SendAckPacketToPeer(); // Packet 5
1579 EXPECT_EQ(1u, least_unacked());
1581 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1583 // Peer acks up to packet 3.
1584 QuicAckFrame frame = InitAckFrame(3);
1585 ProcessAckPacket(&frame);
1586 SendAckPacketToPeer(); // Packet 6
1588 // As soon as we've acked one, we skip ack packets 2 and 3 and note lack of
1589 // ack for 4.
1590 EXPECT_EQ(4u, least_unacked());
1592 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1594 // Peer acks up to packet 4, the last packet.
1595 QuicAckFrame frame2 = InitAckFrame(6);
1596 ProcessAckPacket(&frame2); // Acks don't instigate acks.
1598 // Verify that we did not send an ack.
1599 EXPECT_EQ(6u, writer_->header().packet_packet_number);
1601 // So the last ack has not changed.
1602 EXPECT_EQ(4u, least_unacked());
1604 // If we force an ack, we shouldn't change our retransmit state.
1605 SendAckPacketToPeer(); // Packet 7
1606 EXPECT_EQ(7u, least_unacked());
1608 // But if we send more data it should.
1609 SendStreamDataToPeer(1, "eep", 6, !kFin, &last_packet); // Packet 8
1610 EXPECT_EQ(8u, last_packet);
1611 SendAckPacketToPeer(); // Packet 9
1612 EXPECT_EQ(7u, least_unacked());
1615 // QuicConnection should record the the packet sent-time prior to sending the
1616 // packet.
1617 TEST_P(QuicConnectionTest, RecordSentTimeBeforePacketSent) {
1618 // We're using a MockClock for the tests, so we have complete control over the
1619 // time.
1620 // Our recorded timestamp for the last packet sent time will be passed in to
1621 // the send_algorithm. Make sure that it is set to the correct value.
1622 QuicTime actual_recorded_send_time = QuicTime::Zero();
1623 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1624 .WillOnce(DoAll(SaveArg<0>(&actual_recorded_send_time), Return(true)));
1626 // First send without any pause and check the result.
1627 QuicTime expected_recorded_send_time = clock_.Now();
1628 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
1629 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
1630 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
1631 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
1633 // Now pause during the write, and check the results.
1634 actual_recorded_send_time = QuicTime::Zero();
1635 const QuicTime::Delta write_pause_time_delta =
1636 QuicTime::Delta::FromMilliseconds(5000);
1637 SetWritePauseTimeDelta(write_pause_time_delta);
1638 expected_recorded_send_time = clock_.Now();
1640 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1641 .WillOnce(DoAll(SaveArg<0>(&actual_recorded_send_time), Return(true)));
1642 connection_.SendStreamDataWithString(2, "baz", 0, !kFin, nullptr);
1643 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
1644 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
1645 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
1648 TEST_P(QuicConnectionTest, FECSending) {
1649 // All packets carry version info till version is negotiated.
1650 size_t payload_length;
1651 // GetPacketLengthForOneStream() assumes a stream offset of 0 in determining
1652 // packet length. The size of the offset field in a stream frame is 0 for
1653 // offset 0, and 2 for non-zero offsets up through 64K. Increase
1654 // max_packet_length by 2 so that subsequent packets containing subsequent
1655 // stream frames with non-zero offets will fit within the packet length.
1656 size_t length =
1657 2 + GetPacketLengthForOneStream(connection_.version(), kIncludeVersion,
1658 PACKET_8BYTE_CONNECTION_ID,
1659 PACKET_1BYTE_PACKET_NUMBER, IN_FEC_GROUP,
1660 &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, PACKET_8BYTE_CONNECTION_ID,
1685 PACKET_1BYTE_PACKET_NUMBER, IN_FEC_GROUP, &payload_length);
1686 connection_.set_max_packet_length(length);
1687 EXPECT_TRUE(creator_->IsFecEnabled());
1689 EXPECT_EQ(0u, connection_.NumQueuedPackets());
1690 BlockOnNextWrite();
1691 const string payload(payload_length, 'a');
1692 connection_.SendStreamDataWithStringWithFec(1, payload, 0, !kFin, nullptr);
1693 EXPECT_FALSE(creator_->IsFecGroupOpen());
1694 EXPECT_FALSE(creator_->IsFecProtected());
1695 if (generator_->fec_send_policy() == FEC_ALARM_TRIGGER) {
1696 // Expect the first data packet to be queued and not the FEC packet.
1697 EXPECT_EQ(1u, connection_.NumQueuedPackets());
1698 } else {
1699 // Expect the first data packet and the fec packet to be queued.
1700 EXPECT_EQ(2u, connection_.NumQueuedPackets());
1704 TEST_P(QuicConnectionTest, FECAlarmStoppedWhenFECPacketSent) {
1705 EXPECT_TRUE(creator_->IsFecEnabled());
1706 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1707 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1709 creator_->set_max_packets_per_fec_group(2);
1711 // 1 Data packet. FEC alarm should be set.
1712 EXPECT_CALL(*send_algorithm_,
1713 OnPacketSent(_, _, 1u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1714 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, true, nullptr);
1715 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1717 if (generator_->fec_send_policy() == FEC_ALARM_TRIGGER) {
1718 // If FEC send policy is FEC_ALARM_TRIGGER, FEC packet is not sent.
1719 // FEC alarm should not be set.
1720 EXPECT_CALL(*send_algorithm_,
1721 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1722 } else {
1723 // Second data packet triggers FEC packet out. FEC alarm should not be set.
1724 EXPECT_CALL(*send_algorithm_,
1725 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(2);
1727 connection_.SendStreamDataWithStringWithFec(5, "foo", 0, true, nullptr);
1728 if (generator_->fec_send_policy() == FEC_ANY_TRIGGER) {
1729 EXPECT_TRUE(writer_->header().fec_flag);
1731 EXPECT_FALSE(creator_->IsFecGroupOpen());
1732 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1735 TEST_P(QuicConnectionTest, FECAlarmStoppedOnConnectionClose) {
1736 EXPECT_TRUE(creator_->IsFecEnabled());
1737 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1738 creator_->set_max_packets_per_fec_group(100);
1740 // 1 Data packet. FEC alarm should be set.
1741 EXPECT_CALL(*send_algorithm_,
1742 OnPacketSent(_, _, 1u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1743 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, kFin, nullptr);
1744 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1746 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NO_ERROR, false));
1747 // Closing connection should stop the FEC alarm.
1748 connection_.CloseConnection(QUIC_NO_ERROR, /*from_peer=*/false);
1749 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1752 TEST_P(QuicConnectionTest, RemoveFECFromInflightOnRetransmissionTimeout) {
1753 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1754 EXPECT_TRUE(creator_->IsFecEnabled());
1755 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1756 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1758 // 1 Data packet. FEC alarm should be set.
1759 EXPECT_CALL(*send_algorithm_,
1760 OnPacketSent(_, _, 1u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1761 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, !kFin, nullptr);
1762 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1763 size_t protected_packet =
1764 QuicSentPacketManagerPeer::GetBytesInFlight(manager_);
1766 // Force FEC timeout to send FEC packet out.
1767 EXPECT_CALL(*send_algorithm_,
1768 OnPacketSent(_, _, 2u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1769 connection_.GetFecAlarm()->Fire();
1770 EXPECT_TRUE(writer_->header().fec_flag);
1772 size_t fec_packet = protected_packet;
1773 EXPECT_EQ(protected_packet + fec_packet,
1774 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1775 clock_.AdvanceTime(DefaultRetransmissionTime());
1777 // On RTO, both data and FEC packets are removed from inflight, only the data
1778 // packet is retransmitted, and this retransmission (but not FEC) gets added
1779 // back into the inflight.
1780 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
1781 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1782 connection_.GetRetransmissionAlarm()->Fire();
1784 // The retransmission of packet 1 will be 3 bytes smaller than packet 1, since
1785 // the first transmission will have 1 byte for FEC group number and 2 bytes of
1786 // stream frame size, which are absent in the retransmission.
1787 size_t retransmitted_packet = protected_packet - 3;
1788 EXPECT_EQ(protected_packet + retransmitted_packet,
1789 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1790 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1792 // Receive ack for the retransmission. No data should be outstanding.
1793 QuicAckFrame ack = InitAckFrame(3);
1794 NackPacket(1, &ack);
1795 NackPacket(2, &ack);
1796 PacketNumberSet lost_packets;
1797 lost_packets.insert(1);
1798 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1799 .WillOnce(Return(lost_packets));
1800 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1801 ProcessAckPacket(&ack);
1803 // Ensure the alarm is not set since all packets have been acked or abandoned.
1804 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
1805 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1808 TEST_P(QuicConnectionTest, RemoveFECFromInflightOnLossRetransmission) {
1809 EXPECT_TRUE(creator_->IsFecEnabled());
1810 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1812 // 1 FEC-protected data packet. FEC alarm should be set.
1813 EXPECT_CALL(*send_algorithm_,
1814 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1815 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, kFin, nullptr);
1816 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1817 size_t protected_packet =
1818 QuicSentPacketManagerPeer::GetBytesInFlight(manager_);
1820 // Force FEC timeout to send FEC packet out.
1821 EXPECT_CALL(*send_algorithm_,
1822 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1823 connection_.GetFecAlarm()->Fire();
1824 EXPECT_TRUE(writer_->header().fec_flag);
1825 size_t fec_packet = protected_packet;
1826 EXPECT_EQ(protected_packet + fec_packet,
1827 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1829 // Send more data to trigger NACKs. Note that all data starts at stream offset
1830 // 0 to ensure the same packet size, for ease of testing.
1831 EXPECT_CALL(*send_algorithm_,
1832 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(4);
1833 connection_.SendStreamDataWithString(5, "foo", 0, kFin, nullptr);
1834 connection_.SendStreamDataWithString(7, "foo", 0, kFin, nullptr);
1835 connection_.SendStreamDataWithString(9, "foo", 0, kFin, nullptr);
1836 connection_.SendStreamDataWithString(11, "foo", 0, kFin, nullptr);
1838 // An unprotected packet will be 3 bytes smaller than an FEC-protected packet,
1839 // since the protected packet will have 1 byte for FEC group number and
1840 // 2 bytes of stream frame size, which are absent in the unprotected packet.
1841 size_t unprotected_packet = protected_packet - 3;
1842 EXPECT_EQ(protected_packet + fec_packet + 4 * unprotected_packet,
1843 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1844 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1846 // Ack data packets, and NACK FEC packet and one data packet. Triggers
1847 // NACK-based loss detection of both packets, but only data packet is
1848 // retransmitted and considered oustanding.
1849 QuicAckFrame ack = InitAckFrame(6);
1850 NackPacket(2, &ack);
1851 NackPacket(3, &ack);
1852 PacketNumberSet lost_packets;
1853 lost_packets.insert(2);
1854 lost_packets.insert(3);
1855 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1856 .WillOnce(Return(lost_packets));
1857 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1858 EXPECT_CALL(*send_algorithm_,
1859 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1860 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1861 ProcessAckPacket(&ack);
1862 // On receiving this ack from the server, the client will no longer send
1863 // version number in subsequent packets, including in this retransmission.
1864 size_t unprotected_packet_no_version = unprotected_packet - 4;
1865 EXPECT_EQ(unprotected_packet_no_version,
1866 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1868 // Receive ack for the retransmission. No data should be outstanding.
1869 QuicAckFrame ack2 = InitAckFrame(7);
1870 NackPacket(2, &ack2);
1871 NackPacket(3, &ack2);
1872 PacketNumberSet lost_packets2;
1873 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1874 .WillOnce(Return(lost_packets2));
1875 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1876 ProcessAckPacket(&ack2);
1877 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1880 TEST_P(QuicConnectionTest, FECRemainsInflightOnTLPOfEarlierData) {
1881 // This test checks if TLP is sent correctly when a data and an FEC packet
1882 // are outstanding. TLP should be sent for the data packet when the
1883 // retransmission alarm fires.
1884 // Turn on TLP for this test.
1885 QuicSentPacketManagerPeer::SetMaxTailLossProbes(manager_, 1);
1886 EXPECT_TRUE(creator_->IsFecEnabled());
1887 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1888 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1890 // 1 Data packet. FEC alarm should be set.
1891 EXPECT_CALL(*send_algorithm_,
1892 OnPacketSent(_, _, 1u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1893 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, kFin, nullptr);
1894 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1895 size_t protected_packet =
1896 QuicSentPacketManagerPeer::GetBytesInFlight(manager_);
1897 EXPECT_LT(0u, protected_packet);
1899 // Force FEC timeout to send FEC packet out.
1900 EXPECT_CALL(*send_algorithm_,
1901 OnPacketSent(_, _, 2u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1902 connection_.GetFecAlarm()->Fire();
1903 EXPECT_TRUE(writer_->header().fec_flag);
1904 size_t fec_packet = protected_packet;
1905 EXPECT_EQ(protected_packet + fec_packet,
1906 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1908 // TLP alarm should be set.
1909 QuicTime retransmission_time =
1910 connection_.GetRetransmissionAlarm()->deadline();
1911 EXPECT_NE(QuicTime::Zero(), retransmission_time);
1912 // Simulate the retransmission alarm firing and sending a TLP, so send
1913 // algorithm's OnRetransmissionTimeout is not called.
1914 clock_.AdvanceTime(retransmission_time.Subtract(clock_.Now()));
1915 EXPECT_CALL(*send_algorithm_,
1916 OnPacketSent(_, _, 3u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1917 connection_.GetRetransmissionAlarm()->Fire();
1918 // The TLP retransmission of packet 1 will be 3 bytes smaller than packet 1,
1919 // since packet 1 will have 1 byte for FEC group number and 2 bytes of stream
1920 // frame size, which are absent in the the TLP retransmission.
1921 size_t tlp_packet = protected_packet - 3;
1922 EXPECT_EQ(protected_packet + fec_packet + tlp_packet,
1923 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1926 TEST_P(QuicConnectionTest, FECRemainsInflightOnTLPOfLaterData) {
1927 // Tests if TLP is sent correctly when data packet 1 and an FEC packet are
1928 // sent followed by data packet 2, and data packet 1 is acked. TLP should be
1929 // sent for data packet 2 when the retransmission alarm fires. Turn on TLP for
1930 // this test.
1931 QuicSentPacketManagerPeer::SetMaxTailLossProbes(manager_, 1);
1932 EXPECT_TRUE(creator_->IsFecEnabled());
1933 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1934 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1936 // 1 Data packet. FEC alarm should be set.
1937 EXPECT_CALL(*send_algorithm_,
1938 OnPacketSent(_, _, 1u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1939 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, kFin, nullptr);
1940 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1941 size_t protected_packet =
1942 QuicSentPacketManagerPeer::GetBytesInFlight(manager_);
1943 EXPECT_LT(0u, protected_packet);
1945 // Force FEC timeout to send FEC packet out.
1946 EXPECT_CALL(*send_algorithm_,
1947 OnPacketSent(_, _, 2u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1948 connection_.GetFecAlarm()->Fire();
1949 EXPECT_TRUE(writer_->header().fec_flag);
1950 // Protected data packet and FEC packet oustanding.
1951 size_t fec_packet = protected_packet;
1952 EXPECT_EQ(protected_packet + fec_packet,
1953 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1955 // Send 1 unprotected data packet. No FEC alarm should be set.
1956 EXPECT_CALL(*send_algorithm_,
1957 OnPacketSent(_, _, 3u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1958 connection_.SendStreamDataWithString(5, "foo", 0, kFin, nullptr);
1959 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1960 // Protected data packet, FEC packet, and unprotected data packet oustanding.
1961 // An unprotected packet will be 3 bytes smaller than an FEC-protected packet,
1962 // since the protected packet will have 1 byte for FEC group number and
1963 // 2 bytes of stream frame size, which are absent in the unprotected packet.
1964 size_t unprotected_packet = protected_packet - 3;
1965 EXPECT_EQ(protected_packet + fec_packet + unprotected_packet,
1966 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1968 // Receive ack for first data packet. FEC and second data packet are still
1969 // outstanding.
1970 QuicAckFrame ack = InitAckFrame(1);
1971 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1972 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1973 ProcessAckPacket(&ack);
1974 // FEC packet and unprotected data packet oustanding.
1975 EXPECT_EQ(fec_packet + unprotected_packet,
1976 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1978 // TLP alarm should be set.
1979 QuicTime retransmission_time =
1980 connection_.GetRetransmissionAlarm()->deadline();
1981 EXPECT_NE(QuicTime::Zero(), retransmission_time);
1982 // Simulate the retransmission alarm firing and sending a TLP, so send
1983 // algorithm's OnRetransmissionTimeout is not called.
1984 clock_.AdvanceTime(retransmission_time.Subtract(clock_.Now()));
1985 EXPECT_CALL(*send_algorithm_,
1986 OnPacketSent(_, _, 4u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1987 connection_.GetRetransmissionAlarm()->Fire();
1989 // Having received an ack from the server, the client will no longer send
1990 // version number in subsequent packets, including in this retransmission.
1991 size_t tlp_packet_no_version = unprotected_packet - 4;
1992 EXPECT_EQ(fec_packet + unprotected_packet + tlp_packet_no_version,
1993 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1996 TEST_P(QuicConnectionTest, NoTLPForFECPacket) {
1997 // Turn on TLP for this test.
1998 QuicSentPacketManagerPeer::SetMaxTailLossProbes(manager_, 1);
1999 EXPECT_TRUE(creator_->IsFecEnabled());
2000 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2002 // Send 1 FEC-protected data packet. FEC alarm should be set.
2003 EXPECT_CALL(*send_algorithm_,
2004 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
2005 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, !kFin, nullptr);
2006 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
2007 // Force FEC timeout to send FEC packet out.
2008 EXPECT_CALL(*send_algorithm_,
2009 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
2010 connection_.GetFecAlarm()->Fire();
2011 EXPECT_TRUE(writer_->header().fec_flag);
2013 // Ack data packet, but not FEC packet.
2014 QuicAckFrame ack = InitAckFrame(1);
2015 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2016 ProcessAckPacket(&ack);
2018 // No TLP alarm for FEC, but retransmission alarm should be set for an RTO.
2019 EXPECT_LT(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
2020 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2021 QuicTime rto_time = connection_.GetRetransmissionAlarm()->deadline();
2022 EXPECT_NE(QuicTime::Zero(), rto_time);
2024 // Simulate the retransmission alarm firing. FEC packet is no longer
2025 // outstanding.
2026 clock_.AdvanceTime(rto_time.Subtract(clock_.Now()));
2027 connection_.GetRetransmissionAlarm()->Fire();
2029 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
2030 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
2033 TEST_P(QuicConnectionTest, FramePacking) {
2034 CongestionBlockWrites();
2036 // Send an ack and two stream frames in 1 packet by queueing them.
2037 connection_.SendAck();
2038 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
2039 IgnoreResult(InvokeWithoutArgs(&connection_,
2040 &TestConnection::SendStreamData3)),
2041 IgnoreResult(InvokeWithoutArgs(&connection_,
2042 &TestConnection::SendStreamData5))));
2044 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2045 CongestionUnblockWrites();
2046 connection_.GetSendAlarm()->Fire();
2047 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2048 EXPECT_FALSE(connection_.HasQueuedData());
2050 // Parse the last packet and ensure it's an ack and two stream frames from
2051 // two different streams.
2052 EXPECT_EQ(4u, writer_->frame_count());
2053 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
2054 EXPECT_FALSE(writer_->ack_frames().empty());
2055 ASSERT_EQ(2u, writer_->stream_frames().size());
2056 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id);
2057 EXPECT_EQ(kClientDataStreamId2, writer_->stream_frames()[1].stream_id);
2060 TEST_P(QuicConnectionTest, FramePackingNonCryptoThenCrypto) {
2061 CongestionBlockWrites();
2063 // Send an ack and two stream frames (one non-crypto, then one crypto) in 2
2064 // packets by queueing them.
2065 connection_.SendAck();
2066 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
2067 IgnoreResult(InvokeWithoutArgs(&connection_,
2068 &TestConnection::SendStreamData3)),
2069 IgnoreResult(InvokeWithoutArgs(&connection_,
2070 &TestConnection::SendCryptoStreamData))));
2072 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
2073 CongestionUnblockWrites();
2074 connection_.GetSendAlarm()->Fire();
2075 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2076 EXPECT_FALSE(connection_.HasQueuedData());
2078 // Parse the last packet and ensure it's the crypto stream frame.
2079 EXPECT_EQ(1u, writer_->frame_count());
2080 ASSERT_EQ(1u, writer_->stream_frames().size());
2081 EXPECT_EQ(kCryptoStreamId, writer_->stream_frames()[0].stream_id);
2084 TEST_P(QuicConnectionTest, FramePackingCryptoThenNonCrypto) {
2085 CongestionBlockWrites();
2087 // Send an ack and two stream frames (one crypto, then one non-crypto) in 2
2088 // packets by queueing them.
2089 connection_.SendAck();
2090 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
2091 IgnoreResult(InvokeWithoutArgs(&connection_,
2092 &TestConnection::SendCryptoStreamData)),
2093 IgnoreResult(InvokeWithoutArgs(&connection_,
2094 &TestConnection::SendStreamData3))));
2096 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
2097 CongestionUnblockWrites();
2098 connection_.GetSendAlarm()->Fire();
2099 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2100 EXPECT_FALSE(connection_.HasQueuedData());
2102 // Parse the last packet and ensure it's the stream frame from stream 3.
2103 EXPECT_EQ(1u, writer_->frame_count());
2104 ASSERT_EQ(1u, writer_->stream_frames().size());
2105 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id);
2108 TEST_P(QuicConnectionTest, FramePackingFEC) {
2109 EXPECT_TRUE(creator_->IsFecEnabled());
2111 CongestionBlockWrites();
2113 // Queue an ack and two stream frames. Ack gets flushed when FEC is turned on
2114 // for sending protected data; two stream frames are packed in 1 packet.
2115 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
2116 IgnoreResult(InvokeWithoutArgs(
2117 &connection_, &TestConnection::SendStreamData3WithFec)),
2118 IgnoreResult(InvokeWithoutArgs(
2119 &connection_, &TestConnection::SendStreamData5WithFec))));
2120 connection_.SendAck();
2122 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
2123 CongestionUnblockWrites();
2124 connection_.GetSendAlarm()->Fire();
2125 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2126 EXPECT_FALSE(connection_.HasQueuedData());
2128 // Parse the last packet and ensure it's in an fec group.
2129 EXPECT_EQ(2u, writer_->header().fec_group);
2130 EXPECT_EQ(2u, writer_->frame_count());
2132 // FEC alarm should be set.
2133 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
2136 TEST_P(QuicConnectionTest, FramePackingAckResponse) {
2137 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2138 // Process a data packet to queue up a pending ack.
2139 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2140 ProcessDataPacket(1, 1, kEntropyFlag);
2142 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
2143 IgnoreResult(InvokeWithoutArgs(&connection_,
2144 &TestConnection::SendStreamData3)),
2145 IgnoreResult(InvokeWithoutArgs(&connection_,
2146 &TestConnection::SendStreamData5))));
2148 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2150 // Process an ack to cause the visitor's OnCanWrite to be invoked.
2151 QuicAckFrame ack_one = InitAckFrame(0);
2152 ProcessAckPacket(3, &ack_one);
2154 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2155 EXPECT_FALSE(connection_.HasQueuedData());
2157 // Parse the last packet and ensure it's an ack and two stream frames from
2158 // two different streams.
2159 EXPECT_EQ(4u, writer_->frame_count());
2160 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
2161 EXPECT_FALSE(writer_->ack_frames().empty());
2162 ASSERT_EQ(2u, writer_->stream_frames().size());
2163 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id);
2164 EXPECT_EQ(kClientDataStreamId2, writer_->stream_frames()[1].stream_id);
2167 TEST_P(QuicConnectionTest, FramePackingSendv) {
2168 // Send data in 1 packet by writing multiple blocks in a single iovector
2169 // using writev.
2170 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2172 char data[] = "ABCD";
2173 struct iovec iov[2];
2174 iov[0].iov_base = data;
2175 iov[0].iov_len = 2;
2176 iov[1].iov_base = data + 2;
2177 iov[1].iov_len = 2;
2178 connection_.SendStreamData(1, QuicIOVector(iov, 2, 4), 0, !kFin,
2179 MAY_FEC_PROTECT, nullptr);
2181 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2182 EXPECT_FALSE(connection_.HasQueuedData());
2184 // Parse the last packet and ensure multiple iovector blocks have
2185 // been packed into a single stream frame from one stream.
2186 EXPECT_EQ(1u, writer_->frame_count());
2187 EXPECT_EQ(1u, writer_->stream_frames().size());
2188 QuicStreamFrame frame = writer_->stream_frames()[0];
2189 EXPECT_EQ(1u, frame.stream_id);
2190 EXPECT_EQ("ABCD", frame.data);
2193 TEST_P(QuicConnectionTest, FramePackingSendvQueued) {
2194 // Try to send two stream frames in 1 packet by using writev.
2195 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2197 BlockOnNextWrite();
2198 char data[] = "ABCD";
2199 struct iovec iov[2];
2200 iov[0].iov_base = data;
2201 iov[0].iov_len = 2;
2202 iov[1].iov_base = data + 2;
2203 iov[1].iov_len = 2;
2204 connection_.SendStreamData(1, QuicIOVector(iov, 2, 4), 0, !kFin,
2205 MAY_FEC_PROTECT, nullptr);
2207 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2208 EXPECT_TRUE(connection_.HasQueuedData());
2210 // Unblock the writes and actually send.
2211 writer_->SetWritable();
2212 connection_.OnCanWrite();
2213 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2215 // Parse the last packet and ensure it's one stream frame from one stream.
2216 EXPECT_EQ(1u, writer_->frame_count());
2217 EXPECT_EQ(1u, writer_->stream_frames().size());
2218 EXPECT_EQ(1u, writer_->stream_frames()[0].stream_id);
2221 TEST_P(QuicConnectionTest, SendingZeroBytes) {
2222 // Send a zero byte write with a fin using writev.
2223 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2224 QuicIOVector empty_iov(nullptr, 0, 0);
2225 connection_.SendStreamData(1, empty_iov, 0, kFin, MAY_FEC_PROTECT, nullptr);
2227 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2228 EXPECT_FALSE(connection_.HasQueuedData());
2230 // Parse the last packet and ensure it's one stream frame from one stream.
2231 EXPECT_EQ(1u, writer_->frame_count());
2232 EXPECT_EQ(1u, writer_->stream_frames().size());
2233 EXPECT_EQ(1u, writer_->stream_frames()[0].stream_id);
2234 EXPECT_TRUE(writer_->stream_frames()[0].fin);
2237 TEST_P(QuicConnectionTest, OnCanWrite) {
2238 // Visitor's OnCanWrite will send data, but will have more pending writes.
2239 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
2240 IgnoreResult(InvokeWithoutArgs(&connection_,
2241 &TestConnection::SendStreamData3)),
2242 IgnoreResult(InvokeWithoutArgs(&connection_,
2243 &TestConnection::SendStreamData5))));
2244 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillOnce(Return(true));
2245 EXPECT_CALL(*send_algorithm_,
2246 TimeUntilSend(_, _, _)).WillRepeatedly(
2247 testing::Return(QuicTime::Delta::Zero()));
2249 connection_.OnCanWrite();
2251 // Parse the last packet and ensure it's the two stream frames from
2252 // two different streams.
2253 EXPECT_EQ(2u, writer_->frame_count());
2254 EXPECT_EQ(2u, writer_->stream_frames().size());
2255 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id);
2256 EXPECT_EQ(kClientDataStreamId2, writer_->stream_frames()[1].stream_id);
2259 TEST_P(QuicConnectionTest, RetransmitOnNack) {
2260 QuicPacketNumber last_packet;
2261 QuicByteCount second_packet_size;
2262 SendStreamDataToPeer(3, "foo", 0, !kFin, &last_packet); // Packet 1
2263 second_packet_size =
2264 SendStreamDataToPeer(3, "foos", 3, !kFin, &last_packet); // Packet 2
2265 SendStreamDataToPeer(3, "fooos", 7, !kFin, &last_packet); // Packet 3
2267 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2269 // Don't lose a packet on an ack, and nothing is retransmitted.
2270 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2271 QuicAckFrame ack_one = InitAckFrame(1);
2272 ProcessAckPacket(&ack_one);
2274 // Lose a packet and ensure it triggers retransmission.
2275 QuicAckFrame nack_two = InitAckFrame(3);
2276 NackPacket(2, &nack_two);
2277 PacketNumberSet lost_packets;
2278 lost_packets.insert(2);
2279 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2280 .WillOnce(Return(lost_packets));
2281 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2282 EXPECT_CALL(*send_algorithm_,
2283 OnPacketSent(_, _, _, second_packet_size - kQuicVersionSize, _)).
2284 Times(1);
2285 ProcessAckPacket(&nack_two);
2288 TEST_P(QuicConnectionTest, DoNotSendQueuedPacketForResetStream) {
2289 // Block the connection to queue the packet.
2290 BlockOnNextWrite();
2292 QuicStreamId stream_id = 2;
2293 connection_.SendStreamDataWithString(stream_id, "foo", 0, !kFin, nullptr);
2295 // Now that there is a queued packet, reset the stream.
2296 connection_.SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 14);
2298 // Unblock the connection and verify that only the RST_STREAM is sent.
2299 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2300 writer_->SetWritable();
2301 connection_.OnCanWrite();
2302 EXPECT_EQ(1u, writer_->frame_count());
2303 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
2306 TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnNack) {
2307 QuicStreamId stream_id = 2;
2308 QuicPacketNumber last_packet;
2309 SendStreamDataToPeer(stream_id, "foo", 0, !kFin, &last_packet);
2310 SendStreamDataToPeer(stream_id, "foos", 3, !kFin, &last_packet);
2311 SendStreamDataToPeer(stream_id, "fooos", 7, !kFin, &last_packet);
2313 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2314 connection_.SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 14);
2316 // Lose a packet and ensure it does not trigger retransmission.
2317 QuicAckFrame nack_two = InitAckFrame(last_packet);
2318 NackPacket(last_packet - 1, &nack_two);
2319 PacketNumberSet lost_packets;
2320 lost_packets.insert(last_packet - 1);
2321 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2322 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2323 .WillOnce(Return(lost_packets));
2324 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2325 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
2326 ProcessAckPacket(&nack_two);
2329 TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnRTO) {
2330 QuicStreamId stream_id = 2;
2331 QuicPacketNumber last_packet;
2332 SendStreamDataToPeer(stream_id, "foo", 0, !kFin, &last_packet);
2334 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2335 connection_.SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 14);
2337 // Fire the RTO and verify that the RST_STREAM is resent, not stream data.
2338 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2339 clock_.AdvanceTime(DefaultRetransmissionTime());
2340 connection_.GetRetransmissionAlarm()->Fire();
2341 EXPECT_EQ(1u, writer_->frame_count());
2342 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
2343 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
2346 TEST_P(QuicConnectionTest, DoNotSendPendingRetransmissionForResetStream) {
2347 QuicStreamId stream_id = 2;
2348 QuicPacketNumber last_packet;
2349 SendStreamDataToPeer(stream_id, "foo", 0, !kFin, &last_packet);
2350 SendStreamDataToPeer(stream_id, "foos", 3, !kFin, &last_packet);
2351 BlockOnNextWrite();
2352 connection_.SendStreamDataWithString(stream_id, "fooos", 7, !kFin, nullptr);
2354 // Lose a packet which will trigger a pending retransmission.
2355 QuicAckFrame ack = InitAckFrame(last_packet);
2356 NackPacket(last_packet - 1, &ack);
2357 PacketNumberSet lost_packets;
2358 lost_packets.insert(last_packet - 1);
2359 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2360 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2361 .WillOnce(Return(lost_packets));
2362 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2363 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
2364 ProcessAckPacket(&ack);
2366 connection_.SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 14);
2368 // Unblock the connection and verify that the RST_STREAM is sent but not the
2369 // second data packet nor a retransmit.
2370 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2371 writer_->SetWritable();
2372 connection_.OnCanWrite();
2373 EXPECT_EQ(1u, writer_->frame_count());
2374 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
2375 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
2378 TEST_P(QuicConnectionTest, DiscardRetransmit) {
2379 QuicPacketNumber last_packet;
2380 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet); // Packet 1
2381 SendStreamDataToPeer(1, "foos", 3, !kFin, &last_packet); // Packet 2
2382 SendStreamDataToPeer(1, "fooos", 7, !kFin, &last_packet); // Packet 3
2384 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2386 // Instigate a loss with an ack.
2387 QuicAckFrame nack_two = InitAckFrame(3);
2388 NackPacket(2, &nack_two);
2389 // The first nack should trigger a fast retransmission, but we'll be
2390 // write blocked, so the packet will be queued.
2391 BlockOnNextWrite();
2392 PacketNumberSet lost_packets;
2393 lost_packets.insert(2);
2394 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2395 .WillOnce(Return(lost_packets));
2396 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2397 ProcessAckPacket(&nack_two);
2398 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2400 // Now, ack the previous transmission.
2401 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2402 .WillOnce(Return(PacketNumberSet()));
2403 QuicAckFrame ack_all = InitAckFrame(3);
2404 ProcessAckPacket(&ack_all);
2406 // Unblock the socket and attempt to send the queued packets. However,
2407 // since the previous transmission has been acked, we will not
2408 // send the retransmission.
2409 EXPECT_CALL(*send_algorithm_,
2410 OnPacketSent(_, _, _, _, _)).Times(0);
2412 writer_->SetWritable();
2413 connection_.OnCanWrite();
2415 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2418 TEST_P(QuicConnectionTest, RetransmitNackedLargestObserved) {
2419 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2420 QuicPacketNumber largest_observed;
2421 QuicByteCount packet_size;
2422 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2423 .WillOnce(DoAll(SaveArg<2>(&largest_observed), SaveArg<3>(&packet_size),
2424 Return(true)));
2425 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
2427 QuicAckFrame frame = InitAckFrame(1);
2428 NackPacket(largest_observed, &frame);
2429 // The first nack should retransmit the largest observed packet.
2430 PacketNumberSet lost_packets;
2431 lost_packets.insert(1);
2432 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2433 .WillOnce(Return(lost_packets));
2434 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2435 EXPECT_CALL(*send_algorithm_,
2436 OnPacketSent(_, _, _, packet_size - kQuicVersionSize, _));
2437 ProcessAckPacket(&frame);
2440 TEST_P(QuicConnectionTest, QueueAfterTwoRTOs) {
2441 for (int i = 0; i < 10; ++i) {
2442 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2443 connection_.SendStreamDataWithString(3, "foo", i * 3, !kFin, nullptr);
2446 // Block the writer and ensure they're queued.
2447 BlockOnNextWrite();
2448 clock_.AdvanceTime(DefaultRetransmissionTime());
2449 // Only one packet should be retransmitted.
2450 connection_.GetRetransmissionAlarm()->Fire();
2451 EXPECT_TRUE(connection_.HasQueuedData());
2453 // Unblock the writer.
2454 writer_->SetWritable();
2455 clock_.AdvanceTime(QuicTime::Delta::FromMicroseconds(
2456 2 * DefaultRetransmissionTime().ToMicroseconds()));
2457 // Retransmit already retransmitted packets event though the packet number
2458 // greater than the largest observed.
2459 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
2460 connection_.GetRetransmissionAlarm()->Fire();
2461 connection_.OnCanWrite();
2464 TEST_P(QuicConnectionTest, WriteBlockedBufferedThenSent) {
2465 BlockOnNextWrite();
2466 writer_->set_is_write_blocked_data_buffered(true);
2467 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2468 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
2469 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2471 writer_->SetWritable();
2472 connection_.OnCanWrite();
2473 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2476 TEST_P(QuicConnectionTest, WriteBlockedThenSent) {
2477 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
2478 BlockOnNextWrite();
2479 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
2480 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
2481 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2483 // The second packet should also be queued, in order to ensure packets are
2484 // never sent out of order.
2485 writer_->SetWritable();
2486 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
2487 EXPECT_EQ(2u, connection_.NumQueuedPackets());
2489 // Now both are sent in order when we unblock.
2490 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
2491 connection_.OnCanWrite();
2492 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2495 TEST_P(QuicConnectionTest, RetransmitWriteBlockedAckedOriginalThenSent) {
2496 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2497 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
2498 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2500 BlockOnNextWrite();
2501 writer_->set_is_write_blocked_data_buffered(true);
2502 // Simulate the retransmission alarm firing.
2503 clock_.AdvanceTime(DefaultRetransmissionTime());
2504 connection_.GetRetransmissionAlarm()->Fire();
2506 // Ack the sent packet before the callback returns, which happens in
2507 // rare circumstances with write blocked sockets.
2508 QuicAckFrame ack = InitAckFrame(1);
2509 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2510 ProcessAckPacket(&ack);
2512 writer_->SetWritable();
2513 connection_.OnCanWrite();
2514 // There is now a pending packet, but with no retransmittable frames.
2515 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2516 EXPECT_FALSE(connection_.sent_packet_manager().HasRetransmittableFrames(2));
2519 TEST_P(QuicConnectionTest, AlarmsWhenWriteBlocked) {
2520 // Block the connection.
2521 BlockOnNextWrite();
2522 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
2523 EXPECT_EQ(1u, writer_->packets_write_attempts());
2524 EXPECT_TRUE(writer_->IsWriteBlocked());
2526 // Set the send and resumption alarms. Fire the alarms and ensure they don't
2527 // attempt to write.
2528 connection_.GetResumeWritesAlarm()->Set(clock_.ApproximateNow());
2529 connection_.GetSendAlarm()->Set(clock_.ApproximateNow());
2530 connection_.GetResumeWritesAlarm()->Fire();
2531 connection_.GetSendAlarm()->Fire();
2532 EXPECT_TRUE(writer_->IsWriteBlocked());
2533 EXPECT_EQ(1u, writer_->packets_write_attempts());
2536 TEST_P(QuicConnectionTest, NoLimitPacketsPerNack) {
2537 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2538 int offset = 0;
2539 // Send packets 1 to 15.
2540 for (int i = 0; i < 15; ++i) {
2541 SendStreamDataToPeer(1, "foo", offset, !kFin, nullptr);
2542 offset += 3;
2545 // Ack 15, nack 1-14.
2546 PacketNumberSet lost_packets;
2547 QuicAckFrame nack = InitAckFrame(15);
2548 for (int i = 1; i < 15; ++i) {
2549 NackPacket(i, &nack);
2550 lost_packets.insert(i);
2553 // 14 packets have been NACK'd and lost. In TCP cubic, PRR limits
2554 // the retransmission rate in the case of burst losses.
2555 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2556 .WillOnce(Return(lost_packets));
2557 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2558 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(14);
2559 ProcessAckPacket(&nack);
2562 // Test sending multiple acks from the connection to the session.
2563 TEST_P(QuicConnectionTest, MultipleAcks) {
2564 QuicPacketNumber last_packet;
2565 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet); // Packet 1
2566 EXPECT_EQ(1u, last_packet);
2567 SendStreamDataToPeer(3, "foo", 0, !kFin, &last_packet); // Packet 2
2568 EXPECT_EQ(2u, last_packet);
2569 SendAckPacketToPeer(); // Packet 3
2570 SendStreamDataToPeer(5, "foo", 0, !kFin, &last_packet); // Packet 4
2571 EXPECT_EQ(4u, last_packet);
2572 SendStreamDataToPeer(1, "foo", 3, !kFin, &last_packet); // Packet 5
2573 EXPECT_EQ(5u, last_packet);
2574 SendStreamDataToPeer(3, "foo", 3, !kFin, &last_packet); // Packet 6
2575 EXPECT_EQ(6u, last_packet);
2577 // Client will ack packets 1, 2, [!3], 4, 5.
2578 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2579 QuicAckFrame frame1 = InitAckFrame(5);
2580 NackPacket(3, &frame1);
2581 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2582 ProcessAckPacket(&frame1);
2584 // Now the client implicitly acks 3, and explicitly acks 6.
2585 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2586 QuicAckFrame frame2 = InitAckFrame(6);
2587 ProcessAckPacket(&frame2);
2590 TEST_P(QuicConnectionTest, DontLatchUnackedPacket) {
2591 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr); // Packet 1;
2592 // From now on, we send acks, so the send algorithm won't mark them pending.
2593 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2594 .WillByDefault(Return(false));
2595 SendAckPacketToPeer(); // Packet 2
2597 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2598 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2599 QuicAckFrame frame = InitAckFrame(1);
2600 ProcessAckPacket(&frame);
2602 // Verify that our internal state has least-unacked as 2, because we're still
2603 // waiting for a potential ack for 2.
2605 EXPECT_EQ(2u, stop_waiting()->least_unacked);
2607 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2608 frame = InitAckFrame(2);
2609 ProcessAckPacket(&frame);
2610 EXPECT_EQ(3u, stop_waiting()->least_unacked);
2612 // When we send an ack, we make sure our least-unacked makes sense. In this
2613 // case since we're not waiting on an ack for 2 and all packets are acked, we
2614 // set it to 3.
2615 SendAckPacketToPeer(); // Packet 3
2616 // Least_unacked remains at 3 until another ack is received.
2617 EXPECT_EQ(3u, stop_waiting()->least_unacked);
2618 // Check that the outgoing ack had its packet number as least_unacked.
2619 EXPECT_EQ(3u, least_unacked());
2621 // Ack the ack, which updates the rtt and raises the least unacked.
2622 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2623 frame = InitAckFrame(3);
2624 ProcessAckPacket(&frame);
2626 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2627 .WillByDefault(Return(true));
2628 SendStreamDataToPeer(1, "bar", 3, false, nullptr); // Packet 4
2629 EXPECT_EQ(4u, stop_waiting()->least_unacked);
2630 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2631 .WillByDefault(Return(false));
2632 SendAckPacketToPeer(); // Packet 5
2633 EXPECT_EQ(4u, least_unacked());
2635 // Send two data packets at the end, and ensure if the last one is acked,
2636 // the least unacked is raised above the ack packets.
2637 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2638 .WillByDefault(Return(true));
2639 SendStreamDataToPeer(1, "bar", 6, false, nullptr); // Packet 6
2640 SendStreamDataToPeer(1, "bar", 9, false, nullptr); // Packet 7
2642 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2643 frame = InitAckFrame(7);
2644 NackPacket(5, &frame);
2645 NackPacket(6, &frame);
2646 ProcessAckPacket(&frame);
2648 EXPECT_EQ(6u, stop_waiting()->least_unacked);
2651 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterFecPacket) {
2652 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2654 // Don't send missing packet 1.
2655 ProcessFecPacket(2, 1, true, !kEntropyFlag, nullptr);
2656 // Entropy flag should be false, so entropy should be 0.
2657 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2660 TEST_P(QuicConnectionTest, ReviveMissingPacketWithVaryingSeqNumLengths) {
2661 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2663 // Set up a debug visitor to the connection.
2664 scoped_ptr<FecQuicConnectionDebugVisitor> fec_visitor(
2665 new FecQuicConnectionDebugVisitor());
2666 connection_.set_debug_visitor(fec_visitor.get());
2668 QuicPacketNumber fec_packet = 0;
2669 QuicPacketNumberLength lengths[] = {
2670 PACKET_6BYTE_PACKET_NUMBER, PACKET_4BYTE_PACKET_NUMBER,
2671 PACKET_2BYTE_PACKET_NUMBER, PACKET_1BYTE_PACKET_NUMBER};
2672 // For each packet number length size, revive a packet and check sequence
2673 // number length in the revived packet.
2674 for (size_t i = 0; i < arraysize(lengths); ++i) {
2675 // Set packet_number_length_ (for data and FEC packets).
2676 packet_number_length_ = lengths[i];
2677 fec_packet += 2;
2678 // Don't send missing packet, but send fec packet right after it.
2679 ProcessFecPacket(fec_packet, fec_packet - 1, true, !kEntropyFlag, nullptr);
2680 // packet number length in the revived header should be the same as
2681 // in the original data/fec packet headers.
2682 EXPECT_EQ(packet_number_length_,
2683 fec_visitor->revived_header().public_header.packet_number_length);
2687 TEST_P(QuicConnectionTest, ReviveMissingPacketWithVaryingConnectionIdLengths) {
2688 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2690 // Set up a debug visitor to the connection.
2691 scoped_ptr<FecQuicConnectionDebugVisitor> fec_visitor(
2692 new FecQuicConnectionDebugVisitor());
2693 connection_.set_debug_visitor(fec_visitor.get());
2695 QuicPacketNumber fec_packet = 0;
2696 QuicConnectionIdLength lengths[] = {PACKET_8BYTE_CONNECTION_ID,
2697 PACKET_4BYTE_CONNECTION_ID,
2698 PACKET_1BYTE_CONNECTION_ID,
2699 PACKET_0BYTE_CONNECTION_ID};
2700 // For each connection id length size, revive a packet and check connection
2701 // id length in the revived packet.
2702 for (size_t i = 0; i < arraysize(lengths); ++i) {
2703 // Set connection id length (for data and FEC packets).
2704 connection_id_length_ = lengths[i];
2705 fec_packet += 2;
2706 // Don't send missing packet, but send fec packet right after it.
2707 ProcessFecPacket(fec_packet, fec_packet - 1, true, !kEntropyFlag, nullptr);
2708 // Connection id length in the revived header should be the same as
2709 // in the original data/fec packet headers.
2710 EXPECT_EQ(connection_id_length_,
2711 fec_visitor->revived_header().public_header.connection_id_length);
2715 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPacketThenFecPacket) {
2716 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2718 ProcessFecProtectedPacket(1, false, kEntropyFlag);
2719 // Don't send missing packet 2.
2720 ProcessFecPacket(3, 1, true, !kEntropyFlag, nullptr);
2721 // Entropy flag should be true, so entropy should not be 0.
2722 EXPECT_NE(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2725 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPacketsThenFecPacket) {
2726 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2728 ProcessFecProtectedPacket(1, false, !kEntropyFlag);
2729 // Don't send missing packet 2.
2730 ProcessFecProtectedPacket(3, false, !kEntropyFlag);
2731 ProcessFecPacket(4, 1, true, kEntropyFlag, nullptr);
2732 // Ensure QUIC no longer revives entropy for lost packets.
2733 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2734 EXPECT_NE(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 4));
2737 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPacket) {
2738 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2740 // Don't send missing packet 1.
2741 ProcessFecPacket(3, 1, false, !kEntropyFlag, nullptr);
2742 // Out of order.
2743 ProcessFecProtectedPacket(2, true, !kEntropyFlag);
2744 // Entropy flag should be false, so entropy should be 0.
2745 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2748 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPackets) {
2749 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2751 ProcessFecProtectedPacket(1, false, !kEntropyFlag);
2752 // Don't send missing packet 2.
2753 ProcessFecPacket(6, 1, false, kEntropyFlag, nullptr);
2754 ProcessFecProtectedPacket(3, false, kEntropyFlag);
2755 ProcessFecProtectedPacket(4, false, kEntropyFlag);
2756 ProcessFecProtectedPacket(5, true, !kEntropyFlag);
2757 // Ensure entropy is not revived for the missing packet.
2758 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2759 EXPECT_NE(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 3));
2762 TEST_P(QuicConnectionTest, TLP) {
2763 QuicSentPacketManagerPeer::SetMaxTailLossProbes(manager_, 1);
2765 SendStreamDataToPeer(3, "foo", 0, !kFin, nullptr);
2766 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2767 QuicTime retransmission_time =
2768 connection_.GetRetransmissionAlarm()->deadline();
2769 EXPECT_NE(QuicTime::Zero(), retransmission_time);
2771 EXPECT_EQ(1u, writer_->header().packet_packet_number);
2772 // Simulate the retransmission alarm firing and sending a tlp,
2773 // so send algorithm's OnRetransmissionTimeout is not called.
2774 clock_.AdvanceTime(retransmission_time.Subtract(clock_.Now()));
2775 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 2u, _, _));
2776 connection_.GetRetransmissionAlarm()->Fire();
2777 EXPECT_EQ(2u, writer_->header().packet_packet_number);
2778 // We do not raise the high water mark yet.
2779 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2782 TEST_P(QuicConnectionTest, RTO) {
2783 QuicTime default_retransmission_time = clock_.ApproximateNow().Add(
2784 DefaultRetransmissionTime());
2785 SendStreamDataToPeer(3, "foo", 0, !kFin, nullptr);
2786 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2788 EXPECT_EQ(1u, writer_->header().packet_packet_number);
2789 EXPECT_EQ(default_retransmission_time,
2790 connection_.GetRetransmissionAlarm()->deadline());
2791 // Simulate the retransmission alarm firing.
2792 clock_.AdvanceTime(DefaultRetransmissionTime());
2793 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 2u, _, _));
2794 connection_.GetRetransmissionAlarm()->Fire();
2795 EXPECT_EQ(2u, writer_->header().packet_packet_number);
2796 // We do not raise the high water mark yet.
2797 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2800 TEST_P(QuicConnectionTest, RTOWithSameEncryptionLevel) {
2801 QuicTime default_retransmission_time = clock_.ApproximateNow().Add(
2802 DefaultRetransmissionTime());
2803 use_tagging_decrypter();
2805 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
2806 // the end of the packet. We can test this to check which encrypter was used.
2807 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2808 SendStreamDataToPeer(3, "foo", 0, !kFin, nullptr);
2809 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
2811 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2812 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2813 SendStreamDataToPeer(3, "foo", 0, !kFin, nullptr);
2814 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2816 EXPECT_EQ(default_retransmission_time,
2817 connection_.GetRetransmissionAlarm()->deadline());
2819 InSequence s;
2820 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 3, _, _));
2821 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 4, _, _));
2824 // Simulate the retransmission alarm firing.
2825 clock_.AdvanceTime(DefaultRetransmissionTime());
2826 connection_.GetRetransmissionAlarm()->Fire();
2828 // Packet should have been sent with ENCRYPTION_NONE.
2829 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_previous_packet());
2831 // Packet should have been sent with ENCRYPTION_INITIAL.
2832 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2835 TEST_P(QuicConnectionTest, SendHandshakeMessages) {
2836 use_tagging_decrypter();
2837 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
2838 // the end of the packet. We can test this to check which encrypter was used.
2839 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2841 // Attempt to send a handshake message and have the socket block.
2842 EXPECT_CALL(*send_algorithm_,
2843 TimeUntilSend(_, _, _)).WillRepeatedly(
2844 testing::Return(QuicTime::Delta::Zero()));
2845 BlockOnNextWrite();
2846 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
2847 // The packet should be serialized, but not queued.
2848 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2850 // Switch to the new encrypter.
2851 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2852 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2854 // Now become writeable and flush the packets.
2855 writer_->SetWritable();
2856 EXPECT_CALL(visitor_, OnCanWrite());
2857 connection_.OnCanWrite();
2858 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2860 // Verify that the handshake packet went out at the null encryption.
2861 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
2864 TEST_P(QuicConnectionTest,
2865 DropRetransmitsForNullEncryptedPacketAfterForwardSecure) {
2866 use_tagging_decrypter();
2867 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2868 QuicPacketNumber packet_number;
2869 SendStreamDataToPeer(3, "foo", 0, !kFin, &packet_number);
2871 // Simulate the retransmission alarm firing and the socket blocking.
2872 BlockOnNextWrite();
2873 clock_.AdvanceTime(DefaultRetransmissionTime());
2874 connection_.GetRetransmissionAlarm()->Fire();
2876 // Go forward secure.
2877 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
2878 new TaggingEncrypter(0x02));
2879 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2880 connection_.NeuterUnencryptedPackets();
2882 EXPECT_EQ(QuicTime::Zero(),
2883 connection_.GetRetransmissionAlarm()->deadline());
2884 // Unblock the socket and ensure that no packets are sent.
2885 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
2886 writer_->SetWritable();
2887 connection_.OnCanWrite();
2890 TEST_P(QuicConnectionTest, RetransmitPacketsWithInitialEncryption) {
2891 use_tagging_decrypter();
2892 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2893 connection_.SetDefaultEncryptionLevel(ENCRYPTION_NONE);
2895 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr);
2897 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2898 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2900 SendStreamDataToPeer(2, "bar", 0, !kFin, nullptr);
2901 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2903 connection_.RetransmitUnackedPackets(ALL_INITIAL_RETRANSMISSION);
2906 TEST_P(QuicConnectionTest, DelayForwardSecureEncryptionUntilClientIsReady) {
2907 // A TaggingEncrypter puts kTagSize copies of the given byte (0x02 here) at
2908 // the end of the packet. We can test this to check which encrypter was used.
2909 use_tagging_decrypter();
2910 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2911 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2912 SendAckPacketToPeer();
2913 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2915 // Set a forward-secure encrypter but do not make it the default, and verify
2916 // that it is not yet used.
2917 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
2918 new TaggingEncrypter(0x03));
2919 SendAckPacketToPeer();
2920 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2922 // Now simulate receipt of a forward-secure packet and verify that the
2923 // forward-secure encrypter is now used.
2924 connection_.OnDecryptedPacket(ENCRYPTION_FORWARD_SECURE);
2925 SendAckPacketToPeer();
2926 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
2929 TEST_P(QuicConnectionTest, DelayForwardSecureEncryptionUntilManyPacketSent) {
2930 // Set a congestion window of 10 packets.
2931 QuicPacketCount congestion_window = 10;
2932 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
2933 Return(congestion_window * kDefaultMaxPacketSize));
2935 // A TaggingEncrypter puts kTagSize copies of the given byte (0x02 here) at
2936 // the end of the packet. We can test this to check which encrypter was used.
2937 use_tagging_decrypter();
2938 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2939 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2940 SendAckPacketToPeer();
2941 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2943 // Set a forward-secure encrypter but do not make it the default, and
2944 // verify that it is not yet used.
2945 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
2946 new TaggingEncrypter(0x03));
2947 SendAckPacketToPeer();
2948 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2950 // Now send a packet "Far enough" after the encrypter was set and verify that
2951 // the forward-secure encrypter is now used.
2952 for (uint64 i = 0; i < 3 * congestion_window - 1; ++i) {
2953 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2954 SendAckPacketToPeer();
2956 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
2959 TEST_P(QuicConnectionTest, BufferNonDecryptablePackets) {
2960 // SetFromConfig is always called after construction from InitializeSession.
2961 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
2962 QuicConfig config;
2963 connection_.SetFromConfig(config);
2964 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2965 use_tagging_decrypter();
2967 const uint8 tag = 0x07;
2968 framer_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
2970 // Process an encrypted packet which can not yet be decrypted which should
2971 // result in the packet being buffered.
2972 ProcessDataPacketAtLevel(1, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2974 // Transition to the new encryption state and process another encrypted packet
2975 // which should result in the original packet being processed.
2976 connection_.SetDecrypter(ENCRYPTION_INITIAL, new StrictTaggingDecrypter(tag));
2977 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2978 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
2979 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(2);
2980 ProcessDataPacketAtLevel(2, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2982 // Finally, process a third packet and note that we do not reprocess the
2983 // buffered packet.
2984 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2985 ProcessDataPacketAtLevel(3, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2988 TEST_P(QuicConnectionTest, Buffer100NonDecryptablePackets) {
2989 // SetFromConfig is always called after construction from InitializeSession.
2990 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
2991 QuicConfig config;
2992 config.set_max_undecryptable_packets(100);
2993 connection_.SetFromConfig(config);
2994 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2995 use_tagging_decrypter();
2997 const uint8 tag = 0x07;
2998 framer_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
3000 // Process an encrypted packet which can not yet be decrypted which should
3001 // result in the packet being buffered.
3002 for (QuicPacketNumber i = 1; i <= 100; ++i) {
3003 ProcessDataPacketAtLevel(i, 0, kEntropyFlag, ENCRYPTION_INITIAL);
3006 // Transition to the new encryption state and process another encrypted packet
3007 // which should result in the original packets being processed.
3008 connection_.SetDecrypter(ENCRYPTION_INITIAL, new StrictTaggingDecrypter(tag));
3009 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
3010 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
3011 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(101);
3012 ProcessDataPacketAtLevel(101, 0, kEntropyFlag, ENCRYPTION_INITIAL);
3014 // Finally, process a third packet and note that we do not reprocess the
3015 // buffered packet.
3016 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3017 ProcessDataPacketAtLevel(102, 0, kEntropyFlag, ENCRYPTION_INITIAL);
3020 TEST_P(QuicConnectionTest, TestRetransmitOrder) {
3021 QuicByteCount first_packet_size;
3022 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).WillOnce(
3023 DoAll(SaveArg<3>(&first_packet_size), Return(true)));
3025 connection_.SendStreamDataWithString(3, "first_packet", 0, !kFin, nullptr);
3026 QuicByteCount second_packet_size;
3027 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).WillOnce(
3028 DoAll(SaveArg<3>(&second_packet_size), Return(true)));
3029 connection_.SendStreamDataWithString(3, "second_packet", 12, !kFin, nullptr);
3030 EXPECT_NE(first_packet_size, second_packet_size);
3031 // Advance the clock by huge time to make sure packets will be retransmitted.
3032 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
3034 InSequence s;
3035 EXPECT_CALL(*send_algorithm_,
3036 OnPacketSent(_, _, _, first_packet_size, _));
3037 EXPECT_CALL(*send_algorithm_,
3038 OnPacketSent(_, _, _, second_packet_size, _));
3040 connection_.GetRetransmissionAlarm()->Fire();
3042 // Advance again and expect the packets to be sent again in the same order.
3043 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(20));
3045 InSequence s;
3046 EXPECT_CALL(*send_algorithm_,
3047 OnPacketSent(_, _, _, first_packet_size, _));
3048 EXPECT_CALL(*send_algorithm_,
3049 OnPacketSent(_, _, _, second_packet_size, _));
3051 connection_.GetRetransmissionAlarm()->Fire();
3054 TEST_P(QuicConnectionTest, SetRTOAfterWritingToSocket) {
3055 BlockOnNextWrite();
3056 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
3057 // Make sure that RTO is not started when the packet is queued.
3058 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3060 // Test that RTO is started once we write to the socket.
3061 writer_->SetWritable();
3062 connection_.OnCanWrite();
3063 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3066 TEST_P(QuicConnectionTest, DelayRTOWithAckReceipt) {
3067 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3068 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3069 .Times(2);
3070 connection_.SendStreamDataWithString(2, "foo", 0, !kFin, nullptr);
3071 connection_.SendStreamDataWithString(3, "bar", 0, !kFin, nullptr);
3072 QuicAlarm* retransmission_alarm = connection_.GetRetransmissionAlarm();
3073 EXPECT_TRUE(retransmission_alarm->IsSet());
3074 EXPECT_EQ(clock_.Now().Add(DefaultRetransmissionTime()),
3075 retransmission_alarm->deadline());
3077 // Advance the time right before the RTO, then receive an ack for the first
3078 // packet to delay the RTO.
3079 clock_.AdvanceTime(DefaultRetransmissionTime());
3080 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3081 QuicAckFrame ack = InitAckFrame(1);
3082 ProcessAckPacket(&ack);
3083 EXPECT_TRUE(retransmission_alarm->IsSet());
3084 EXPECT_GT(retransmission_alarm->deadline(), clock_.Now());
3086 // Move forward past the original RTO and ensure the RTO is still pending.
3087 clock_.AdvanceTime(DefaultRetransmissionTime().Multiply(2));
3089 // Ensure the second packet gets retransmitted when it finally fires.
3090 EXPECT_TRUE(retransmission_alarm->IsSet());
3091 EXPECT_LT(retransmission_alarm->deadline(), clock_.ApproximateNow());
3092 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3093 // Manually cancel the alarm to simulate a real test.
3094 connection_.GetRetransmissionAlarm()->Fire();
3096 // The new retransmitted packet number should set the RTO to a larger value
3097 // than previously.
3098 EXPECT_TRUE(retransmission_alarm->IsSet());
3099 QuicTime next_rto_time = retransmission_alarm->deadline();
3100 QuicTime expected_rto_time =
3101 connection_.sent_packet_manager().GetRetransmissionTime();
3102 EXPECT_EQ(next_rto_time, expected_rto_time);
3105 TEST_P(QuicConnectionTest, TestQueued) {
3106 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3107 BlockOnNextWrite();
3108 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
3109 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3111 // Unblock the writes and actually send.
3112 writer_->SetWritable();
3113 connection_.OnCanWrite();
3114 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3117 TEST_P(QuicConnectionTest, CloseFecGroup) {
3118 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3119 // Don't send missing packet 1.
3120 // Don't send missing packet 2.
3121 ProcessFecProtectedPacket(3, false, !kEntropyFlag);
3122 // Don't send missing FEC packet 3.
3123 ASSERT_EQ(1u, connection_.NumFecGroups());
3125 // Now send non-fec protected ack packet and close the group.
3126 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 4);
3127 QuicStopWaitingFrame frame = InitStopWaitingFrame(5);
3128 ProcessStopWaitingPacket(&frame);
3129 ASSERT_EQ(0u, connection_.NumFecGroups());
3132 TEST_P(QuicConnectionTest, InitialTimeout) {
3133 EXPECT_TRUE(connection_.connected());
3134 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
3135 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3137 // SetFromConfig sets the initial timeouts before negotiation.
3138 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3139 QuicConfig config;
3140 connection_.SetFromConfig(config);
3141 // Subtract a second from the idle timeout on the client side.
3142 QuicTime default_timeout = clock_.ApproximateNow().Add(
3143 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1));
3144 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
3146 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_CONNECTION_TIMED_OUT, false));
3147 // Simulate the timeout alarm firing.
3148 clock_.AdvanceTime(
3149 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1));
3150 connection_.GetTimeoutAlarm()->Fire();
3152 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3153 EXPECT_FALSE(connection_.connected());
3155 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3156 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
3157 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
3158 EXPECT_FALSE(connection_.GetResumeWritesAlarm()->IsSet());
3159 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3160 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
3161 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
3164 TEST_P(QuicConnectionTest, OverallTimeout) {
3165 // Use a shorter overall connection timeout than idle timeout for this test.
3166 const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(5);
3167 connection_.SetNetworkTimeouts(timeout, timeout);
3168 EXPECT_TRUE(connection_.connected());
3169 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
3171 QuicTime overall_timeout = clock_.ApproximateNow().Add(timeout).Subtract(
3172 QuicTime::Delta::FromSeconds(1));
3173 EXPECT_EQ(overall_timeout, connection_.GetTimeoutAlarm()->deadline());
3174 EXPECT_TRUE(connection_.connected());
3176 // Send and ack new data 3 seconds later to lengthen the idle timeout.
3177 SendStreamDataToPeer(1, "GET /", 0, kFin, nullptr);
3178 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(3));
3179 QuicAckFrame frame = InitAckFrame(1);
3180 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3181 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3182 ProcessAckPacket(&frame);
3184 // Fire early to verify it wouldn't timeout yet.
3185 connection_.GetTimeoutAlarm()->Fire();
3186 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
3187 EXPECT_TRUE(connection_.connected());
3189 clock_.AdvanceTime(timeout.Subtract(QuicTime::Delta::FromSeconds(2)));
3191 EXPECT_CALL(visitor_,
3192 OnConnectionClosed(QUIC_CONNECTION_OVERALL_TIMED_OUT, false));
3193 // Simulate the timeout alarm firing.
3194 connection_.GetTimeoutAlarm()->Fire();
3196 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3197 EXPECT_FALSE(connection_.connected());
3199 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3200 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
3201 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
3202 EXPECT_FALSE(connection_.GetResumeWritesAlarm()->IsSet());
3203 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3204 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
3207 TEST_P(QuicConnectionTest, PingAfterSend) {
3208 EXPECT_TRUE(connection_.connected());
3209 EXPECT_CALL(visitor_, HasOpenDynamicStreams()).WillRepeatedly(Return(true));
3210 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
3212 // Advance to 5ms, and send a packet to the peer, which will set
3213 // the ping alarm.
3214 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
3215 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3216 SendStreamDataToPeer(1, "GET /", 0, kFin, nullptr);
3217 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
3218 EXPECT_EQ(clock_.ApproximateNow().Add(QuicTime::Delta::FromSeconds(15)),
3219 connection_.GetPingAlarm()->deadline());
3221 // Now recevie and ACK of the previous packet, which will move the
3222 // ping alarm forward.
3223 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
3224 QuicAckFrame frame = InitAckFrame(1);
3225 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3226 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3227 ProcessAckPacket(&frame);
3228 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
3229 // The ping timer is set slightly less than 15 seconds in the future, because
3230 // of the 1s ping timer alarm granularity.
3231 EXPECT_EQ(clock_.ApproximateNow().Add(QuicTime::Delta::FromSeconds(15))
3232 .Subtract(QuicTime::Delta::FromMilliseconds(5)),
3233 connection_.GetPingAlarm()->deadline());
3235 writer_->Reset();
3236 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15));
3237 connection_.GetPingAlarm()->Fire();
3238 EXPECT_EQ(1u, writer_->frame_count());
3239 ASSERT_EQ(1u, writer_->ping_frames().size());
3240 writer_->Reset();
3242 EXPECT_CALL(visitor_, HasOpenDynamicStreams()).WillRepeatedly(Return(false));
3243 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
3244 SendAckPacketToPeer();
3246 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
3249 // Tests whether sending an MTU discovery packet to peer successfully causes the
3250 // maximum packet size to increase.
3251 TEST_P(QuicConnectionTest, SendMtuDiscoveryPacket) {
3252 EXPECT_TRUE(connection_.connected());
3254 // Send an MTU probe.
3255 const size_t new_mtu = kDefaultMaxPacketSize + 100;
3256 QuicByteCount mtu_probe_size;
3257 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3258 .WillOnce(DoAll(SaveArg<3>(&mtu_probe_size), Return(true)));
3259 connection_.SendMtuDiscoveryPacket(new_mtu);
3260 EXPECT_EQ(new_mtu, mtu_probe_size);
3261 EXPECT_EQ(1u, creator_->packet_number());
3263 // Send more than MTU worth of data. No acknowledgement was received so far,
3264 // so the MTU should be at its old value.
3265 const string data(kDefaultMaxPacketSize + 1, '.');
3266 QuicByteCount size_before_mtu_change;
3267 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3268 .WillOnce(DoAll(SaveArg<3>(&size_before_mtu_change), Return(true)))
3269 .WillOnce(Return(true));
3270 connection_.SendStreamDataWithString(3, data, 0, kFin, nullptr);
3271 EXPECT_EQ(3u, creator_->packet_number());
3272 EXPECT_EQ(kDefaultMaxPacketSize, size_before_mtu_change);
3274 // Acknowledge all packets so far.
3275 QuicAckFrame probe_ack = InitAckFrame(3);
3276 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3277 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3278 ProcessAckPacket(&probe_ack);
3279 EXPECT_EQ(new_mtu, connection_.max_packet_length());
3281 // Send the same data again. Check that it fits into a single packet now.
3282 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3283 connection_.SendStreamDataWithString(3, data, 0, kFin, nullptr);
3284 EXPECT_EQ(4u, creator_->packet_number());
3287 // Tests whether MTU discovery does not happen when it is not explicitly enabled
3288 // by the connection options.
3289 TEST_P(QuicConnectionTest, MtuDiscoveryDisabled) {
3290 EXPECT_TRUE(connection_.connected());
3292 // Restore the current value FLAGS_quic_do_path_mtu_discovery after the test.
3293 ValueRestore<bool> old_flag(&FLAGS_quic_do_path_mtu_discovery, true);
3295 const QuicPacketCount number_of_packets = kPacketsBetweenMtuProbesBase * 2;
3296 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
3297 SendStreamDataToPeer(3, ".", i, /*fin=*/false, nullptr);
3298 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
3299 EXPECT_EQ(0u, connection_.mtu_probe_count());
3303 // Tests whether MTU discovery works when the probe gets acknowledged on the
3304 // first try.
3305 TEST_P(QuicConnectionTest, MtuDiscoveryEnabled) {
3306 EXPECT_TRUE(connection_.connected());
3308 // Restore the current value FLAGS_quic_do_path_mtu_discovery after the test.
3309 ValueRestore<bool> old_flag(&FLAGS_quic_do_path_mtu_discovery, true);
3310 connection_.EnablePathMtuDiscovery(send_algorithm_);
3312 // Send enough packets so that the next one triggers path MTU discovery.
3313 for (QuicPacketCount i = 0; i < kPacketsBetweenMtuProbesBase - 1; i++) {
3314 SendStreamDataToPeer(3, ".", i, /*fin=*/false, nullptr);
3315 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
3318 // Trigger the probe.
3319 SendStreamDataToPeer(3, "!", kPacketsBetweenMtuProbesBase,
3320 /*fin=*/false, nullptr);
3321 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
3322 QuicByteCount probe_size;
3323 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3324 .WillOnce(DoAll(SaveArg<3>(&probe_size), Return(true)));
3325 connection_.GetMtuDiscoveryAlarm()->Fire();
3326 EXPECT_EQ(kMtuDiscoveryTargetPacketSizeHigh, probe_size);
3328 const QuicPacketCount probe_packet_number = kPacketsBetweenMtuProbesBase + 1;
3329 ASSERT_EQ(probe_packet_number, creator_->packet_number());
3331 // Acknowledge all packets sent so far.
3332 QuicAckFrame probe_ack = InitAckFrame(probe_packet_number);
3333 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3334 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3335 ProcessAckPacket(&probe_ack);
3336 EXPECT_EQ(kMtuDiscoveryTargetPacketSizeHigh, connection_.max_packet_length());
3337 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
3339 // Send more packets, and ensure that none of them sets the alarm.
3340 for (QuicPacketCount i = 0; i < 4 * kPacketsBetweenMtuProbesBase; i++) {
3341 SendStreamDataToPeer(3, ".", i, /*fin=*/false, nullptr);
3342 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
3345 EXPECT_EQ(1u, connection_.mtu_probe_count());
3348 // Tests whether MTU discovery works correctly when the probes never get
3349 // acknowledged.
3350 TEST_P(QuicConnectionTest, MtuDiscoveryFailed) {
3351 EXPECT_TRUE(connection_.connected());
3353 // Restore the current value FLAGS_quic_do_path_mtu_discovery after the test.
3354 ValueRestore<bool> old_flag(&FLAGS_quic_do_path_mtu_discovery, true);
3355 connection_.EnablePathMtuDiscovery(send_algorithm_);
3357 const QuicTime::Delta rtt = QuicTime::Delta::FromMilliseconds(100);
3359 EXPECT_EQ(kPacketsBetweenMtuProbesBase,
3360 QuicConnectionPeer::GetPacketsBetweenMtuProbes(&connection_));
3361 // Lower the number of probes between packets in order to make the test go
3362 // much faster.
3363 const QuicPacketCount packets_between_probes_base = 10;
3364 QuicConnectionPeer::SetPacketsBetweenMtuProbes(&connection_,
3365 packets_between_probes_base);
3366 QuicConnectionPeer::SetNextMtuProbeAt(&connection_,
3367 packets_between_probes_base);
3369 // This tests sends more packets than strictly necessary to make sure that if
3370 // the connection was to send more discovery packets than needed, those would
3371 // get caught as well.
3372 const QuicPacketCount number_of_packets =
3373 packets_between_probes_base * (1 << (kMtuDiscoveryAttempts + 1));
3374 vector<QuicPacketNumber> mtu_discovery_packets;
3375 // Called by the first ack.
3376 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3377 // Called on many acks.
3378 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _))
3379 .Times(AnyNumber());
3380 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
3381 SendStreamDataToPeer(3, "!", i, /*fin=*/false, nullptr);
3382 clock_.AdvanceTime(rtt);
3384 // Receive an ACK, which marks all data packets as received, and all MTU
3385 // discovery packets as missing.
3386 QuicAckFrame ack = InitAckFrame(creator_->packet_number());
3387 for (QuicPacketNumber& packet : mtu_discovery_packets) {
3388 NackPacket(packet, &ack);
3390 ProcessAckPacket(&ack);
3392 // Trigger MTU probe if it would be scheduled now.
3393 if (!connection_.GetMtuDiscoveryAlarm()->IsSet()) {
3394 continue;
3397 // Fire the alarm. The alarm should cause a packet to be sent.
3398 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3399 .WillOnce(Return(true));
3400 connection_.GetMtuDiscoveryAlarm()->Fire();
3401 // Record the packet number of the MTU discovery packet in order to
3402 // mark it as NACK'd.
3403 mtu_discovery_packets.push_back(creator_->packet_number());
3406 // Ensure the number of packets between probes grows exponentially by checking
3407 // it against the closed-form expression for the packet number.
3408 ASSERT_EQ(kMtuDiscoveryAttempts, mtu_discovery_packets.size());
3409 for (QuicPacketNumber i = 0; i < kMtuDiscoveryAttempts; i++) {
3410 // 2^0 + 2^1 + 2^2 + ... + 2^n = 2^(n + 1) - 1
3411 const QuicPacketCount packets_between_probes =
3412 packets_between_probes_base * ((1 << (i + 1)) - 1);
3413 EXPECT_EQ(packets_between_probes + (i + 1), mtu_discovery_packets[i]);
3416 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
3417 EXPECT_EQ(kDefaultMaxPacketSize, connection_.max_packet_length());
3418 EXPECT_EQ(kMtuDiscoveryAttempts, connection_.mtu_probe_count());
3421 TEST_P(QuicConnectionTest, NoMtuDiscoveryAfterConnectionClosed) {
3422 EXPECT_TRUE(connection_.connected());
3424 // Restore the current value FLAGS_quic_do_path_mtu_discovery after the test.
3425 ValueRestore<bool> old_flag(&FLAGS_quic_do_path_mtu_discovery, true);
3426 connection_.EnablePathMtuDiscovery(send_algorithm_);
3428 // Send enough packets so that the next one triggers path MTU discovery.
3429 for (QuicPacketCount i = 0; i < kPacketsBetweenMtuProbesBase - 1; i++) {
3430 SendStreamDataToPeer(3, ".", i, /*fin=*/false, nullptr);
3431 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
3434 SendStreamDataToPeer(3, "!", kPacketsBetweenMtuProbesBase,
3435 /*fin=*/false, nullptr);
3436 EXPECT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
3438 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
3439 connection_.CloseConnection(QUIC_INTERNAL_ERROR, /*from_peer=*/false);
3440 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
3443 TEST_P(QuicConnectionTest, TimeoutAfterSend) {
3444 EXPECT_TRUE(connection_.connected());
3445 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3446 QuicConfig config;
3447 connection_.SetFromConfig(config);
3448 EXPECT_FALSE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
3450 const QuicTime::Delta initial_idle_timeout =
3451 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
3452 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
3453 QuicTime default_timeout = clock_.ApproximateNow().Add(initial_idle_timeout);
3455 // When we send a packet, the timeout will change to 5ms +
3456 // kInitialIdleTimeoutSecs.
3457 clock_.AdvanceTime(five_ms);
3459 // Send an ack so we don't set the retransmission alarm.
3460 SendAckPacketToPeer();
3461 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
3463 // The original alarm will fire. We should not time out because we had a
3464 // network event at t=5ms. The alarm will reregister.
3465 clock_.AdvanceTime(initial_idle_timeout.Subtract(five_ms));
3466 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
3467 connection_.GetTimeoutAlarm()->Fire();
3468 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
3469 EXPECT_TRUE(connection_.connected());
3470 EXPECT_EQ(default_timeout.Add(five_ms),
3471 connection_.GetTimeoutAlarm()->deadline());
3473 // This time, we should time out.
3474 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_CONNECTION_TIMED_OUT, false));
3475 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3476 clock_.AdvanceTime(five_ms);
3477 EXPECT_EQ(default_timeout.Add(five_ms), clock_.ApproximateNow());
3478 connection_.GetTimeoutAlarm()->Fire();
3479 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3480 EXPECT_FALSE(connection_.connected());
3483 TEST_P(QuicConnectionTest, TimeoutAfterSendSilentClose) {
3484 // Same test as above, but complete a handshake which enables silent close,
3485 // causing no connection close packet to be sent.
3486 EXPECT_TRUE(connection_.connected());
3487 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3488 QuicConfig config;
3490 // Create a handshake message that also enables silent close.
3491 CryptoHandshakeMessage msg;
3492 string error_details;
3493 QuicConfig client_config;
3494 client_config.SetInitialStreamFlowControlWindowToSend(
3495 kInitialStreamFlowControlWindowForTest);
3496 client_config.SetInitialSessionFlowControlWindowToSend(
3497 kInitialSessionFlowControlWindowForTest);
3498 client_config.SetIdleConnectionStateLifetime(
3499 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs),
3500 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs));
3501 client_config.ToHandshakeMessage(&msg);
3502 const QuicErrorCode error =
3503 config.ProcessPeerHello(msg, CLIENT, &error_details);
3504 EXPECT_EQ(QUIC_NO_ERROR, error);
3506 connection_.SetFromConfig(config);
3507 EXPECT_TRUE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
3509 const QuicTime::Delta default_idle_timeout =
3510 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs - 1);
3511 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
3512 QuicTime default_timeout = clock_.ApproximateNow().Add(default_idle_timeout);
3514 // When we send a packet, the timeout will change to 5ms +
3515 // kInitialIdleTimeoutSecs.
3516 clock_.AdvanceTime(five_ms);
3518 // Send an ack so we don't set the retransmission alarm.
3519 SendAckPacketToPeer();
3520 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
3522 // The original alarm will fire. We should not time out because we had a
3523 // network event at t=5ms. The alarm will reregister.
3524 clock_.AdvanceTime(default_idle_timeout.Subtract(five_ms));
3525 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
3526 connection_.GetTimeoutAlarm()->Fire();
3527 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
3528 EXPECT_TRUE(connection_.connected());
3529 EXPECT_EQ(default_timeout.Add(five_ms),
3530 connection_.GetTimeoutAlarm()->deadline());
3532 // This time, we should time out.
3533 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_CONNECTION_TIMED_OUT, false));
3534 clock_.AdvanceTime(five_ms);
3535 EXPECT_EQ(default_timeout.Add(five_ms), clock_.ApproximateNow());
3536 connection_.GetTimeoutAlarm()->Fire();
3537 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3538 EXPECT_FALSE(connection_.connected());
3541 TEST_P(QuicConnectionTest, SendScheduler) {
3542 // Test that if we send a packet without delay, it is not queued.
3543 QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
3544 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3545 connection_.SendPacket(ENCRYPTION_NONE, 1, packet, kTestEntropyHash,
3546 HAS_RETRANSMITTABLE_DATA, false, false);
3547 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3550 TEST_P(QuicConnectionTest, SendSchedulerEAGAIN) {
3551 QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
3552 BlockOnNextWrite();
3553 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 1, _, _)).Times(0);
3554 connection_.SendPacket(ENCRYPTION_NONE, 1, packet, kTestEntropyHash,
3555 HAS_RETRANSMITTABLE_DATA, false, false);
3556 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3559 TEST_P(QuicConnectionTest, TestQueueLimitsOnSendStreamData) {
3560 // All packets carry version info till version is negotiated.
3561 size_t payload_length;
3562 size_t length = GetPacketLengthForOneStream(
3563 connection_.version(), kIncludeVersion, PACKET_8BYTE_CONNECTION_ID,
3564 PACKET_1BYTE_PACKET_NUMBER, NOT_IN_FEC_GROUP, &payload_length);
3565 connection_.set_max_packet_length(length);
3567 // Queue the first packet.
3568 EXPECT_CALL(*send_algorithm_,
3569 TimeUntilSend(_, _, _)).WillOnce(
3570 testing::Return(QuicTime::Delta::FromMicroseconds(10)));
3571 const string payload(payload_length, 'a');
3572 EXPECT_EQ(0u, connection_.SendStreamDataWithString(3, payload, 0, !kFin,
3573 nullptr).bytes_consumed);
3574 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3577 TEST_P(QuicConnectionTest, LoopThroughSendingPackets) {
3578 // All packets carry version info till version is negotiated.
3579 size_t payload_length;
3580 // GetPacketLengthForOneStream() assumes a stream offset of 0 in determining
3581 // packet length. The size of the offset field in a stream frame is 0 for
3582 // offset 0, and 2 for non-zero offsets up through 16K. Increase
3583 // max_packet_length by 2 so that subsequent packets containing subsequent
3584 // stream frames with non-zero offets will fit within the packet length.
3585 size_t length =
3586 2 + GetPacketLengthForOneStream(connection_.version(), kIncludeVersion,
3587 PACKET_8BYTE_CONNECTION_ID,
3588 PACKET_1BYTE_PACKET_NUMBER,
3589 NOT_IN_FEC_GROUP, &payload_length);
3590 connection_.set_max_packet_length(length);
3592 // Queue the first packet.
3593 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(7);
3594 // The first stream frame will have 2 fewer overhead bytes than the other six.
3595 const string payload(payload_length * 7 + 2, 'a');
3596 EXPECT_EQ(payload.size(),
3597 connection_.SendStreamDataWithString(1, payload, 0, !kFin, nullptr)
3598 .bytes_consumed);
3601 TEST_P(QuicConnectionTest, LoopThroughSendingPacketsWithTruncation) {
3602 // Set up a larger payload than will fit in one packet.
3603 const string payload(connection_.max_packet_length(), 'a');
3604 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
3606 // Now send some packets with no truncation.
3607 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3608 EXPECT_EQ(payload.size(),
3609 connection_.SendStreamDataWithString(
3610 3, payload, 0, !kFin, nullptr).bytes_consumed);
3611 // Track the size of the second packet here. The overhead will be the largest
3612 // we see in this test, due to the non-truncated connection id.
3613 size_t non_truncated_packet_size = writer_->last_packet_size();
3615 // Change to a 4 byte connection id.
3616 QuicConfig config;
3617 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 4);
3618 connection_.SetFromConfig(config);
3619 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3620 EXPECT_EQ(payload.size(),
3621 connection_.SendStreamDataWithString(
3622 3, payload, 0, !kFin, nullptr).bytes_consumed);
3623 // Verify that we have 8 fewer bytes than in the non-truncated case. The
3624 // first packet got 4 bytes of extra payload due to the truncation, and the
3625 // headers here are also 4 byte smaller.
3626 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() + 8);
3628 // Change to a 1 byte connection id.
3629 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 1);
3630 connection_.SetFromConfig(config);
3631 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3632 EXPECT_EQ(payload.size(),
3633 connection_.SendStreamDataWithString(
3634 3, payload, 0, !kFin, nullptr).bytes_consumed);
3635 // Just like above, we save 7 bytes on payload, and 7 on truncation.
3636 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() + 7 * 2);
3638 // Change to a 0 byte connection id.
3639 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
3640 connection_.SetFromConfig(config);
3641 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3642 EXPECT_EQ(payload.size(),
3643 connection_.SendStreamDataWithString(
3644 3, payload, 0, !kFin, nullptr).bytes_consumed);
3645 // Just like above, we save 8 bytes on payload, and 8 on truncation.
3646 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() + 8 * 2);
3649 TEST_P(QuicConnectionTest, SendDelayedAck) {
3650 QuicTime ack_time = clock_.ApproximateNow().Add(DefaultDelayedAckTime());
3651 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3652 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3653 const uint8 tag = 0x07;
3654 connection_.SetDecrypter(ENCRYPTION_INITIAL, new StrictTaggingDecrypter(tag));
3655 framer_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
3656 // Process a packet from the non-crypto stream.
3657 frame1_.stream_id = 3;
3659 // The same as ProcessPacket(1) except that ENCRYPTION_INITIAL is used
3660 // instead of ENCRYPTION_NONE.
3661 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3662 ProcessDataPacketAtLevel(1, 0, !kEntropyFlag, ENCRYPTION_INITIAL);
3664 // Check if delayed ack timer is running for the expected interval.
3665 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3666 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
3667 // Simulate delayed ack alarm firing.
3668 connection_.GetAckAlarm()->Fire();
3669 // Check that ack is sent and that delayed ack alarm is reset.
3670 EXPECT_EQ(2u, writer_->frame_count());
3671 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3672 EXPECT_FALSE(writer_->ack_frames().empty());
3673 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3676 TEST_P(QuicConnectionTest, SendDelayedAckOnHandshakeConfirmed) {
3677 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3678 ProcessPacket(1);
3679 // Check that ack is sent and that delayed ack alarm is set.
3680 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3681 QuicTime ack_time = clock_.ApproximateNow().Add(DefaultDelayedAckTime());
3682 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
3684 // Completing the handshake as the server does nothing.
3685 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_SERVER);
3686 connection_.OnHandshakeComplete();
3687 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3688 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
3690 // Complete the handshake as the client decreases the delayed ack time to 0ms.
3691 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_CLIENT);
3692 connection_.OnHandshakeComplete();
3693 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3694 EXPECT_EQ(clock_.ApproximateNow(), connection_.GetAckAlarm()->deadline());
3697 TEST_P(QuicConnectionTest, SendDelayedAckOnSecondPacket) {
3698 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3699 ProcessPacket(1);
3700 ProcessPacket(2);
3701 // Check that ack is sent and that delayed ack alarm is reset.
3702 EXPECT_EQ(2u, writer_->frame_count());
3703 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3704 EXPECT_FALSE(writer_->ack_frames().empty());
3705 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3708 TEST_P(QuicConnectionTest, NoAckOnOldNacks) {
3709 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3710 // Drop one packet, triggering a sequence of acks.
3711 ProcessPacket(2);
3712 size_t frames_per_ack = 2;
3713 EXPECT_EQ(frames_per_ack, writer_->frame_count());
3714 EXPECT_FALSE(writer_->ack_frames().empty());
3715 writer_->Reset();
3716 ProcessPacket(3);
3717 EXPECT_EQ(frames_per_ack, writer_->frame_count());
3718 EXPECT_FALSE(writer_->ack_frames().empty());
3719 writer_->Reset();
3720 ProcessPacket(4);
3721 EXPECT_EQ(frames_per_ack, writer_->frame_count());
3722 EXPECT_FALSE(writer_->ack_frames().empty());
3723 writer_->Reset();
3724 ProcessPacket(5);
3725 EXPECT_EQ(frames_per_ack, writer_->frame_count());
3726 EXPECT_FALSE(writer_->ack_frames().empty());
3727 writer_->Reset();
3728 // Now only set the timer on the 6th packet, instead of sending another ack.
3729 ProcessPacket(6);
3730 EXPECT_EQ(0u, writer_->frame_count());
3731 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3734 TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingPacket) {
3735 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3736 ProcessPacket(1);
3737 connection_.SendStreamDataWithString(kClientDataStreamId1, "foo", 0, !kFin,
3738 nullptr);
3739 // Check that ack is bundled with outgoing data and that delayed ack
3740 // alarm is reset.
3741 EXPECT_EQ(3u, writer_->frame_count());
3742 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3743 EXPECT_FALSE(writer_->ack_frames().empty());
3744 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3747 TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingCryptoPacket) {
3748 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3749 ProcessPacket(1);
3750 connection_.SendStreamDataWithString(kCryptoStreamId, "foo", 0, !kFin,
3751 nullptr);
3752 // Check that ack is bundled with outgoing crypto data.
3753 EXPECT_EQ(3u, writer_->frame_count());
3754 EXPECT_FALSE(writer_->ack_frames().empty());
3755 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3758 TEST_P(QuicConnectionTest, BlockAndBufferOnFirstCHLOPacketOfTwo) {
3759 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3760 ProcessPacket(1);
3761 BlockOnNextWrite();
3762 writer_->set_is_write_blocked_data_buffered(true);
3763 connection_.SendStreamDataWithString(kCryptoStreamId, "foo", 0, !kFin,
3764 nullptr);
3765 EXPECT_TRUE(writer_->IsWriteBlocked());
3766 EXPECT_FALSE(connection_.HasQueuedData());
3767 connection_.SendStreamDataWithString(kCryptoStreamId, "bar", 3, !kFin,
3768 nullptr);
3769 EXPECT_TRUE(writer_->IsWriteBlocked());
3770 EXPECT_TRUE(connection_.HasQueuedData());
3773 TEST_P(QuicConnectionTest, BundleAckForSecondCHLO) {
3774 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3775 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3776 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(
3777 IgnoreResult(InvokeWithoutArgs(&connection_,
3778 &TestConnection::SendCryptoStreamData)));
3779 // Process a packet from the crypto stream, which is frame1_'s default.
3780 // Receiving the CHLO as packet 2 first will cause the connection to
3781 // immediately send an ack, due to the packet gap.
3782 ProcessPacket(2);
3783 // Check that ack is sent and that delayed ack alarm is reset.
3784 EXPECT_EQ(3u, writer_->frame_count());
3785 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3786 EXPECT_EQ(1u, writer_->stream_frames().size());
3787 EXPECT_FALSE(writer_->ack_frames().empty());
3788 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3791 TEST_P(QuicConnectionTest, BundleAckWithDataOnIncomingAck) {
3792 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3793 connection_.SendStreamDataWithString(kClientDataStreamId1, "foo", 0, !kFin,
3794 nullptr);
3795 connection_.SendStreamDataWithString(kClientDataStreamId1, "foo", 3, !kFin,
3796 nullptr);
3797 // Ack the second packet, which will retransmit the first packet.
3798 QuicAckFrame ack = InitAckFrame(2);
3799 NackPacket(1, &ack);
3800 PacketNumberSet lost_packets;
3801 lost_packets.insert(1);
3802 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3803 .WillOnce(Return(lost_packets));
3804 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3805 ProcessAckPacket(&ack);
3806 EXPECT_EQ(1u, writer_->frame_count());
3807 EXPECT_EQ(1u, writer_->stream_frames().size());
3808 writer_->Reset();
3810 // Now ack the retransmission, which will both raise the high water mark
3811 // and see if there is more data to send.
3812 ack = InitAckFrame(3);
3813 NackPacket(1, &ack);
3814 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3815 .WillOnce(Return(PacketNumberSet()));
3816 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3817 ProcessAckPacket(&ack);
3819 // Check that no packet is sent and the ack alarm isn't set.
3820 EXPECT_EQ(0u, writer_->frame_count());
3821 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3822 writer_->Reset();
3824 // Send the same ack, but send both data and an ack together.
3825 ack = InitAckFrame(3);
3826 NackPacket(1, &ack);
3827 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3828 .WillOnce(Return(PacketNumberSet()));
3829 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(
3830 IgnoreResult(InvokeWithoutArgs(
3831 &connection_,
3832 &TestConnection::EnsureWritableAndSendStreamData5)));
3833 ProcessAckPacket(&ack);
3835 // Check that ack is bundled with outgoing data and the delayed ack
3836 // alarm is reset.
3837 EXPECT_EQ(3u, writer_->frame_count());
3838 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3839 EXPECT_FALSE(writer_->ack_frames().empty());
3840 EXPECT_EQ(1u, writer_->stream_frames().size());
3841 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3844 TEST_P(QuicConnectionTest, NoAckSentForClose) {
3845 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3846 ProcessPacket(1);
3847 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, true));
3848 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3849 ProcessClosePacket(2, 0);
3852 TEST_P(QuicConnectionTest, SendWhenDisconnected) {
3853 EXPECT_TRUE(connection_.connected());
3854 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, false));
3855 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, false);
3856 EXPECT_FALSE(connection_.connected());
3857 EXPECT_FALSE(connection_.CanWriteStreamData());
3858 QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
3859 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 1, _, _)).Times(0);
3860 connection_.SendPacket(ENCRYPTION_NONE, 1, packet, kTestEntropyHash,
3861 HAS_RETRANSMITTABLE_DATA, false, false);
3864 TEST_P(QuicConnectionTest, PublicReset) {
3865 QuicPublicResetPacket header;
3866 header.public_header.connection_id = connection_id_;
3867 header.public_header.reset_flag = true;
3868 header.public_header.version_flag = false;
3869 header.rejected_packet_number = 10101;
3870 scoped_ptr<QuicEncryptedPacket> packet(
3871 framer_.BuildPublicResetPacket(header));
3872 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PUBLIC_RESET, true));
3873 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *packet);
3876 TEST_P(QuicConnectionTest, GoAway) {
3877 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3879 QuicGoAwayFrame goaway;
3880 goaway.last_good_stream_id = 1;
3881 goaway.error_code = QUIC_PEER_GOING_AWAY;
3882 goaway.reason_phrase = "Going away.";
3883 EXPECT_CALL(visitor_, OnGoAway(_));
3884 ProcessGoAwayPacket(&goaway);
3887 TEST_P(QuicConnectionTest, WindowUpdate) {
3888 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3890 QuicWindowUpdateFrame window_update;
3891 window_update.stream_id = 3;
3892 window_update.byte_offset = 1234;
3893 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
3894 ProcessFramePacket(QuicFrame(&window_update));
3897 TEST_P(QuicConnectionTest, Blocked) {
3898 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3900 QuicBlockedFrame blocked;
3901 blocked.stream_id = 3;
3902 EXPECT_CALL(visitor_, OnBlockedFrame(_));
3903 ProcessFramePacket(QuicFrame(&blocked));
3906 TEST_P(QuicConnectionTest, ZeroBytePacket) {
3907 // Don't close the connection for zero byte packets.
3908 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
3909 QuicEncryptedPacket encrypted(nullptr, 0);
3910 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), encrypted);
3913 TEST_P(QuicConnectionTest, MissingPacketsBeforeLeastUnacked) {
3914 // Set the packet number of the ack packet to be least unacked (4).
3915 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 3);
3916 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3917 QuicStopWaitingFrame frame = InitStopWaitingFrame(4);
3918 ProcessStopWaitingPacket(&frame);
3919 EXPECT_TRUE(outgoing_ack()->missing_packets.empty());
3922 TEST_P(QuicConnectionTest, ReceivedEntropyHashCalculation) {
3923 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AtLeast(1));
3924 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3925 ProcessDataPacket(1, 1, kEntropyFlag);
3926 ProcessDataPacket(4, 1, kEntropyFlag);
3927 ProcessDataPacket(3, 1, !kEntropyFlag);
3928 ProcessDataPacket(7, 1, kEntropyFlag);
3929 EXPECT_EQ(146u, outgoing_ack()->entropy_hash);
3932 TEST_P(QuicConnectionTest, ReceivedEntropyHashCalculationHalfFEC) {
3933 // FEC packets should not change the entropy hash calculation.
3934 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AtLeast(1));
3935 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3936 ProcessDataPacket(1, 1, kEntropyFlag);
3937 ProcessFecPacket(4, 1, false, kEntropyFlag, nullptr);
3938 ProcessDataPacket(3, 3, !kEntropyFlag);
3939 ProcessFecPacket(7, 3, false, kEntropyFlag, nullptr);
3940 EXPECT_EQ(146u, outgoing_ack()->entropy_hash);
3943 TEST_P(QuicConnectionTest, UpdateEntropyForReceivedPackets) {
3944 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AtLeast(1));
3945 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3946 ProcessDataPacket(1, 1, kEntropyFlag);
3947 ProcessDataPacket(5, 1, kEntropyFlag);
3948 ProcessDataPacket(4, 1, !kEntropyFlag);
3949 EXPECT_EQ(34u, outgoing_ack()->entropy_hash);
3950 // Make 4th packet my least unacked, and update entropy for 2, 3 packets.
3951 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
3952 QuicPacketEntropyHash six_packet_entropy_hash = 0;
3953 QuicPacketEntropyHash random_entropy_hash = 129u;
3954 QuicStopWaitingFrame frame = InitStopWaitingFrame(4);
3955 frame.entropy_hash = random_entropy_hash;
3956 if (ProcessStopWaitingPacket(&frame)) {
3957 six_packet_entropy_hash = 1 << 6;
3960 EXPECT_EQ((random_entropy_hash + (1 << 5) + six_packet_entropy_hash),
3961 outgoing_ack()->entropy_hash);
3964 TEST_P(QuicConnectionTest, UpdateEntropyHashUptoCurrentPacket) {
3965 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AtLeast(1));
3966 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3967 ProcessDataPacket(1, 1, kEntropyFlag);
3968 ProcessDataPacket(5, 1, !kEntropyFlag);
3969 ProcessDataPacket(22, 1, kEntropyFlag);
3970 EXPECT_EQ(66u, outgoing_ack()->entropy_hash);
3971 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 22);
3972 QuicPacketEntropyHash random_entropy_hash = 85u;
3973 // Current packet is the least unacked packet.
3974 QuicPacketEntropyHash ack_entropy_hash;
3975 QuicStopWaitingFrame frame = InitStopWaitingFrame(23);
3976 frame.entropy_hash = random_entropy_hash;
3977 ack_entropy_hash = ProcessStopWaitingPacket(&frame);
3978 EXPECT_EQ((random_entropy_hash + ack_entropy_hash),
3979 outgoing_ack()->entropy_hash);
3980 ProcessDataPacket(25, 1, kEntropyFlag);
3981 EXPECT_EQ((random_entropy_hash + ack_entropy_hash + (1 << (25 % 8))),
3982 outgoing_ack()->entropy_hash);
3985 TEST_P(QuicConnectionTest, EntropyCalculationForTruncatedAck) {
3986 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AtLeast(1));
3987 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3988 QuicPacketEntropyHash entropy[51];
3989 entropy[0] = 0;
3990 for (int i = 1; i < 51; ++i) {
3991 bool should_send = i % 10 != 1;
3992 bool entropy_flag = (i & (i - 1)) != 0;
3993 if (!should_send) {
3994 entropy[i] = entropy[i - 1];
3995 continue;
3997 if (entropy_flag) {
3998 entropy[i] = entropy[i - 1] ^ (1 << (i % 8));
3999 } else {
4000 entropy[i] = entropy[i - 1];
4002 ProcessDataPacket(i, 1, entropy_flag);
4004 for (int i = 1; i < 50; ++i) {
4005 EXPECT_EQ(entropy[i], QuicConnectionPeer::ReceivedEntropyHash(
4006 &connection_, i));
4010 TEST_P(QuicConnectionTest, ServerSendsVersionNegotiationPacket) {
4011 connection_.SetSupportedVersions(QuicSupportedVersions());
4012 framer_.set_version_for_tests(QUIC_VERSION_UNSUPPORTED);
4014 QuicPacketHeader header;
4015 header.public_header.connection_id = connection_id_;
4016 header.public_header.version_flag = true;
4017 header.packet_packet_number = 12;
4019 QuicFrames frames;
4020 frames.push_back(QuicFrame(&frame1_));
4021 scoped_ptr<QuicPacket> packet(ConstructPacket(header, frames));
4022 char buffer[kMaxPacketSize];
4023 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPayload(
4024 ENCRYPTION_NONE, 12, *packet, buffer, kMaxPacketSize));
4026 framer_.set_version(version());
4027 connection_.set_perspective(Perspective::IS_SERVER);
4028 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
4029 EXPECT_TRUE(writer_->version_negotiation_packet() != nullptr);
4031 size_t num_versions = arraysize(kSupportedQuicVersions);
4032 ASSERT_EQ(num_versions,
4033 writer_->version_negotiation_packet()->versions.size());
4035 // We expect all versions in kSupportedQuicVersions to be
4036 // included in the packet.
4037 for (size_t i = 0; i < num_versions; ++i) {
4038 EXPECT_EQ(kSupportedQuicVersions[i],
4039 writer_->version_negotiation_packet()->versions[i]);
4043 TEST_P(QuicConnectionTest, ServerSendsVersionNegotiationPacketSocketBlocked) {
4044 connection_.SetSupportedVersions(QuicSupportedVersions());
4045 framer_.set_version_for_tests(QUIC_VERSION_UNSUPPORTED);
4047 QuicPacketHeader header;
4048 header.public_header.connection_id = connection_id_;
4049 header.public_header.version_flag = true;
4050 header.packet_packet_number = 12;
4052 QuicFrames frames;
4053 frames.push_back(QuicFrame(&frame1_));
4054 scoped_ptr<QuicPacket> packet(ConstructPacket(header, frames));
4055 char buffer[kMaxPacketSize];
4056 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPayload(
4057 ENCRYPTION_NONE, 12, *packet, buffer, kMaxPacketSize));
4059 framer_.set_version(version());
4060 connection_.set_perspective(Perspective::IS_SERVER);
4061 BlockOnNextWrite();
4062 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
4063 EXPECT_EQ(0u, writer_->last_packet_size());
4064 EXPECT_TRUE(connection_.HasQueuedData());
4066 writer_->SetWritable();
4067 connection_.OnCanWrite();
4068 EXPECT_TRUE(writer_->version_negotiation_packet() != nullptr);
4070 size_t num_versions = arraysize(kSupportedQuicVersions);
4071 ASSERT_EQ(num_versions,
4072 writer_->version_negotiation_packet()->versions.size());
4074 // We expect all versions in kSupportedQuicVersions to be
4075 // included in the packet.
4076 for (size_t i = 0; i < num_versions; ++i) {
4077 EXPECT_EQ(kSupportedQuicVersions[i],
4078 writer_->version_negotiation_packet()->versions[i]);
4082 TEST_P(QuicConnectionTest,
4083 ServerSendsVersionNegotiationPacketSocketBlockedDataBuffered) {
4084 connection_.SetSupportedVersions(QuicSupportedVersions());
4085 framer_.set_version_for_tests(QUIC_VERSION_UNSUPPORTED);
4087 QuicPacketHeader header;
4088 header.public_header.connection_id = connection_id_;
4089 header.public_header.version_flag = true;
4090 header.packet_packet_number = 12;
4092 QuicFrames frames;
4093 frames.push_back(QuicFrame(&frame1_));
4094 scoped_ptr<QuicPacket> packet(ConstructPacket(header, frames));
4095 char buffer[kMaxPacketSize];
4096 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPayload(
4097 ENCRYPTION_NONE, 12, *packet, buffer, kMaxPacketSize));
4099 framer_.set_version(version());
4100 connection_.set_perspective(Perspective::IS_SERVER);
4101 BlockOnNextWrite();
4102 writer_->set_is_write_blocked_data_buffered(true);
4103 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
4104 EXPECT_EQ(0u, writer_->last_packet_size());
4105 EXPECT_FALSE(connection_.HasQueuedData());
4108 TEST_P(QuicConnectionTest, ClientHandlesVersionNegotiation) {
4109 // Start out with some unsupported version.
4110 QuicConnectionPeer::GetFramer(&connection_)->set_version_for_tests(
4111 QUIC_VERSION_UNSUPPORTED);
4113 QuicPacketHeader header;
4114 header.public_header.connection_id = connection_id_;
4115 header.public_header.version_flag = true;
4116 header.packet_packet_number = 12;
4118 QuicVersionVector supported_versions;
4119 for (size_t i = 0; i < arraysize(kSupportedQuicVersions); ++i) {
4120 supported_versions.push_back(kSupportedQuicVersions[i]);
4123 // Send a version negotiation packet.
4124 scoped_ptr<QuicEncryptedPacket> encrypted(
4125 framer_.BuildVersionNegotiationPacket(
4126 header.public_header, supported_versions));
4127 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
4129 // Now force another packet. The connection should transition into
4130 // NEGOTIATED_VERSION state and tell the packet creator to StopSendingVersion.
4131 header.public_header.version_flag = false;
4132 QuicFrames frames;
4133 frames.push_back(QuicFrame(&frame1_));
4134 scoped_ptr<QuicPacket> packet(ConstructPacket(header, frames));
4135 char buffer[kMaxPacketSize];
4136 encrypted.reset(framer_.EncryptPayload(ENCRYPTION_NONE, 12, *packet, buffer,
4137 kMaxPacketSize));
4138 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4139 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4140 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
4142 ASSERT_FALSE(QuicPacketCreatorPeer::SendVersionInPacket(creator_));
4145 TEST_P(QuicConnectionTest, BadVersionNegotiation) {
4146 QuicPacketHeader header;
4147 header.public_header.connection_id = connection_id_;
4148 header.public_header.version_flag = true;
4149 header.packet_packet_number = 12;
4151 QuicVersionVector supported_versions;
4152 for (size_t i = 0; i < arraysize(kSupportedQuicVersions); ++i) {
4153 supported_versions.push_back(kSupportedQuicVersions[i]);
4156 // Send a version negotiation packet with the version the client started with.
4157 // It should be rejected.
4158 EXPECT_CALL(visitor_,
4159 OnConnectionClosed(QUIC_INVALID_VERSION_NEGOTIATION_PACKET,
4160 false));
4161 scoped_ptr<QuicEncryptedPacket> encrypted(
4162 framer_.BuildVersionNegotiationPacket(
4163 header.public_header, supported_versions));
4164 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
4167 TEST_P(QuicConnectionTest, CheckSendStats) {
4168 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4169 connection_.SendStreamDataWithString(3, "first", 0, !kFin, nullptr);
4170 size_t first_packet_size = writer_->last_packet_size();
4172 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4173 connection_.SendStreamDataWithString(5, "second", 0, !kFin, nullptr);
4174 size_t second_packet_size = writer_->last_packet_size();
4176 // 2 retransmissions due to rto, 1 due to explicit nack.
4177 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
4178 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
4180 // Retransmit due to RTO.
4181 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
4182 connection_.GetRetransmissionAlarm()->Fire();
4184 // Retransmit due to explicit nacks.
4185 QuicAckFrame nack_three = InitAckFrame(4);
4186 NackPacket(3, &nack_three);
4187 NackPacket(1, &nack_three);
4188 PacketNumberSet lost_packets;
4189 lost_packets.insert(1);
4190 lost_packets.insert(3);
4191 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4192 .WillOnce(Return(lost_packets));
4193 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4194 EXPECT_CALL(visitor_, OnCanWrite());
4195 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4196 ProcessAckPacket(&nack_three);
4198 EXPECT_CALL(*send_algorithm_, BandwidthEstimate()).WillOnce(
4199 Return(QuicBandwidth::Zero()));
4201 const QuicConnectionStats& stats = connection_.GetStats();
4202 EXPECT_EQ(3 * first_packet_size + 2 * second_packet_size - kQuicVersionSize,
4203 stats.bytes_sent);
4204 EXPECT_EQ(5u, stats.packets_sent);
4205 EXPECT_EQ(2 * first_packet_size + second_packet_size - kQuicVersionSize,
4206 stats.bytes_retransmitted);
4207 EXPECT_EQ(3u, stats.packets_retransmitted);
4208 EXPECT_EQ(1u, stats.rto_count);
4209 EXPECT_EQ(kDefaultMaxPacketSize, stats.max_packet_size);
4212 TEST_P(QuicConnectionTest, CheckReceiveStats) {
4213 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4215 size_t received_bytes = 0;
4216 received_bytes += ProcessFecProtectedPacket(1, false, !kEntropyFlag);
4217 received_bytes += ProcessFecProtectedPacket(3, false, !kEntropyFlag);
4218 // Should be counted against dropped packets.
4219 received_bytes += ProcessDataPacket(3, 1, !kEntropyFlag);
4220 received_bytes += ProcessFecPacket(4, 1, true, !kEntropyFlag, nullptr);
4222 EXPECT_CALL(*send_algorithm_, BandwidthEstimate()).WillOnce(
4223 Return(QuicBandwidth::Zero()));
4225 const QuicConnectionStats& stats = connection_.GetStats();
4226 EXPECT_EQ(received_bytes, stats.bytes_received);
4227 EXPECT_EQ(4u, stats.packets_received);
4229 EXPECT_EQ(1u, stats.packets_revived);
4230 EXPECT_EQ(1u, stats.packets_dropped);
4233 TEST_P(QuicConnectionTest, TestFecGroupLimits) {
4234 // Create and return a group for 1.
4235 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 1) != nullptr);
4237 // Create and return a group for 2.
4238 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 2) != nullptr);
4240 // Create and return a group for 4. This should remove 1 but not 2.
4241 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 4) != nullptr);
4242 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 1) == nullptr);
4243 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 2) != nullptr);
4245 // Create and return a group for 3. This will kill off 2.
4246 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 3) != nullptr);
4247 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 2) == nullptr);
4249 // Verify that adding 5 kills off 3, despite 4 being created before 3.
4250 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 5) != nullptr);
4251 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 4) != nullptr);
4252 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 3) == nullptr);
4255 TEST_P(QuicConnectionTest, ProcessFramesIfPacketClosedConnection) {
4256 // Construct a packet with stream frame and connection close frame.
4257 QuicPacketHeader header;
4258 header.public_header.connection_id = connection_id_;
4259 header.packet_packet_number = 1;
4260 header.public_header.version_flag = false;
4262 QuicConnectionCloseFrame qccf;
4263 qccf.error_code = QUIC_PEER_GOING_AWAY;
4265 QuicFrames frames;
4266 frames.push_back(QuicFrame(&frame1_));
4267 frames.push_back(QuicFrame(&qccf));
4268 scoped_ptr<QuicPacket> packet(ConstructPacket(header, frames));
4269 EXPECT_TRUE(nullptr != packet.get());
4270 char buffer[kMaxPacketSize];
4271 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPayload(
4272 ENCRYPTION_NONE, 1, *packet, buffer, kMaxPacketSize));
4274 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, true));
4275 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4276 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4278 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
4281 TEST_P(QuicConnectionTest, SelectMutualVersion) {
4282 connection_.SetSupportedVersions(QuicSupportedVersions());
4283 // Set the connection to speak the lowest quic version.
4284 connection_.set_version(QuicVersionMin());
4285 EXPECT_EQ(QuicVersionMin(), connection_.version());
4287 // Pass in available versions which includes a higher mutually supported
4288 // version. The higher mutually supported version should be selected.
4289 QuicVersionVector supported_versions;
4290 for (size_t i = 0; i < arraysize(kSupportedQuicVersions); ++i) {
4291 supported_versions.push_back(kSupportedQuicVersions[i]);
4293 EXPECT_TRUE(connection_.SelectMutualVersion(supported_versions));
4294 EXPECT_EQ(QuicVersionMax(), connection_.version());
4296 // Expect that the lowest version is selected.
4297 // Ensure the lowest supported version is less than the max, unless they're
4298 // the same.
4299 EXPECT_LE(QuicVersionMin(), QuicVersionMax());
4300 QuicVersionVector lowest_version_vector;
4301 lowest_version_vector.push_back(QuicVersionMin());
4302 EXPECT_TRUE(connection_.SelectMutualVersion(lowest_version_vector));
4303 EXPECT_EQ(QuicVersionMin(), connection_.version());
4305 // Shouldn't be able to find a mutually supported version.
4306 QuicVersionVector unsupported_version;
4307 unsupported_version.push_back(QUIC_VERSION_UNSUPPORTED);
4308 EXPECT_FALSE(connection_.SelectMutualVersion(unsupported_version));
4311 TEST_P(QuicConnectionTest, ConnectionCloseWhenWritable) {
4312 EXPECT_FALSE(writer_->IsWriteBlocked());
4314 // Send a packet.
4315 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
4316 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4317 EXPECT_EQ(1u, writer_->packets_write_attempts());
4319 TriggerConnectionClose();
4320 EXPECT_EQ(2u, writer_->packets_write_attempts());
4323 TEST_P(QuicConnectionTest, ConnectionCloseGettingWriteBlocked) {
4324 BlockOnNextWrite();
4325 TriggerConnectionClose();
4326 EXPECT_EQ(1u, writer_->packets_write_attempts());
4327 EXPECT_TRUE(writer_->IsWriteBlocked());
4330 TEST_P(QuicConnectionTest, ConnectionCloseWhenWriteBlocked) {
4331 BlockOnNextWrite();
4332 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
4333 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4334 EXPECT_EQ(1u, writer_->packets_write_attempts());
4335 EXPECT_TRUE(writer_->IsWriteBlocked());
4336 TriggerConnectionClose();
4337 EXPECT_EQ(1u, writer_->packets_write_attempts());
4340 TEST_P(QuicConnectionTest, AckNotifierTriggerCallback) {
4341 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4343 // Create a delegate which we expect to be called.
4344 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4345 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(1);
4347 // Send some data, which will register the delegate to be notified.
4348 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
4350 // Process an ACK from the server which should trigger the callback.
4351 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4352 QuicAckFrame frame = InitAckFrame(1);
4353 ProcessAckPacket(&frame);
4356 TEST_P(QuicConnectionTest, AckNotifierFailToTriggerCallback) {
4357 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4359 // Create a delegate which we don't expect to be called.
4360 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4361 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(0);
4363 // Send some data, which will register the delegate to be notified. This will
4364 // not be ACKed and so the delegate should never be called.
4365 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
4367 // Send some other data which we will ACK.
4368 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
4369 connection_.SendStreamDataWithString(1, "bar", 0, !kFin, nullptr);
4371 // Now we receive ACK for packets 2 and 3, but importantly missing packet 1
4372 // which we registered to be notified about.
4373 QuicAckFrame frame = InitAckFrame(3);
4374 NackPacket(1, &frame);
4375 PacketNumberSet lost_packets;
4376 lost_packets.insert(1);
4377 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4378 .WillOnce(Return(lost_packets));
4379 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4380 ProcessAckPacket(&frame);
4383 TEST_P(QuicConnectionTest, AckNotifierCallbackAfterRetransmission) {
4384 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4386 // Create a delegate which we expect to be called.
4387 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4388 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(1);
4390 // Send four packets, and register to be notified on ACK of packet 2.
4391 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
4392 connection_.SendStreamDataWithString(3, "bar", 0, !kFin, delegate.get());
4393 connection_.SendStreamDataWithString(3, "baz", 0, !kFin, nullptr);
4394 connection_.SendStreamDataWithString(3, "qux", 0, !kFin, nullptr);
4396 // Now we receive ACK for packets 1, 3, and 4 and lose 2.
4397 QuicAckFrame frame = InitAckFrame(4);
4398 NackPacket(2, &frame);
4399 PacketNumberSet lost_packets;
4400 lost_packets.insert(2);
4401 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4402 .WillOnce(Return(lost_packets));
4403 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4404 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4405 ProcessAckPacket(&frame);
4407 // Now we get an ACK for packet 5 (retransmitted packet 2), which should
4408 // trigger the callback.
4409 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4410 .WillRepeatedly(Return(PacketNumberSet()));
4411 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4412 QuicAckFrame second_ack_frame = InitAckFrame(5);
4413 ProcessAckPacket(&second_ack_frame);
4416 // AckNotifierCallback is triggered by the ack of a packet that timed
4417 // out and was retransmitted, even though the retransmission has a
4418 // different packet number.
4419 TEST_P(QuicConnectionTest, AckNotifierCallbackForAckAfterRTO) {
4420 InSequence s;
4422 // Create a delegate which we expect to be called.
4423 scoped_refptr<MockAckNotifierDelegate> delegate(
4424 new StrictMock<MockAckNotifierDelegate>);
4426 QuicTime default_retransmission_time = clock_.ApproximateNow().Add(
4427 DefaultRetransmissionTime());
4428 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, delegate.get());
4429 EXPECT_EQ(1u, stop_waiting()->least_unacked);
4431 EXPECT_EQ(1u, writer_->header().packet_packet_number);
4432 EXPECT_EQ(default_retransmission_time,
4433 connection_.GetRetransmissionAlarm()->deadline());
4434 // Simulate the retransmission alarm firing.
4435 clock_.AdvanceTime(DefaultRetransmissionTime());
4436 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 2u, _, _));
4437 connection_.GetRetransmissionAlarm()->Fire();
4438 EXPECT_EQ(2u, writer_->header().packet_packet_number);
4439 // We do not raise the high water mark yet.
4440 EXPECT_EQ(1u, stop_waiting()->least_unacked);
4442 // Ack the original packet, which will revert the RTO.
4443 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4444 EXPECT_CALL(*delegate, OnAckNotification(1, _, _));
4445 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4446 QuicAckFrame ack_frame = InitAckFrame(1);
4447 ProcessAckPacket(&ack_frame);
4449 // Delegate is not notified again when the retransmit is acked.
4450 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4451 QuicAckFrame second_ack_frame = InitAckFrame(2);
4452 ProcessAckPacket(&second_ack_frame);
4455 // AckNotifierCallback is triggered by the ack of a packet that was
4456 // previously nacked, even though the retransmission has a different
4457 // packet number.
4458 TEST_P(QuicConnectionTest, AckNotifierCallbackForAckOfNackedPacket) {
4459 InSequence s;
4461 // Create a delegate which we expect to be called.
4462 scoped_refptr<MockAckNotifierDelegate> delegate(
4463 new StrictMock<MockAckNotifierDelegate>);
4465 // Send four packets, and register to be notified on ACK of packet 2.
4466 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
4467 connection_.SendStreamDataWithString(3, "bar", 0, !kFin, delegate.get());
4468 connection_.SendStreamDataWithString(3, "baz", 0, !kFin, nullptr);
4469 connection_.SendStreamDataWithString(3, "qux", 0, !kFin, nullptr);
4471 // Now we receive ACK for packets 1, 3, and 4 and lose 2.
4472 QuicAckFrame frame = InitAckFrame(4);
4473 NackPacket(2, &frame);
4474 PacketNumberSet lost_packets;
4475 lost_packets.insert(2);
4476 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4477 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4478 .WillOnce(Return(lost_packets));
4479 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4480 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4481 ProcessAckPacket(&frame);
4483 // Now we get an ACK for packet 2, which was previously nacked.
4484 PacketNumberSet no_lost_packets;
4485 EXPECT_CALL(*delegate.get(), OnAckNotification(1, _, _));
4486 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4487 .WillOnce(Return(no_lost_packets));
4488 QuicAckFrame second_ack_frame = InitAckFrame(4);
4489 ProcessAckPacket(&second_ack_frame);
4491 // Verify that the delegate is not notified again when the
4492 // retransmit is acked.
4493 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4494 .WillOnce(Return(no_lost_packets));
4495 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4496 QuicAckFrame third_ack_frame = InitAckFrame(5);
4497 ProcessAckPacket(&third_ack_frame);
4500 TEST_P(QuicConnectionTest, AckNotifierFECTriggerCallback) {
4501 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4503 // Create a delegate which we expect to be called.
4504 scoped_refptr<MockAckNotifierDelegate> delegate(
4505 new MockAckNotifierDelegate);
4506 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(1);
4508 // Send some data, which will register the delegate to be notified.
4509 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
4510 connection_.SendStreamDataWithString(2, "bar", 0, !kFin, nullptr);
4512 // Process an ACK from the server with a revived packet, which should trigger
4513 // the callback.
4514 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4515 QuicAckFrame frame = InitAckFrame(2);
4516 NackPacket(1, &frame);
4517 frame.revived_packets.insert(1);
4518 ProcessAckPacket(&frame);
4519 // If the ack is processed again, the notifier should not be called again.
4520 ProcessAckPacket(&frame);
4523 TEST_P(QuicConnectionTest, AckNotifierCallbackAfterFECRecovery) {
4524 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4525 EXPECT_CALL(visitor_, OnCanWrite());
4527 // Create a delegate which we expect to be called.
4528 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4529 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(1);
4531 // Expect ACKs for 1 packet.
4532 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4534 // Send one packet, and register to be notified on ACK.
4535 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
4537 // Ack packet gets dropped, but we receive an FEC packet that covers it.
4538 // Should recover the Ack packet and trigger the notification callback.
4539 QuicFrames frames;
4541 QuicAckFrame ack_frame = InitAckFrame(1);
4542 frames.push_back(QuicFrame(&ack_frame));
4544 // Dummy stream frame to satisfy expectations set elsewhere.
4545 frames.push_back(QuicFrame(&frame1_));
4547 QuicPacketHeader ack_header;
4548 ack_header.public_header.connection_id = connection_id_;
4549 ack_header.public_header.reset_flag = false;
4550 ack_header.public_header.version_flag = false;
4551 ack_header.entropy_flag = !kEntropyFlag;
4552 ack_header.fec_flag = true;
4553 ack_header.packet_packet_number = 1;
4554 ack_header.is_in_fec_group = IN_FEC_GROUP;
4555 ack_header.fec_group = 1;
4557 QuicPacket* packet = BuildUnsizedDataPacket(&framer_, ack_header, frames);
4559 // Take the packet which contains the ACK frame, and construct and deliver an
4560 // FEC packet which allows the ACK packet to be recovered.
4561 ProcessFecPacket(2, 1, true, !kEntropyFlag, packet);
4564 TEST_P(QuicConnectionTest, NetworkChangeVisitorCwndCallbackChangesFecState) {
4565 size_t max_packets_per_fec_group = creator_->max_packets_per_fec_group();
4567 QuicSentPacketManager::NetworkChangeVisitor* visitor =
4568 QuicSentPacketManagerPeer::GetNetworkChangeVisitor(manager_);
4569 EXPECT_TRUE(visitor);
4571 // Increase FEC group size by increasing congestion window to a large number.
4572 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
4573 Return(1000 * kDefaultTCPMSS));
4574 visitor->OnCongestionWindowChange();
4575 EXPECT_LT(max_packets_per_fec_group, creator_->max_packets_per_fec_group());
4578 TEST_P(QuicConnectionTest, NetworkChangeVisitorConfigCallbackChangesFecState) {
4579 QuicSentPacketManager::NetworkChangeVisitor* visitor =
4580 QuicSentPacketManagerPeer::GetNetworkChangeVisitor(manager_);
4581 EXPECT_TRUE(visitor);
4582 EXPECT_EQ(QuicTime::Delta::Zero(),
4583 QuicPacketGeneratorPeer::GetFecTimeout(generator_));
4585 // Verify that sending a config with a new initial rtt changes fec timeout.
4586 // Create and process a config with a non-zero initial RTT.
4587 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4588 QuicConfig config;
4589 config.SetInitialRoundTripTimeUsToSend(300000);
4590 connection_.SetFromConfig(config);
4591 EXPECT_LT(QuicTime::Delta::Zero(),
4592 QuicPacketGeneratorPeer::GetFecTimeout(generator_));
4595 TEST_P(QuicConnectionTest, NetworkChangeVisitorRttCallbackChangesFecState) {
4596 // Verify that sending a config with a new initial rtt changes fec timeout.
4597 QuicSentPacketManager::NetworkChangeVisitor* visitor =
4598 QuicSentPacketManagerPeer::GetNetworkChangeVisitor(manager_);
4599 EXPECT_TRUE(visitor);
4600 EXPECT_EQ(QuicTime::Delta::Zero(),
4601 QuicPacketGeneratorPeer::GetFecTimeout(generator_));
4603 // Increase FEC timeout by increasing RTT.
4604 RttStats* rtt_stats = QuicSentPacketManagerPeer::GetRttStats(manager_);
4605 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(300),
4606 QuicTime::Delta::Zero(), QuicTime::Zero());
4607 visitor->OnRttChange();
4608 EXPECT_LT(QuicTime::Delta::Zero(),
4609 QuicPacketGeneratorPeer::GetFecTimeout(generator_));
4612 TEST_P(QuicConnectionTest, OnPacketHeaderDebugVisitor) {
4613 QuicPacketHeader header;
4615 scoped_ptr<MockQuicConnectionDebugVisitor> debug_visitor(
4616 new MockQuicConnectionDebugVisitor());
4617 connection_.set_debug_visitor(debug_visitor.get());
4618 EXPECT_CALL(*debug_visitor, OnPacketHeader(Ref(header))).Times(1);
4619 connection_.OnPacketHeader(header);
4622 TEST_P(QuicConnectionTest, Pacing) {
4623 TestConnection server(connection_id_, IPEndPoint(), helper_.get(), factory_,
4624 Perspective::IS_SERVER, version());
4625 TestConnection client(connection_id_, IPEndPoint(), helper_.get(), factory_,
4626 Perspective::IS_CLIENT, version());
4627 EXPECT_FALSE(client.sent_packet_manager().using_pacing());
4628 EXPECT_FALSE(server.sent_packet_manager().using_pacing());
4631 TEST_P(QuicConnectionTest, ControlFramesInstigateAcks) {
4632 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4634 // Send a WINDOW_UPDATE frame.
4635 QuicWindowUpdateFrame window_update;
4636 window_update.stream_id = 3;
4637 window_update.byte_offset = 1234;
4638 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
4639 ProcessFramePacket(QuicFrame(&window_update));
4641 // Ensure that this has caused the ACK alarm to be set.
4642 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
4643 EXPECT_TRUE(ack_alarm->IsSet());
4645 // Cancel alarm, and try again with BLOCKED frame.
4646 ack_alarm->Cancel();
4647 QuicBlockedFrame blocked;
4648 blocked.stream_id = 3;
4649 EXPECT_CALL(visitor_, OnBlockedFrame(_));
4650 ProcessFramePacket(QuicFrame(&blocked));
4651 EXPECT_TRUE(ack_alarm->IsSet());
4654 TEST_P(QuicConnectionTest, NoDataNoFin) {
4655 // Make sure that a call to SendStreamWithData, with no data and no FIN, does
4656 // not result in a QuicAckNotifier being used-after-free (fail under ASAN).
4657 // Regression test for b/18594622
4658 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4659 EXPECT_DFATAL(
4660 connection_.SendStreamDataWithString(3, "", 0, !kFin, delegate.get()),
4661 "Attempt to send empty stream frame");
4664 TEST_P(QuicConnectionTest, FecSendPolicyReceivedConnectionOption) {
4665 // Test sending SetReceivedConnectionOptions when FEC send policy is
4666 // FEC_ANY_TRIGGER.
4667 if (GetParam().fec_send_policy == FEC_ALARM_TRIGGER) {
4668 return;
4670 connection_.set_perspective(Perspective::IS_SERVER);
4672 // Test ReceivedConnectionOptions.
4673 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4674 QuicConfig config;
4675 QuicTagVector copt;
4676 copt.push_back(kFSPA);
4677 QuicConfigPeer::SetReceivedConnectionOptions(&config, copt);
4678 EXPECT_EQ(FEC_ANY_TRIGGER, generator_->fec_send_policy());
4679 connection_.SetFromConfig(config);
4680 EXPECT_EQ(FEC_ALARM_TRIGGER, generator_->fec_send_policy());
4683 // TODO(rtenneti): Delete this code after the 0.25 RTT FEC experiment.
4684 TEST_P(QuicConnectionTest, FecRTTMultiplierReceivedConnectionOption) {
4685 connection_.set_perspective(Perspective::IS_SERVER);
4687 // Test ReceivedConnectionOptions.
4688 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4689 QuicConfig config;
4690 QuicTagVector copt;
4691 copt.push_back(kFRTT);
4692 QuicConfigPeer::SetReceivedConnectionOptions(&config, copt);
4693 float rtt_multiplier_for_fec_timeout =
4694 generator_->rtt_multiplier_for_fec_timeout();
4695 connection_.SetFromConfig(config);
4696 // New RTT multiplier is half of the old RTT multiplier.
4697 EXPECT_EQ(rtt_multiplier_for_fec_timeout,
4698 generator_->rtt_multiplier_for_fec_timeout() * 2);
4701 TEST_P(QuicConnectionTest, DoNotSendGoAwayTwice) {
4702 EXPECT_FALSE(connection_.goaway_sent());
4703 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4704 connection_.SendGoAway(QUIC_PEER_GOING_AWAY, kHeadersStreamId, "Going Away.");
4705 EXPECT_TRUE(connection_.goaway_sent());
4706 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4707 connection_.SendGoAway(QUIC_PEER_GOING_AWAY, kHeadersStreamId, "Going Away.");
4710 } // namespace
4711 } // namespace test
4712 } // namespace net