Update V8 to version 4.7.42.
[chromium-blink-merge.git] / net / quic / quic_connection_test.cc
blob5bff36b3f9dee4c91a066abcb1a78165df4513e7
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 // clang-format off
2670 QuicPacketNumberLength lengths[] = {
2671 PACKET_6BYTE_PACKET_NUMBER, PACKET_4BYTE_PACKET_NUMBER,
2672 PACKET_2BYTE_PACKET_NUMBER, PACKET_1BYTE_PACKET_NUMBER};
2673 // clang-format on
2674 // For each packet number length size, revive a packet and check sequence
2675 // number length in the revived packet.
2676 for (size_t i = 0; i < arraysize(lengths); ++i) {
2677 // Set packet_number_length_ (for data and FEC packets).
2678 packet_number_length_ = lengths[i];
2679 fec_packet += 2;
2680 // Don't send missing packet, but send fec packet right after it.
2681 ProcessFecPacket(fec_packet, fec_packet - 1, true, !kEntropyFlag, nullptr);
2682 // packet number length in the revived header should be the same as
2683 // in the original data/fec packet headers.
2684 EXPECT_EQ(packet_number_length_,
2685 fec_visitor->revived_header().public_header.packet_number_length);
2689 TEST_P(QuicConnectionTest, ReviveMissingPacketWithVaryingConnectionIdLengths) {
2690 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2692 // Set up a debug visitor to the connection.
2693 scoped_ptr<FecQuicConnectionDebugVisitor> fec_visitor(
2694 new FecQuicConnectionDebugVisitor());
2695 connection_.set_debug_visitor(fec_visitor.get());
2697 QuicPacketNumber fec_packet = 0;
2698 QuicConnectionIdLength lengths[] = {PACKET_8BYTE_CONNECTION_ID,
2699 PACKET_4BYTE_CONNECTION_ID,
2700 PACKET_1BYTE_CONNECTION_ID,
2701 PACKET_0BYTE_CONNECTION_ID};
2702 // For each connection id length size, revive a packet and check connection
2703 // id length in the revived packet.
2704 for (size_t i = 0; i < arraysize(lengths); ++i) {
2705 // Set connection id length (for data and FEC packets).
2706 connection_id_length_ = lengths[i];
2707 fec_packet += 2;
2708 // Don't send missing packet, but send fec packet right after it.
2709 ProcessFecPacket(fec_packet, fec_packet - 1, true, !kEntropyFlag, nullptr);
2710 // Connection id length in the revived header should be the same as
2711 // in the original data/fec packet headers.
2712 EXPECT_EQ(connection_id_length_,
2713 fec_visitor->revived_header().public_header.connection_id_length);
2717 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPacketThenFecPacket) {
2718 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2720 ProcessFecProtectedPacket(1, false, kEntropyFlag);
2721 // Don't send missing packet 2.
2722 ProcessFecPacket(3, 1, true, !kEntropyFlag, nullptr);
2723 // Entropy flag should be true, so entropy should not be 0.
2724 EXPECT_NE(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2727 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPacketsThenFecPacket) {
2728 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2730 ProcessFecProtectedPacket(1, false, !kEntropyFlag);
2731 // Don't send missing packet 2.
2732 ProcessFecProtectedPacket(3, false, !kEntropyFlag);
2733 ProcessFecPacket(4, 1, true, kEntropyFlag, nullptr);
2734 // Ensure QUIC no longer revives entropy for lost packets.
2735 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2736 EXPECT_NE(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 4));
2739 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPacket) {
2740 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2742 // Don't send missing packet 1.
2743 ProcessFecPacket(3, 1, false, !kEntropyFlag, nullptr);
2744 // Out of order.
2745 ProcessFecProtectedPacket(2, true, !kEntropyFlag);
2746 // Entropy flag should be false, so entropy should be 0.
2747 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2750 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPackets) {
2751 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2753 ProcessFecProtectedPacket(1, false, !kEntropyFlag);
2754 // Don't send missing packet 2.
2755 ProcessFecPacket(6, 1, false, kEntropyFlag, nullptr);
2756 ProcessFecProtectedPacket(3, false, kEntropyFlag);
2757 ProcessFecProtectedPacket(4, false, kEntropyFlag);
2758 ProcessFecProtectedPacket(5, true, !kEntropyFlag);
2759 // Ensure entropy is not revived for the missing packet.
2760 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2761 EXPECT_NE(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 3));
2764 TEST_P(QuicConnectionTest, TLP) {
2765 QuicSentPacketManagerPeer::SetMaxTailLossProbes(manager_, 1);
2767 SendStreamDataToPeer(3, "foo", 0, !kFin, nullptr);
2768 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2769 QuicTime retransmission_time =
2770 connection_.GetRetransmissionAlarm()->deadline();
2771 EXPECT_NE(QuicTime::Zero(), retransmission_time);
2773 EXPECT_EQ(1u, writer_->header().packet_packet_number);
2774 // Simulate the retransmission alarm firing and sending a tlp,
2775 // so send algorithm's OnRetransmissionTimeout is not called.
2776 clock_.AdvanceTime(retransmission_time.Subtract(clock_.Now()));
2777 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 2u, _, _));
2778 connection_.GetRetransmissionAlarm()->Fire();
2779 EXPECT_EQ(2u, writer_->header().packet_packet_number);
2780 // We do not raise the high water mark yet.
2781 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2784 TEST_P(QuicConnectionTest, RTO) {
2785 QuicTime default_retransmission_time = clock_.ApproximateNow().Add(
2786 DefaultRetransmissionTime());
2787 SendStreamDataToPeer(3, "foo", 0, !kFin, nullptr);
2788 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2790 EXPECT_EQ(1u, writer_->header().packet_packet_number);
2791 EXPECT_EQ(default_retransmission_time,
2792 connection_.GetRetransmissionAlarm()->deadline());
2793 // Simulate the retransmission alarm firing.
2794 clock_.AdvanceTime(DefaultRetransmissionTime());
2795 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 2u, _, _));
2796 connection_.GetRetransmissionAlarm()->Fire();
2797 EXPECT_EQ(2u, writer_->header().packet_packet_number);
2798 // We do not raise the high water mark yet.
2799 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2802 TEST_P(QuicConnectionTest, RTOWithSameEncryptionLevel) {
2803 QuicTime default_retransmission_time = clock_.ApproximateNow().Add(
2804 DefaultRetransmissionTime());
2805 use_tagging_decrypter();
2807 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
2808 // the end of the packet. We can test this to check which encrypter was used.
2809 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2810 SendStreamDataToPeer(3, "foo", 0, !kFin, nullptr);
2811 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
2813 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2814 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2815 SendStreamDataToPeer(3, "foo", 0, !kFin, nullptr);
2816 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2818 EXPECT_EQ(default_retransmission_time,
2819 connection_.GetRetransmissionAlarm()->deadline());
2821 InSequence s;
2822 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 3, _, _));
2823 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 4, _, _));
2826 // Simulate the retransmission alarm firing.
2827 clock_.AdvanceTime(DefaultRetransmissionTime());
2828 connection_.GetRetransmissionAlarm()->Fire();
2830 // Packet should have been sent with ENCRYPTION_NONE.
2831 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_previous_packet());
2833 // Packet should have been sent with ENCRYPTION_INITIAL.
2834 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2837 TEST_P(QuicConnectionTest, SendHandshakeMessages) {
2838 use_tagging_decrypter();
2839 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
2840 // the end of the packet. We can test this to check which encrypter was used.
2841 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2843 // Attempt to send a handshake message and have the socket block.
2844 EXPECT_CALL(*send_algorithm_,
2845 TimeUntilSend(_, _, _)).WillRepeatedly(
2846 testing::Return(QuicTime::Delta::Zero()));
2847 BlockOnNextWrite();
2848 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
2849 // The packet should be serialized, but not queued.
2850 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2852 // Switch to the new encrypter.
2853 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2854 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2856 // Now become writeable and flush the packets.
2857 writer_->SetWritable();
2858 EXPECT_CALL(visitor_, OnCanWrite());
2859 connection_.OnCanWrite();
2860 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2862 // Verify that the handshake packet went out at the null encryption.
2863 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
2866 TEST_P(QuicConnectionTest,
2867 DropRetransmitsForNullEncryptedPacketAfterForwardSecure) {
2868 use_tagging_decrypter();
2869 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2870 QuicPacketNumber packet_number;
2871 SendStreamDataToPeer(3, "foo", 0, !kFin, &packet_number);
2873 // Simulate the retransmission alarm firing and the socket blocking.
2874 BlockOnNextWrite();
2875 clock_.AdvanceTime(DefaultRetransmissionTime());
2876 connection_.GetRetransmissionAlarm()->Fire();
2878 // Go forward secure.
2879 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
2880 new TaggingEncrypter(0x02));
2881 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2882 connection_.NeuterUnencryptedPackets();
2884 EXPECT_EQ(QuicTime::Zero(),
2885 connection_.GetRetransmissionAlarm()->deadline());
2886 // Unblock the socket and ensure that no packets are sent.
2887 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
2888 writer_->SetWritable();
2889 connection_.OnCanWrite();
2892 TEST_P(QuicConnectionTest, RetransmitPacketsWithInitialEncryption) {
2893 use_tagging_decrypter();
2894 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2895 connection_.SetDefaultEncryptionLevel(ENCRYPTION_NONE);
2897 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr);
2899 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2900 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2902 SendStreamDataToPeer(2, "bar", 0, !kFin, nullptr);
2903 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2905 connection_.RetransmitUnackedPackets(ALL_INITIAL_RETRANSMISSION);
2908 TEST_P(QuicConnectionTest, DelayForwardSecureEncryptionUntilClientIsReady) {
2909 // A TaggingEncrypter puts kTagSize copies of the given byte (0x02 here) at
2910 // the end of the packet. We can test this to check which encrypter was used.
2911 use_tagging_decrypter();
2912 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2913 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2914 SendAckPacketToPeer();
2915 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2917 // Set a forward-secure encrypter but do not make it the default, and verify
2918 // that it is not yet used.
2919 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
2920 new TaggingEncrypter(0x03));
2921 SendAckPacketToPeer();
2922 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2924 // Now simulate receipt of a forward-secure packet and verify that the
2925 // forward-secure encrypter is now used.
2926 connection_.OnDecryptedPacket(ENCRYPTION_FORWARD_SECURE);
2927 SendAckPacketToPeer();
2928 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
2931 TEST_P(QuicConnectionTest, DelayForwardSecureEncryptionUntilManyPacketSent) {
2932 // Set a congestion window of 10 packets.
2933 QuicPacketCount congestion_window = 10;
2934 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
2935 Return(congestion_window * kDefaultMaxPacketSize));
2937 // A TaggingEncrypter puts kTagSize copies of the given byte (0x02 here) at
2938 // the end of the packet. We can test this to check which encrypter was used.
2939 use_tagging_decrypter();
2940 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2941 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2942 SendAckPacketToPeer();
2943 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2945 // Set a forward-secure encrypter but do not make it the default, and
2946 // verify that it is not yet used.
2947 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
2948 new TaggingEncrypter(0x03));
2949 SendAckPacketToPeer();
2950 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2952 // Now send a packet "Far enough" after the encrypter was set and verify that
2953 // the forward-secure encrypter is now used.
2954 for (uint64 i = 0; i < 3 * congestion_window - 1; ++i) {
2955 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2956 SendAckPacketToPeer();
2958 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
2961 TEST_P(QuicConnectionTest, BufferNonDecryptablePackets) {
2962 // SetFromConfig is always called after construction from InitializeSession.
2963 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
2964 QuicConfig config;
2965 connection_.SetFromConfig(config);
2966 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2967 use_tagging_decrypter();
2969 const uint8 tag = 0x07;
2970 framer_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
2972 // Process an encrypted packet which can not yet be decrypted which should
2973 // result in the packet being buffered.
2974 ProcessDataPacketAtLevel(1, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2976 // Transition to the new encryption state and process another encrypted packet
2977 // which should result in the original packet being processed.
2978 connection_.SetDecrypter(ENCRYPTION_INITIAL, new StrictTaggingDecrypter(tag));
2979 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2980 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
2981 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(2);
2982 ProcessDataPacketAtLevel(2, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2984 // Finally, process a third packet and note that we do not reprocess the
2985 // buffered packet.
2986 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2987 ProcessDataPacketAtLevel(3, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2990 TEST_P(QuicConnectionTest, Buffer100NonDecryptablePackets) {
2991 // SetFromConfig is always called after construction from InitializeSession.
2992 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
2993 QuicConfig config;
2994 config.set_max_undecryptable_packets(100);
2995 connection_.SetFromConfig(config);
2996 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2997 use_tagging_decrypter();
2999 const uint8 tag = 0x07;
3000 framer_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
3002 // Process an encrypted packet which can not yet be decrypted which should
3003 // result in the packet being buffered.
3004 for (QuicPacketNumber i = 1; i <= 100; ++i) {
3005 ProcessDataPacketAtLevel(i, 0, kEntropyFlag, ENCRYPTION_INITIAL);
3008 // Transition to the new encryption state and process another encrypted packet
3009 // which should result in the original packets being processed.
3010 connection_.SetDecrypter(ENCRYPTION_INITIAL, new StrictTaggingDecrypter(tag));
3011 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
3012 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
3013 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(101);
3014 ProcessDataPacketAtLevel(101, 0, kEntropyFlag, ENCRYPTION_INITIAL);
3016 // Finally, process a third packet and note that we do not reprocess the
3017 // buffered packet.
3018 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3019 ProcessDataPacketAtLevel(102, 0, kEntropyFlag, ENCRYPTION_INITIAL);
3022 TEST_P(QuicConnectionTest, TestRetransmitOrder) {
3023 QuicByteCount first_packet_size;
3024 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).WillOnce(
3025 DoAll(SaveArg<3>(&first_packet_size), Return(true)));
3027 connection_.SendStreamDataWithString(3, "first_packet", 0, !kFin, nullptr);
3028 QuicByteCount second_packet_size;
3029 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).WillOnce(
3030 DoAll(SaveArg<3>(&second_packet_size), Return(true)));
3031 connection_.SendStreamDataWithString(3, "second_packet", 12, !kFin, nullptr);
3032 EXPECT_NE(first_packet_size, second_packet_size);
3033 // Advance the clock by huge time to make sure packets will be retransmitted.
3034 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
3036 InSequence s;
3037 EXPECT_CALL(*send_algorithm_,
3038 OnPacketSent(_, _, _, first_packet_size, _));
3039 EXPECT_CALL(*send_algorithm_,
3040 OnPacketSent(_, _, _, second_packet_size, _));
3042 connection_.GetRetransmissionAlarm()->Fire();
3044 // Advance again and expect the packets to be sent again in the same order.
3045 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(20));
3047 InSequence s;
3048 EXPECT_CALL(*send_algorithm_,
3049 OnPacketSent(_, _, _, first_packet_size, _));
3050 EXPECT_CALL(*send_algorithm_,
3051 OnPacketSent(_, _, _, second_packet_size, _));
3053 connection_.GetRetransmissionAlarm()->Fire();
3056 TEST_P(QuicConnectionTest, SetRTOAfterWritingToSocket) {
3057 BlockOnNextWrite();
3058 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
3059 // Make sure that RTO is not started when the packet is queued.
3060 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3062 // Test that RTO is started once we write to the socket.
3063 writer_->SetWritable();
3064 connection_.OnCanWrite();
3065 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3068 TEST_P(QuicConnectionTest, DelayRTOWithAckReceipt) {
3069 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3070 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3071 .Times(2);
3072 connection_.SendStreamDataWithString(2, "foo", 0, !kFin, nullptr);
3073 connection_.SendStreamDataWithString(3, "bar", 0, !kFin, nullptr);
3074 QuicAlarm* retransmission_alarm = connection_.GetRetransmissionAlarm();
3075 EXPECT_TRUE(retransmission_alarm->IsSet());
3076 EXPECT_EQ(clock_.Now().Add(DefaultRetransmissionTime()),
3077 retransmission_alarm->deadline());
3079 // Advance the time right before the RTO, then receive an ack for the first
3080 // packet to delay the RTO.
3081 clock_.AdvanceTime(DefaultRetransmissionTime());
3082 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3083 QuicAckFrame ack = InitAckFrame(1);
3084 ProcessAckPacket(&ack);
3085 EXPECT_TRUE(retransmission_alarm->IsSet());
3086 EXPECT_GT(retransmission_alarm->deadline(), clock_.Now());
3088 // Move forward past the original RTO and ensure the RTO is still pending.
3089 clock_.AdvanceTime(DefaultRetransmissionTime().Multiply(2));
3091 // Ensure the second packet gets retransmitted when it finally fires.
3092 EXPECT_TRUE(retransmission_alarm->IsSet());
3093 EXPECT_LT(retransmission_alarm->deadline(), clock_.ApproximateNow());
3094 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3095 // Manually cancel the alarm to simulate a real test.
3096 connection_.GetRetransmissionAlarm()->Fire();
3098 // The new retransmitted packet number should set the RTO to a larger value
3099 // than previously.
3100 EXPECT_TRUE(retransmission_alarm->IsSet());
3101 QuicTime next_rto_time = retransmission_alarm->deadline();
3102 QuicTime expected_rto_time =
3103 connection_.sent_packet_manager().GetRetransmissionTime();
3104 EXPECT_EQ(next_rto_time, expected_rto_time);
3107 TEST_P(QuicConnectionTest, TestQueued) {
3108 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3109 BlockOnNextWrite();
3110 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
3111 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3113 // Unblock the writes and actually send.
3114 writer_->SetWritable();
3115 connection_.OnCanWrite();
3116 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3119 TEST_P(QuicConnectionTest, CloseFecGroup) {
3120 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3121 // Don't send missing packet 1.
3122 // Don't send missing packet 2.
3123 ProcessFecProtectedPacket(3, false, !kEntropyFlag);
3124 // Don't send missing FEC packet 3.
3125 ASSERT_EQ(1u, connection_.NumFecGroups());
3127 // Now send non-fec protected ack packet and close the group.
3128 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 4);
3129 QuicStopWaitingFrame frame = InitStopWaitingFrame(5);
3130 ProcessStopWaitingPacket(&frame);
3131 ASSERT_EQ(0u, connection_.NumFecGroups());
3134 TEST_P(QuicConnectionTest, InitialTimeout) {
3135 EXPECT_TRUE(connection_.connected());
3136 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
3137 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3139 // SetFromConfig sets the initial timeouts before negotiation.
3140 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3141 QuicConfig config;
3142 connection_.SetFromConfig(config);
3143 // Subtract a second from the idle timeout on the client side.
3144 QuicTime default_timeout = clock_.ApproximateNow().Add(
3145 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1));
3146 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
3148 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_CONNECTION_TIMED_OUT, false));
3149 // Simulate the timeout alarm firing.
3150 clock_.AdvanceTime(
3151 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1));
3152 connection_.GetTimeoutAlarm()->Fire();
3154 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3155 EXPECT_FALSE(connection_.connected());
3157 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3158 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
3159 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
3160 EXPECT_FALSE(connection_.GetResumeWritesAlarm()->IsSet());
3161 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3162 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
3163 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
3166 TEST_P(QuicConnectionTest, OverallTimeout) {
3167 // Use a shorter overall connection timeout than idle timeout for this test.
3168 const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(5);
3169 connection_.SetNetworkTimeouts(timeout, timeout);
3170 EXPECT_TRUE(connection_.connected());
3171 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
3173 QuicTime overall_timeout = clock_.ApproximateNow().Add(timeout).Subtract(
3174 QuicTime::Delta::FromSeconds(1));
3175 EXPECT_EQ(overall_timeout, connection_.GetTimeoutAlarm()->deadline());
3176 EXPECT_TRUE(connection_.connected());
3178 // Send and ack new data 3 seconds later to lengthen the idle timeout.
3179 SendStreamDataToPeer(1, "GET /", 0, kFin, nullptr);
3180 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(3));
3181 QuicAckFrame frame = InitAckFrame(1);
3182 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3183 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3184 ProcessAckPacket(&frame);
3186 // Fire early to verify it wouldn't timeout yet.
3187 connection_.GetTimeoutAlarm()->Fire();
3188 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
3189 EXPECT_TRUE(connection_.connected());
3191 clock_.AdvanceTime(timeout.Subtract(QuicTime::Delta::FromSeconds(2)));
3193 EXPECT_CALL(visitor_,
3194 OnConnectionClosed(QUIC_CONNECTION_OVERALL_TIMED_OUT, false));
3195 // Simulate the timeout alarm firing.
3196 connection_.GetTimeoutAlarm()->Fire();
3198 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3199 EXPECT_FALSE(connection_.connected());
3201 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3202 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
3203 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
3204 EXPECT_FALSE(connection_.GetResumeWritesAlarm()->IsSet());
3205 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3206 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
3209 TEST_P(QuicConnectionTest, PingAfterSend) {
3210 EXPECT_TRUE(connection_.connected());
3211 EXPECT_CALL(visitor_, HasOpenDynamicStreams()).WillRepeatedly(Return(true));
3212 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
3214 // Advance to 5ms, and send a packet to the peer, which will set
3215 // the ping alarm.
3216 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
3217 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3218 SendStreamDataToPeer(1, "GET /", 0, kFin, nullptr);
3219 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
3220 EXPECT_EQ(clock_.ApproximateNow().Add(QuicTime::Delta::FromSeconds(15)),
3221 connection_.GetPingAlarm()->deadline());
3223 // Now recevie and ACK of the previous packet, which will move the
3224 // ping alarm forward.
3225 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
3226 QuicAckFrame frame = InitAckFrame(1);
3227 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3228 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3229 ProcessAckPacket(&frame);
3230 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
3231 // The ping timer is set slightly less than 15 seconds in the future, because
3232 // of the 1s ping timer alarm granularity.
3233 EXPECT_EQ(clock_.ApproximateNow().Add(QuicTime::Delta::FromSeconds(15))
3234 .Subtract(QuicTime::Delta::FromMilliseconds(5)),
3235 connection_.GetPingAlarm()->deadline());
3237 writer_->Reset();
3238 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15));
3239 connection_.GetPingAlarm()->Fire();
3240 EXPECT_EQ(1u, writer_->frame_count());
3241 ASSERT_EQ(1u, writer_->ping_frames().size());
3242 writer_->Reset();
3244 EXPECT_CALL(visitor_, HasOpenDynamicStreams()).WillRepeatedly(Return(false));
3245 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
3246 SendAckPacketToPeer();
3248 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
3251 // Tests whether sending an MTU discovery packet to peer successfully causes the
3252 // maximum packet size to increase.
3253 TEST_P(QuicConnectionTest, SendMtuDiscoveryPacket) {
3254 EXPECT_TRUE(connection_.connected());
3256 // Send an MTU probe.
3257 const size_t new_mtu = kDefaultMaxPacketSize + 100;
3258 QuicByteCount mtu_probe_size;
3259 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3260 .WillOnce(DoAll(SaveArg<3>(&mtu_probe_size), Return(true)));
3261 connection_.SendMtuDiscoveryPacket(new_mtu);
3262 EXPECT_EQ(new_mtu, mtu_probe_size);
3263 EXPECT_EQ(1u, creator_->packet_number());
3265 // Send more than MTU worth of data. No acknowledgement was received so far,
3266 // so the MTU should be at its old value.
3267 const string data(kDefaultMaxPacketSize + 1, '.');
3268 QuicByteCount size_before_mtu_change;
3269 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3270 .WillOnce(DoAll(SaveArg<3>(&size_before_mtu_change), Return(true)))
3271 .WillOnce(Return(true));
3272 connection_.SendStreamDataWithString(3, data, 0, kFin, nullptr);
3273 EXPECT_EQ(3u, creator_->packet_number());
3274 EXPECT_EQ(kDefaultMaxPacketSize, size_before_mtu_change);
3276 // Acknowledge all packets so far.
3277 QuicAckFrame probe_ack = InitAckFrame(3);
3278 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3279 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3280 ProcessAckPacket(&probe_ack);
3281 EXPECT_EQ(new_mtu, connection_.max_packet_length());
3283 // Send the same data again. Check that it fits into a single packet now.
3284 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3285 connection_.SendStreamDataWithString(3, data, 0, kFin, nullptr);
3286 EXPECT_EQ(4u, creator_->packet_number());
3289 // Tests whether MTU discovery does not happen when it is not explicitly enabled
3290 // by the connection options.
3291 TEST_P(QuicConnectionTest, MtuDiscoveryDisabled) {
3292 EXPECT_TRUE(connection_.connected());
3294 // Restore the current value FLAGS_quic_do_path_mtu_discovery after the test.
3295 ValueRestore<bool> old_flag(&FLAGS_quic_do_path_mtu_discovery, true);
3297 const QuicPacketCount number_of_packets = kPacketsBetweenMtuProbesBase * 2;
3298 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
3299 SendStreamDataToPeer(3, ".", i, /*fin=*/false, nullptr);
3300 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
3301 EXPECT_EQ(0u, connection_.mtu_probe_count());
3305 // Tests whether MTU discovery works when the probe gets acknowledged on the
3306 // first try.
3307 TEST_P(QuicConnectionTest, MtuDiscoveryEnabled) {
3308 EXPECT_TRUE(connection_.connected());
3310 // Restore the current value FLAGS_quic_do_path_mtu_discovery after the test.
3311 ValueRestore<bool> old_flag(&FLAGS_quic_do_path_mtu_discovery, true);
3312 connection_.EnablePathMtuDiscovery(send_algorithm_);
3314 // Send enough packets so that the next one triggers path MTU discovery.
3315 for (QuicPacketCount i = 0; i < kPacketsBetweenMtuProbesBase - 1; i++) {
3316 SendStreamDataToPeer(3, ".", i, /*fin=*/false, nullptr);
3317 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
3320 // Trigger the probe.
3321 SendStreamDataToPeer(3, "!", kPacketsBetweenMtuProbesBase,
3322 /*fin=*/false, nullptr);
3323 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
3324 QuicByteCount probe_size;
3325 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3326 .WillOnce(DoAll(SaveArg<3>(&probe_size), Return(true)));
3327 connection_.GetMtuDiscoveryAlarm()->Fire();
3328 EXPECT_EQ(kMtuDiscoveryTargetPacketSizeHigh, probe_size);
3330 const QuicPacketCount probe_packet_number = kPacketsBetweenMtuProbesBase + 1;
3331 ASSERT_EQ(probe_packet_number, creator_->packet_number());
3333 // Acknowledge all packets sent so far.
3334 QuicAckFrame probe_ack = InitAckFrame(probe_packet_number);
3335 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3336 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3337 ProcessAckPacket(&probe_ack);
3338 EXPECT_EQ(kMtuDiscoveryTargetPacketSizeHigh, connection_.max_packet_length());
3339 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
3341 // Send more packets, and ensure that none of them sets the alarm.
3342 for (QuicPacketCount i = 0; i < 4 * kPacketsBetweenMtuProbesBase; i++) {
3343 SendStreamDataToPeer(3, ".", i, /*fin=*/false, nullptr);
3344 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
3347 EXPECT_EQ(1u, connection_.mtu_probe_count());
3350 // Tests whether MTU discovery works correctly when the probes never get
3351 // acknowledged.
3352 TEST_P(QuicConnectionTest, MtuDiscoveryFailed) {
3353 EXPECT_TRUE(connection_.connected());
3355 // Restore the current value FLAGS_quic_do_path_mtu_discovery after the test.
3356 ValueRestore<bool> old_flag(&FLAGS_quic_do_path_mtu_discovery, true);
3357 connection_.EnablePathMtuDiscovery(send_algorithm_);
3359 const QuicTime::Delta rtt = QuicTime::Delta::FromMilliseconds(100);
3361 EXPECT_EQ(kPacketsBetweenMtuProbesBase,
3362 QuicConnectionPeer::GetPacketsBetweenMtuProbes(&connection_));
3363 // Lower the number of probes between packets in order to make the test go
3364 // much faster.
3365 const QuicPacketCount packets_between_probes_base = 10;
3366 QuicConnectionPeer::SetPacketsBetweenMtuProbes(&connection_,
3367 packets_between_probes_base);
3368 QuicConnectionPeer::SetNextMtuProbeAt(&connection_,
3369 packets_between_probes_base);
3371 // This tests sends more packets than strictly necessary to make sure that if
3372 // the connection was to send more discovery packets than needed, those would
3373 // get caught as well.
3374 const QuicPacketCount number_of_packets =
3375 packets_between_probes_base * (1 << (kMtuDiscoveryAttempts + 1));
3376 vector<QuicPacketNumber> mtu_discovery_packets;
3377 // Called by the first ack.
3378 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3379 // Called on many acks.
3380 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _))
3381 .Times(AnyNumber());
3382 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
3383 SendStreamDataToPeer(3, "!", i, /*fin=*/false, nullptr);
3384 clock_.AdvanceTime(rtt);
3386 // Receive an ACK, which marks all data packets as received, and all MTU
3387 // discovery packets as missing.
3388 QuicAckFrame ack = InitAckFrame(creator_->packet_number());
3389 for (QuicPacketNumber& packet : mtu_discovery_packets) {
3390 NackPacket(packet, &ack);
3392 ProcessAckPacket(&ack);
3394 // Trigger MTU probe if it would be scheduled now.
3395 if (!connection_.GetMtuDiscoveryAlarm()->IsSet()) {
3396 continue;
3399 // Fire the alarm. The alarm should cause a packet to be sent.
3400 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3401 .WillOnce(Return(true));
3402 connection_.GetMtuDiscoveryAlarm()->Fire();
3403 // Record the packet number of the MTU discovery packet in order to
3404 // mark it as NACK'd.
3405 mtu_discovery_packets.push_back(creator_->packet_number());
3408 // Ensure the number of packets between probes grows exponentially by checking
3409 // it against the closed-form expression for the packet number.
3410 ASSERT_EQ(kMtuDiscoveryAttempts, mtu_discovery_packets.size());
3411 for (QuicPacketNumber i = 0; i < kMtuDiscoveryAttempts; i++) {
3412 // 2^0 + 2^1 + 2^2 + ... + 2^n = 2^(n + 1) - 1
3413 const QuicPacketCount packets_between_probes =
3414 packets_between_probes_base * ((1 << (i + 1)) - 1);
3415 EXPECT_EQ(packets_between_probes + (i + 1), mtu_discovery_packets[i]);
3418 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
3419 EXPECT_EQ(kDefaultMaxPacketSize, connection_.max_packet_length());
3420 EXPECT_EQ(kMtuDiscoveryAttempts, connection_.mtu_probe_count());
3423 TEST_P(QuicConnectionTest, NoMtuDiscoveryAfterConnectionClosed) {
3424 EXPECT_TRUE(connection_.connected());
3426 // Restore the current value FLAGS_quic_do_path_mtu_discovery after the test.
3427 ValueRestore<bool> old_flag(&FLAGS_quic_do_path_mtu_discovery, true);
3428 connection_.EnablePathMtuDiscovery(send_algorithm_);
3430 // Send enough packets so that the next one triggers path MTU discovery.
3431 for (QuicPacketCount i = 0; i < kPacketsBetweenMtuProbesBase - 1; i++) {
3432 SendStreamDataToPeer(3, ".", i, /*fin=*/false, nullptr);
3433 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
3436 SendStreamDataToPeer(3, "!", kPacketsBetweenMtuProbesBase,
3437 /*fin=*/false, nullptr);
3438 EXPECT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
3440 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
3441 connection_.CloseConnection(QUIC_INTERNAL_ERROR, /*from_peer=*/false);
3442 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
3445 TEST_P(QuicConnectionTest, TimeoutAfterSend) {
3446 EXPECT_TRUE(connection_.connected());
3447 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3448 QuicConfig config;
3449 connection_.SetFromConfig(config);
3450 EXPECT_FALSE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
3452 const QuicTime::Delta initial_idle_timeout =
3453 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
3454 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
3455 QuicTime default_timeout = clock_.ApproximateNow().Add(initial_idle_timeout);
3457 // When we send a packet, the timeout will change to 5ms +
3458 // kInitialIdleTimeoutSecs.
3459 clock_.AdvanceTime(five_ms);
3461 // Send an ack so we don't set the retransmission alarm.
3462 SendAckPacketToPeer();
3463 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
3465 // The original alarm will fire. We should not time out because we had a
3466 // network event at t=5ms. The alarm will reregister.
3467 clock_.AdvanceTime(initial_idle_timeout.Subtract(five_ms));
3468 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
3469 connection_.GetTimeoutAlarm()->Fire();
3470 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
3471 EXPECT_TRUE(connection_.connected());
3472 EXPECT_EQ(default_timeout.Add(five_ms),
3473 connection_.GetTimeoutAlarm()->deadline());
3475 // This time, we should time out.
3476 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_CONNECTION_TIMED_OUT, false));
3477 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3478 clock_.AdvanceTime(five_ms);
3479 EXPECT_EQ(default_timeout.Add(five_ms), clock_.ApproximateNow());
3480 connection_.GetTimeoutAlarm()->Fire();
3481 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3482 EXPECT_FALSE(connection_.connected());
3485 TEST_P(QuicConnectionTest, TimeoutAfterSendSilentClose) {
3486 // Same test as above, but complete a handshake which enables silent close,
3487 // causing no connection close packet to be sent.
3488 EXPECT_TRUE(connection_.connected());
3489 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3490 QuicConfig config;
3492 // Create a handshake message that also enables silent close.
3493 CryptoHandshakeMessage msg;
3494 string error_details;
3495 QuicConfig client_config;
3496 client_config.SetInitialStreamFlowControlWindowToSend(
3497 kInitialStreamFlowControlWindowForTest);
3498 client_config.SetInitialSessionFlowControlWindowToSend(
3499 kInitialSessionFlowControlWindowForTest);
3500 client_config.SetIdleConnectionStateLifetime(
3501 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs),
3502 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs));
3503 client_config.ToHandshakeMessage(&msg);
3504 const QuicErrorCode error =
3505 config.ProcessPeerHello(msg, CLIENT, &error_details);
3506 EXPECT_EQ(QUIC_NO_ERROR, error);
3508 connection_.SetFromConfig(config);
3509 EXPECT_TRUE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
3511 const QuicTime::Delta default_idle_timeout =
3512 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs - 1);
3513 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
3514 QuicTime default_timeout = clock_.ApproximateNow().Add(default_idle_timeout);
3516 // When we send a packet, the timeout will change to 5ms +
3517 // kInitialIdleTimeoutSecs.
3518 clock_.AdvanceTime(five_ms);
3520 // Send an ack so we don't set the retransmission alarm.
3521 SendAckPacketToPeer();
3522 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
3524 // The original alarm will fire. We should not time out because we had a
3525 // network event at t=5ms. The alarm will reregister.
3526 clock_.AdvanceTime(default_idle_timeout.Subtract(five_ms));
3527 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
3528 connection_.GetTimeoutAlarm()->Fire();
3529 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
3530 EXPECT_TRUE(connection_.connected());
3531 EXPECT_EQ(default_timeout.Add(five_ms),
3532 connection_.GetTimeoutAlarm()->deadline());
3534 // This time, we should time out.
3535 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_CONNECTION_TIMED_OUT, false));
3536 clock_.AdvanceTime(five_ms);
3537 EXPECT_EQ(default_timeout.Add(five_ms), clock_.ApproximateNow());
3538 connection_.GetTimeoutAlarm()->Fire();
3539 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3540 EXPECT_FALSE(connection_.connected());
3543 TEST_P(QuicConnectionTest, SendScheduler) {
3544 // Test that if we send a packet without delay, it is not queued.
3545 QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
3546 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3547 connection_.SendPacket(ENCRYPTION_NONE, 1, packet, kTestEntropyHash,
3548 HAS_RETRANSMITTABLE_DATA, false, false);
3549 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3552 TEST_P(QuicConnectionTest, SendSchedulerEAGAIN) {
3553 QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
3554 BlockOnNextWrite();
3555 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 1, _, _)).Times(0);
3556 connection_.SendPacket(ENCRYPTION_NONE, 1, packet, kTestEntropyHash,
3557 HAS_RETRANSMITTABLE_DATA, false, false);
3558 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3561 TEST_P(QuicConnectionTest, TestQueueLimitsOnSendStreamData) {
3562 // All packets carry version info till version is negotiated.
3563 size_t payload_length;
3564 size_t length = GetPacketLengthForOneStream(
3565 connection_.version(), kIncludeVersion, PACKET_8BYTE_CONNECTION_ID,
3566 PACKET_1BYTE_PACKET_NUMBER, NOT_IN_FEC_GROUP, &payload_length);
3567 connection_.set_max_packet_length(length);
3569 // Queue the first packet.
3570 EXPECT_CALL(*send_algorithm_,
3571 TimeUntilSend(_, _, _)).WillOnce(
3572 testing::Return(QuicTime::Delta::FromMicroseconds(10)));
3573 const string payload(payload_length, 'a');
3574 EXPECT_EQ(0u, connection_.SendStreamDataWithString(3, payload, 0, !kFin,
3575 nullptr).bytes_consumed);
3576 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3579 TEST_P(QuicConnectionTest, LoopThroughSendingPackets) {
3580 // All packets carry version info till version is negotiated.
3581 size_t payload_length;
3582 // GetPacketLengthForOneStream() assumes a stream offset of 0 in determining
3583 // packet length. The size of the offset field in a stream frame is 0 for
3584 // offset 0, and 2 for non-zero offsets up through 16K. Increase
3585 // max_packet_length by 2 so that subsequent packets containing subsequent
3586 // stream frames with non-zero offets will fit within the packet length.
3587 size_t length =
3588 2 + GetPacketLengthForOneStream(connection_.version(), kIncludeVersion,
3589 PACKET_8BYTE_CONNECTION_ID,
3590 PACKET_1BYTE_PACKET_NUMBER,
3591 NOT_IN_FEC_GROUP, &payload_length);
3592 connection_.set_max_packet_length(length);
3594 // Queue the first packet.
3595 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(7);
3596 // The first stream frame will have 2 fewer overhead bytes than the other six.
3597 const string payload(payload_length * 7 + 2, 'a');
3598 EXPECT_EQ(payload.size(),
3599 connection_.SendStreamDataWithString(1, payload, 0, !kFin, nullptr)
3600 .bytes_consumed);
3603 TEST_P(QuicConnectionTest, LoopThroughSendingPacketsWithTruncation) {
3604 // Set up a larger payload than will fit in one packet.
3605 const string payload(connection_.max_packet_length(), 'a');
3606 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
3608 // Now send some packets with no truncation.
3609 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3610 EXPECT_EQ(payload.size(),
3611 connection_.SendStreamDataWithString(
3612 3, payload, 0, !kFin, nullptr).bytes_consumed);
3613 // Track the size of the second packet here. The overhead will be the largest
3614 // we see in this test, due to the non-truncated connection id.
3615 size_t non_truncated_packet_size = writer_->last_packet_size();
3617 // Change to a 4 byte connection id.
3618 QuicConfig config;
3619 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 4);
3620 connection_.SetFromConfig(config);
3621 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3622 EXPECT_EQ(payload.size(),
3623 connection_.SendStreamDataWithString(
3624 3, payload, 0, !kFin, nullptr).bytes_consumed);
3625 // Verify that we have 8 fewer bytes than in the non-truncated case. The
3626 // first packet got 4 bytes of extra payload due to the truncation, and the
3627 // headers here are also 4 byte smaller.
3628 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() + 8);
3630 // Change to a 1 byte connection id.
3631 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 1);
3632 connection_.SetFromConfig(config);
3633 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3634 EXPECT_EQ(payload.size(),
3635 connection_.SendStreamDataWithString(
3636 3, payload, 0, !kFin, nullptr).bytes_consumed);
3637 // Just like above, we save 7 bytes on payload, and 7 on truncation.
3638 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() + 7 * 2);
3640 // Change to a 0 byte connection id.
3641 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
3642 connection_.SetFromConfig(config);
3643 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3644 EXPECT_EQ(payload.size(),
3645 connection_.SendStreamDataWithString(
3646 3, payload, 0, !kFin, nullptr).bytes_consumed);
3647 // Just like above, we save 8 bytes on payload, and 8 on truncation.
3648 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() + 8 * 2);
3651 TEST_P(QuicConnectionTest, SendDelayedAck) {
3652 QuicTime ack_time = clock_.ApproximateNow().Add(DefaultDelayedAckTime());
3653 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3654 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3655 const uint8 tag = 0x07;
3656 connection_.SetDecrypter(ENCRYPTION_INITIAL, new StrictTaggingDecrypter(tag));
3657 framer_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
3658 // Process a packet from the non-crypto stream.
3659 frame1_.stream_id = 3;
3661 // The same as ProcessPacket(1) except that ENCRYPTION_INITIAL is used
3662 // instead of ENCRYPTION_NONE.
3663 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3664 ProcessDataPacketAtLevel(1, 0, !kEntropyFlag, ENCRYPTION_INITIAL);
3666 // Check if delayed ack timer is running for the expected interval.
3667 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3668 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
3669 // Simulate delayed ack alarm firing.
3670 connection_.GetAckAlarm()->Fire();
3671 // Check that ack is sent and that delayed ack alarm is reset.
3672 EXPECT_EQ(2u, writer_->frame_count());
3673 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3674 EXPECT_FALSE(writer_->ack_frames().empty());
3675 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3678 TEST_P(QuicConnectionTest, SendDelayedAckOnHandshakeConfirmed) {
3679 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3680 ProcessPacket(1);
3681 // Check that ack is sent and that delayed ack alarm is set.
3682 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3683 QuicTime ack_time = clock_.ApproximateNow().Add(DefaultDelayedAckTime());
3684 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
3686 // Completing the handshake as the server does nothing.
3687 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_SERVER);
3688 connection_.OnHandshakeComplete();
3689 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3690 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
3692 // Complete the handshake as the client decreases the delayed ack time to 0ms.
3693 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_CLIENT);
3694 connection_.OnHandshakeComplete();
3695 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3696 EXPECT_EQ(clock_.ApproximateNow(), connection_.GetAckAlarm()->deadline());
3699 TEST_P(QuicConnectionTest, SendDelayedAckOnSecondPacket) {
3700 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3701 ProcessPacket(1);
3702 ProcessPacket(2);
3703 // Check that ack is sent and that delayed ack alarm is reset.
3704 EXPECT_EQ(2u, writer_->frame_count());
3705 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3706 EXPECT_FALSE(writer_->ack_frames().empty());
3707 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3710 TEST_P(QuicConnectionTest, NoAckOnOldNacks) {
3711 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3712 // Drop one packet, triggering a sequence of acks.
3713 ProcessPacket(2);
3714 size_t frames_per_ack = 2;
3715 EXPECT_EQ(frames_per_ack, writer_->frame_count());
3716 EXPECT_FALSE(writer_->ack_frames().empty());
3717 writer_->Reset();
3718 ProcessPacket(3);
3719 EXPECT_EQ(frames_per_ack, writer_->frame_count());
3720 EXPECT_FALSE(writer_->ack_frames().empty());
3721 writer_->Reset();
3722 ProcessPacket(4);
3723 EXPECT_EQ(frames_per_ack, writer_->frame_count());
3724 EXPECT_FALSE(writer_->ack_frames().empty());
3725 writer_->Reset();
3726 ProcessPacket(5);
3727 EXPECT_EQ(frames_per_ack, writer_->frame_count());
3728 EXPECT_FALSE(writer_->ack_frames().empty());
3729 writer_->Reset();
3730 // Now only set the timer on the 6th packet, instead of sending another ack.
3731 ProcessPacket(6);
3732 EXPECT_EQ(0u, writer_->frame_count());
3733 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3736 TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingPacket) {
3737 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3738 ProcessPacket(1);
3739 connection_.SendStreamDataWithString(kClientDataStreamId1, "foo", 0, !kFin,
3740 nullptr);
3741 // Check that ack is bundled with outgoing data and that delayed ack
3742 // alarm is reset.
3743 EXPECT_EQ(3u, writer_->frame_count());
3744 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3745 EXPECT_FALSE(writer_->ack_frames().empty());
3746 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3749 TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingCryptoPacket) {
3750 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3751 ProcessPacket(1);
3752 connection_.SendStreamDataWithString(kCryptoStreamId, "foo", 0, !kFin,
3753 nullptr);
3754 // Check that ack is bundled with outgoing crypto data.
3755 EXPECT_EQ(3u, writer_->frame_count());
3756 EXPECT_FALSE(writer_->ack_frames().empty());
3757 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3760 TEST_P(QuicConnectionTest, BlockAndBufferOnFirstCHLOPacketOfTwo) {
3761 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3762 ProcessPacket(1);
3763 BlockOnNextWrite();
3764 writer_->set_is_write_blocked_data_buffered(true);
3765 connection_.SendStreamDataWithString(kCryptoStreamId, "foo", 0, !kFin,
3766 nullptr);
3767 EXPECT_TRUE(writer_->IsWriteBlocked());
3768 EXPECT_FALSE(connection_.HasQueuedData());
3769 connection_.SendStreamDataWithString(kCryptoStreamId, "bar", 3, !kFin,
3770 nullptr);
3771 EXPECT_TRUE(writer_->IsWriteBlocked());
3772 EXPECT_TRUE(connection_.HasQueuedData());
3775 TEST_P(QuicConnectionTest, BundleAckForSecondCHLO) {
3776 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3777 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3778 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(
3779 IgnoreResult(InvokeWithoutArgs(&connection_,
3780 &TestConnection::SendCryptoStreamData)));
3781 // Process a packet from the crypto stream, which is frame1_'s default.
3782 // Receiving the CHLO as packet 2 first will cause the connection to
3783 // immediately send an ack, due to the packet gap.
3784 ProcessPacket(2);
3785 // Check that ack is sent and that delayed ack alarm is reset.
3786 EXPECT_EQ(3u, writer_->frame_count());
3787 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3788 EXPECT_EQ(1u, writer_->stream_frames().size());
3789 EXPECT_FALSE(writer_->ack_frames().empty());
3790 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3793 TEST_P(QuicConnectionTest, BundleAckWithDataOnIncomingAck) {
3794 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3795 connection_.SendStreamDataWithString(kClientDataStreamId1, "foo", 0, !kFin,
3796 nullptr);
3797 connection_.SendStreamDataWithString(kClientDataStreamId1, "foo", 3, !kFin,
3798 nullptr);
3799 // Ack the second packet, which will retransmit the first packet.
3800 QuicAckFrame ack = InitAckFrame(2);
3801 NackPacket(1, &ack);
3802 PacketNumberSet lost_packets;
3803 lost_packets.insert(1);
3804 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3805 .WillOnce(Return(lost_packets));
3806 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3807 ProcessAckPacket(&ack);
3808 EXPECT_EQ(1u, writer_->frame_count());
3809 EXPECT_EQ(1u, writer_->stream_frames().size());
3810 writer_->Reset();
3812 // Now ack the retransmission, which will both raise the high water mark
3813 // and see if there is more data to send.
3814 ack = InitAckFrame(3);
3815 NackPacket(1, &ack);
3816 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3817 .WillOnce(Return(PacketNumberSet()));
3818 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3819 ProcessAckPacket(&ack);
3821 // Check that no packet is sent and the ack alarm isn't set.
3822 EXPECT_EQ(0u, writer_->frame_count());
3823 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3824 writer_->Reset();
3826 // Send the same ack, but send both data and an ack together.
3827 ack = InitAckFrame(3);
3828 NackPacket(1, &ack);
3829 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3830 .WillOnce(Return(PacketNumberSet()));
3831 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(
3832 IgnoreResult(InvokeWithoutArgs(
3833 &connection_,
3834 &TestConnection::EnsureWritableAndSendStreamData5)));
3835 ProcessAckPacket(&ack);
3837 // Check that ack is bundled with outgoing data and the delayed ack
3838 // alarm is reset.
3839 EXPECT_EQ(3u, writer_->frame_count());
3840 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3841 EXPECT_FALSE(writer_->ack_frames().empty());
3842 EXPECT_EQ(1u, writer_->stream_frames().size());
3843 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3846 TEST_P(QuicConnectionTest, NoAckSentForClose) {
3847 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3848 ProcessPacket(1);
3849 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, true));
3850 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3851 ProcessClosePacket(2, 0);
3854 TEST_P(QuicConnectionTest, SendWhenDisconnected) {
3855 EXPECT_TRUE(connection_.connected());
3856 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, false));
3857 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, false);
3858 EXPECT_FALSE(connection_.connected());
3859 EXPECT_FALSE(connection_.CanWriteStreamData());
3860 QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
3861 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 1, _, _)).Times(0);
3862 connection_.SendPacket(ENCRYPTION_NONE, 1, packet, kTestEntropyHash,
3863 HAS_RETRANSMITTABLE_DATA, false, false);
3866 TEST_P(QuicConnectionTest, PublicReset) {
3867 QuicPublicResetPacket header;
3868 header.public_header.connection_id = connection_id_;
3869 header.public_header.reset_flag = true;
3870 header.public_header.version_flag = false;
3871 header.rejected_packet_number = 10101;
3872 scoped_ptr<QuicEncryptedPacket> packet(
3873 framer_.BuildPublicResetPacket(header));
3874 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PUBLIC_RESET, true));
3875 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *packet);
3878 TEST_P(QuicConnectionTest, GoAway) {
3879 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3881 QuicGoAwayFrame goaway;
3882 goaway.last_good_stream_id = 1;
3883 goaway.error_code = QUIC_PEER_GOING_AWAY;
3884 goaway.reason_phrase = "Going away.";
3885 EXPECT_CALL(visitor_, OnGoAway(_));
3886 ProcessGoAwayPacket(&goaway);
3889 TEST_P(QuicConnectionTest, WindowUpdate) {
3890 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3892 QuicWindowUpdateFrame window_update;
3893 window_update.stream_id = 3;
3894 window_update.byte_offset = 1234;
3895 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
3896 ProcessFramePacket(QuicFrame(&window_update));
3899 TEST_P(QuicConnectionTest, Blocked) {
3900 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3902 QuicBlockedFrame blocked;
3903 blocked.stream_id = 3;
3904 EXPECT_CALL(visitor_, OnBlockedFrame(_));
3905 ProcessFramePacket(QuicFrame(&blocked));
3908 TEST_P(QuicConnectionTest, ZeroBytePacket) {
3909 // Don't close the connection for zero byte packets.
3910 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
3911 QuicEncryptedPacket encrypted(nullptr, 0);
3912 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), encrypted);
3915 TEST_P(QuicConnectionTest, MissingPacketsBeforeLeastUnacked) {
3916 // Set the packet number of the ack packet to be least unacked (4).
3917 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 3);
3918 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3919 QuicStopWaitingFrame frame = InitStopWaitingFrame(4);
3920 ProcessStopWaitingPacket(&frame);
3921 EXPECT_TRUE(outgoing_ack()->missing_packets.empty());
3924 TEST_P(QuicConnectionTest, ReceivedEntropyHashCalculation) {
3925 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AtLeast(1));
3926 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3927 ProcessDataPacket(1, 1, kEntropyFlag);
3928 ProcessDataPacket(4, 1, kEntropyFlag);
3929 ProcessDataPacket(3, 1, !kEntropyFlag);
3930 ProcessDataPacket(7, 1, kEntropyFlag);
3931 EXPECT_EQ(146u, outgoing_ack()->entropy_hash);
3934 TEST_P(QuicConnectionTest, ReceivedEntropyHashCalculationHalfFEC) {
3935 // FEC packets should not change the entropy hash calculation.
3936 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AtLeast(1));
3937 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3938 ProcessDataPacket(1, 1, kEntropyFlag);
3939 ProcessFecPacket(4, 1, false, kEntropyFlag, nullptr);
3940 ProcessDataPacket(3, 3, !kEntropyFlag);
3941 ProcessFecPacket(7, 3, false, kEntropyFlag, nullptr);
3942 EXPECT_EQ(146u, outgoing_ack()->entropy_hash);
3945 TEST_P(QuicConnectionTest, UpdateEntropyForReceivedPackets) {
3946 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AtLeast(1));
3947 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3948 ProcessDataPacket(1, 1, kEntropyFlag);
3949 ProcessDataPacket(5, 1, kEntropyFlag);
3950 ProcessDataPacket(4, 1, !kEntropyFlag);
3951 EXPECT_EQ(34u, outgoing_ack()->entropy_hash);
3952 // Make 4th packet my least unacked, and update entropy for 2, 3 packets.
3953 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
3954 QuicPacketEntropyHash six_packet_entropy_hash = 0;
3955 QuicPacketEntropyHash random_entropy_hash = 129u;
3956 QuicStopWaitingFrame frame = InitStopWaitingFrame(4);
3957 frame.entropy_hash = random_entropy_hash;
3958 if (ProcessStopWaitingPacket(&frame)) {
3959 six_packet_entropy_hash = 1 << 6;
3962 EXPECT_EQ((random_entropy_hash + (1 << 5) + six_packet_entropy_hash),
3963 outgoing_ack()->entropy_hash);
3966 TEST_P(QuicConnectionTest, UpdateEntropyHashUptoCurrentPacket) {
3967 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AtLeast(1));
3968 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3969 ProcessDataPacket(1, 1, kEntropyFlag);
3970 ProcessDataPacket(5, 1, !kEntropyFlag);
3971 ProcessDataPacket(22, 1, kEntropyFlag);
3972 EXPECT_EQ(66u, outgoing_ack()->entropy_hash);
3973 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 22);
3974 QuicPacketEntropyHash random_entropy_hash = 85u;
3975 // Current packet is the least unacked packet.
3976 QuicPacketEntropyHash ack_entropy_hash;
3977 QuicStopWaitingFrame frame = InitStopWaitingFrame(23);
3978 frame.entropy_hash = random_entropy_hash;
3979 ack_entropy_hash = ProcessStopWaitingPacket(&frame);
3980 EXPECT_EQ((random_entropy_hash + ack_entropy_hash),
3981 outgoing_ack()->entropy_hash);
3982 ProcessDataPacket(25, 1, kEntropyFlag);
3983 EXPECT_EQ((random_entropy_hash + ack_entropy_hash + (1 << (25 % 8))),
3984 outgoing_ack()->entropy_hash);
3987 TEST_P(QuicConnectionTest, EntropyCalculationForTruncatedAck) {
3988 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AtLeast(1));
3989 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3990 QuicPacketEntropyHash entropy[51];
3991 entropy[0] = 0;
3992 for (int i = 1; i < 51; ++i) {
3993 bool should_send = i % 10 != 1;
3994 bool entropy_flag = (i & (i - 1)) != 0;
3995 if (!should_send) {
3996 entropy[i] = entropy[i - 1];
3997 continue;
3999 if (entropy_flag) {
4000 entropy[i] = entropy[i - 1] ^ (1 << (i % 8));
4001 } else {
4002 entropy[i] = entropy[i - 1];
4004 ProcessDataPacket(i, 1, entropy_flag);
4006 for (int i = 1; i < 50; ++i) {
4007 EXPECT_EQ(entropy[i], QuicConnectionPeer::ReceivedEntropyHash(
4008 &connection_, i));
4012 TEST_P(QuicConnectionTest, ServerSendsVersionNegotiationPacket) {
4013 connection_.SetSupportedVersions(QuicSupportedVersions());
4014 framer_.set_version_for_tests(QUIC_VERSION_UNSUPPORTED);
4016 QuicPacketHeader header;
4017 header.public_header.connection_id = connection_id_;
4018 header.public_header.version_flag = true;
4019 header.packet_packet_number = 12;
4021 QuicFrames frames;
4022 frames.push_back(QuicFrame(&frame1_));
4023 scoped_ptr<QuicPacket> packet(ConstructPacket(header, frames));
4024 char buffer[kMaxPacketSize];
4025 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPayload(
4026 ENCRYPTION_NONE, 12, *packet, buffer, kMaxPacketSize));
4028 framer_.set_version(version());
4029 connection_.set_perspective(Perspective::IS_SERVER);
4030 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
4031 EXPECT_TRUE(writer_->version_negotiation_packet() != nullptr);
4033 size_t num_versions = arraysize(kSupportedQuicVersions);
4034 ASSERT_EQ(num_versions,
4035 writer_->version_negotiation_packet()->versions.size());
4037 // We expect all versions in kSupportedQuicVersions to be
4038 // included in the packet.
4039 for (size_t i = 0; i < num_versions; ++i) {
4040 EXPECT_EQ(kSupportedQuicVersions[i],
4041 writer_->version_negotiation_packet()->versions[i]);
4045 TEST_P(QuicConnectionTest, ServerSendsVersionNegotiationPacketSocketBlocked) {
4046 connection_.SetSupportedVersions(QuicSupportedVersions());
4047 framer_.set_version_for_tests(QUIC_VERSION_UNSUPPORTED);
4049 QuicPacketHeader header;
4050 header.public_header.connection_id = connection_id_;
4051 header.public_header.version_flag = true;
4052 header.packet_packet_number = 12;
4054 QuicFrames frames;
4055 frames.push_back(QuicFrame(&frame1_));
4056 scoped_ptr<QuicPacket> packet(ConstructPacket(header, frames));
4057 char buffer[kMaxPacketSize];
4058 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPayload(
4059 ENCRYPTION_NONE, 12, *packet, buffer, kMaxPacketSize));
4061 framer_.set_version(version());
4062 connection_.set_perspective(Perspective::IS_SERVER);
4063 BlockOnNextWrite();
4064 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
4065 EXPECT_EQ(0u, writer_->last_packet_size());
4066 EXPECT_TRUE(connection_.HasQueuedData());
4068 writer_->SetWritable();
4069 connection_.OnCanWrite();
4070 EXPECT_TRUE(writer_->version_negotiation_packet() != nullptr);
4072 size_t num_versions = arraysize(kSupportedQuicVersions);
4073 ASSERT_EQ(num_versions,
4074 writer_->version_negotiation_packet()->versions.size());
4076 // We expect all versions in kSupportedQuicVersions to be
4077 // included in the packet.
4078 for (size_t i = 0; i < num_versions; ++i) {
4079 EXPECT_EQ(kSupportedQuicVersions[i],
4080 writer_->version_negotiation_packet()->versions[i]);
4084 TEST_P(QuicConnectionTest,
4085 ServerSendsVersionNegotiationPacketSocketBlockedDataBuffered) {
4086 connection_.SetSupportedVersions(QuicSupportedVersions());
4087 framer_.set_version_for_tests(QUIC_VERSION_UNSUPPORTED);
4089 QuicPacketHeader header;
4090 header.public_header.connection_id = connection_id_;
4091 header.public_header.version_flag = true;
4092 header.packet_packet_number = 12;
4094 QuicFrames frames;
4095 frames.push_back(QuicFrame(&frame1_));
4096 scoped_ptr<QuicPacket> packet(ConstructPacket(header, frames));
4097 char buffer[kMaxPacketSize];
4098 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPayload(
4099 ENCRYPTION_NONE, 12, *packet, buffer, kMaxPacketSize));
4101 framer_.set_version(version());
4102 connection_.set_perspective(Perspective::IS_SERVER);
4103 BlockOnNextWrite();
4104 writer_->set_is_write_blocked_data_buffered(true);
4105 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
4106 EXPECT_EQ(0u, writer_->last_packet_size());
4107 EXPECT_FALSE(connection_.HasQueuedData());
4110 TEST_P(QuicConnectionTest, ClientHandlesVersionNegotiation) {
4111 // Start out with some unsupported version.
4112 QuicConnectionPeer::GetFramer(&connection_)->set_version_for_tests(
4113 QUIC_VERSION_UNSUPPORTED);
4115 QuicPacketHeader header;
4116 header.public_header.connection_id = connection_id_;
4117 header.public_header.version_flag = true;
4118 header.packet_packet_number = 12;
4120 QuicVersionVector supported_versions;
4121 for (size_t i = 0; i < arraysize(kSupportedQuicVersions); ++i) {
4122 supported_versions.push_back(kSupportedQuicVersions[i]);
4125 // Send a version negotiation packet.
4126 scoped_ptr<QuicEncryptedPacket> encrypted(
4127 framer_.BuildVersionNegotiationPacket(
4128 header.public_header, supported_versions));
4129 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
4131 // Now force another packet. The connection should transition into
4132 // NEGOTIATED_VERSION state and tell the packet creator to StopSendingVersion.
4133 header.public_header.version_flag = false;
4134 QuicFrames frames;
4135 frames.push_back(QuicFrame(&frame1_));
4136 scoped_ptr<QuicPacket> packet(ConstructPacket(header, frames));
4137 char buffer[kMaxPacketSize];
4138 encrypted.reset(framer_.EncryptPayload(ENCRYPTION_NONE, 12, *packet, buffer,
4139 kMaxPacketSize));
4140 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4141 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4142 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
4144 ASSERT_FALSE(QuicPacketCreatorPeer::SendVersionInPacket(creator_));
4147 TEST_P(QuicConnectionTest, BadVersionNegotiation) {
4148 QuicPacketHeader header;
4149 header.public_header.connection_id = connection_id_;
4150 header.public_header.version_flag = true;
4151 header.packet_packet_number = 12;
4153 QuicVersionVector supported_versions;
4154 for (size_t i = 0; i < arraysize(kSupportedQuicVersions); ++i) {
4155 supported_versions.push_back(kSupportedQuicVersions[i]);
4158 // Send a version negotiation packet with the version the client started with.
4159 // It should be rejected.
4160 EXPECT_CALL(visitor_,
4161 OnConnectionClosed(QUIC_INVALID_VERSION_NEGOTIATION_PACKET,
4162 false));
4163 scoped_ptr<QuicEncryptedPacket> encrypted(
4164 framer_.BuildVersionNegotiationPacket(
4165 header.public_header, supported_versions));
4166 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
4169 TEST_P(QuicConnectionTest, CheckSendStats) {
4170 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4171 connection_.SendStreamDataWithString(3, "first", 0, !kFin, nullptr);
4172 size_t first_packet_size = writer_->last_packet_size();
4174 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4175 connection_.SendStreamDataWithString(5, "second", 0, !kFin, nullptr);
4176 size_t second_packet_size = writer_->last_packet_size();
4178 // 2 retransmissions due to rto, 1 due to explicit nack.
4179 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
4180 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
4182 // Retransmit due to RTO.
4183 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
4184 connection_.GetRetransmissionAlarm()->Fire();
4186 // Retransmit due to explicit nacks.
4187 QuicAckFrame nack_three = InitAckFrame(4);
4188 NackPacket(3, &nack_three);
4189 NackPacket(1, &nack_three);
4190 PacketNumberSet lost_packets;
4191 lost_packets.insert(1);
4192 lost_packets.insert(3);
4193 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4194 .WillOnce(Return(lost_packets));
4195 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4196 EXPECT_CALL(visitor_, OnCanWrite());
4197 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4198 ProcessAckPacket(&nack_three);
4200 EXPECT_CALL(*send_algorithm_, BandwidthEstimate()).WillOnce(
4201 Return(QuicBandwidth::Zero()));
4203 const QuicConnectionStats& stats = connection_.GetStats();
4204 EXPECT_EQ(3 * first_packet_size + 2 * second_packet_size - kQuicVersionSize,
4205 stats.bytes_sent);
4206 EXPECT_EQ(5u, stats.packets_sent);
4207 EXPECT_EQ(2 * first_packet_size + second_packet_size - kQuicVersionSize,
4208 stats.bytes_retransmitted);
4209 EXPECT_EQ(3u, stats.packets_retransmitted);
4210 EXPECT_EQ(1u, stats.rto_count);
4211 EXPECT_EQ(kDefaultMaxPacketSize, stats.max_packet_size);
4214 TEST_P(QuicConnectionTest, CheckReceiveStats) {
4215 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4217 size_t received_bytes = 0;
4218 received_bytes += ProcessFecProtectedPacket(1, false, !kEntropyFlag);
4219 received_bytes += ProcessFecProtectedPacket(3, false, !kEntropyFlag);
4220 // Should be counted against dropped packets.
4221 received_bytes += ProcessDataPacket(3, 1, !kEntropyFlag);
4222 received_bytes += ProcessFecPacket(4, 1, true, !kEntropyFlag, nullptr);
4224 EXPECT_CALL(*send_algorithm_, BandwidthEstimate()).WillOnce(
4225 Return(QuicBandwidth::Zero()));
4227 const QuicConnectionStats& stats = connection_.GetStats();
4228 EXPECT_EQ(received_bytes, stats.bytes_received);
4229 EXPECT_EQ(4u, stats.packets_received);
4231 EXPECT_EQ(1u, stats.packets_revived);
4232 EXPECT_EQ(1u, stats.packets_dropped);
4235 TEST_P(QuicConnectionTest, TestFecGroupLimits) {
4236 // Create and return a group for 1.
4237 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 1) != nullptr);
4239 // Create and return a group for 2.
4240 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 2) != nullptr);
4242 // Create and return a group for 4. This should remove 1 but not 2.
4243 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 4) != nullptr);
4244 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 1) == nullptr);
4245 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 2) != nullptr);
4247 // Create and return a group for 3. This will kill off 2.
4248 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 3) != nullptr);
4249 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 2) == nullptr);
4251 // Verify that adding 5 kills off 3, despite 4 being created before 3.
4252 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 5) != nullptr);
4253 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 4) != nullptr);
4254 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 3) == nullptr);
4257 TEST_P(QuicConnectionTest, ProcessFramesIfPacketClosedConnection) {
4258 // Construct a packet with stream frame and connection close frame.
4259 QuicPacketHeader header;
4260 header.public_header.connection_id = connection_id_;
4261 header.packet_packet_number = 1;
4262 header.public_header.version_flag = false;
4264 QuicConnectionCloseFrame qccf;
4265 qccf.error_code = QUIC_PEER_GOING_AWAY;
4267 QuicFrames frames;
4268 frames.push_back(QuicFrame(&frame1_));
4269 frames.push_back(QuicFrame(&qccf));
4270 scoped_ptr<QuicPacket> packet(ConstructPacket(header, frames));
4271 EXPECT_TRUE(nullptr != packet.get());
4272 char buffer[kMaxPacketSize];
4273 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPayload(
4274 ENCRYPTION_NONE, 1, *packet, buffer, kMaxPacketSize));
4276 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, true));
4277 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4278 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4280 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
4283 TEST_P(QuicConnectionTest, SelectMutualVersion) {
4284 connection_.SetSupportedVersions(QuicSupportedVersions());
4285 // Set the connection to speak the lowest quic version.
4286 connection_.set_version(QuicVersionMin());
4287 EXPECT_EQ(QuicVersionMin(), connection_.version());
4289 // Pass in available versions which includes a higher mutually supported
4290 // version. The higher mutually supported version should be selected.
4291 QuicVersionVector supported_versions;
4292 for (size_t i = 0; i < arraysize(kSupportedQuicVersions); ++i) {
4293 supported_versions.push_back(kSupportedQuicVersions[i]);
4295 EXPECT_TRUE(connection_.SelectMutualVersion(supported_versions));
4296 EXPECT_EQ(QuicVersionMax(), connection_.version());
4298 // Expect that the lowest version is selected.
4299 // Ensure the lowest supported version is less than the max, unless they're
4300 // the same.
4301 EXPECT_LE(QuicVersionMin(), QuicVersionMax());
4302 QuicVersionVector lowest_version_vector;
4303 lowest_version_vector.push_back(QuicVersionMin());
4304 EXPECT_TRUE(connection_.SelectMutualVersion(lowest_version_vector));
4305 EXPECT_EQ(QuicVersionMin(), connection_.version());
4307 // Shouldn't be able to find a mutually supported version.
4308 QuicVersionVector unsupported_version;
4309 unsupported_version.push_back(QUIC_VERSION_UNSUPPORTED);
4310 EXPECT_FALSE(connection_.SelectMutualVersion(unsupported_version));
4313 TEST_P(QuicConnectionTest, ConnectionCloseWhenWritable) {
4314 EXPECT_FALSE(writer_->IsWriteBlocked());
4316 // Send a packet.
4317 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
4318 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4319 EXPECT_EQ(1u, writer_->packets_write_attempts());
4321 TriggerConnectionClose();
4322 EXPECT_EQ(2u, writer_->packets_write_attempts());
4325 TEST_P(QuicConnectionTest, ConnectionCloseGettingWriteBlocked) {
4326 BlockOnNextWrite();
4327 TriggerConnectionClose();
4328 EXPECT_EQ(1u, writer_->packets_write_attempts());
4329 EXPECT_TRUE(writer_->IsWriteBlocked());
4332 TEST_P(QuicConnectionTest, ConnectionCloseWhenWriteBlocked) {
4333 BlockOnNextWrite();
4334 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
4335 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4336 EXPECT_EQ(1u, writer_->packets_write_attempts());
4337 EXPECT_TRUE(writer_->IsWriteBlocked());
4338 TriggerConnectionClose();
4339 EXPECT_EQ(1u, writer_->packets_write_attempts());
4342 TEST_P(QuicConnectionTest, AckNotifierTriggerCallback) {
4343 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4345 // Create a delegate which we expect to be called.
4346 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4347 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(1);
4349 // Send some data, which will register the delegate to be notified.
4350 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
4352 // Process an ACK from the server which should trigger the callback.
4353 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4354 QuicAckFrame frame = InitAckFrame(1);
4355 ProcessAckPacket(&frame);
4358 TEST_P(QuicConnectionTest, AckNotifierFailToTriggerCallback) {
4359 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4361 // Create a delegate which we don't expect to be called.
4362 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4363 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(0);
4365 // Send some data, which will register the delegate to be notified. This will
4366 // not be ACKed and so the delegate should never be called.
4367 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
4369 // Send some other data which we will ACK.
4370 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
4371 connection_.SendStreamDataWithString(1, "bar", 0, !kFin, nullptr);
4373 // Now we receive ACK for packets 2 and 3, but importantly missing packet 1
4374 // which we registered to be notified about.
4375 QuicAckFrame frame = InitAckFrame(3);
4376 NackPacket(1, &frame);
4377 PacketNumberSet lost_packets;
4378 lost_packets.insert(1);
4379 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4380 .WillOnce(Return(lost_packets));
4381 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4382 ProcessAckPacket(&frame);
4385 TEST_P(QuicConnectionTest, AckNotifierCallbackAfterRetransmission) {
4386 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4388 // Create a delegate which we expect to be called.
4389 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4390 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(1);
4392 // Send four packets, and register to be notified on ACK of packet 2.
4393 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
4394 connection_.SendStreamDataWithString(3, "bar", 0, !kFin, delegate.get());
4395 connection_.SendStreamDataWithString(3, "baz", 0, !kFin, nullptr);
4396 connection_.SendStreamDataWithString(3, "qux", 0, !kFin, nullptr);
4398 // Now we receive ACK for packets 1, 3, and 4 and lose 2.
4399 QuicAckFrame frame = InitAckFrame(4);
4400 NackPacket(2, &frame);
4401 PacketNumberSet lost_packets;
4402 lost_packets.insert(2);
4403 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4404 .WillOnce(Return(lost_packets));
4405 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4406 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4407 ProcessAckPacket(&frame);
4409 // Now we get an ACK for packet 5 (retransmitted packet 2), which should
4410 // trigger the callback.
4411 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4412 .WillRepeatedly(Return(PacketNumberSet()));
4413 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4414 QuicAckFrame second_ack_frame = InitAckFrame(5);
4415 ProcessAckPacket(&second_ack_frame);
4418 // AckNotifierCallback is triggered by the ack of a packet that timed
4419 // out and was retransmitted, even though the retransmission has a
4420 // different packet number.
4421 TEST_P(QuicConnectionTest, AckNotifierCallbackForAckAfterRTO) {
4422 InSequence s;
4424 // Create a delegate which we expect to be called.
4425 scoped_refptr<MockAckNotifierDelegate> delegate(
4426 new StrictMock<MockAckNotifierDelegate>);
4428 QuicTime default_retransmission_time = clock_.ApproximateNow().Add(
4429 DefaultRetransmissionTime());
4430 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, delegate.get());
4431 EXPECT_EQ(1u, stop_waiting()->least_unacked);
4433 EXPECT_EQ(1u, writer_->header().packet_packet_number);
4434 EXPECT_EQ(default_retransmission_time,
4435 connection_.GetRetransmissionAlarm()->deadline());
4436 // Simulate the retransmission alarm firing.
4437 clock_.AdvanceTime(DefaultRetransmissionTime());
4438 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 2u, _, _));
4439 connection_.GetRetransmissionAlarm()->Fire();
4440 EXPECT_EQ(2u, writer_->header().packet_packet_number);
4441 // We do not raise the high water mark yet.
4442 EXPECT_EQ(1u, stop_waiting()->least_unacked);
4444 // Ack the original packet, which will revert the RTO.
4445 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4446 EXPECT_CALL(*delegate, OnAckNotification(1, _, _));
4447 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4448 QuicAckFrame ack_frame = InitAckFrame(1);
4449 ProcessAckPacket(&ack_frame);
4451 // Delegate is not notified again when the retransmit is acked.
4452 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4453 QuicAckFrame second_ack_frame = InitAckFrame(2);
4454 ProcessAckPacket(&second_ack_frame);
4457 // AckNotifierCallback is triggered by the ack of a packet that was
4458 // previously nacked, even though the retransmission has a different
4459 // packet number.
4460 TEST_P(QuicConnectionTest, AckNotifierCallbackForAckOfNackedPacket) {
4461 InSequence s;
4463 // Create a delegate which we expect to be called.
4464 scoped_refptr<MockAckNotifierDelegate> delegate(
4465 new StrictMock<MockAckNotifierDelegate>);
4467 // Send four packets, and register to be notified on ACK of packet 2.
4468 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
4469 connection_.SendStreamDataWithString(3, "bar", 0, !kFin, delegate.get());
4470 connection_.SendStreamDataWithString(3, "baz", 0, !kFin, nullptr);
4471 connection_.SendStreamDataWithString(3, "qux", 0, !kFin, nullptr);
4473 // Now we receive ACK for packets 1, 3, and 4 and lose 2.
4474 QuicAckFrame frame = InitAckFrame(4);
4475 NackPacket(2, &frame);
4476 PacketNumberSet lost_packets;
4477 lost_packets.insert(2);
4478 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4479 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4480 .WillOnce(Return(lost_packets));
4481 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4482 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4483 ProcessAckPacket(&frame);
4485 // Now we get an ACK for packet 2, which was previously nacked.
4486 PacketNumberSet no_lost_packets;
4487 EXPECT_CALL(*delegate.get(), OnAckNotification(1, _, _));
4488 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4489 .WillOnce(Return(no_lost_packets));
4490 QuicAckFrame second_ack_frame = InitAckFrame(4);
4491 ProcessAckPacket(&second_ack_frame);
4493 // Verify that the delegate is not notified again when the
4494 // retransmit is acked.
4495 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4496 .WillOnce(Return(no_lost_packets));
4497 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4498 QuicAckFrame third_ack_frame = InitAckFrame(5);
4499 ProcessAckPacket(&third_ack_frame);
4502 TEST_P(QuicConnectionTest, AckNotifierFECTriggerCallback) {
4503 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4505 // Create a delegate which we expect to be called.
4506 scoped_refptr<MockAckNotifierDelegate> delegate(
4507 new MockAckNotifierDelegate);
4508 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(1);
4510 // Send some data, which will register the delegate to be notified.
4511 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
4512 connection_.SendStreamDataWithString(2, "bar", 0, !kFin, nullptr);
4514 // Process an ACK from the server with a revived packet, which should trigger
4515 // the callback.
4516 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4517 QuicAckFrame frame = InitAckFrame(2);
4518 NackPacket(1, &frame);
4519 frame.revived_packets.insert(1);
4520 ProcessAckPacket(&frame);
4521 // If the ack is processed again, the notifier should not be called again.
4522 ProcessAckPacket(&frame);
4525 TEST_P(QuicConnectionTest, AckNotifierCallbackAfterFECRecovery) {
4526 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4527 EXPECT_CALL(visitor_, OnCanWrite());
4529 // Create a delegate which we expect to be called.
4530 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4531 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(1);
4533 // Expect ACKs for 1 packet.
4534 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4536 // Send one packet, and register to be notified on ACK.
4537 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
4539 // Ack packet gets dropped, but we receive an FEC packet that covers it.
4540 // Should recover the Ack packet and trigger the notification callback.
4541 QuicFrames frames;
4543 QuicAckFrame ack_frame = InitAckFrame(1);
4544 frames.push_back(QuicFrame(&ack_frame));
4546 // Dummy stream frame to satisfy expectations set elsewhere.
4547 frames.push_back(QuicFrame(&frame1_));
4549 QuicPacketHeader ack_header;
4550 ack_header.public_header.connection_id = connection_id_;
4551 ack_header.public_header.reset_flag = false;
4552 ack_header.public_header.version_flag = false;
4553 ack_header.entropy_flag = !kEntropyFlag;
4554 ack_header.fec_flag = true;
4555 ack_header.packet_packet_number = 1;
4556 ack_header.is_in_fec_group = IN_FEC_GROUP;
4557 ack_header.fec_group = 1;
4559 QuicPacket* packet = BuildUnsizedDataPacket(&framer_, ack_header, frames);
4561 // Take the packet which contains the ACK frame, and construct and deliver an
4562 // FEC packet which allows the ACK packet to be recovered.
4563 ProcessFecPacket(2, 1, true, !kEntropyFlag, packet);
4566 TEST_P(QuicConnectionTest, NetworkChangeVisitorCwndCallbackChangesFecState) {
4567 size_t max_packets_per_fec_group = creator_->max_packets_per_fec_group();
4569 QuicSentPacketManager::NetworkChangeVisitor* visitor =
4570 QuicSentPacketManagerPeer::GetNetworkChangeVisitor(manager_);
4571 EXPECT_TRUE(visitor);
4573 // Increase FEC group size by increasing congestion window to a large number.
4574 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
4575 Return(1000 * kDefaultTCPMSS));
4576 visitor->OnCongestionWindowChange();
4577 EXPECT_LT(max_packets_per_fec_group, creator_->max_packets_per_fec_group());
4580 TEST_P(QuicConnectionTest, NetworkChangeVisitorConfigCallbackChangesFecState) {
4581 QuicSentPacketManager::NetworkChangeVisitor* visitor =
4582 QuicSentPacketManagerPeer::GetNetworkChangeVisitor(manager_);
4583 EXPECT_TRUE(visitor);
4584 EXPECT_EQ(QuicTime::Delta::Zero(),
4585 QuicPacketGeneratorPeer::GetFecTimeout(generator_));
4587 // Verify that sending a config with a new initial rtt changes fec timeout.
4588 // Create and process a config with a non-zero initial RTT.
4589 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4590 QuicConfig config;
4591 config.SetInitialRoundTripTimeUsToSend(300000);
4592 connection_.SetFromConfig(config);
4593 EXPECT_LT(QuicTime::Delta::Zero(),
4594 QuicPacketGeneratorPeer::GetFecTimeout(generator_));
4597 TEST_P(QuicConnectionTest, NetworkChangeVisitorRttCallbackChangesFecState) {
4598 // Verify that sending a config with a new initial rtt changes fec timeout.
4599 QuicSentPacketManager::NetworkChangeVisitor* visitor =
4600 QuicSentPacketManagerPeer::GetNetworkChangeVisitor(manager_);
4601 EXPECT_TRUE(visitor);
4602 EXPECT_EQ(QuicTime::Delta::Zero(),
4603 QuicPacketGeneratorPeer::GetFecTimeout(generator_));
4605 // Increase FEC timeout by increasing RTT.
4606 RttStats* rtt_stats = QuicSentPacketManagerPeer::GetRttStats(manager_);
4607 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(300),
4608 QuicTime::Delta::Zero(), QuicTime::Zero());
4609 visitor->OnRttChange();
4610 EXPECT_LT(QuicTime::Delta::Zero(),
4611 QuicPacketGeneratorPeer::GetFecTimeout(generator_));
4614 TEST_P(QuicConnectionTest, OnPacketHeaderDebugVisitor) {
4615 QuicPacketHeader header;
4617 scoped_ptr<MockQuicConnectionDebugVisitor> debug_visitor(
4618 new MockQuicConnectionDebugVisitor());
4619 connection_.set_debug_visitor(debug_visitor.get());
4620 EXPECT_CALL(*debug_visitor, OnPacketHeader(Ref(header))).Times(1);
4621 connection_.OnPacketHeader(header);
4624 TEST_P(QuicConnectionTest, Pacing) {
4625 TestConnection server(connection_id_, IPEndPoint(), helper_.get(), factory_,
4626 Perspective::IS_SERVER, version());
4627 TestConnection client(connection_id_, IPEndPoint(), helper_.get(), factory_,
4628 Perspective::IS_CLIENT, version());
4629 EXPECT_FALSE(client.sent_packet_manager().using_pacing());
4630 EXPECT_FALSE(server.sent_packet_manager().using_pacing());
4633 TEST_P(QuicConnectionTest, ControlFramesInstigateAcks) {
4634 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4636 // Send a WINDOW_UPDATE frame.
4637 QuicWindowUpdateFrame window_update;
4638 window_update.stream_id = 3;
4639 window_update.byte_offset = 1234;
4640 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
4641 ProcessFramePacket(QuicFrame(&window_update));
4643 // Ensure that this has caused the ACK alarm to be set.
4644 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
4645 EXPECT_TRUE(ack_alarm->IsSet());
4647 // Cancel alarm, and try again with BLOCKED frame.
4648 ack_alarm->Cancel();
4649 QuicBlockedFrame blocked;
4650 blocked.stream_id = 3;
4651 EXPECT_CALL(visitor_, OnBlockedFrame(_));
4652 ProcessFramePacket(QuicFrame(&blocked));
4653 EXPECT_TRUE(ack_alarm->IsSet());
4656 TEST_P(QuicConnectionTest, NoDataNoFin) {
4657 // Make sure that a call to SendStreamWithData, with no data and no FIN, does
4658 // not result in a QuicAckNotifier being used-after-free (fail under ASAN).
4659 // Regression test for b/18594622
4660 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4661 EXPECT_DFATAL(
4662 connection_.SendStreamDataWithString(3, "", 0, !kFin, delegate.get()),
4663 "Attempt to send empty stream frame");
4666 TEST_P(QuicConnectionTest, FecSendPolicyReceivedConnectionOption) {
4667 // Test sending SetReceivedConnectionOptions when FEC send policy is
4668 // FEC_ANY_TRIGGER.
4669 if (GetParam().fec_send_policy == FEC_ALARM_TRIGGER) {
4670 return;
4672 connection_.set_perspective(Perspective::IS_SERVER);
4674 // Test ReceivedConnectionOptions.
4675 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4676 QuicConfig config;
4677 QuicTagVector copt;
4678 copt.push_back(kFSPA);
4679 QuicConfigPeer::SetReceivedConnectionOptions(&config, copt);
4680 EXPECT_EQ(FEC_ANY_TRIGGER, generator_->fec_send_policy());
4681 connection_.SetFromConfig(config);
4682 EXPECT_EQ(FEC_ALARM_TRIGGER, generator_->fec_send_policy());
4685 // TODO(rtenneti): Delete this code after the 0.25 RTT FEC experiment.
4686 TEST_P(QuicConnectionTest, FecRTTMultiplierReceivedConnectionOption) {
4687 connection_.set_perspective(Perspective::IS_SERVER);
4689 // Test ReceivedConnectionOptions.
4690 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4691 QuicConfig config;
4692 QuicTagVector copt;
4693 copt.push_back(kFRTT);
4694 QuicConfigPeer::SetReceivedConnectionOptions(&config, copt);
4695 float rtt_multiplier_for_fec_timeout =
4696 generator_->rtt_multiplier_for_fec_timeout();
4697 connection_.SetFromConfig(config);
4698 // New RTT multiplier is half of the old RTT multiplier.
4699 EXPECT_EQ(rtt_multiplier_for_fec_timeout,
4700 generator_->rtt_multiplier_for_fec_timeout() * 2);
4703 TEST_P(QuicConnectionTest, DoNotSendGoAwayTwice) {
4704 EXPECT_FALSE(connection_.goaway_sent());
4705 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4706 connection_.SendGoAway(QUIC_PEER_GOING_AWAY, kHeadersStreamId, "Going Away.");
4707 EXPECT_TRUE(connection_.goaway_sent());
4708 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4709 connection_.SendGoAway(QUIC_PEER_GOING_AWAY, kHeadersStreamId, "Going Away.");
4712 } // namespace
4713 } // namespace test
4714 } // namespace net