Rewrite AndroidSyncSettings to be significantly simpler.
[chromium-blink-merge.git] / net / quic / quic_connection_test.cc
blob57c55ce320dfea4dba6a0c70ba6f186a15e5ed8c
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 "base/basictypes.h"
8 #include "base/bind.h"
9 #include "base/stl_util.h"
10 #include "net/base/net_errors.h"
11 #include "net/quic/congestion_control/loss_detection_interface.h"
12 #include "net/quic/congestion_control/send_algorithm_interface.h"
13 #include "net/quic/crypto/null_encrypter.h"
14 #include "net/quic/crypto/quic_decrypter.h"
15 #include "net/quic/crypto/quic_encrypter.h"
16 #include "net/quic/quic_ack_notifier.h"
17 #include "net/quic/quic_flags.h"
18 #include "net/quic/quic_protocol.h"
19 #include "net/quic/quic_utils.h"
20 #include "net/quic/test_tools/mock_clock.h"
21 #include "net/quic/test_tools/mock_random.h"
22 #include "net/quic/test_tools/quic_config_peer.h"
23 #include "net/quic/test_tools/quic_connection_peer.h"
24 #include "net/quic/test_tools/quic_framer_peer.h"
25 #include "net/quic/test_tools/quic_packet_creator_peer.h"
26 #include "net/quic/test_tools/quic_packet_generator_peer.h"
27 #include "net/quic/test_tools/quic_sent_packet_manager_peer.h"
28 #include "net/quic/test_tools/quic_test_utils.h"
29 #include "net/quic/test_tools/simple_quic_framer.h"
30 #include "net/test/gtest_util.h"
31 #include "testing/gmock/include/gmock/gmock.h"
32 #include "testing/gtest/include/gtest/gtest.h"
34 using base::StringPiece;
35 using std::map;
36 using std::string;
37 using std::vector;
38 using testing::AnyNumber;
39 using testing::AtLeast;
40 using testing::ContainerEq;
41 using testing::Contains;
42 using testing::DoAll;
43 using testing::InSequence;
44 using testing::InvokeWithoutArgs;
45 using testing::NiceMock;
46 using testing::Ref;
47 using testing::Return;
48 using testing::SaveArg;
49 using testing::StrictMock;
50 using testing::_;
52 namespace net {
53 namespace test {
54 namespace {
56 const char data1[] = "foo";
57 const char data2[] = "bar";
59 const bool kFin = true;
60 const bool kEntropyFlag = true;
62 const QuicPacketEntropyHash kTestEntropyHash = 76;
64 const int kDefaultRetransmissionTimeMs = 500;
66 // TaggingEncrypter appends kTagSize bytes of |tag| to the end of each message.
67 class TaggingEncrypter : public QuicEncrypter {
68 public:
69 explicit TaggingEncrypter(uint8 tag)
70 : tag_(tag) {
73 ~TaggingEncrypter() override {}
75 // QuicEncrypter interface.
76 bool SetKey(StringPiece key) override { return true; }
78 bool SetNoncePrefix(StringPiece nonce_prefix) override { return true; }
80 bool Encrypt(StringPiece nonce,
81 StringPiece associated_data,
82 StringPiece plaintext,
83 unsigned char* output) override {
84 memcpy(output, plaintext.data(), plaintext.size());
85 output += plaintext.size();
86 memset(output, tag_, kTagSize);
87 return true;
90 bool EncryptPacket(QuicPacketSequenceNumber sequence_number,
91 StringPiece associated_data,
92 StringPiece plaintext,
93 char* output,
94 size_t* output_length,
95 size_t max_output_length) override {
96 const size_t len = plaintext.size() + kTagSize;
97 if (max_output_length < len) {
98 return false;
100 Encrypt(StringPiece(), associated_data, plaintext,
101 reinterpret_cast<unsigned char*>(output));
102 *output_length = len;
103 return true;
106 size_t GetKeySize() const override { return 0; }
107 size_t GetNoncePrefixSize() const override { return 0; }
109 size_t GetMaxPlaintextSize(size_t ciphertext_size) const override {
110 return ciphertext_size - kTagSize;
113 size_t GetCiphertextSize(size_t plaintext_size) const override {
114 return plaintext_size + kTagSize;
117 StringPiece GetKey() const override { return StringPiece(); }
119 StringPiece GetNoncePrefix() const override { return StringPiece(); }
121 private:
122 enum {
123 kTagSize = 12,
126 const uint8 tag_;
128 DISALLOW_COPY_AND_ASSIGN(TaggingEncrypter);
131 // TaggingDecrypter ensures that the final kTagSize bytes of the message all
132 // have the same value and then removes them.
133 class TaggingDecrypter : public QuicDecrypter {
134 public:
135 ~TaggingDecrypter() override {}
137 // QuicDecrypter interface
138 bool SetKey(StringPiece key) override { return true; }
140 bool SetNoncePrefix(StringPiece nonce_prefix) override { return true; }
142 bool DecryptPacket(QuicPacketSequenceNumber sequence_number,
143 const StringPiece& associated_data,
144 const StringPiece& ciphertext,
145 char* output,
146 size_t* output_length,
147 size_t max_output_length) override {
148 if (ciphertext.size() < kTagSize) {
149 return false;
151 if (!CheckTag(ciphertext, GetTag(ciphertext))) {
152 return false;
154 *output_length = ciphertext.size() - kTagSize;
155 memcpy(output, ciphertext.data(), *output_length);
156 return true;
159 StringPiece GetKey() const override { return StringPiece(); }
160 StringPiece GetNoncePrefix() const override { return StringPiece(); }
162 protected:
163 virtual uint8 GetTag(StringPiece ciphertext) {
164 return ciphertext.data()[ciphertext.size()-1];
167 private:
168 enum {
169 kTagSize = 12,
172 bool CheckTag(StringPiece ciphertext, uint8 tag) {
173 for (size_t i = ciphertext.size() - kTagSize; i < ciphertext.size(); i++) {
174 if (ciphertext.data()[i] != tag) {
175 return false;
179 return true;
183 // StringTaggingDecrypter ensures that the final kTagSize bytes of the message
184 // match the expected value.
185 class StrictTaggingDecrypter : public TaggingDecrypter {
186 public:
187 explicit StrictTaggingDecrypter(uint8 tag) : tag_(tag) {}
188 ~StrictTaggingDecrypter() override {}
190 // TaggingQuicDecrypter
191 uint8 GetTag(StringPiece ciphertext) override { return tag_; }
193 private:
194 const uint8 tag_;
197 class TestConnectionHelper : public QuicConnectionHelperInterface {
198 public:
199 class TestAlarm : public QuicAlarm {
200 public:
201 explicit TestAlarm(QuicAlarm::Delegate* delegate)
202 : QuicAlarm(delegate) {
205 void SetImpl() override {}
206 void CancelImpl() override {}
207 using QuicAlarm::Fire;
210 TestConnectionHelper(MockClock* clock, MockRandom* random_generator)
211 : clock_(clock),
212 random_generator_(random_generator) {
213 clock_->AdvanceTime(QuicTime::Delta::FromSeconds(1));
216 // QuicConnectionHelperInterface
217 const QuicClock* GetClock() const override { return clock_; }
219 QuicRandom* GetRandomGenerator() override { return random_generator_; }
221 QuicAlarm* CreateAlarm(QuicAlarm::Delegate* delegate) override {
222 return new TestAlarm(delegate);
225 private:
226 MockClock* clock_;
227 MockRandom* random_generator_;
229 DISALLOW_COPY_AND_ASSIGN(TestConnectionHelper);
232 class TestPacketWriter : public QuicPacketWriter {
233 public:
234 TestPacketWriter(QuicVersion version, MockClock *clock)
235 : version_(version),
236 framer_(SupportedVersions(version_)),
237 last_packet_size_(0),
238 write_blocked_(false),
239 block_on_next_write_(false),
240 is_write_blocked_data_buffered_(false),
241 final_bytes_of_last_packet_(0),
242 final_bytes_of_previous_packet_(0),
243 use_tagging_decrypter_(false),
244 packets_write_attempts_(0),
245 clock_(clock),
246 write_pause_time_delta_(QuicTime::Delta::Zero()) {
249 // QuicPacketWriter interface
250 WriteResult WritePacket(const char* buffer,
251 size_t buf_len,
252 const IPAddressNumber& self_address,
253 const IPEndPoint& peer_address) override {
254 QuicEncryptedPacket packet(buffer, buf_len);
255 ++packets_write_attempts_;
257 if (packet.length() >= sizeof(final_bytes_of_last_packet_)) {
258 final_bytes_of_previous_packet_ = final_bytes_of_last_packet_;
259 memcpy(&final_bytes_of_last_packet_, packet.data() + packet.length() - 4,
260 sizeof(final_bytes_of_last_packet_));
263 if (use_tagging_decrypter_) {
264 framer_.framer()->SetDecrypter(new TaggingDecrypter, ENCRYPTION_NONE);
266 EXPECT_TRUE(framer_.ProcessPacket(packet));
267 if (block_on_next_write_) {
268 write_blocked_ = true;
269 block_on_next_write_ = false;
271 if (IsWriteBlocked()) {
272 return WriteResult(WRITE_STATUS_BLOCKED, -1);
274 last_packet_size_ = packet.length();
276 if (!write_pause_time_delta_.IsZero()) {
277 clock_->AdvanceTime(write_pause_time_delta_);
279 return WriteResult(WRITE_STATUS_OK, last_packet_size_);
282 bool IsWriteBlockedDataBuffered() const override {
283 return is_write_blocked_data_buffered_;
286 bool IsWriteBlocked() const override { return write_blocked_; }
288 void SetWritable() override { write_blocked_ = false; }
290 void BlockOnNextWrite() { block_on_next_write_ = true; }
292 // Sets the amount of time that the writer should before the actual write.
293 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
294 write_pause_time_delta_ = delta;
297 const QuicPacketHeader& header() { return framer_.header(); }
299 size_t frame_count() const { return framer_.num_frames(); }
301 const vector<QuicAckFrame>& ack_frames() const {
302 return framer_.ack_frames();
305 const vector<QuicStopWaitingFrame>& stop_waiting_frames() const {
306 return framer_.stop_waiting_frames();
309 const vector<QuicConnectionCloseFrame>& connection_close_frames() const {
310 return framer_.connection_close_frames();
313 const vector<QuicStreamFrame>& stream_frames() const {
314 return framer_.stream_frames();
317 const vector<QuicPingFrame>& ping_frames() const {
318 return framer_.ping_frames();
321 size_t last_packet_size() {
322 return last_packet_size_;
325 const QuicVersionNegotiationPacket* version_negotiation_packet() {
326 return framer_.version_negotiation_packet();
329 void set_is_write_blocked_data_buffered(bool buffered) {
330 is_write_blocked_data_buffered_ = buffered;
333 void set_is_server(bool is_server) {
334 // We invert is_server here, because the framer needs to parse packets
335 // we send.
336 QuicFramerPeer::SetIsServer(framer_.framer(), !is_server);
339 // final_bytes_of_last_packet_ returns the last four bytes of the previous
340 // packet as a little-endian, uint32. This is intended to be used with a
341 // TaggingEncrypter so that tests can determine which encrypter was used for
342 // a given packet.
343 uint32 final_bytes_of_last_packet() { return final_bytes_of_last_packet_; }
345 // Returns the final bytes of the second to last packet.
346 uint32 final_bytes_of_previous_packet() {
347 return final_bytes_of_previous_packet_;
350 void use_tagging_decrypter() {
351 use_tagging_decrypter_ = true;
354 uint32 packets_write_attempts() { return packets_write_attempts_; }
356 void Reset() { framer_.Reset(); }
358 void SetSupportedVersions(const QuicVersionVector& versions) {
359 framer_.SetSupportedVersions(versions);
362 private:
363 QuicVersion version_;
364 SimpleQuicFramer framer_;
365 size_t last_packet_size_;
366 bool write_blocked_;
367 bool block_on_next_write_;
368 bool is_write_blocked_data_buffered_;
369 uint32 final_bytes_of_last_packet_;
370 uint32 final_bytes_of_previous_packet_;
371 bool use_tagging_decrypter_;
372 uint32 packets_write_attempts_;
373 MockClock *clock_;
374 // If non-zero, the clock will pause during WritePacket for this amount of
375 // time.
376 QuicTime::Delta write_pause_time_delta_;
378 DISALLOW_COPY_AND_ASSIGN(TestPacketWriter);
381 class TestConnection : public QuicConnection {
382 public:
383 TestConnection(QuicConnectionId connection_id,
384 IPEndPoint address,
385 TestConnectionHelper* helper,
386 const PacketWriterFactory& factory,
387 bool is_server,
388 QuicVersion version)
389 : QuicConnection(connection_id,
390 address,
391 helper,
392 factory,
393 /* owns_writer= */ false,
394 is_server,
395 /* is_secure= */ false,
396 SupportedVersions(version)) {
397 // Disable tail loss probes for most tests.
398 QuicSentPacketManagerPeer::SetMaxTailLossProbes(
399 QuicConnectionPeer::GetSentPacketManager(this), 0);
400 writer()->set_is_server(is_server);
403 void SendAck() {
404 QuicConnectionPeer::SendAck(this);
407 void SetSendAlgorithm(SendAlgorithmInterface* send_algorithm) {
408 QuicConnectionPeer::SetSendAlgorithm(this, send_algorithm);
411 void SetLossAlgorithm(LossDetectionInterface* loss_algorithm) {
412 QuicSentPacketManagerPeer::SetLossAlgorithm(
413 QuicConnectionPeer::GetSentPacketManager(this), loss_algorithm);
416 void SendPacket(EncryptionLevel level,
417 QuicPacketSequenceNumber sequence_number,
418 QuicPacket* packet,
419 QuicPacketEntropyHash entropy_hash,
420 HasRetransmittableData retransmittable) {
421 RetransmittableFrames* retransmittable_frames =
422 retransmittable == HAS_RETRANSMITTABLE_DATA
423 ? new RetransmittableFrames(ENCRYPTION_NONE)
424 : nullptr;
425 QuicEncryptedPacket* encrypted =
426 QuicConnectionPeer::GetFramer(this)
427 ->EncryptPacket(ENCRYPTION_NONE, sequence_number, *packet);
428 delete packet;
429 OnSerializedPacket(SerializedPacket(sequence_number,
430 PACKET_6BYTE_SEQUENCE_NUMBER, encrypted,
431 entropy_hash, retransmittable_frames));
434 QuicConsumedData SendStreamDataWithString(
435 QuicStreamId id,
436 StringPiece data,
437 QuicStreamOffset offset,
438 bool fin,
439 QuicAckNotifier::DelegateInterface* delegate) {
440 return SendStreamDataWithStringHelper(id, data, offset, fin,
441 MAY_FEC_PROTECT, delegate);
444 QuicConsumedData SendStreamDataWithStringWithFec(
445 QuicStreamId id,
446 StringPiece data,
447 QuicStreamOffset offset,
448 bool fin,
449 QuicAckNotifier::DelegateInterface* delegate) {
450 return SendStreamDataWithStringHelper(id, data, offset, fin,
451 MUST_FEC_PROTECT, delegate);
454 QuicConsumedData SendStreamDataWithStringHelper(
455 QuicStreamId id,
456 StringPiece data,
457 QuicStreamOffset offset,
458 bool fin,
459 FecProtection fec_protection,
460 QuicAckNotifier::DelegateInterface* delegate) {
461 IOVector data_iov;
462 if (!data.empty()) {
463 data_iov.Append(const_cast<char*>(data.data()), data.size());
465 return QuicConnection::SendStreamData(id, data_iov, offset, fin,
466 fec_protection, delegate);
469 QuicConsumedData SendStreamData3() {
470 return SendStreamDataWithString(kClientDataStreamId1, "food", 0, !kFin,
471 nullptr);
474 QuicConsumedData SendStreamData3WithFec() {
475 return SendStreamDataWithStringWithFec(kClientDataStreamId1, "food", 0,
476 !kFin, nullptr);
479 QuicConsumedData SendStreamData5() {
480 return SendStreamDataWithString(kClientDataStreamId2, "food2", 0, !kFin,
481 nullptr);
484 QuicConsumedData SendStreamData5WithFec() {
485 return SendStreamDataWithStringWithFec(kClientDataStreamId2, "food2", 0,
486 !kFin, nullptr);
488 // Ensures the connection can write stream data before writing.
489 QuicConsumedData EnsureWritableAndSendStreamData5() {
490 EXPECT_TRUE(CanWriteStreamData());
491 return SendStreamData5();
494 // The crypto stream has special semantics so that it is not blocked by a
495 // congestion window limitation, and also so that it gets put into a separate
496 // packet (so that it is easier to reason about a crypto frame not being
497 // split needlessly across packet boundaries). As a result, we have separate
498 // tests for some cases for this stream.
499 QuicConsumedData SendCryptoStreamData() {
500 return SendStreamDataWithString(kCryptoStreamId, "chlo", 0, !kFin, nullptr);
503 bool is_server() {
504 return QuicConnectionPeer::IsServer(this);
507 void set_version(QuicVersion version) {
508 QuicConnectionPeer::GetFramer(this)->set_version(version);
511 void SetSupportedVersions(const QuicVersionVector& versions) {
512 QuicConnectionPeer::GetFramer(this)->SetSupportedVersions(versions);
513 writer()->SetSupportedVersions(versions);
516 void set_is_server(bool is_server) {
517 writer()->set_is_server(is_server);
518 QuicConnectionPeer::SetIsServer(this, is_server);
521 TestConnectionHelper::TestAlarm* GetAckAlarm() {
522 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
523 QuicConnectionPeer::GetAckAlarm(this));
526 TestConnectionHelper::TestAlarm* GetPingAlarm() {
527 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
528 QuicConnectionPeer::GetPingAlarm(this));
531 TestConnectionHelper::TestAlarm* GetFecAlarm() {
532 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
533 QuicConnectionPeer::GetFecAlarm(this));
536 TestConnectionHelper::TestAlarm* GetResumeWritesAlarm() {
537 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
538 QuicConnectionPeer::GetResumeWritesAlarm(this));
541 TestConnectionHelper::TestAlarm* GetRetransmissionAlarm() {
542 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
543 QuicConnectionPeer::GetRetransmissionAlarm(this));
546 TestConnectionHelper::TestAlarm* GetSendAlarm() {
547 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
548 QuicConnectionPeer::GetSendAlarm(this));
551 TestConnectionHelper::TestAlarm* GetTimeoutAlarm() {
552 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
553 QuicConnectionPeer::GetTimeoutAlarm(this));
556 using QuicConnection::SelectMutualVersion;
558 private:
559 TestPacketWriter* writer() {
560 return static_cast<TestPacketWriter*>(QuicConnection::writer());
563 DISALLOW_COPY_AND_ASSIGN(TestConnection);
566 // Used for testing packets revived from FEC packets.
567 class FecQuicConnectionDebugVisitor
568 : public QuicConnectionDebugVisitor {
569 public:
570 void OnRevivedPacket(const QuicPacketHeader& header,
571 StringPiece data) override {
572 revived_header_ = header;
575 // Public accessor method.
576 QuicPacketHeader revived_header() const {
577 return revived_header_;
580 private:
581 QuicPacketHeader revived_header_;
584 class MockPacketWriterFactory : public QuicConnection::PacketWriterFactory {
585 public:
586 explicit MockPacketWriterFactory(QuicPacketWriter* writer) {
587 ON_CALL(*this, Create(_)).WillByDefault(Return(writer));
589 ~MockPacketWriterFactory() override {}
591 MOCK_CONST_METHOD1(Create, QuicPacketWriter*(QuicConnection* connection));
594 class QuicConnectionTest : public ::testing::TestWithParam<QuicVersion> {
595 protected:
596 QuicConnectionTest()
597 : connection_id_(42),
598 framer_(SupportedVersions(version()), QuicTime::Zero(), false),
599 peer_creator_(connection_id_, &framer_, &random_generator_),
600 send_algorithm_(new StrictMock<MockSendAlgorithm>),
601 loss_algorithm_(new MockLossAlgorithm()),
602 helper_(new TestConnectionHelper(&clock_, &random_generator_)),
603 writer_(new TestPacketWriter(version(), &clock_)),
604 factory_(writer_.get()),
605 connection_(connection_id_,
606 IPEndPoint(),
607 helper_.get(),
608 factory_,
609 false,
610 version()),
611 creator_(QuicConnectionPeer::GetPacketCreator(&connection_)),
612 generator_(QuicConnectionPeer::GetPacketGenerator(&connection_)),
613 manager_(QuicConnectionPeer::GetSentPacketManager(&connection_)),
614 frame1_(1, false, 0, MakeIOVector(data1)),
615 frame2_(1, false, 3, MakeIOVector(data2)),
616 sequence_number_length_(PACKET_6BYTE_SEQUENCE_NUMBER),
617 connection_id_length_(PACKET_8BYTE_CONNECTION_ID) {
618 connection_.set_visitor(&visitor_);
619 connection_.SetSendAlgorithm(send_algorithm_);
620 connection_.SetLossAlgorithm(loss_algorithm_);
621 framer_.set_received_entropy_calculator(&entropy_calculator_);
622 EXPECT_CALL(
623 *send_algorithm_, TimeUntilSend(_, _, _)).WillRepeatedly(Return(
624 QuicTime::Delta::Zero()));
625 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
626 .Times(AnyNumber());
627 EXPECT_CALL(*send_algorithm_, RetransmissionDelay()).WillRepeatedly(
628 Return(QuicTime::Delta::Zero()));
629 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
630 Return(kMaxPacketSize));
631 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
632 .WillByDefault(Return(true));
633 EXPECT_CALL(*send_algorithm_, HasReliableBandwidthEstimate())
634 .Times(AnyNumber());
635 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
636 .Times(AnyNumber())
637 .WillRepeatedly(Return(QuicBandwidth::Zero()));
638 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
639 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
640 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).Times(AnyNumber());
641 EXPECT_CALL(visitor_, HasPendingHandshake()).Times(AnyNumber());
642 EXPECT_CALL(visitor_, OnCanWrite()).Times(AnyNumber());
643 EXPECT_CALL(visitor_, HasOpenDataStreams()).WillRepeatedly(Return(false));
644 EXPECT_CALL(visitor_, OnCongestionWindowChange(_)).Times(AnyNumber());
646 EXPECT_CALL(*loss_algorithm_, GetLossTimeout())
647 .WillRepeatedly(Return(QuicTime::Zero()));
648 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
649 .WillRepeatedly(Return(SequenceNumberSet()));
652 QuicVersion version() {
653 return GetParam();
656 QuicAckFrame* outgoing_ack() {
657 QuicConnectionPeer::PopulateAckFrame(&connection_, &ack_);
658 return &ack_;
661 QuicStopWaitingFrame* stop_waiting() {
662 QuicConnectionPeer::PopulateStopWaitingFrame(&connection_, &stop_waiting_);
663 return &stop_waiting_;
666 QuicPacketSequenceNumber least_unacked() {
667 if (writer_->stop_waiting_frames().empty()) {
668 return 0;
670 return writer_->stop_waiting_frames()[0].least_unacked;
673 void use_tagging_decrypter() {
674 writer_->use_tagging_decrypter();
677 void ProcessPacket(QuicPacketSequenceNumber number) {
678 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
679 ProcessDataPacket(number, 0, !kEntropyFlag);
682 QuicPacketEntropyHash ProcessFramePacket(QuicFrame frame) {
683 QuicFrames frames;
684 frames.push_back(QuicFrame(frame));
685 QuicPacketCreatorPeer::SetSendVersionInPacket(&peer_creator_,
686 connection_.is_server());
687 SerializedPacket serialized_packet =
688 peer_creator_.SerializeAllFrames(frames);
689 scoped_ptr<QuicEncryptedPacket> encrypted(serialized_packet.packet);
690 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
691 return serialized_packet.entropy_hash;
694 size_t ProcessDataPacket(QuicPacketSequenceNumber number,
695 QuicFecGroupNumber fec_group,
696 bool entropy_flag) {
697 return ProcessDataPacketAtLevel(number, fec_group, entropy_flag,
698 ENCRYPTION_NONE);
701 size_t ProcessDataPacketAtLevel(QuicPacketSequenceNumber number,
702 QuicFecGroupNumber fec_group,
703 bool entropy_flag,
704 EncryptionLevel level) {
705 scoped_ptr<QuicPacket> packet(ConstructDataPacket(number, fec_group,
706 entropy_flag));
707 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPacket(
708 level, number, *packet));
709 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
710 return encrypted->length();
713 void ProcessPingPacket(QuicPacketSequenceNumber number) {
714 scoped_ptr<QuicPacket> packet(ConstructPingPacket(number));
715 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPacket(
716 ENCRYPTION_NONE, number, *packet));
717 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
720 void ProcessClosePacket(QuicPacketSequenceNumber number,
721 QuicFecGroupNumber fec_group) {
722 scoped_ptr<QuicPacket> packet(ConstructClosePacket(number, fec_group));
723 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPacket(
724 ENCRYPTION_NONE, number, *packet));
725 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
728 size_t ProcessFecProtectedPacket(QuicPacketSequenceNumber number,
729 bool expect_revival, bool entropy_flag) {
730 if (expect_revival) {
731 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
733 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1).
734 RetiresOnSaturation();
735 return ProcessDataPacket(number, 1, entropy_flag);
738 // Processes an FEC packet that covers the packets that would have been
739 // received.
740 size_t ProcessFecPacket(QuicPacketSequenceNumber number,
741 QuicPacketSequenceNumber min_protected_packet,
742 bool expect_revival,
743 bool entropy_flag,
744 QuicPacket* packet) {
745 if (expect_revival) {
746 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
749 // Construct the decrypted data packet so we can compute the correct
750 // redundancy. If |packet| has been provided then use that, otherwise
751 // construct a default data packet.
752 scoped_ptr<QuicPacket> data_packet;
753 if (packet) {
754 data_packet.reset(packet);
755 } else {
756 data_packet.reset(ConstructDataPacket(number, 1, !kEntropyFlag));
759 header_.public_header.connection_id = connection_id_;
760 header_.public_header.reset_flag = false;
761 header_.public_header.version_flag = false;
762 header_.public_header.sequence_number_length = sequence_number_length_;
763 header_.public_header.connection_id_length = connection_id_length_;
764 header_.packet_sequence_number = number;
765 header_.entropy_flag = entropy_flag;
766 header_.fec_flag = true;
767 header_.is_in_fec_group = IN_FEC_GROUP;
768 header_.fec_group = min_protected_packet;
769 QuicFecData fec_data;
770 fec_data.fec_group = header_.fec_group;
772 // Since all data packets in this test have the same payload, the
773 // redundancy is either equal to that payload or the xor of that payload
774 // with itself, depending on the number of packets.
775 if (((number - min_protected_packet) % 2) == 0) {
776 for (size_t i = GetStartOfFecProtectedData(
777 header_.public_header.connection_id_length,
778 header_.public_header.version_flag,
779 header_.public_header.sequence_number_length);
780 i < data_packet->length(); ++i) {
781 data_packet->mutable_data()[i] ^= data_packet->data()[i];
784 fec_data.redundancy = data_packet->FecProtectedData();
786 scoped_ptr<QuicPacket> fec_packet(
787 framer_.BuildFecPacket(header_, fec_data));
788 scoped_ptr<QuicEncryptedPacket> encrypted(
789 framer_.EncryptPacket(ENCRYPTION_NONE, number, *fec_packet));
791 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
792 return encrypted->length();
795 QuicByteCount SendStreamDataToPeer(QuicStreamId id,
796 StringPiece data,
797 QuicStreamOffset offset,
798 bool fin,
799 QuicPacketSequenceNumber* last_packet) {
800 QuicByteCount packet_size;
801 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
802 .WillOnce(DoAll(SaveArg<3>(&packet_size), Return(true)));
803 connection_.SendStreamDataWithString(id, data, offset, fin, nullptr);
804 if (last_packet != nullptr) {
805 *last_packet = creator_->sequence_number();
807 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
808 .Times(AnyNumber());
809 return packet_size;
812 void SendAckPacketToPeer() {
813 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
814 connection_.SendAck();
815 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
816 .Times(AnyNumber());
819 QuicPacketEntropyHash ProcessAckPacket(QuicAckFrame* frame) {
820 return ProcessFramePacket(QuicFrame(frame));
823 QuicPacketEntropyHash ProcessStopWaitingPacket(QuicStopWaitingFrame* frame) {
824 return ProcessFramePacket(QuicFrame(frame));
827 QuicPacketEntropyHash ProcessGoAwayPacket(QuicGoAwayFrame* frame) {
828 return ProcessFramePacket(QuicFrame(frame));
831 bool IsMissing(QuicPacketSequenceNumber number) {
832 return IsAwaitingPacket(*outgoing_ack(), number);
835 QuicPacket* ConstructDataPacket(QuicPacketSequenceNumber number,
836 QuicFecGroupNumber fec_group,
837 bool entropy_flag) {
838 header_.public_header.connection_id = connection_id_;
839 header_.public_header.reset_flag = false;
840 header_.public_header.version_flag = false;
841 header_.public_header.sequence_number_length = sequence_number_length_;
842 header_.public_header.connection_id_length = connection_id_length_;
843 header_.entropy_flag = entropy_flag;
844 header_.fec_flag = false;
845 header_.packet_sequence_number = number;
846 header_.is_in_fec_group = fec_group == 0u ? NOT_IN_FEC_GROUP : IN_FEC_GROUP;
847 header_.fec_group = fec_group;
849 QuicFrames frames;
850 QuicFrame frame(&frame1_);
851 frames.push_back(frame);
852 QuicPacket* packet = BuildUnsizedDataPacket(&framer_, header_, frames);
853 EXPECT_TRUE(packet != nullptr);
854 return packet;
857 QuicPacket* ConstructPingPacket(QuicPacketSequenceNumber number) {
858 header_.public_header.connection_id = connection_id_;
859 header_.packet_sequence_number = number;
860 header_.public_header.reset_flag = false;
861 header_.public_header.version_flag = false;
862 header_.entropy_flag = false;
863 header_.fec_flag = false;
864 header_.is_in_fec_group = NOT_IN_FEC_GROUP;
865 header_.fec_group = 0;
867 QuicPingFrame ping;
869 QuicFrames frames;
870 QuicFrame frame(&ping);
871 frames.push_back(frame);
872 QuicPacket* packet = BuildUnsizedDataPacket(&framer_, header_, frames);
873 EXPECT_TRUE(packet != nullptr);
874 return packet;
877 QuicPacket* ConstructClosePacket(QuicPacketSequenceNumber number,
878 QuicFecGroupNumber fec_group) {
879 header_.public_header.connection_id = connection_id_;
880 header_.packet_sequence_number = number;
881 header_.public_header.reset_flag = false;
882 header_.public_header.version_flag = false;
883 header_.entropy_flag = false;
884 header_.fec_flag = false;
885 header_.is_in_fec_group = fec_group == 0u ? NOT_IN_FEC_GROUP : IN_FEC_GROUP;
886 header_.fec_group = fec_group;
888 QuicConnectionCloseFrame qccf;
889 qccf.error_code = QUIC_PEER_GOING_AWAY;
891 QuicFrames frames;
892 QuicFrame frame(&qccf);
893 frames.push_back(frame);
894 QuicPacket* packet = BuildUnsizedDataPacket(&framer_, header_, frames);
895 EXPECT_TRUE(packet != nullptr);
896 return packet;
899 QuicTime::Delta DefaultRetransmissionTime() {
900 return QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
903 QuicTime::Delta DefaultDelayedAckTime() {
904 return QuicTime::Delta::FromMilliseconds(kMaxDelayedAckTimeMs);
907 // Initialize a frame acknowledging all packets up to largest_observed.
908 const QuicAckFrame InitAckFrame(QuicPacketSequenceNumber largest_observed) {
909 QuicAckFrame frame(MakeAckFrame(largest_observed));
910 if (largest_observed > 0) {
911 frame.entropy_hash =
912 QuicConnectionPeer::GetSentEntropyHash(&connection_,
913 largest_observed);
915 return frame;
918 const QuicStopWaitingFrame InitStopWaitingFrame(
919 QuicPacketSequenceNumber least_unacked) {
920 QuicStopWaitingFrame frame;
921 frame.least_unacked = least_unacked;
922 return frame;
925 // Explicitly nack a packet.
926 void NackPacket(QuicPacketSequenceNumber missing, QuicAckFrame* frame) {
927 frame->missing_packets.insert(missing);
928 frame->entropy_hash ^=
929 QuicConnectionPeer::PacketEntropy(&connection_, missing);
932 // Undo nacking a packet within the frame.
933 void AckPacket(QuicPacketSequenceNumber arrived, QuicAckFrame* frame) {
934 EXPECT_THAT(frame->missing_packets, Contains(arrived));
935 frame->missing_packets.erase(arrived);
936 frame->entropy_hash ^=
937 QuicConnectionPeer::PacketEntropy(&connection_, arrived);
940 void TriggerConnectionClose() {
941 // Send an erroneous packet to close the connection.
942 EXPECT_CALL(visitor_,
943 OnConnectionClosed(QUIC_INVALID_PACKET_HEADER, false));
944 // Call ProcessDataPacket rather than ProcessPacket, as we should not get a
945 // packet call to the visitor.
946 ProcessDataPacket(6000, 0, !kEntropyFlag);
947 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
948 nullptr);
951 void BlockOnNextWrite() {
952 writer_->BlockOnNextWrite();
953 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
956 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
957 writer_->SetWritePauseTimeDelta(delta);
960 void CongestionBlockWrites() {
961 EXPECT_CALL(*send_algorithm_,
962 TimeUntilSend(_, _, _)).WillRepeatedly(
963 testing::Return(QuicTime::Delta::FromSeconds(1)));
966 void CongestionUnblockWrites() {
967 EXPECT_CALL(*send_algorithm_,
968 TimeUntilSend(_, _, _)).WillRepeatedly(
969 testing::Return(QuicTime::Delta::Zero()));
972 QuicConnectionId connection_id_;
973 QuicFramer framer_;
974 QuicPacketCreator peer_creator_;
975 MockEntropyCalculator entropy_calculator_;
977 MockSendAlgorithm* send_algorithm_;
978 MockLossAlgorithm* loss_algorithm_;
979 MockClock clock_;
980 MockRandom random_generator_;
981 scoped_ptr<TestConnectionHelper> helper_;
982 scoped_ptr<TestPacketWriter> writer_;
983 NiceMock<MockPacketWriterFactory> factory_;
984 TestConnection connection_;
985 QuicPacketCreator* creator_;
986 QuicPacketGenerator* generator_;
987 QuicSentPacketManager* manager_;
988 StrictMock<MockConnectionVisitor> visitor_;
990 QuicPacketHeader header_;
991 QuicStreamFrame frame1_;
992 QuicStreamFrame frame2_;
993 QuicAckFrame ack_;
994 QuicStopWaitingFrame stop_waiting_;
995 QuicSequenceNumberLength sequence_number_length_;
996 QuicConnectionIdLength connection_id_length_;
998 private:
999 DISALLOW_COPY_AND_ASSIGN(QuicConnectionTest);
1002 // Run all end to end tests with all supported versions.
1003 INSTANTIATE_TEST_CASE_P(SupportedVersion,
1004 QuicConnectionTest,
1005 ::testing::ValuesIn(QuicSupportedVersions()));
1007 TEST_P(QuicConnectionTest, MaxPacketSize) {
1008 EXPECT_FALSE(connection_.is_server());
1009 EXPECT_EQ(1350u, connection_.max_packet_length());
1012 TEST_P(QuicConnectionTest, SmallerServerMaxPacketSize) {
1013 ValueRestore<bool> old_flag(&FLAGS_quic_small_default_packet_size, true);
1014 QuicConnectionId connection_id = 42;
1015 bool kIsServer = true;
1016 TestConnection connection(connection_id, IPEndPoint(), helper_.get(),
1017 factory_, kIsServer, version());
1018 EXPECT_TRUE(connection.is_server());
1019 EXPECT_EQ(1000u, connection.max_packet_length());
1022 TEST_P(QuicConnectionTest, ServerMaxPacketSize) {
1023 ValueRestore<bool> old_flag(&FLAGS_quic_small_default_packet_size, false);
1024 QuicConnectionId connection_id = 42;
1025 bool kIsServer = true;
1026 TestConnection connection(connection_id, IPEndPoint(), helper_.get(),
1027 factory_, kIsServer, version());
1028 EXPECT_TRUE(connection.is_server());
1029 EXPECT_EQ(1350u, connection.max_packet_length());
1032 TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSize) {
1033 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1035 connection_.set_is_server(true);
1036 connection_.set_max_packet_length(1000);
1038 QuicPacketHeader header;
1039 header.public_header.connection_id = connection_id_;
1040 header.public_header.reset_flag = false;
1041 header.public_header.version_flag = true;
1042 header.entropy_flag = false;
1043 header.fec_flag = false;
1044 header.packet_sequence_number = 1;
1045 header.fec_group = 0;
1047 QuicFrames frames;
1048 QuicPaddingFrame padding;
1049 frames.push_back(QuicFrame(&frame1_));
1050 frames.push_back(QuicFrame(&padding));
1052 scoped_ptr<QuicPacket> packet(
1053 BuildUnsizedDataPacket(&framer_, header, frames));
1054 scoped_ptr<QuicEncryptedPacket> encrypted(
1055 framer_.EncryptPacket(ENCRYPTION_NONE, 12, *packet));
1056 EXPECT_EQ(kMaxPacketSize, encrypted->length());
1058 framer_.set_version(version());
1059 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
1060 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
1062 EXPECT_EQ(kMaxPacketSize, connection_.max_packet_length());
1065 TEST_P(QuicConnectionTest, PacketsInOrder) {
1066 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1068 ProcessPacket(1);
1069 EXPECT_EQ(1u, outgoing_ack()->largest_observed);
1070 EXPECT_EQ(0u, outgoing_ack()->missing_packets.size());
1072 ProcessPacket(2);
1073 EXPECT_EQ(2u, outgoing_ack()->largest_observed);
1074 EXPECT_EQ(0u, outgoing_ack()->missing_packets.size());
1076 ProcessPacket(3);
1077 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1078 EXPECT_EQ(0u, outgoing_ack()->missing_packets.size());
1081 TEST_P(QuicConnectionTest, PacketsOutOfOrder) {
1082 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1084 ProcessPacket(3);
1085 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1086 EXPECT_TRUE(IsMissing(2));
1087 EXPECT_TRUE(IsMissing(1));
1089 ProcessPacket(2);
1090 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1091 EXPECT_FALSE(IsMissing(2));
1092 EXPECT_TRUE(IsMissing(1));
1094 ProcessPacket(1);
1095 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1096 EXPECT_FALSE(IsMissing(2));
1097 EXPECT_FALSE(IsMissing(1));
1100 TEST_P(QuicConnectionTest, DuplicatePacket) {
1101 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1103 ProcessPacket(3);
1104 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1105 EXPECT_TRUE(IsMissing(2));
1106 EXPECT_TRUE(IsMissing(1));
1108 // Send packet 3 again, but do not set the expectation that
1109 // the visitor OnStreamFrames() will be called.
1110 ProcessDataPacket(3, 0, !kEntropyFlag);
1111 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1112 EXPECT_TRUE(IsMissing(2));
1113 EXPECT_TRUE(IsMissing(1));
1116 TEST_P(QuicConnectionTest, PacketsOutOfOrderWithAdditionsAndLeastAwaiting) {
1117 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1119 ProcessPacket(3);
1120 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1121 EXPECT_TRUE(IsMissing(2));
1122 EXPECT_TRUE(IsMissing(1));
1124 ProcessPacket(2);
1125 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1126 EXPECT_TRUE(IsMissing(1));
1128 ProcessPacket(5);
1129 EXPECT_EQ(5u, outgoing_ack()->largest_observed);
1130 EXPECT_TRUE(IsMissing(1));
1131 EXPECT_TRUE(IsMissing(4));
1133 // Pretend at this point the client has gotten acks for 2 and 3 and 1 is a
1134 // packet the peer will not retransmit. It indicates this by sending 'least
1135 // awaiting' is 4. The connection should then realize 1 will not be
1136 // retransmitted, and will remove it from the missing list.
1137 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 5);
1138 QuicAckFrame frame = InitAckFrame(1);
1139 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _));
1140 ProcessAckPacket(&frame);
1142 // Force an ack to be sent.
1143 SendAckPacketToPeer();
1144 EXPECT_TRUE(IsMissing(4));
1147 TEST_P(QuicConnectionTest, RejectPacketTooFarOut) {
1148 EXPECT_CALL(visitor_,
1149 OnConnectionClosed(QUIC_INVALID_PACKET_HEADER, false));
1150 // Call ProcessDataPacket rather than ProcessPacket, as we should not get a
1151 // packet call to the visitor.
1152 ProcessDataPacket(6000, 0, !kEntropyFlag);
1153 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1154 nullptr);
1157 TEST_P(QuicConnectionTest, RejectUnencryptedStreamData) {
1158 // Process an unencrypted packet from the non-crypto stream.
1159 frame1_.stream_id = 3;
1160 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1161 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_UNENCRYPTED_STREAM_DATA,
1162 false));
1163 ProcessDataPacket(1, 0, !kEntropyFlag);
1164 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1165 nullptr);
1166 const vector<QuicConnectionCloseFrame>& connection_close_frames =
1167 writer_->connection_close_frames();
1168 EXPECT_EQ(1u, connection_close_frames.size());
1169 EXPECT_EQ(QUIC_UNENCRYPTED_STREAM_DATA,
1170 connection_close_frames[0].error_code);
1173 TEST_P(QuicConnectionTest, TruncatedAck) {
1174 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1175 QuicPacketSequenceNumber num_packets = 256 * 2 + 1;
1176 for (QuicPacketSequenceNumber i = 0; i < num_packets; ++i) {
1177 SendStreamDataToPeer(3, "foo", i * 3, !kFin, nullptr);
1180 QuicAckFrame frame = InitAckFrame(num_packets);
1181 SequenceNumberSet lost_packets;
1182 // Create an ack with 256 nacks, none adjacent to one another.
1183 for (QuicPacketSequenceNumber i = 1; i <= 256; ++i) {
1184 NackPacket(i * 2, &frame);
1185 if (i < 256) { // Last packet is nacked, but not lost.
1186 lost_packets.insert(i * 2);
1189 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1190 .WillOnce(Return(lost_packets));
1191 EXPECT_CALL(entropy_calculator_, EntropyHash(511))
1192 .WillOnce(Return(static_cast<QuicPacketEntropyHash>(0)));
1193 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1194 ProcessAckPacket(&frame);
1196 // A truncated ack will not have the true largest observed.
1197 EXPECT_GT(num_packets, manager_->largest_observed());
1199 AckPacket(192, &frame);
1201 // Removing one missing packet allows us to ack 192 and one more range, but
1202 // 192 has already been declared lost, so it doesn't register as an ack.
1203 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1204 .WillOnce(Return(SequenceNumberSet()));
1205 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1206 ProcessAckPacket(&frame);
1207 EXPECT_EQ(num_packets, manager_->largest_observed());
1210 TEST_P(QuicConnectionTest, AckReceiptCausesAckSendBadEntropy) {
1211 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1213 ProcessPacket(1);
1214 // Delay sending, then queue up an ack.
1215 EXPECT_CALL(*send_algorithm_,
1216 TimeUntilSend(_, _, _)).WillOnce(
1217 testing::Return(QuicTime::Delta::FromMicroseconds(1)));
1218 QuicConnectionPeer::SendAck(&connection_);
1220 // Process an ack with a least unacked of the received ack.
1221 // This causes an ack to be sent when TimeUntilSend returns 0.
1222 EXPECT_CALL(*send_algorithm_,
1223 TimeUntilSend(_, _, _)).WillRepeatedly(
1224 testing::Return(QuicTime::Delta::Zero()));
1225 // Skip a packet and then record an ack.
1226 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 2);
1227 QuicAckFrame frame = InitAckFrame(0);
1228 ProcessAckPacket(&frame);
1231 TEST_P(QuicConnectionTest, OutOfOrderReceiptCausesAckSend) {
1232 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1234 ProcessPacket(3);
1235 // Should ack immediately since we have missing packets.
1236 EXPECT_EQ(1u, writer_->packets_write_attempts());
1238 ProcessPacket(2);
1239 // Should ack immediately since we have missing packets.
1240 EXPECT_EQ(2u, writer_->packets_write_attempts());
1242 ProcessPacket(1);
1243 // Should ack immediately, since this fills the last hole.
1244 EXPECT_EQ(3u, writer_->packets_write_attempts());
1246 ProcessPacket(4);
1247 // Should not cause an ack.
1248 EXPECT_EQ(3u, writer_->packets_write_attempts());
1251 TEST_P(QuicConnectionTest, AckReceiptCausesAckSend) {
1252 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1254 QuicPacketSequenceNumber original;
1255 QuicByteCount packet_size;
1256 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1257 .WillOnce(DoAll(SaveArg<2>(&original), SaveArg<3>(&packet_size),
1258 Return(true)));
1259 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
1260 QuicAckFrame frame = InitAckFrame(original);
1261 NackPacket(original, &frame);
1262 // First nack triggers early retransmit.
1263 SequenceNumberSet lost_packets;
1264 lost_packets.insert(1);
1265 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1266 .WillOnce(Return(lost_packets));
1267 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1268 QuicPacketSequenceNumber retransmission;
1269 EXPECT_CALL(*send_algorithm_,
1270 OnPacketSent(_, _, _, packet_size - kQuicVersionSize, _))
1271 .WillOnce(DoAll(SaveArg<2>(&retransmission), Return(true)));
1273 ProcessAckPacket(&frame);
1275 QuicAckFrame frame2 = InitAckFrame(retransmission);
1276 NackPacket(original, &frame2);
1277 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1278 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1279 .WillOnce(Return(SequenceNumberSet()));
1280 ProcessAckPacket(&frame2);
1282 // Now if the peer sends an ack which still reports the retransmitted packet
1283 // as missing, that will bundle an ack with data after two acks in a row
1284 // indicate the high water mark needs to be raised.
1285 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _,
1286 HAS_RETRANSMITTABLE_DATA));
1287 connection_.SendStreamDataWithString(3, "foo", 3, !kFin, nullptr);
1288 // No ack sent.
1289 EXPECT_EQ(1u, writer_->frame_count());
1290 EXPECT_EQ(1u, writer_->stream_frames().size());
1292 // No more packet loss for the rest of the test.
1293 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1294 .WillRepeatedly(Return(SequenceNumberSet()));
1295 ProcessAckPacket(&frame2);
1296 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _,
1297 HAS_RETRANSMITTABLE_DATA));
1298 connection_.SendStreamDataWithString(3, "foo", 3, !kFin, nullptr);
1299 // Ack bundled.
1300 EXPECT_EQ(3u, writer_->frame_count());
1301 EXPECT_EQ(1u, writer_->stream_frames().size());
1302 EXPECT_FALSE(writer_->ack_frames().empty());
1304 // But an ack with no missing packets will not send an ack.
1305 AckPacket(original, &frame2);
1306 ProcessAckPacket(&frame2);
1307 ProcessAckPacket(&frame2);
1310 TEST_P(QuicConnectionTest, 20AcksCausesAckSend) {
1311 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1313 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr);
1315 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
1316 // But an ack with no missing packets will not send an ack.
1317 QuicAckFrame frame = InitAckFrame(1);
1318 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1319 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1320 .WillRepeatedly(Return(SequenceNumberSet()));
1321 for (int i = 0; i < 20; ++i) {
1322 EXPECT_FALSE(ack_alarm->IsSet());
1323 ProcessAckPacket(&frame);
1325 EXPECT_TRUE(ack_alarm->IsSet());
1328 TEST_P(QuicConnectionTest, LeastUnackedLower) {
1329 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1331 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr);
1332 SendStreamDataToPeer(1, "bar", 3, !kFin, nullptr);
1333 SendStreamDataToPeer(1, "eep", 6, !kFin, nullptr);
1335 // Start out saying the least unacked is 2.
1336 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 5);
1337 QuicStopWaitingFrame frame = InitStopWaitingFrame(2);
1338 ProcessStopWaitingPacket(&frame);
1340 // Change it to 1, but lower the sequence number to fake out-of-order packets.
1341 // This should be fine.
1342 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 1);
1343 // The scheduler will not process out of order acks, but all packet processing
1344 // causes the connection to try to write.
1345 EXPECT_CALL(visitor_, OnCanWrite());
1346 QuicStopWaitingFrame frame2 = InitStopWaitingFrame(1);
1347 ProcessStopWaitingPacket(&frame2);
1349 // Now claim it's one, but set the ordering so it was sent "after" the first
1350 // one. This should cause a connection error.
1351 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
1352 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 7);
1353 EXPECT_CALL(visitor_,
1354 OnConnectionClosed(QUIC_INVALID_STOP_WAITING_DATA, false));
1355 QuicStopWaitingFrame frame3 = InitStopWaitingFrame(1);
1356 ProcessStopWaitingPacket(&frame3);
1359 TEST_P(QuicConnectionTest, TooManySentPackets) {
1360 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1362 for (int i = 0; i < 1100; ++i) {
1363 SendStreamDataToPeer(1, "foo", 3 * i, !kFin, nullptr);
1366 // Ack packet 1, which leaves more than the limit outstanding.
1367 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1368 EXPECT_CALL(visitor_, OnConnectionClosed(
1369 QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS, false));
1370 // We're receive buffer limited, so the connection won't try to write more.
1371 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
1373 // Nack every packet except the last one, leaving a huge gap.
1374 QuicAckFrame frame1 = InitAckFrame(1100);
1375 for (QuicPacketSequenceNumber i = 1; i < 1100; ++i) {
1376 NackPacket(i, &frame1);
1378 ProcessAckPacket(&frame1);
1381 TEST_P(QuicConnectionTest, TooManyReceivedPackets) {
1382 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1383 EXPECT_CALL(visitor_, OnConnectionClosed(
1384 QUIC_TOO_MANY_OUTSTANDING_RECEIVED_PACKETS, false));
1386 // Miss every other packet for 1000 packets.
1387 for (QuicPacketSequenceNumber i = 1; i < 1000; ++i) {
1388 ProcessPacket(i * 2);
1389 if (!connection_.connected()) {
1390 break;
1395 TEST_P(QuicConnectionTest, LargestObservedLower) {
1396 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1398 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr);
1399 SendStreamDataToPeer(1, "bar", 3, !kFin, nullptr);
1400 SendStreamDataToPeer(1, "eep", 6, !kFin, nullptr);
1401 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1403 // Start out saying the largest observed is 2.
1404 QuicAckFrame frame1 = InitAckFrame(1);
1405 QuicAckFrame frame2 = InitAckFrame(2);
1406 ProcessAckPacket(&frame2);
1408 // Now change it to 1, and it should cause a connection error.
1409 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, false));
1410 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
1411 ProcessAckPacket(&frame1);
1414 TEST_P(QuicConnectionTest, AckUnsentData) {
1415 // Ack a packet which has not been sent.
1416 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, false));
1417 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1418 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
1419 QuicAckFrame frame(MakeAckFrame(1));
1420 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
1421 ProcessAckPacket(&frame);
1424 TEST_P(QuicConnectionTest, AckAll) {
1425 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1426 ProcessPacket(1);
1428 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 1);
1429 QuicAckFrame frame1 = InitAckFrame(0);
1430 ProcessAckPacket(&frame1);
1433 TEST_P(QuicConnectionTest, SendingDifferentSequenceNumberLengthsBandwidth) {
1434 QuicPacketSequenceNumber last_packet;
1435 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet);
1436 EXPECT_EQ(1u, last_packet);
1437 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1438 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1439 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1440 writer_->header().public_header.sequence_number_length);
1442 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
1443 Return(kMaxPacketSize * 256));
1445 SendStreamDataToPeer(1, "bar", 3, !kFin, &last_packet);
1446 EXPECT_EQ(2u, last_packet);
1447 EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER,
1448 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1449 // The 1 packet lag is due to the sequence number length being recalculated in
1450 // QuicConnection after a packet is sent.
1451 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1452 writer_->header().public_header.sequence_number_length);
1454 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
1455 Return(kMaxPacketSize * 256 * 256));
1457 SendStreamDataToPeer(1, "foo", 6, !kFin, &last_packet);
1458 EXPECT_EQ(3u, last_packet);
1459 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1460 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1461 EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER,
1462 writer_->header().public_header.sequence_number_length);
1464 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
1465 Return(kMaxPacketSize * 256 * 256 * 256));
1467 SendStreamDataToPeer(1, "bar", 9, !kFin, &last_packet);
1468 EXPECT_EQ(4u, last_packet);
1469 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1470 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1471 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1472 writer_->header().public_header.sequence_number_length);
1474 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
1475 Return(kMaxPacketSize * 256 * 256 * 256 * 256));
1477 SendStreamDataToPeer(1, "foo", 12, !kFin, &last_packet);
1478 EXPECT_EQ(5u, last_packet);
1479 EXPECT_EQ(PACKET_6BYTE_SEQUENCE_NUMBER,
1480 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1481 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1482 writer_->header().public_header.sequence_number_length);
1485 // TODO(ianswett): Re-enable this test by finding a good way to test different
1486 // sequence number lengths without sending packets with giant gaps.
1487 TEST_P(QuicConnectionTest,
1488 DISABLED_SendingDifferentSequenceNumberLengthsUnackedDelta) {
1489 QuicPacketSequenceNumber last_packet;
1490 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet);
1491 EXPECT_EQ(1u, last_packet);
1492 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1493 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1494 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1495 writer_->header().public_header.sequence_number_length);
1497 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 100);
1499 SendStreamDataToPeer(1, "bar", 3, !kFin, &last_packet);
1500 EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER,
1501 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1502 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1503 writer_->header().public_header.sequence_number_length);
1505 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 100 * 256);
1507 SendStreamDataToPeer(1, "foo", 6, !kFin, &last_packet);
1508 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1509 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1510 EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER,
1511 writer_->header().public_header.sequence_number_length);
1513 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 100 * 256 * 256);
1515 SendStreamDataToPeer(1, "bar", 9, !kFin, &last_packet);
1516 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1517 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1518 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1519 writer_->header().public_header.sequence_number_length);
1521 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_,
1522 100 * 256 * 256 * 256);
1524 SendStreamDataToPeer(1, "foo", 12, !kFin, &last_packet);
1525 EXPECT_EQ(PACKET_6BYTE_SEQUENCE_NUMBER,
1526 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1527 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1528 writer_->header().public_header.sequence_number_length);
1531 TEST_P(QuicConnectionTest, BasicSending) {
1532 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1533 QuicPacketSequenceNumber last_packet;
1534 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet); // Packet 1
1535 EXPECT_EQ(1u, last_packet);
1536 SendAckPacketToPeer(); // Packet 2
1538 EXPECT_EQ(1u, least_unacked());
1540 SendAckPacketToPeer(); // Packet 3
1541 EXPECT_EQ(1u, least_unacked());
1543 SendStreamDataToPeer(1, "bar", 3, !kFin, &last_packet); // Packet 4
1544 EXPECT_EQ(4u, last_packet);
1545 SendAckPacketToPeer(); // Packet 5
1546 EXPECT_EQ(1u, least_unacked());
1548 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1550 // Peer acks up to packet 3.
1551 QuicAckFrame frame = InitAckFrame(3);
1552 ProcessAckPacket(&frame);
1553 SendAckPacketToPeer(); // Packet 6
1555 // As soon as we've acked one, we skip ack packets 2 and 3 and note lack of
1556 // ack for 4.
1557 EXPECT_EQ(4u, least_unacked());
1559 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1561 // Peer acks up to packet 4, the last packet.
1562 QuicAckFrame frame2 = InitAckFrame(6);
1563 ProcessAckPacket(&frame2); // Acks don't instigate acks.
1565 // Verify that we did not send an ack.
1566 EXPECT_EQ(6u, writer_->header().packet_sequence_number);
1568 // So the last ack has not changed.
1569 EXPECT_EQ(4u, least_unacked());
1571 // If we force an ack, we shouldn't change our retransmit state.
1572 SendAckPacketToPeer(); // Packet 7
1573 EXPECT_EQ(7u, least_unacked());
1575 // But if we send more data it should.
1576 SendStreamDataToPeer(1, "eep", 6, !kFin, &last_packet); // Packet 8
1577 EXPECT_EQ(8u, last_packet);
1578 SendAckPacketToPeer(); // Packet 9
1579 EXPECT_EQ(7u, least_unacked());
1582 // If FLAGS_quic_record_send_time_before_write is disabled, QuicConnection
1583 // should record the packet sen-tdime after the packet is sent.
1584 TEST_P(QuicConnectionTest, RecordSentTimeAfterPacketSent) {
1585 ValueRestore<bool> old_flag(&FLAGS_quic_record_send_time_before_write, false);
1586 // We're using a MockClock for the tests, so we have complete control over the
1587 // time.
1588 // Our recorded timestamp for the last packet sent time will be passed in to
1589 // the send_algorithm. Make sure that it is set to the correct value.
1590 QuicTime actual_recorded_send_time = QuicTime::Zero();
1591 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1592 .WillOnce(DoAll(SaveArg<0>(&actual_recorded_send_time), Return(true)));
1594 // First send without any pause and check the result.
1595 QuicTime expected_recorded_send_time = clock_.Now();
1596 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
1597 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
1598 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
1599 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
1601 // Now pause during the write, and check the results.
1602 actual_recorded_send_time = QuicTime::Zero();
1603 const QuicTime::Delta kWritePauseTimeDelta =
1604 QuicTime::Delta::FromMilliseconds(5000);
1605 SetWritePauseTimeDelta(kWritePauseTimeDelta);
1606 expected_recorded_send_time = clock_.Now().Add(kWritePauseTimeDelta);
1608 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1609 .WillOnce(DoAll(SaveArg<0>(&actual_recorded_send_time), Return(true)));
1610 connection_.SendStreamDataWithString(2, "baz", 0, !kFin, nullptr);
1611 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
1612 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
1613 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
1616 // If FLAGS_quic_record_send_time_before_write is enabled, QuicConnection should
1617 // record the the packet sent-time prior to sending the packet.
1618 TEST_P(QuicConnectionTest, RecordSentTimeBeforePacketSent) {
1619 ValueRestore<bool> old_flag(&FLAGS_quic_record_send_time_before_write, true);
1620 // We're using a MockClock for the tests, so we have complete control over the
1621 // time.
1622 // Our recorded timestamp for the last packet sent time will be passed in to
1623 // the send_algorithm. Make sure that it is set to the correct value.
1624 QuicTime actual_recorded_send_time = QuicTime::Zero();
1625 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1626 .WillOnce(DoAll(SaveArg<0>(&actual_recorded_send_time), Return(true)));
1628 // First send without any pause and check the result.
1629 QuicTime expected_recorded_send_time = clock_.Now();
1630 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
1631 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
1632 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
1633 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
1635 // Now pause during the write, and check the results.
1636 actual_recorded_send_time = QuicTime::Zero();
1637 const QuicTime::Delta kWritePauseTimeDelta =
1638 QuicTime::Delta::FromMilliseconds(5000);
1639 SetWritePauseTimeDelta(kWritePauseTimeDelta);
1640 expected_recorded_send_time = clock_.Now();
1642 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1643 .WillOnce(DoAll(SaveArg<0>(&actual_recorded_send_time), Return(true)));
1644 connection_.SendStreamDataWithString(2, "baz", 0, !kFin, nullptr);
1645 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
1646 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
1647 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
1650 TEST_P(QuicConnectionTest, FECSending) {
1651 // All packets carry version info till version is negotiated.
1652 size_t payload_length;
1653 // GetPacketLengthForOneStream() assumes a stream offset of 0 in determining
1654 // packet length. The size of the offset field in a stream frame is 0 for
1655 // offset 0, and 2 for non-zero offsets up through 64K. Increase
1656 // max_packet_length by 2 so that subsequent packets containing subsequent
1657 // stream frames with non-zero offets will fit within the packet length.
1658 size_t length = 2 + GetPacketLengthForOneStream(
1659 connection_.version(), kIncludeVersion,
1660 PACKET_8BYTE_CONNECTION_ID, PACKET_1BYTE_SEQUENCE_NUMBER,
1661 IN_FEC_GROUP, &payload_length);
1662 creator_->set_max_packet_length(length);
1664 // Send 4 protected data packets, which should also trigger 1 FEC packet.
1665 EXPECT_CALL(*send_algorithm_,
1666 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(5);
1667 // The first stream frame will have 2 fewer overhead bytes than the other 3.
1668 const string payload(payload_length * 4 + 2, 'a');
1669 connection_.SendStreamDataWithStringWithFec(1, payload, 0, !kFin, nullptr);
1670 // Expect the FEC group to be closed after SendStreamDataWithString.
1671 EXPECT_FALSE(creator_->IsFecGroupOpen());
1672 EXPECT_FALSE(creator_->IsFecProtected());
1675 TEST_P(QuicConnectionTest, FECQueueing) {
1676 // All packets carry version info till version is negotiated.
1677 size_t payload_length;
1678 size_t length = GetPacketLengthForOneStream(
1679 connection_.version(), kIncludeVersion,
1680 PACKET_8BYTE_CONNECTION_ID, PACKET_1BYTE_SEQUENCE_NUMBER,
1681 IN_FEC_GROUP, &payload_length);
1682 creator_->set_max_packet_length(length);
1683 EXPECT_TRUE(creator_->IsFecEnabled());
1685 EXPECT_EQ(0u, connection_.NumQueuedPackets());
1686 BlockOnNextWrite();
1687 const string payload(payload_length, 'a');
1688 connection_.SendStreamDataWithStringWithFec(1, payload, 0, !kFin, nullptr);
1689 EXPECT_FALSE(creator_->IsFecGroupOpen());
1690 EXPECT_FALSE(creator_->IsFecProtected());
1691 // Expect the first data packet and the fec packet to be queued.
1692 EXPECT_EQ(2u, connection_.NumQueuedPackets());
1695 TEST_P(QuicConnectionTest, FECAlarmStoppedWhenFECPacketSent) {
1696 EXPECT_TRUE(creator_->IsFecEnabled());
1697 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1698 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1700 creator_->set_max_packets_per_fec_group(2);
1702 // 1 Data packet. FEC alarm should be set.
1703 EXPECT_CALL(*send_algorithm_,
1704 OnPacketSent(_, _, 1u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1705 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, true, nullptr);
1706 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1708 // Second data packet triggers FEC packet out. FEC alarm should not be set.
1709 EXPECT_CALL(*send_algorithm_,
1710 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(2);
1711 connection_.SendStreamDataWithStringWithFec(5, "foo", 0, true, nullptr);
1712 EXPECT_TRUE(writer_->header().fec_flag);
1713 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1716 TEST_P(QuicConnectionTest, FECAlarmStoppedOnConnectionClose) {
1717 EXPECT_TRUE(creator_->IsFecEnabled());
1718 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1719 creator_->set_max_packets_per_fec_group(100);
1721 // 1 Data packet. FEC alarm should be set.
1722 EXPECT_CALL(*send_algorithm_,
1723 OnPacketSent(_, _, 1u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1724 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, kFin, nullptr);
1725 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1727 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NO_ERROR, false));
1728 // Closing connection should stop the FEC alarm.
1729 connection_.CloseConnection(QUIC_NO_ERROR, /*from_peer=*/false);
1730 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1733 TEST_P(QuicConnectionTest, RemoveFECFromInflightOnRetransmissionTimeout) {
1734 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1735 EXPECT_TRUE(creator_->IsFecEnabled());
1736 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1737 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1739 // 1 Data packet. FEC alarm should be set.
1740 EXPECT_CALL(*send_algorithm_,
1741 OnPacketSent(_, _, 1u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1742 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, !kFin, nullptr);
1743 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1744 size_t protected_packet =
1745 QuicSentPacketManagerPeer::GetBytesInFlight(manager_);
1747 // Force FEC timeout to send FEC packet out.
1748 EXPECT_CALL(*send_algorithm_,
1749 OnPacketSent(_, _, 2u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1750 connection_.GetFecAlarm()->Fire();
1751 EXPECT_TRUE(writer_->header().fec_flag);
1753 size_t fec_packet = protected_packet;
1754 EXPECT_EQ(protected_packet + fec_packet,
1755 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1756 clock_.AdvanceTime(DefaultRetransmissionTime());
1758 // On RTO, both data and FEC packets are removed from inflight, only the data
1759 // packet is retransmitted, and this retransmission (but not FEC) gets added
1760 // back into the inflight.
1761 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
1762 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1763 connection_.GetRetransmissionAlarm()->Fire();
1765 // The retransmission of packet 1 will be 3 bytes smaller than packet 1, since
1766 // the first transmission will have 1 byte for FEC group number and 2 bytes of
1767 // stream frame size, which are absent in the retransmission.
1768 size_t retransmitted_packet = protected_packet - 3;
1769 EXPECT_EQ(protected_packet + retransmitted_packet,
1770 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1771 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1773 // Receive ack for the retransmission. No data should be outstanding.
1774 QuicAckFrame ack = InitAckFrame(3);
1775 NackPacket(1, &ack);
1776 NackPacket(2, &ack);
1777 SequenceNumberSet lost_packets;
1778 lost_packets.insert(1);
1779 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1780 .WillOnce(Return(lost_packets));
1781 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1782 ProcessAckPacket(&ack);
1784 // Ensure the alarm is not set since all packets have been acked or abandoned.
1785 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
1786 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1789 TEST_P(QuicConnectionTest, RemoveFECFromInflightOnLossRetransmission) {
1790 EXPECT_TRUE(creator_->IsFecEnabled());
1791 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1793 // 1 FEC-protected data packet. FEC alarm should be set.
1794 EXPECT_CALL(*send_algorithm_,
1795 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1796 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, kFin, nullptr);
1797 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1798 size_t protected_packet =
1799 QuicSentPacketManagerPeer::GetBytesInFlight(manager_);
1801 // Force FEC timeout to send FEC packet out.
1802 EXPECT_CALL(*send_algorithm_,
1803 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1804 connection_.GetFecAlarm()->Fire();
1805 EXPECT_TRUE(writer_->header().fec_flag);
1806 size_t fec_packet = protected_packet;
1807 EXPECT_EQ(protected_packet + fec_packet,
1808 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1810 // Send more data to trigger NACKs. Note that all data starts at stream offset
1811 // 0 to ensure the same packet size, for ease of testing.
1812 EXPECT_CALL(*send_algorithm_,
1813 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(4);
1814 connection_.SendStreamDataWithString(5, "foo", 0, kFin, nullptr);
1815 connection_.SendStreamDataWithString(7, "foo", 0, kFin, nullptr);
1816 connection_.SendStreamDataWithString(9, "foo", 0, kFin, nullptr);
1817 connection_.SendStreamDataWithString(11, "foo", 0, kFin, nullptr);
1819 // An unprotected packet will be 3 bytes smaller than an FEC-protected packet,
1820 // since the protected packet will have 1 byte for FEC group number and
1821 // 2 bytes of stream frame size, which are absent in the unprotected packet.
1822 size_t unprotected_packet = protected_packet - 3;
1823 EXPECT_EQ(protected_packet + fec_packet + 4 * unprotected_packet,
1824 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1825 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1827 // Ack data packets, and NACK FEC packet and one data packet. Triggers
1828 // NACK-based loss detection of both packets, but only data packet is
1829 // retransmitted and considered oustanding.
1830 QuicAckFrame ack = InitAckFrame(6);
1831 NackPacket(2, &ack);
1832 NackPacket(3, &ack);
1833 SequenceNumberSet lost_packets;
1834 lost_packets.insert(2);
1835 lost_packets.insert(3);
1836 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1837 .WillOnce(Return(lost_packets));
1838 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1839 EXPECT_CALL(*send_algorithm_,
1840 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1841 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1842 ProcessAckPacket(&ack);
1843 // On receiving this ack from the server, the client will no longer send
1844 // version number in subsequent packets, including in this retransmission.
1845 size_t unprotected_packet_no_version = unprotected_packet - 4;
1846 EXPECT_EQ(unprotected_packet_no_version,
1847 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1849 // Receive ack for the retransmission. No data should be outstanding.
1850 QuicAckFrame ack2 = InitAckFrame(7);
1851 NackPacket(2, &ack2);
1852 NackPacket(3, &ack2);
1853 SequenceNumberSet lost_packets2;
1854 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1855 .WillOnce(Return(lost_packets2));
1856 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1857 ProcessAckPacket(&ack2);
1858 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1861 TEST_P(QuicConnectionTest, FECRemainsInflightOnTLPOfEarlierData) {
1862 // This test checks if TLP is sent correctly when a data and an FEC packet
1863 // are outstanding. TLP should be sent for the data packet when the
1864 // retransmission alarm fires.
1865 // Turn on TLP for this test.
1866 QuicSentPacketManagerPeer::SetMaxTailLossProbes(manager_, 1);
1867 EXPECT_TRUE(creator_->IsFecEnabled());
1868 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1869 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1871 // 1 Data packet. FEC alarm should be set.
1872 EXPECT_CALL(*send_algorithm_,
1873 OnPacketSent(_, _, 1u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1874 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, kFin, nullptr);
1875 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1876 size_t protected_packet =
1877 QuicSentPacketManagerPeer::GetBytesInFlight(manager_);
1878 EXPECT_LT(0u, protected_packet);
1880 // Force FEC timeout to send FEC packet out.
1881 EXPECT_CALL(*send_algorithm_,
1882 OnPacketSent(_, _, 2u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1883 connection_.GetFecAlarm()->Fire();
1884 EXPECT_TRUE(writer_->header().fec_flag);
1885 size_t fec_packet = protected_packet;
1886 EXPECT_EQ(protected_packet + fec_packet,
1887 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1889 // TLP alarm should be set.
1890 QuicTime retransmission_time =
1891 connection_.GetRetransmissionAlarm()->deadline();
1892 EXPECT_NE(QuicTime::Zero(), retransmission_time);
1893 // Simulate the retransmission alarm firing and sending a TLP, so send
1894 // algorithm's OnRetransmissionTimeout is not called.
1895 clock_.AdvanceTime(retransmission_time.Subtract(clock_.Now()));
1896 EXPECT_CALL(*send_algorithm_,
1897 OnPacketSent(_, _, 3u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1898 connection_.GetRetransmissionAlarm()->Fire();
1899 // The TLP retransmission of packet 1 will be 3 bytes smaller than packet 1,
1900 // since packet 1 will have 1 byte for FEC group number and 2 bytes of stream
1901 // frame size, which are absent in the the TLP retransmission.
1902 size_t tlp_packet = protected_packet - 3;
1903 EXPECT_EQ(protected_packet + fec_packet + tlp_packet,
1904 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1907 TEST_P(QuicConnectionTest, FECRemainsInflightOnTLPOfLaterData) {
1908 // Tests if TLP is sent correctly when data packet 1 and an FEC packet are
1909 // sent followed by data packet 2, and data packet 1 is acked. TLP should be
1910 // sent for data packet 2 when the retransmission alarm fires. Turn on TLP for
1911 // this test.
1912 QuicSentPacketManagerPeer::SetMaxTailLossProbes(manager_, 1);
1913 EXPECT_TRUE(creator_->IsFecEnabled());
1914 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1915 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1917 // 1 Data packet. FEC alarm should be set.
1918 EXPECT_CALL(*send_algorithm_,
1919 OnPacketSent(_, _, 1u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1920 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, kFin, nullptr);
1921 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1922 size_t protected_packet =
1923 QuicSentPacketManagerPeer::GetBytesInFlight(manager_);
1924 EXPECT_LT(0u, protected_packet);
1926 // Force FEC timeout to send FEC packet out.
1927 EXPECT_CALL(*send_algorithm_,
1928 OnPacketSent(_, _, 2u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1929 connection_.GetFecAlarm()->Fire();
1930 EXPECT_TRUE(writer_->header().fec_flag);
1931 // Protected data packet and FEC packet oustanding.
1932 size_t fec_packet = protected_packet;
1933 EXPECT_EQ(protected_packet + fec_packet,
1934 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1936 // Send 1 unprotected data packet. No FEC alarm should be set.
1937 EXPECT_CALL(*send_algorithm_,
1938 OnPacketSent(_, _, 3u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1939 connection_.SendStreamDataWithString(5, "foo", 0, kFin, nullptr);
1940 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1941 // Protected data packet, FEC packet, and unprotected data packet oustanding.
1942 // An unprotected packet will be 3 bytes smaller than an FEC-protected packet,
1943 // since the protected packet will have 1 byte for FEC group number and
1944 // 2 bytes of stream frame size, which are absent in the unprotected packet.
1945 size_t unprotected_packet = protected_packet - 3;
1946 EXPECT_EQ(protected_packet + fec_packet + unprotected_packet,
1947 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1949 // Receive ack for first data packet. FEC and second data packet are still
1950 // outstanding.
1951 QuicAckFrame ack = InitAckFrame(1);
1952 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1953 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1954 ProcessAckPacket(&ack);
1955 // FEC packet and unprotected data packet oustanding.
1956 EXPECT_EQ(fec_packet + unprotected_packet,
1957 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1959 // TLP alarm should be set.
1960 QuicTime retransmission_time =
1961 connection_.GetRetransmissionAlarm()->deadline();
1962 EXPECT_NE(QuicTime::Zero(), retransmission_time);
1963 // Simulate the retransmission alarm firing and sending a TLP, so send
1964 // algorithm's OnRetransmissionTimeout is not called.
1965 clock_.AdvanceTime(retransmission_time.Subtract(clock_.Now()));
1966 EXPECT_CALL(*send_algorithm_,
1967 OnPacketSent(_, _, 4u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1968 connection_.GetRetransmissionAlarm()->Fire();
1970 // Having received an ack from the server, the client will no longer send
1971 // version number in subsequent packets, including in this retransmission.
1972 size_t tlp_packet_no_version = unprotected_packet - 4;
1973 EXPECT_EQ(fec_packet + unprotected_packet + tlp_packet_no_version,
1974 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1977 TEST_P(QuicConnectionTest, NoTLPForFECPacket) {
1978 // Turn on TLP for this test.
1979 QuicSentPacketManagerPeer::SetMaxTailLossProbes(manager_, 1);
1980 EXPECT_TRUE(creator_->IsFecEnabled());
1981 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1983 // Send 1 FEC-protected data packet. FEC alarm should be set.
1984 EXPECT_CALL(*send_algorithm_,
1985 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1986 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, !kFin, nullptr);
1987 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1988 // Force FEC timeout to send FEC packet out.
1989 EXPECT_CALL(*send_algorithm_,
1990 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1991 connection_.GetFecAlarm()->Fire();
1992 EXPECT_TRUE(writer_->header().fec_flag);
1994 // Ack data packet, but not FEC packet.
1995 QuicAckFrame ack = InitAckFrame(1);
1996 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1997 ProcessAckPacket(&ack);
1999 // No TLP alarm for FEC, but retransmission alarm should be set for an RTO.
2000 EXPECT_LT(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
2001 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2002 QuicTime rto_time = connection_.GetRetransmissionAlarm()->deadline();
2003 EXPECT_NE(QuicTime::Zero(), rto_time);
2005 // Simulate the retransmission alarm firing. FEC packet is no longer
2006 // outstanding.
2007 clock_.AdvanceTime(rto_time.Subtract(clock_.Now()));
2008 connection_.GetRetransmissionAlarm()->Fire();
2010 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
2011 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
2014 TEST_P(QuicConnectionTest, FramePacking) {
2015 CongestionBlockWrites();
2017 // Send an ack and two stream frames in 1 packet by queueing them.
2018 connection_.SendAck();
2019 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
2020 IgnoreResult(InvokeWithoutArgs(&connection_,
2021 &TestConnection::SendStreamData3)),
2022 IgnoreResult(InvokeWithoutArgs(&connection_,
2023 &TestConnection::SendStreamData5))));
2025 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2026 CongestionUnblockWrites();
2027 connection_.GetSendAlarm()->Fire();
2028 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2029 EXPECT_FALSE(connection_.HasQueuedData());
2031 // Parse the last packet and ensure it's an ack and two stream frames from
2032 // two different streams.
2033 EXPECT_EQ(4u, writer_->frame_count());
2034 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
2035 EXPECT_FALSE(writer_->ack_frames().empty());
2036 ASSERT_EQ(2u, writer_->stream_frames().size());
2037 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id);
2038 EXPECT_EQ(kClientDataStreamId2, writer_->stream_frames()[1].stream_id);
2041 TEST_P(QuicConnectionTest, FramePackingNonCryptoThenCrypto) {
2042 CongestionBlockWrites();
2044 // Send an ack and two stream frames (one non-crypto, then one crypto) in 2
2045 // packets by queueing them.
2046 connection_.SendAck();
2047 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
2048 IgnoreResult(InvokeWithoutArgs(&connection_,
2049 &TestConnection::SendStreamData3)),
2050 IgnoreResult(InvokeWithoutArgs(&connection_,
2051 &TestConnection::SendCryptoStreamData))));
2053 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
2054 CongestionUnblockWrites();
2055 connection_.GetSendAlarm()->Fire();
2056 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2057 EXPECT_FALSE(connection_.HasQueuedData());
2059 // Parse the last packet and ensure it's the crypto stream frame.
2060 EXPECT_EQ(1u, writer_->frame_count());
2061 ASSERT_EQ(1u, writer_->stream_frames().size());
2062 EXPECT_EQ(kCryptoStreamId, writer_->stream_frames()[0].stream_id);
2065 TEST_P(QuicConnectionTest, FramePackingCryptoThenNonCrypto) {
2066 CongestionBlockWrites();
2068 // Send an ack and two stream frames (one crypto, then one non-crypto) in 2
2069 // packets by queueing them.
2070 connection_.SendAck();
2071 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
2072 IgnoreResult(InvokeWithoutArgs(&connection_,
2073 &TestConnection::SendCryptoStreamData)),
2074 IgnoreResult(InvokeWithoutArgs(&connection_,
2075 &TestConnection::SendStreamData3))));
2077 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
2078 CongestionUnblockWrites();
2079 connection_.GetSendAlarm()->Fire();
2080 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2081 EXPECT_FALSE(connection_.HasQueuedData());
2083 // Parse the last packet and ensure it's the stream frame from stream 3.
2084 EXPECT_EQ(1u, writer_->frame_count());
2085 ASSERT_EQ(1u, writer_->stream_frames().size());
2086 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id);
2089 TEST_P(QuicConnectionTest, FramePackingFEC) {
2090 EXPECT_TRUE(creator_->IsFecEnabled());
2092 CongestionBlockWrites();
2094 // Queue an ack and two stream frames. Ack gets flushed when FEC is turned on
2095 // for sending protected data; two stream frames are packed in 1 packet.
2096 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
2097 IgnoreResult(InvokeWithoutArgs(
2098 &connection_, &TestConnection::SendStreamData3WithFec)),
2099 IgnoreResult(InvokeWithoutArgs(
2100 &connection_, &TestConnection::SendStreamData5WithFec))));
2101 connection_.SendAck();
2103 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
2104 CongestionUnblockWrites();
2105 connection_.GetSendAlarm()->Fire();
2106 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2107 EXPECT_FALSE(connection_.HasQueuedData());
2109 // Parse the last packet and ensure it's in an fec group.
2110 EXPECT_EQ(2u, writer_->header().fec_group);
2111 EXPECT_EQ(2u, writer_->frame_count());
2113 // FEC alarm should be set.
2114 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
2117 TEST_P(QuicConnectionTest, FramePackingAckResponse) {
2118 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2119 // Process a data packet to queue up a pending ack.
2120 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
2121 ProcessDataPacket(1, 1, kEntropyFlag);
2123 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
2124 IgnoreResult(InvokeWithoutArgs(&connection_,
2125 &TestConnection::SendStreamData3)),
2126 IgnoreResult(InvokeWithoutArgs(&connection_,
2127 &TestConnection::SendStreamData5))));
2129 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2131 // Process an ack to cause the visitor's OnCanWrite to be invoked.
2132 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 2);
2133 QuicAckFrame ack_one = InitAckFrame(0);
2134 ProcessAckPacket(&ack_one);
2136 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2137 EXPECT_FALSE(connection_.HasQueuedData());
2139 // Parse the last packet and ensure it's an ack and two stream frames from
2140 // two different streams.
2141 EXPECT_EQ(4u, writer_->frame_count());
2142 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
2143 EXPECT_FALSE(writer_->ack_frames().empty());
2144 ASSERT_EQ(2u, writer_->stream_frames().size());
2145 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id);
2146 EXPECT_EQ(kClientDataStreamId2, writer_->stream_frames()[1].stream_id);
2149 TEST_P(QuicConnectionTest, FramePackingSendv) {
2150 // Send data in 1 packet by writing multiple blocks in a single iovector
2151 // using writev.
2152 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2154 char data[] = "ABCD";
2155 IOVector data_iov;
2156 data_iov.AppendNoCoalesce(data, 2);
2157 data_iov.AppendNoCoalesce(data + 2, 2);
2158 connection_.SendStreamData(1, data_iov, 0, !kFin, MAY_FEC_PROTECT, nullptr);
2160 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2161 EXPECT_FALSE(connection_.HasQueuedData());
2163 // Parse the last packet and ensure multiple iovector blocks have
2164 // been packed into a single stream frame from one stream.
2165 EXPECT_EQ(1u, writer_->frame_count());
2166 EXPECT_EQ(1u, writer_->stream_frames().size());
2167 QuicStreamFrame frame = writer_->stream_frames()[0];
2168 EXPECT_EQ(1u, frame.stream_id);
2169 EXPECT_EQ("ABCD", string(static_cast<char*>
2170 (frame.data.iovec()[0].iov_base),
2171 (frame.data.iovec()[0].iov_len)));
2174 TEST_P(QuicConnectionTest, FramePackingSendvQueued) {
2175 // Try to send two stream frames in 1 packet by using writev.
2176 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2178 BlockOnNextWrite();
2179 char data[] = "ABCD";
2180 IOVector data_iov;
2181 data_iov.AppendNoCoalesce(data, 2);
2182 data_iov.AppendNoCoalesce(data + 2, 2);
2183 connection_.SendStreamData(1, data_iov, 0, !kFin, MAY_FEC_PROTECT, nullptr);
2185 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2186 EXPECT_TRUE(connection_.HasQueuedData());
2188 // Unblock the writes and actually send.
2189 writer_->SetWritable();
2190 connection_.OnCanWrite();
2191 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2193 // Parse the last packet and ensure it's one stream frame from one stream.
2194 EXPECT_EQ(1u, writer_->frame_count());
2195 EXPECT_EQ(1u, writer_->stream_frames().size());
2196 EXPECT_EQ(1u, writer_->stream_frames()[0].stream_id);
2199 TEST_P(QuicConnectionTest, SendingZeroBytes) {
2200 // Send a zero byte write with a fin using writev.
2201 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2202 IOVector empty_iov;
2203 connection_.SendStreamData(1, empty_iov, 0, kFin, MAY_FEC_PROTECT, nullptr);
2205 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2206 EXPECT_FALSE(connection_.HasQueuedData());
2208 // Parse the last packet and ensure it's one stream frame from one stream.
2209 EXPECT_EQ(1u, writer_->frame_count());
2210 EXPECT_EQ(1u, writer_->stream_frames().size());
2211 EXPECT_EQ(1u, writer_->stream_frames()[0].stream_id);
2212 EXPECT_TRUE(writer_->stream_frames()[0].fin);
2215 TEST_P(QuicConnectionTest, OnCanWrite) {
2216 // Visitor's OnCanWrite will send data, but will have more pending writes.
2217 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
2218 IgnoreResult(InvokeWithoutArgs(&connection_,
2219 &TestConnection::SendStreamData3)),
2220 IgnoreResult(InvokeWithoutArgs(&connection_,
2221 &TestConnection::SendStreamData5))));
2222 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillOnce(Return(true));
2223 EXPECT_CALL(*send_algorithm_,
2224 TimeUntilSend(_, _, _)).WillRepeatedly(
2225 testing::Return(QuicTime::Delta::Zero()));
2227 connection_.OnCanWrite();
2229 // Parse the last packet and ensure it's the two stream frames from
2230 // two different streams.
2231 EXPECT_EQ(2u, writer_->frame_count());
2232 EXPECT_EQ(2u, writer_->stream_frames().size());
2233 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id);
2234 EXPECT_EQ(kClientDataStreamId2, writer_->stream_frames()[1].stream_id);
2237 TEST_P(QuicConnectionTest, RetransmitOnNack) {
2238 QuicPacketSequenceNumber last_packet;
2239 QuicByteCount second_packet_size;
2240 SendStreamDataToPeer(3, "foo", 0, !kFin, &last_packet); // Packet 1
2241 second_packet_size =
2242 SendStreamDataToPeer(3, "foos", 3, !kFin, &last_packet); // Packet 2
2243 SendStreamDataToPeer(3, "fooos", 7, !kFin, &last_packet); // Packet 3
2245 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2247 // Don't lose a packet on an ack, and nothing is retransmitted.
2248 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2249 QuicAckFrame ack_one = InitAckFrame(1);
2250 ProcessAckPacket(&ack_one);
2252 // Lose a packet and ensure it triggers retransmission.
2253 QuicAckFrame nack_two = InitAckFrame(3);
2254 NackPacket(2, &nack_two);
2255 SequenceNumberSet lost_packets;
2256 lost_packets.insert(2);
2257 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2258 .WillOnce(Return(lost_packets));
2259 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2260 EXPECT_CALL(*send_algorithm_,
2261 OnPacketSent(_, _, _, second_packet_size - kQuicVersionSize, _)).
2262 Times(1);
2263 ProcessAckPacket(&nack_two);
2266 TEST_P(QuicConnectionTest, DiscardRetransmit) {
2267 QuicPacketSequenceNumber last_packet;
2268 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet); // Packet 1
2269 SendStreamDataToPeer(1, "foos", 3, !kFin, &last_packet); // Packet 2
2270 SendStreamDataToPeer(1, "fooos", 7, !kFin, &last_packet); // Packet 3
2272 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2274 // Instigate a loss with an ack.
2275 QuicAckFrame nack_two = InitAckFrame(3);
2276 NackPacket(2, &nack_two);
2277 // The first nack should trigger a fast retransmission, but we'll be
2278 // write blocked, so the packet will be queued.
2279 BlockOnNextWrite();
2280 SequenceNumberSet lost_packets;
2281 lost_packets.insert(2);
2282 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2283 .WillOnce(Return(lost_packets));
2284 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2285 ProcessAckPacket(&nack_two);
2286 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2288 // Now, ack the previous transmission.
2289 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2290 .WillOnce(Return(SequenceNumberSet()));
2291 QuicAckFrame ack_all = InitAckFrame(3);
2292 ProcessAckPacket(&ack_all);
2294 // Unblock the socket and attempt to send the queued packets. However,
2295 // since the previous transmission has been acked, we will not
2296 // send the retransmission.
2297 EXPECT_CALL(*send_algorithm_,
2298 OnPacketSent(_, _, _, _, _)).Times(0);
2300 writer_->SetWritable();
2301 connection_.OnCanWrite();
2303 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2306 TEST_P(QuicConnectionTest, RetransmitNackedLargestObserved) {
2307 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2308 QuicPacketSequenceNumber largest_observed;
2309 QuicByteCount packet_size;
2310 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2311 .WillOnce(DoAll(SaveArg<2>(&largest_observed), SaveArg<3>(&packet_size),
2312 Return(true)));
2313 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
2315 QuicAckFrame frame = InitAckFrame(1);
2316 NackPacket(largest_observed, &frame);
2317 // The first nack should retransmit the largest observed packet.
2318 SequenceNumberSet lost_packets;
2319 lost_packets.insert(1);
2320 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2321 .WillOnce(Return(lost_packets));
2322 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2323 EXPECT_CALL(*send_algorithm_,
2324 OnPacketSent(_, _, _, packet_size - kQuicVersionSize, _));
2325 ProcessAckPacket(&frame);
2328 TEST_P(QuicConnectionTest, QueueAfterTwoRTOs) {
2329 for (int i = 0; i < 10; ++i) {
2330 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2331 connection_.SendStreamDataWithString(3, "foo", i * 3, !kFin, nullptr);
2334 // Block the writer and ensure they're queued.
2335 BlockOnNextWrite();
2336 clock_.AdvanceTime(DefaultRetransmissionTime());
2337 // Only one packet should be retransmitted.
2338 connection_.GetRetransmissionAlarm()->Fire();
2339 EXPECT_TRUE(connection_.HasQueuedData());
2341 // Unblock the writer.
2342 writer_->SetWritable();
2343 clock_.AdvanceTime(QuicTime::Delta::FromMicroseconds(
2344 2 * DefaultRetransmissionTime().ToMicroseconds()));
2345 // Retransmit already retransmitted packets event though the sequence number
2346 // greater than the largest observed.
2347 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
2348 connection_.GetRetransmissionAlarm()->Fire();
2349 connection_.OnCanWrite();
2352 TEST_P(QuicConnectionTest, WriteBlockedThenSent) {
2353 BlockOnNextWrite();
2354 writer_->set_is_write_blocked_data_buffered(true);
2355 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2356 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
2357 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2359 writer_->SetWritable();
2360 connection_.OnCanWrite();
2361 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2364 TEST_P(QuicConnectionTest, RetransmitWriteBlockedAckedOriginalThenSent) {
2365 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2366 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
2367 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2369 BlockOnNextWrite();
2370 writer_->set_is_write_blocked_data_buffered(true);
2371 // Simulate the retransmission alarm firing.
2372 clock_.AdvanceTime(DefaultRetransmissionTime());
2373 connection_.GetRetransmissionAlarm()->Fire();
2375 // Ack the sent packet before the callback returns, which happens in
2376 // rare circumstances with write blocked sockets.
2377 QuicAckFrame ack = InitAckFrame(1);
2378 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2379 ProcessAckPacket(&ack);
2381 writer_->SetWritable();
2382 connection_.OnCanWrite();
2383 // There is now a pending packet, but with no retransmittable frames.
2384 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2385 EXPECT_FALSE(connection_.sent_packet_manager().HasRetransmittableFrames(2));
2388 TEST_P(QuicConnectionTest, AlarmsWhenWriteBlocked) {
2389 // Block the connection.
2390 BlockOnNextWrite();
2391 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
2392 EXPECT_EQ(1u, writer_->packets_write_attempts());
2393 EXPECT_TRUE(writer_->IsWriteBlocked());
2395 // Set the send and resumption alarms. Fire the alarms and ensure they don't
2396 // attempt to write.
2397 connection_.GetResumeWritesAlarm()->Set(clock_.ApproximateNow());
2398 connection_.GetSendAlarm()->Set(clock_.ApproximateNow());
2399 connection_.GetResumeWritesAlarm()->Fire();
2400 connection_.GetSendAlarm()->Fire();
2401 EXPECT_TRUE(writer_->IsWriteBlocked());
2402 EXPECT_EQ(1u, writer_->packets_write_attempts());
2405 TEST_P(QuicConnectionTest, NoLimitPacketsPerNack) {
2406 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2407 int offset = 0;
2408 // Send packets 1 to 15.
2409 for (int i = 0; i < 15; ++i) {
2410 SendStreamDataToPeer(1, "foo", offset, !kFin, nullptr);
2411 offset += 3;
2414 // Ack 15, nack 1-14.
2415 SequenceNumberSet lost_packets;
2416 QuicAckFrame nack = InitAckFrame(15);
2417 for (int i = 1; i < 15; ++i) {
2418 NackPacket(i, &nack);
2419 lost_packets.insert(i);
2422 // 14 packets have been NACK'd and lost. In TCP cubic, PRR limits
2423 // the retransmission rate in the case of burst losses.
2424 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2425 .WillOnce(Return(lost_packets));
2426 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2427 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(14);
2428 ProcessAckPacket(&nack);
2431 // Test sending multiple acks from the connection to the session.
2432 TEST_P(QuicConnectionTest, MultipleAcks) {
2433 QuicPacketSequenceNumber last_packet;
2434 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet); // Packet 1
2435 EXPECT_EQ(1u, last_packet);
2436 SendStreamDataToPeer(3, "foo", 0, !kFin, &last_packet); // Packet 2
2437 EXPECT_EQ(2u, last_packet);
2438 SendAckPacketToPeer(); // Packet 3
2439 SendStreamDataToPeer(5, "foo", 0, !kFin, &last_packet); // Packet 4
2440 EXPECT_EQ(4u, last_packet);
2441 SendStreamDataToPeer(1, "foo", 3, !kFin, &last_packet); // Packet 5
2442 EXPECT_EQ(5u, last_packet);
2443 SendStreamDataToPeer(3, "foo", 3, !kFin, &last_packet); // Packet 6
2444 EXPECT_EQ(6u, last_packet);
2446 // Client will ack packets 1, 2, [!3], 4, 5.
2447 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2448 QuicAckFrame frame1 = InitAckFrame(5);
2449 NackPacket(3, &frame1);
2450 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2451 ProcessAckPacket(&frame1);
2453 // Now the client implicitly acks 3, and explicitly acks 6.
2454 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2455 QuicAckFrame frame2 = InitAckFrame(6);
2456 ProcessAckPacket(&frame2);
2459 TEST_P(QuicConnectionTest, DontLatchUnackedPacket) {
2460 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr); // Packet 1;
2461 // From now on, we send acks, so the send algorithm won't mark them pending.
2462 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2463 .WillByDefault(Return(false));
2464 SendAckPacketToPeer(); // Packet 2
2466 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2467 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2468 QuicAckFrame frame = InitAckFrame(1);
2469 ProcessAckPacket(&frame);
2471 // Verify that our internal state has least-unacked as 2, because we're still
2472 // waiting for a potential ack for 2.
2474 EXPECT_EQ(2u, stop_waiting()->least_unacked);
2476 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2477 frame = InitAckFrame(2);
2478 ProcessAckPacket(&frame);
2479 EXPECT_EQ(3u, stop_waiting()->least_unacked);
2481 // When we send an ack, we make sure our least-unacked makes sense. In this
2482 // case since we're not waiting on an ack for 2 and all packets are acked, we
2483 // set it to 3.
2484 SendAckPacketToPeer(); // Packet 3
2485 // Least_unacked remains at 3 until another ack is received.
2486 EXPECT_EQ(3u, stop_waiting()->least_unacked);
2487 // Check that the outgoing ack had its sequence number as least_unacked.
2488 EXPECT_EQ(3u, least_unacked());
2490 // Ack the ack, which updates the rtt and raises the least unacked.
2491 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2492 frame = InitAckFrame(3);
2493 ProcessAckPacket(&frame);
2495 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2496 .WillByDefault(Return(true));
2497 SendStreamDataToPeer(1, "bar", 3, false, nullptr); // Packet 4
2498 EXPECT_EQ(4u, stop_waiting()->least_unacked);
2499 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2500 .WillByDefault(Return(false));
2501 SendAckPacketToPeer(); // Packet 5
2502 EXPECT_EQ(4u, least_unacked());
2504 // Send two data packets at the end, and ensure if the last one is acked,
2505 // the least unacked is raised above the ack packets.
2506 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2507 .WillByDefault(Return(true));
2508 SendStreamDataToPeer(1, "bar", 6, false, nullptr); // Packet 6
2509 SendStreamDataToPeer(1, "bar", 9, false, nullptr); // Packet 7
2511 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2512 frame = InitAckFrame(7);
2513 NackPacket(5, &frame);
2514 NackPacket(6, &frame);
2515 ProcessAckPacket(&frame);
2517 EXPECT_EQ(6u, stop_waiting()->least_unacked);
2520 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterFecPacket) {
2521 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2523 // Don't send missing packet 1.
2524 ProcessFecPacket(2, 1, true, !kEntropyFlag, nullptr);
2525 // Entropy flag should be false, so entropy should be 0.
2526 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2529 TEST_P(QuicConnectionTest, ReviveMissingPacketWithVaryingSeqNumLengths) {
2530 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2532 // Set up a debug visitor to the connection.
2533 FecQuicConnectionDebugVisitor* fec_visitor =
2534 new FecQuicConnectionDebugVisitor();
2535 connection_.set_debug_visitor(fec_visitor);
2537 QuicPacketSequenceNumber fec_packet = 0;
2538 QuicSequenceNumberLength lengths[] = {PACKET_6BYTE_SEQUENCE_NUMBER,
2539 PACKET_4BYTE_SEQUENCE_NUMBER,
2540 PACKET_2BYTE_SEQUENCE_NUMBER,
2541 PACKET_1BYTE_SEQUENCE_NUMBER};
2542 // For each sequence number length size, revive a packet and check sequence
2543 // number length in the revived packet.
2544 for (size_t i = 0; i < arraysize(lengths); ++i) {
2545 // Set sequence_number_length_ (for data and FEC packets).
2546 sequence_number_length_ = lengths[i];
2547 fec_packet += 2;
2548 // Don't send missing packet, but send fec packet right after it.
2549 ProcessFecPacket(fec_packet, fec_packet - 1, true, !kEntropyFlag, nullptr);
2550 // Sequence number length in the revived header should be the same as
2551 // in the original data/fec packet headers.
2552 EXPECT_EQ(sequence_number_length_, fec_visitor->revived_header().
2553 public_header.sequence_number_length);
2557 TEST_P(QuicConnectionTest, ReviveMissingPacketWithVaryingConnectionIdLengths) {
2558 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2560 // Set up a debug visitor to the connection.
2561 FecQuicConnectionDebugVisitor* fec_visitor =
2562 new FecQuicConnectionDebugVisitor();
2563 connection_.set_debug_visitor(fec_visitor);
2565 QuicPacketSequenceNumber fec_packet = 0;
2566 QuicConnectionIdLength lengths[] = {PACKET_8BYTE_CONNECTION_ID,
2567 PACKET_4BYTE_CONNECTION_ID,
2568 PACKET_1BYTE_CONNECTION_ID,
2569 PACKET_0BYTE_CONNECTION_ID};
2570 // For each connection id length size, revive a packet and check connection
2571 // id length in the revived packet.
2572 for (size_t i = 0; i < arraysize(lengths); ++i) {
2573 // Set connection id length (for data and FEC packets).
2574 connection_id_length_ = lengths[i];
2575 fec_packet += 2;
2576 // Don't send missing packet, but send fec packet right after it.
2577 ProcessFecPacket(fec_packet, fec_packet - 1, true, !kEntropyFlag, nullptr);
2578 // Connection id length in the revived header should be the same as
2579 // in the original data/fec packet headers.
2580 EXPECT_EQ(connection_id_length_,
2581 fec_visitor->revived_header().public_header.connection_id_length);
2585 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPacketThenFecPacket) {
2586 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2588 ProcessFecProtectedPacket(1, false, kEntropyFlag);
2589 // Don't send missing packet 2.
2590 ProcessFecPacket(3, 1, true, !kEntropyFlag, nullptr);
2591 // Entropy flag should be true, so entropy should not be 0.
2592 EXPECT_NE(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2595 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPacketsThenFecPacket) {
2596 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2598 ProcessFecProtectedPacket(1, false, !kEntropyFlag);
2599 // Don't send missing packet 2.
2600 ProcessFecProtectedPacket(3, false, !kEntropyFlag);
2601 ProcessFecPacket(4, 1, true, kEntropyFlag, nullptr);
2602 // Ensure QUIC no longer revives entropy for lost packets.
2603 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2604 EXPECT_NE(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 4));
2607 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPacket) {
2608 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2610 // Don't send missing packet 1.
2611 ProcessFecPacket(3, 1, false, !kEntropyFlag, nullptr);
2612 // Out of order.
2613 ProcessFecProtectedPacket(2, true, !kEntropyFlag);
2614 // Entropy flag should be false, so entropy should be 0.
2615 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2618 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPackets) {
2619 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2621 ProcessFecProtectedPacket(1, false, !kEntropyFlag);
2622 // Don't send missing packet 2.
2623 ProcessFecPacket(6, 1, false, kEntropyFlag, nullptr);
2624 ProcessFecProtectedPacket(3, false, kEntropyFlag);
2625 ProcessFecProtectedPacket(4, false, kEntropyFlag);
2626 ProcessFecProtectedPacket(5, true, !kEntropyFlag);
2627 // Ensure entropy is not revived for the missing packet.
2628 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2629 EXPECT_NE(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 3));
2632 TEST_P(QuicConnectionTest, TLP) {
2633 QuicSentPacketManagerPeer::SetMaxTailLossProbes(manager_, 1);
2635 SendStreamDataToPeer(3, "foo", 0, !kFin, nullptr);
2636 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2637 QuicTime retransmission_time =
2638 connection_.GetRetransmissionAlarm()->deadline();
2639 EXPECT_NE(QuicTime::Zero(), retransmission_time);
2641 EXPECT_EQ(1u, writer_->header().packet_sequence_number);
2642 // Simulate the retransmission alarm firing and sending a tlp,
2643 // so send algorithm's OnRetransmissionTimeout is not called.
2644 clock_.AdvanceTime(retransmission_time.Subtract(clock_.Now()));
2645 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 2u, _, _));
2646 connection_.GetRetransmissionAlarm()->Fire();
2647 EXPECT_EQ(2u, writer_->header().packet_sequence_number);
2648 // We do not raise the high water mark yet.
2649 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2652 TEST_P(QuicConnectionTest, RTO) {
2653 QuicTime default_retransmission_time = clock_.ApproximateNow().Add(
2654 DefaultRetransmissionTime());
2655 SendStreamDataToPeer(3, "foo", 0, !kFin, nullptr);
2656 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2658 EXPECT_EQ(1u, writer_->header().packet_sequence_number);
2659 EXPECT_EQ(default_retransmission_time,
2660 connection_.GetRetransmissionAlarm()->deadline());
2661 // Simulate the retransmission alarm firing.
2662 clock_.AdvanceTime(DefaultRetransmissionTime());
2663 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 2u, _, _));
2664 connection_.GetRetransmissionAlarm()->Fire();
2665 EXPECT_EQ(2u, writer_->header().packet_sequence_number);
2666 // We do not raise the high water mark yet.
2667 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2670 TEST_P(QuicConnectionTest, RTOWithSameEncryptionLevel) {
2671 QuicTime default_retransmission_time = clock_.ApproximateNow().Add(
2672 DefaultRetransmissionTime());
2673 use_tagging_decrypter();
2675 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
2676 // the end of the packet. We can test this to check which encrypter was used.
2677 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2678 SendStreamDataToPeer(3, "foo", 0, !kFin, nullptr);
2679 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
2681 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2682 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2683 SendStreamDataToPeer(3, "foo", 0, !kFin, nullptr);
2684 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2686 EXPECT_EQ(default_retransmission_time,
2687 connection_.GetRetransmissionAlarm()->deadline());
2689 InSequence s;
2690 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 3, _, _));
2691 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 4, _, _));
2694 // Simulate the retransmission alarm firing.
2695 clock_.AdvanceTime(DefaultRetransmissionTime());
2696 connection_.GetRetransmissionAlarm()->Fire();
2698 // Packet should have been sent with ENCRYPTION_NONE.
2699 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_previous_packet());
2701 // Packet should have been sent with ENCRYPTION_INITIAL.
2702 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2705 TEST_P(QuicConnectionTest, SendHandshakeMessages) {
2706 use_tagging_decrypter();
2707 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
2708 // the end of the packet. We can test this to check which encrypter was used.
2709 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2711 // Attempt to send a handshake message and have the socket block.
2712 EXPECT_CALL(*send_algorithm_,
2713 TimeUntilSend(_, _, _)).WillRepeatedly(
2714 testing::Return(QuicTime::Delta::Zero()));
2715 BlockOnNextWrite();
2716 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
2717 // The packet should be serialized, but not queued.
2718 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2720 // Switch to the new encrypter.
2721 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2722 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2724 // Now become writeable and flush the packets.
2725 writer_->SetWritable();
2726 EXPECT_CALL(visitor_, OnCanWrite());
2727 connection_.OnCanWrite();
2728 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2730 // Verify that the handshake packet went out at the null encryption.
2731 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
2734 TEST_P(QuicConnectionTest,
2735 DropRetransmitsForNullEncryptedPacketAfterForwardSecure) {
2736 use_tagging_decrypter();
2737 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2738 QuicPacketSequenceNumber sequence_number;
2739 SendStreamDataToPeer(3, "foo", 0, !kFin, &sequence_number);
2741 // Simulate the retransmission alarm firing and the socket blocking.
2742 BlockOnNextWrite();
2743 clock_.AdvanceTime(DefaultRetransmissionTime());
2744 connection_.GetRetransmissionAlarm()->Fire();
2746 // Go forward secure.
2747 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
2748 new TaggingEncrypter(0x02));
2749 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2750 connection_.NeuterUnencryptedPackets();
2752 EXPECT_EQ(QuicTime::Zero(),
2753 connection_.GetRetransmissionAlarm()->deadline());
2754 // Unblock the socket and ensure that no packets are sent.
2755 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
2756 writer_->SetWritable();
2757 connection_.OnCanWrite();
2760 TEST_P(QuicConnectionTest, RetransmitPacketsWithInitialEncryption) {
2761 use_tagging_decrypter();
2762 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2763 connection_.SetDefaultEncryptionLevel(ENCRYPTION_NONE);
2765 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr);
2767 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2768 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2770 SendStreamDataToPeer(2, "bar", 0, !kFin, nullptr);
2771 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2773 connection_.RetransmitUnackedPackets(ALL_INITIAL_RETRANSMISSION);
2776 TEST_P(QuicConnectionTest, DelayForwardSecureEncryptionUntilClientIsReady) {
2777 // A TaggingEncrypter puts kTagSize copies of the given byte (0x02 here) at
2778 // the end of the packet. We can test this to check which encrypter was used.
2779 use_tagging_decrypter();
2780 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2781 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2782 SendAckPacketToPeer();
2783 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2785 // Set a forward-secure encrypter but do not make it the default, and verify
2786 // that it is not yet used.
2787 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
2788 new TaggingEncrypter(0x03));
2789 SendAckPacketToPeer();
2790 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2792 // Now simulate receipt of a forward-secure packet and verify that the
2793 // forward-secure encrypter is now used.
2794 connection_.OnDecryptedPacket(ENCRYPTION_FORWARD_SECURE);
2795 SendAckPacketToPeer();
2796 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
2799 TEST_P(QuicConnectionTest, DelayForwardSecureEncryptionUntilManyPacketSent) {
2800 // Set a congestion window of 10 packets.
2801 QuicPacketCount congestion_window = 10;
2802 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
2803 Return(congestion_window * kDefaultMaxPacketSize));
2805 // A TaggingEncrypter puts kTagSize copies of the given byte (0x02 here) at
2806 // the end of the packet. We can test this to check which encrypter was used.
2807 use_tagging_decrypter();
2808 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2809 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2810 SendAckPacketToPeer();
2811 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2813 // Set a forward-secure encrypter but do not make it the default, and
2814 // verify that it is not yet used.
2815 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
2816 new TaggingEncrypter(0x03));
2817 SendAckPacketToPeer();
2818 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2820 // Now send a packet "Far enough" after the encrypter was set and verify that
2821 // the forward-secure encrypter is now used.
2822 for (uint64 i = 0; i < 3 * congestion_window - 1; ++i) {
2823 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2824 SendAckPacketToPeer();
2826 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
2829 TEST_P(QuicConnectionTest, BufferNonDecryptablePackets) {
2830 // SetFromConfig is always called after construction from InitializeSession.
2831 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _, _));
2832 QuicConfig config;
2833 connection_.SetFromConfig(config);
2834 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2835 use_tagging_decrypter();
2837 const uint8 tag = 0x07;
2838 framer_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
2840 // Process an encrypted packet which can not yet be decrypted which should
2841 // result in the packet being buffered.
2842 ProcessDataPacketAtLevel(1, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2844 // Transition to the new encryption state and process another encrypted packet
2845 // which should result in the original packet being processed.
2846 connection_.SetDecrypter(new StrictTaggingDecrypter(tag),
2847 ENCRYPTION_INITIAL);
2848 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2849 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
2850 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(2);
2851 ProcessDataPacketAtLevel(2, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2853 // Finally, process a third packet and note that we do not reprocess the
2854 // buffered packet.
2855 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
2856 ProcessDataPacketAtLevel(3, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2859 TEST_P(QuicConnectionTest, Buffer100NonDecryptablePackets) {
2860 // SetFromConfig is always called after construction from InitializeSession.
2861 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _, _));
2862 QuicConfig config;
2863 config.set_max_undecryptable_packets(100);
2864 connection_.SetFromConfig(config);
2865 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2866 use_tagging_decrypter();
2868 const uint8 tag = 0x07;
2869 framer_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
2871 // Process an encrypted packet which can not yet be decrypted which should
2872 // result in the packet being buffered.
2873 for (QuicPacketSequenceNumber i = 1; i <= 100; ++i) {
2874 ProcessDataPacketAtLevel(i, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2877 // Transition to the new encryption state and process another encrypted packet
2878 // which should result in the original packets being processed.
2879 connection_.SetDecrypter(new StrictTaggingDecrypter(tag), ENCRYPTION_INITIAL);
2880 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2881 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
2882 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(101);
2883 ProcessDataPacketAtLevel(101, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2885 // Finally, process a third packet and note that we do not reprocess the
2886 // buffered packet.
2887 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
2888 ProcessDataPacketAtLevel(102, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2891 TEST_P(QuicConnectionTest, TestRetransmitOrder) {
2892 QuicByteCount first_packet_size;
2893 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).WillOnce(
2894 DoAll(SaveArg<3>(&first_packet_size), Return(true)));
2896 connection_.SendStreamDataWithString(3, "first_packet", 0, !kFin, nullptr);
2897 QuicByteCount second_packet_size;
2898 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).WillOnce(
2899 DoAll(SaveArg<3>(&second_packet_size), Return(true)));
2900 connection_.SendStreamDataWithString(3, "second_packet", 12, !kFin, nullptr);
2901 EXPECT_NE(first_packet_size, second_packet_size);
2902 // Advance the clock by huge time to make sure packets will be retransmitted.
2903 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
2905 InSequence s;
2906 EXPECT_CALL(*send_algorithm_,
2907 OnPacketSent(_, _, _, first_packet_size, _));
2908 EXPECT_CALL(*send_algorithm_,
2909 OnPacketSent(_, _, _, second_packet_size, _));
2911 connection_.GetRetransmissionAlarm()->Fire();
2913 // Advance again and expect the packets to be sent again in the same order.
2914 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(20));
2916 InSequence s;
2917 EXPECT_CALL(*send_algorithm_,
2918 OnPacketSent(_, _, _, first_packet_size, _));
2919 EXPECT_CALL(*send_algorithm_,
2920 OnPacketSent(_, _, _, second_packet_size, _));
2922 connection_.GetRetransmissionAlarm()->Fire();
2925 TEST_P(QuicConnectionTest, SetRTOAfterWritingToSocket) {
2926 BlockOnNextWrite();
2927 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
2928 // Make sure that RTO is not started when the packet is queued.
2929 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
2931 // Test that RTO is started once we write to the socket.
2932 writer_->SetWritable();
2933 connection_.OnCanWrite();
2934 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2937 TEST_P(QuicConnectionTest, DelayRTOWithAckReceipt) {
2938 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2939 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2940 .Times(2);
2941 connection_.SendStreamDataWithString(2, "foo", 0, !kFin, nullptr);
2942 connection_.SendStreamDataWithString(3, "bar", 0, !kFin, nullptr);
2943 QuicAlarm* retransmission_alarm = connection_.GetRetransmissionAlarm();
2944 EXPECT_TRUE(retransmission_alarm->IsSet());
2945 EXPECT_EQ(clock_.Now().Add(DefaultRetransmissionTime()),
2946 retransmission_alarm->deadline());
2948 // Advance the time right before the RTO, then receive an ack for the first
2949 // packet to delay the RTO.
2950 clock_.AdvanceTime(DefaultRetransmissionTime());
2951 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2952 QuicAckFrame ack = InitAckFrame(1);
2953 ProcessAckPacket(&ack);
2954 EXPECT_TRUE(retransmission_alarm->IsSet());
2955 EXPECT_GT(retransmission_alarm->deadline(), clock_.Now());
2957 // Move forward past the original RTO and ensure the RTO is still pending.
2958 clock_.AdvanceTime(DefaultRetransmissionTime().Multiply(2));
2960 // Ensure the second packet gets retransmitted when it finally fires.
2961 EXPECT_TRUE(retransmission_alarm->IsSet());
2962 EXPECT_LT(retransmission_alarm->deadline(), clock_.ApproximateNow());
2963 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2964 // Manually cancel the alarm to simulate a real test.
2965 connection_.GetRetransmissionAlarm()->Fire();
2967 // The new retransmitted sequence number should set the RTO to a larger value
2968 // than previously.
2969 EXPECT_TRUE(retransmission_alarm->IsSet());
2970 QuicTime next_rto_time = retransmission_alarm->deadline();
2971 QuicTime expected_rto_time =
2972 connection_.sent_packet_manager().GetRetransmissionTime();
2973 EXPECT_EQ(next_rto_time, expected_rto_time);
2976 TEST_P(QuicConnectionTest, TestQueued) {
2977 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2978 BlockOnNextWrite();
2979 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
2980 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2982 // Unblock the writes and actually send.
2983 writer_->SetWritable();
2984 connection_.OnCanWrite();
2985 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2988 TEST_P(QuicConnectionTest, CloseFecGroup) {
2989 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2990 // Don't send missing packet 1.
2991 // Don't send missing packet 2.
2992 ProcessFecProtectedPacket(3, false, !kEntropyFlag);
2993 // Don't send missing FEC packet 3.
2994 ASSERT_EQ(1u, connection_.NumFecGroups());
2996 // Now send non-fec protected ack packet and close the group.
2997 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 4);
2998 QuicStopWaitingFrame frame = InitStopWaitingFrame(5);
2999 ProcessStopWaitingPacket(&frame);
3000 ASSERT_EQ(0u, connection_.NumFecGroups());
3003 TEST_P(QuicConnectionTest, InitialTimeout) {
3004 EXPECT_TRUE(connection_.connected());
3005 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
3006 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3008 // SetFromConfig sets the initial timeouts before negotiation.
3009 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _, _));
3010 QuicConfig config;
3011 connection_.SetFromConfig(config);
3012 // Subtract a second from the idle timeout on the client side.
3013 QuicTime default_timeout = clock_.ApproximateNow().Add(
3014 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1));
3015 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
3017 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_CONNECTION_TIMED_OUT, false));
3018 // Simulate the timeout alarm firing.
3019 clock_.AdvanceTime(
3020 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1));
3021 connection_.GetTimeoutAlarm()->Fire();
3023 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3024 EXPECT_FALSE(connection_.connected());
3026 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3027 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
3028 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
3029 EXPECT_FALSE(connection_.GetResumeWritesAlarm()->IsSet());
3030 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3031 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
3034 TEST_P(QuicConnectionTest, OverallTimeout) {
3035 // Use a shorter overall connection timeout than idle timeout for this test.
3036 const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(5);
3037 connection_.SetNetworkTimeouts(timeout, timeout);
3038 EXPECT_TRUE(connection_.connected());
3039 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
3041 QuicTime overall_timeout = clock_.ApproximateNow().Add(timeout).Subtract(
3042 QuicTime::Delta::FromSeconds(1));
3043 EXPECT_EQ(overall_timeout, connection_.GetTimeoutAlarm()->deadline());
3044 EXPECT_TRUE(connection_.connected());
3046 // Send and ack new data 3 seconds later to lengthen the idle timeout.
3047 SendStreamDataToPeer(1, "GET /", 0, kFin, nullptr);
3048 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(3));
3049 QuicAckFrame frame = InitAckFrame(1);
3050 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3051 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3052 ProcessAckPacket(&frame);
3054 // Fire early to verify it wouldn't timeout yet.
3055 connection_.GetTimeoutAlarm()->Fire();
3056 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
3057 EXPECT_TRUE(connection_.connected());
3059 clock_.AdvanceTime(timeout.Subtract(QuicTime::Delta::FromSeconds(2)));
3061 EXPECT_CALL(visitor_,
3062 OnConnectionClosed(QUIC_CONNECTION_OVERALL_TIMED_OUT, false));
3063 // Simulate the timeout alarm firing.
3064 connection_.GetTimeoutAlarm()->Fire();
3066 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3067 EXPECT_FALSE(connection_.connected());
3069 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3070 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
3071 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
3072 EXPECT_FALSE(connection_.GetResumeWritesAlarm()->IsSet());
3073 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3074 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
3077 TEST_P(QuicConnectionTest, PingAfterSend) {
3078 EXPECT_TRUE(connection_.connected());
3079 EXPECT_CALL(visitor_, HasOpenDataStreams()).WillRepeatedly(Return(true));
3080 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
3082 // Advance to 5ms, and send a packet to the peer, which will set
3083 // the ping alarm.
3084 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
3085 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3086 SendStreamDataToPeer(1, "GET /", 0, kFin, nullptr);
3087 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
3088 EXPECT_EQ(clock_.ApproximateNow().Add(QuicTime::Delta::FromSeconds(15)),
3089 connection_.GetPingAlarm()->deadline());
3091 // Now recevie and ACK of the previous packet, which will move the
3092 // ping alarm forward.
3093 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
3094 QuicAckFrame frame = InitAckFrame(1);
3095 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3096 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3097 ProcessAckPacket(&frame);
3098 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
3099 // The ping timer is set slightly less than 15 seconds in the future, because
3100 // of the 1s ping timer alarm granularity.
3101 EXPECT_EQ(clock_.ApproximateNow().Add(QuicTime::Delta::FromSeconds(15))
3102 .Subtract(QuicTime::Delta::FromMilliseconds(5)),
3103 connection_.GetPingAlarm()->deadline());
3105 writer_->Reset();
3106 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15));
3107 connection_.GetPingAlarm()->Fire();
3108 EXPECT_EQ(1u, writer_->frame_count());
3109 ASSERT_EQ(1u, writer_->ping_frames().size());
3110 writer_->Reset();
3112 EXPECT_CALL(visitor_, HasOpenDataStreams()).WillRepeatedly(Return(false));
3113 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
3114 SendAckPacketToPeer();
3116 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
3119 TEST_P(QuicConnectionTest, TimeoutAfterSend) {
3120 EXPECT_TRUE(connection_.connected());
3121 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _, _));
3122 QuicConfig config;
3123 connection_.SetFromConfig(config);
3124 EXPECT_FALSE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
3126 const QuicTime::Delta initial_idle_timeout =
3127 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
3128 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
3129 QuicTime default_timeout = clock_.ApproximateNow().Add(initial_idle_timeout);
3131 // When we send a packet, the timeout will change to 5ms +
3132 // kInitialIdleTimeoutSecs.
3133 clock_.AdvanceTime(five_ms);
3135 // Send an ack so we don't set the retransmission alarm.
3136 SendAckPacketToPeer();
3137 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
3139 // The original alarm will fire. We should not time out because we had a
3140 // network event at t=5ms. The alarm will reregister.
3141 clock_.AdvanceTime(initial_idle_timeout.Subtract(five_ms));
3142 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
3143 connection_.GetTimeoutAlarm()->Fire();
3144 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
3145 EXPECT_TRUE(connection_.connected());
3146 EXPECT_EQ(default_timeout.Add(five_ms),
3147 connection_.GetTimeoutAlarm()->deadline());
3149 // This time, we should time out.
3150 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_CONNECTION_TIMED_OUT, false));
3151 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3152 clock_.AdvanceTime(five_ms);
3153 EXPECT_EQ(default_timeout.Add(five_ms), clock_.ApproximateNow());
3154 connection_.GetTimeoutAlarm()->Fire();
3155 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3156 EXPECT_FALSE(connection_.connected());
3159 TEST_P(QuicConnectionTest, TimeoutAfterSendSilentClose) {
3160 // Same test as above, but complete a handshake which enables silent close,
3161 // causing no connection close packet to be sent.
3162 EXPECT_TRUE(connection_.connected());
3163 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _, _));
3164 QuicConfig config;
3166 // Create a handshake message that also enables silent close.
3167 CryptoHandshakeMessage msg;
3168 string error_details;
3169 QuicConfig client_config;
3170 client_config.SetInitialStreamFlowControlWindowToSend(
3171 kInitialStreamFlowControlWindowForTest);
3172 client_config.SetInitialSessionFlowControlWindowToSend(
3173 kInitialSessionFlowControlWindowForTest);
3174 client_config.SetIdleConnectionStateLifetime(
3175 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs),
3176 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs));
3177 client_config.ToHandshakeMessage(&msg);
3178 const QuicErrorCode error =
3179 config.ProcessPeerHello(msg, CLIENT, &error_details);
3180 EXPECT_EQ(QUIC_NO_ERROR, error);
3182 connection_.SetFromConfig(config);
3183 EXPECT_TRUE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
3185 const QuicTime::Delta default_idle_timeout =
3186 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs - 1);
3187 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
3188 QuicTime default_timeout = clock_.ApproximateNow().Add(default_idle_timeout);
3190 // When we send a packet, the timeout will change to 5ms +
3191 // kInitialIdleTimeoutSecs.
3192 clock_.AdvanceTime(five_ms);
3194 // Send an ack so we don't set the retransmission alarm.
3195 SendAckPacketToPeer();
3196 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
3198 // The original alarm will fire. We should not time out because we had a
3199 // network event at t=5ms. The alarm will reregister.
3200 clock_.AdvanceTime(default_idle_timeout.Subtract(five_ms));
3201 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
3202 connection_.GetTimeoutAlarm()->Fire();
3203 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
3204 EXPECT_TRUE(connection_.connected());
3205 EXPECT_EQ(default_timeout.Add(five_ms),
3206 connection_.GetTimeoutAlarm()->deadline());
3208 // This time, we should time out.
3209 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_CONNECTION_TIMED_OUT, false));
3210 clock_.AdvanceTime(five_ms);
3211 EXPECT_EQ(default_timeout.Add(five_ms), clock_.ApproximateNow());
3212 connection_.GetTimeoutAlarm()->Fire();
3213 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3214 EXPECT_FALSE(connection_.connected());
3217 TEST_P(QuicConnectionTest, SendScheduler) {
3218 // Test that if we send a packet without delay, it is not queued.
3219 QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
3220 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3221 connection_.SendPacket(
3222 ENCRYPTION_NONE, 1, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA);
3223 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3226 TEST_P(QuicConnectionTest, SendSchedulerEAGAIN) {
3227 QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
3228 BlockOnNextWrite();
3229 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 1, _, _)).Times(0);
3230 connection_.SendPacket(
3231 ENCRYPTION_NONE, 1, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA);
3232 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3235 TEST_P(QuicConnectionTest, TestQueueLimitsOnSendStreamData) {
3236 // All packets carry version info till version is negotiated.
3237 size_t payload_length;
3238 size_t length = GetPacketLengthForOneStream(
3239 connection_.version(), kIncludeVersion,
3240 PACKET_8BYTE_CONNECTION_ID, PACKET_1BYTE_SEQUENCE_NUMBER,
3241 NOT_IN_FEC_GROUP, &payload_length);
3242 creator_->set_max_packet_length(length);
3244 // Queue the first packet.
3245 EXPECT_CALL(*send_algorithm_,
3246 TimeUntilSend(_, _, _)).WillOnce(
3247 testing::Return(QuicTime::Delta::FromMicroseconds(10)));
3248 const string payload(payload_length, 'a');
3249 EXPECT_EQ(0u, connection_.SendStreamDataWithString(3, payload, 0, !kFin,
3250 nullptr).bytes_consumed);
3251 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3254 TEST_P(QuicConnectionTest, LoopThroughSendingPackets) {
3255 // All packets carry version info till version is negotiated.
3256 size_t payload_length;
3257 // GetPacketLengthForOneStream() assumes a stream offset of 0 in determining
3258 // packet length. The size of the offset field in a stream frame is 0 for
3259 // offset 0, and 2 for non-zero offsets up through 16K. Increase
3260 // max_packet_length by 2 so that subsequent packets containing subsequent
3261 // stream frames with non-zero offets will fit within the packet length.
3262 size_t length = 2 + GetPacketLengthForOneStream(
3263 connection_.version(), kIncludeVersion,
3264 PACKET_8BYTE_CONNECTION_ID, PACKET_1BYTE_SEQUENCE_NUMBER,
3265 NOT_IN_FEC_GROUP, &payload_length);
3266 creator_->set_max_packet_length(length);
3268 // Queue the first packet.
3269 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(7);
3270 // The first stream frame will have 2 fewer overhead bytes than the other six.
3271 const string payload(payload_length * 7 + 2, 'a');
3272 EXPECT_EQ(payload.size(),
3273 connection_.SendStreamDataWithString(1, payload, 0, !kFin, nullptr)
3274 .bytes_consumed);
3277 TEST_P(QuicConnectionTest, LoopThroughSendingPacketsWithTruncation) {
3278 // Set up a larger payload than will fit in one packet.
3279 const string payload(connection_.max_packet_length(), 'a');
3280 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _, _)).Times(AnyNumber());
3282 // Now send some packets with no truncation.
3283 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3284 EXPECT_EQ(payload.size(),
3285 connection_.SendStreamDataWithString(
3286 3, payload, 0, !kFin, nullptr).bytes_consumed);
3287 // Track the size of the second packet here. The overhead will be the largest
3288 // we see in this test, due to the non-truncated CID.
3289 size_t non_truncated_packet_size = writer_->last_packet_size();
3291 // Change to a 4 byte CID.
3292 QuicConfig config;
3293 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 4);
3294 connection_.SetFromConfig(config);
3295 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3296 EXPECT_EQ(payload.size(),
3297 connection_.SendStreamDataWithString(
3298 3, payload, 0, !kFin, nullptr).bytes_consumed);
3299 // Verify that we have 8 fewer bytes than in the non-truncated case. The
3300 // first packet got 4 bytes of extra payload due to the truncation, and the
3301 // headers here are also 4 byte smaller.
3302 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() + 8);
3305 // Change to a 1 byte CID.
3306 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 1);
3307 connection_.SetFromConfig(config);
3308 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3309 EXPECT_EQ(payload.size(),
3310 connection_.SendStreamDataWithString(
3311 3, payload, 0, !kFin, nullptr).bytes_consumed);
3312 // Just like above, we save 7 bytes on payload, and 7 on truncation.
3313 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() + 7 * 2);
3315 // Change to a 0 byte CID.
3316 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
3317 connection_.SetFromConfig(config);
3318 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3319 EXPECT_EQ(payload.size(),
3320 connection_.SendStreamDataWithString(
3321 3, payload, 0, !kFin, nullptr).bytes_consumed);
3322 // Just like above, we save 8 bytes on payload, and 8 on truncation.
3323 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() + 8 * 2);
3326 TEST_P(QuicConnectionTest, SendDelayedAck) {
3327 QuicTime ack_time = clock_.ApproximateNow().Add(DefaultDelayedAckTime());
3328 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3329 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3330 const uint8 tag = 0x07;
3331 connection_.SetDecrypter(new StrictTaggingDecrypter(tag),
3332 ENCRYPTION_INITIAL);
3333 framer_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
3334 // Process a packet from the non-crypto stream.
3335 frame1_.stream_id = 3;
3337 // The same as ProcessPacket(1) except that ENCRYPTION_INITIAL is used
3338 // instead of ENCRYPTION_NONE.
3339 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
3340 ProcessDataPacketAtLevel(1, 0, !kEntropyFlag, ENCRYPTION_INITIAL);
3342 // Check if delayed ack timer is running for the expected interval.
3343 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3344 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
3345 // Simulate delayed ack alarm firing.
3346 connection_.GetAckAlarm()->Fire();
3347 // Check that ack is sent and that delayed ack alarm is reset.
3348 EXPECT_EQ(2u, writer_->frame_count());
3349 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3350 EXPECT_FALSE(writer_->ack_frames().empty());
3351 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3354 TEST_P(QuicConnectionTest, SendDelayedAckOnHandshakeConfirmed) {
3355 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3356 ProcessPacket(1);
3357 // Check that ack is sent and that delayed ack alarm is set.
3358 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3359 QuicTime ack_time = clock_.ApproximateNow().Add(DefaultDelayedAckTime());
3360 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
3362 // Completing the handshake as the server does nothing.
3363 QuicConnectionPeer::SetIsServer(&connection_, true);
3364 connection_.OnHandshakeComplete();
3365 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3366 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
3368 // Complete the handshake as the client decreases the delayed ack time to 0ms.
3369 QuicConnectionPeer::SetIsServer(&connection_, false);
3370 connection_.OnHandshakeComplete();
3371 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3372 EXPECT_EQ(clock_.ApproximateNow(), connection_.GetAckAlarm()->deadline());
3375 TEST_P(QuicConnectionTest, SendDelayedAckOnSecondPacket) {
3376 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3377 ProcessPacket(1);
3378 ProcessPacket(2);
3379 // Check that ack is sent and that delayed ack alarm is reset.
3380 EXPECT_EQ(2u, writer_->frame_count());
3381 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3382 EXPECT_FALSE(writer_->ack_frames().empty());
3383 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3386 TEST_P(QuicConnectionTest, NoAckOnOldNacks) {
3387 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3388 // Drop one packet, triggering a sequence of acks.
3389 ProcessPacket(2);
3390 size_t frames_per_ack = 2;
3391 EXPECT_EQ(frames_per_ack, writer_->frame_count());
3392 EXPECT_FALSE(writer_->ack_frames().empty());
3393 writer_->Reset();
3394 ProcessPacket(3);
3395 EXPECT_EQ(frames_per_ack, writer_->frame_count());
3396 EXPECT_FALSE(writer_->ack_frames().empty());
3397 writer_->Reset();
3398 ProcessPacket(4);
3399 EXPECT_EQ(frames_per_ack, writer_->frame_count());
3400 EXPECT_FALSE(writer_->ack_frames().empty());
3401 writer_->Reset();
3402 ProcessPacket(5);
3403 EXPECT_EQ(frames_per_ack, writer_->frame_count());
3404 EXPECT_FALSE(writer_->ack_frames().empty());
3405 writer_->Reset();
3406 // Now only set the timer on the 6th packet, instead of sending another ack.
3407 ProcessPacket(6);
3408 EXPECT_EQ(0u, writer_->frame_count());
3409 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3412 TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingPacket) {
3413 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3414 ProcessPacket(1);
3415 connection_.SendStreamDataWithString(kClientDataStreamId1, "foo", 0, !kFin,
3416 nullptr);
3417 // Check that ack is bundled with outgoing data and that delayed ack
3418 // alarm is reset.
3419 EXPECT_EQ(3u, writer_->frame_count());
3420 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3421 EXPECT_FALSE(writer_->ack_frames().empty());
3422 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3425 TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingCryptoPacket) {
3426 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3427 ProcessPacket(1);
3428 connection_.SendStreamDataWithString(kCryptoStreamId, "foo", 0, !kFin,
3429 nullptr);
3430 // Check that ack is bundled with outgoing crypto data.
3431 EXPECT_EQ(3u, writer_->frame_count());
3432 EXPECT_FALSE(writer_->ack_frames().empty());
3433 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3436 TEST_P(QuicConnectionTest, BlockAndBufferOnFirstCHLOPacketOfTwo) {
3437 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3438 ProcessPacket(1);
3439 BlockOnNextWrite();
3440 writer_->set_is_write_blocked_data_buffered(true);
3441 connection_.SendStreamDataWithString(kCryptoStreamId, "foo", 0, !kFin,
3442 nullptr);
3443 EXPECT_TRUE(writer_->IsWriteBlocked());
3444 EXPECT_FALSE(connection_.HasQueuedData());
3445 connection_.SendStreamDataWithString(kCryptoStreamId, "bar", 3, !kFin,
3446 nullptr);
3447 EXPECT_TRUE(writer_->IsWriteBlocked());
3448 EXPECT_TRUE(connection_.HasQueuedData());
3451 TEST_P(QuicConnectionTest, BundleAckForSecondCHLO) {
3452 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3453 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3454 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(
3455 IgnoreResult(InvokeWithoutArgs(&connection_,
3456 &TestConnection::SendCryptoStreamData)));
3457 // Process a packet from the crypto stream, which is frame1_'s default.
3458 // Receiving the CHLO as packet 2 first will cause the connection to
3459 // immediately send an ack, due to the packet gap.
3460 ProcessPacket(2);
3461 // Check that ack is sent and that delayed ack alarm is reset.
3462 EXPECT_EQ(3u, writer_->frame_count());
3463 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3464 EXPECT_EQ(1u, writer_->stream_frames().size());
3465 EXPECT_FALSE(writer_->ack_frames().empty());
3466 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3469 TEST_P(QuicConnectionTest, BundleAckWithDataOnIncomingAck) {
3470 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3471 connection_.SendStreamDataWithString(kClientDataStreamId1, "foo", 0, !kFin,
3472 nullptr);
3473 connection_.SendStreamDataWithString(kClientDataStreamId1, "foo", 3, !kFin,
3474 nullptr);
3475 // Ack the second packet, which will retransmit the first packet.
3476 QuicAckFrame ack = InitAckFrame(2);
3477 NackPacket(1, &ack);
3478 SequenceNumberSet lost_packets;
3479 lost_packets.insert(1);
3480 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3481 .WillOnce(Return(lost_packets));
3482 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3483 ProcessAckPacket(&ack);
3484 EXPECT_EQ(1u, writer_->frame_count());
3485 EXPECT_EQ(1u, writer_->stream_frames().size());
3486 writer_->Reset();
3488 // Now ack the retransmission, which will both raise the high water mark
3489 // and see if there is more data to send.
3490 ack = InitAckFrame(3);
3491 NackPacket(1, &ack);
3492 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3493 .WillOnce(Return(SequenceNumberSet()));
3494 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3495 ProcessAckPacket(&ack);
3497 // Check that no packet is sent and the ack alarm isn't set.
3498 EXPECT_EQ(0u, writer_->frame_count());
3499 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3500 writer_->Reset();
3502 // Send the same ack, but send both data and an ack together.
3503 ack = InitAckFrame(3);
3504 NackPacket(1, &ack);
3505 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3506 .WillOnce(Return(SequenceNumberSet()));
3507 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(
3508 IgnoreResult(InvokeWithoutArgs(
3509 &connection_,
3510 &TestConnection::EnsureWritableAndSendStreamData5)));
3511 ProcessAckPacket(&ack);
3513 // Check that ack is bundled with outgoing data and the delayed ack
3514 // alarm is reset.
3515 EXPECT_EQ(3u, writer_->frame_count());
3516 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3517 EXPECT_FALSE(writer_->ack_frames().empty());
3518 EXPECT_EQ(1u, writer_->stream_frames().size());
3519 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3522 TEST_P(QuicConnectionTest, NoAckSentForClose) {
3523 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3524 ProcessPacket(1);
3525 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, true));
3526 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3527 ProcessClosePacket(2, 0);
3530 TEST_P(QuicConnectionTest, SendWhenDisconnected) {
3531 EXPECT_TRUE(connection_.connected());
3532 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, false));
3533 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, false);
3534 EXPECT_FALSE(connection_.connected());
3535 EXPECT_FALSE(connection_.CanWriteStreamData());
3536 QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
3537 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 1, _, _)).Times(0);
3538 connection_.SendPacket(
3539 ENCRYPTION_NONE, 1, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA);
3542 TEST_P(QuicConnectionTest, PublicReset) {
3543 QuicPublicResetPacket header;
3544 header.public_header.connection_id = connection_id_;
3545 header.public_header.reset_flag = true;
3546 header.public_header.version_flag = false;
3547 header.rejected_sequence_number = 10101;
3548 scoped_ptr<QuicEncryptedPacket> packet(
3549 framer_.BuildPublicResetPacket(header));
3550 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PUBLIC_RESET, true));
3551 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *packet);
3554 TEST_P(QuicConnectionTest, GoAway) {
3555 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3557 QuicGoAwayFrame goaway;
3558 goaway.last_good_stream_id = 1;
3559 goaway.error_code = QUIC_PEER_GOING_AWAY;
3560 goaway.reason_phrase = "Going away.";
3561 EXPECT_CALL(visitor_, OnGoAway(_));
3562 ProcessGoAwayPacket(&goaway);
3565 TEST_P(QuicConnectionTest, WindowUpdate) {
3566 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3568 QuicWindowUpdateFrame window_update;
3569 window_update.stream_id = 3;
3570 window_update.byte_offset = 1234;
3571 EXPECT_CALL(visitor_, OnWindowUpdateFrames(_));
3572 ProcessFramePacket(QuicFrame(&window_update));
3575 TEST_P(QuicConnectionTest, Blocked) {
3576 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3578 QuicBlockedFrame blocked;
3579 blocked.stream_id = 3;
3580 EXPECT_CALL(visitor_, OnBlockedFrames(_));
3581 ProcessFramePacket(QuicFrame(&blocked));
3584 TEST_P(QuicConnectionTest, ZeroBytePacket) {
3585 // Don't close the connection for zero byte packets.
3586 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
3587 QuicEncryptedPacket encrypted(nullptr, 0);
3588 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), encrypted);
3591 TEST_P(QuicConnectionTest, MissingPacketsBeforeLeastUnacked) {
3592 // Set the sequence number of the ack packet to be least unacked (4).
3593 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 3);
3594 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3595 QuicStopWaitingFrame frame = InitStopWaitingFrame(4);
3596 ProcessStopWaitingPacket(&frame);
3597 EXPECT_TRUE(outgoing_ack()->missing_packets.empty());
3600 TEST_P(QuicConnectionTest, ReceivedEntropyHashCalculation) {
3601 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(AtLeast(1));
3602 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3603 ProcessDataPacket(1, 1, kEntropyFlag);
3604 ProcessDataPacket(4, 1, kEntropyFlag);
3605 ProcessDataPacket(3, 1, !kEntropyFlag);
3606 ProcessDataPacket(7, 1, kEntropyFlag);
3607 EXPECT_EQ(146u, outgoing_ack()->entropy_hash);
3610 TEST_P(QuicConnectionTest, ReceivedEntropyHashCalculationHalfFEC) {
3611 // FEC packets should not change the entropy hash calculation.
3612 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(AtLeast(1));
3613 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3614 ProcessDataPacket(1, 1, kEntropyFlag);
3615 ProcessFecPacket(4, 1, false, kEntropyFlag, nullptr);
3616 ProcessDataPacket(3, 3, !kEntropyFlag);
3617 ProcessFecPacket(7, 3, false, kEntropyFlag, nullptr);
3618 EXPECT_EQ(146u, outgoing_ack()->entropy_hash);
3621 TEST_P(QuicConnectionTest, UpdateEntropyForReceivedPackets) {
3622 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(AtLeast(1));
3623 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3624 ProcessDataPacket(1, 1, kEntropyFlag);
3625 ProcessDataPacket(5, 1, kEntropyFlag);
3626 ProcessDataPacket(4, 1, !kEntropyFlag);
3627 EXPECT_EQ(34u, outgoing_ack()->entropy_hash);
3628 // Make 4th packet my least unacked, and update entropy for 2, 3 packets.
3629 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 5);
3630 QuicPacketEntropyHash six_packet_entropy_hash = 0;
3631 QuicPacketEntropyHash kRandomEntropyHash = 129u;
3632 QuicStopWaitingFrame frame = InitStopWaitingFrame(4);
3633 frame.entropy_hash = kRandomEntropyHash;
3634 if (ProcessStopWaitingPacket(&frame)) {
3635 six_packet_entropy_hash = 1 << 6;
3638 EXPECT_EQ((kRandomEntropyHash + (1 << 5) + six_packet_entropy_hash),
3639 outgoing_ack()->entropy_hash);
3642 TEST_P(QuicConnectionTest, UpdateEntropyHashUptoCurrentPacket) {
3643 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(AtLeast(1));
3644 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3645 ProcessDataPacket(1, 1, kEntropyFlag);
3646 ProcessDataPacket(5, 1, !kEntropyFlag);
3647 ProcessDataPacket(22, 1, kEntropyFlag);
3648 EXPECT_EQ(66u, outgoing_ack()->entropy_hash);
3649 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 22);
3650 QuicPacketEntropyHash kRandomEntropyHash = 85u;
3651 // Current packet is the least unacked packet.
3652 QuicPacketEntropyHash ack_entropy_hash;
3653 QuicStopWaitingFrame frame = InitStopWaitingFrame(23);
3654 frame.entropy_hash = kRandomEntropyHash;
3655 ack_entropy_hash = ProcessStopWaitingPacket(&frame);
3656 EXPECT_EQ((kRandomEntropyHash + ack_entropy_hash),
3657 outgoing_ack()->entropy_hash);
3658 ProcessDataPacket(25, 1, kEntropyFlag);
3659 EXPECT_EQ((kRandomEntropyHash + ack_entropy_hash + (1 << (25 % 8))),
3660 outgoing_ack()->entropy_hash);
3663 TEST_P(QuicConnectionTest, EntropyCalculationForTruncatedAck) {
3664 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(AtLeast(1));
3665 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3666 QuicPacketEntropyHash entropy[51];
3667 entropy[0] = 0;
3668 for (int i = 1; i < 51; ++i) {
3669 bool should_send = i % 10 != 1;
3670 bool entropy_flag = (i & (i - 1)) != 0;
3671 if (!should_send) {
3672 entropy[i] = entropy[i - 1];
3673 continue;
3675 if (entropy_flag) {
3676 entropy[i] = entropy[i - 1] ^ (1 << (i % 8));
3677 } else {
3678 entropy[i] = entropy[i - 1];
3680 ProcessDataPacket(i, 1, entropy_flag);
3682 for (int i = 1; i < 50; ++i) {
3683 EXPECT_EQ(entropy[i], QuicConnectionPeer::ReceivedEntropyHash(
3684 &connection_, i));
3688 TEST_P(QuicConnectionTest, ServerSendsVersionNegotiationPacket) {
3689 connection_.SetSupportedVersions(QuicSupportedVersions());
3690 framer_.set_version_for_tests(QUIC_VERSION_UNSUPPORTED);
3692 QuicPacketHeader header;
3693 header.public_header.connection_id = connection_id_;
3694 header.public_header.reset_flag = false;
3695 header.public_header.version_flag = true;
3696 header.entropy_flag = false;
3697 header.fec_flag = false;
3698 header.packet_sequence_number = 12;
3699 header.fec_group = 0;
3701 QuicFrames frames;
3702 QuicFrame frame(&frame1_);
3703 frames.push_back(frame);
3704 scoped_ptr<QuicPacket> packet(
3705 BuildUnsizedDataPacket(&framer_, header, frames));
3706 scoped_ptr<QuicEncryptedPacket> encrypted(
3707 framer_.EncryptPacket(ENCRYPTION_NONE, 12, *packet));
3709 framer_.set_version(version());
3710 connection_.set_is_server(true);
3711 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3712 EXPECT_TRUE(writer_->version_negotiation_packet() != nullptr);
3714 size_t num_versions = arraysize(kSupportedQuicVersions);
3715 ASSERT_EQ(num_versions,
3716 writer_->version_negotiation_packet()->versions.size());
3718 // We expect all versions in kSupportedQuicVersions to be
3719 // included in the packet.
3720 for (size_t i = 0; i < num_versions; ++i) {
3721 EXPECT_EQ(kSupportedQuicVersions[i],
3722 writer_->version_negotiation_packet()->versions[i]);
3726 TEST_P(QuicConnectionTest, ServerSendsVersionNegotiationPacketSocketBlocked) {
3727 connection_.SetSupportedVersions(QuicSupportedVersions());
3728 framer_.set_version_for_tests(QUIC_VERSION_UNSUPPORTED);
3730 QuicPacketHeader header;
3731 header.public_header.connection_id = connection_id_;
3732 header.public_header.reset_flag = false;
3733 header.public_header.version_flag = true;
3734 header.entropy_flag = false;
3735 header.fec_flag = false;
3736 header.packet_sequence_number = 12;
3737 header.fec_group = 0;
3739 QuicFrames frames;
3740 QuicFrame frame(&frame1_);
3741 frames.push_back(frame);
3742 scoped_ptr<QuicPacket> packet(
3743 BuildUnsizedDataPacket(&framer_, header, frames));
3744 scoped_ptr<QuicEncryptedPacket> encrypted(
3745 framer_.EncryptPacket(ENCRYPTION_NONE, 12, *packet));
3747 framer_.set_version(version());
3748 connection_.set_is_server(true);
3749 BlockOnNextWrite();
3750 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3751 EXPECT_EQ(0u, writer_->last_packet_size());
3752 EXPECT_TRUE(connection_.HasQueuedData());
3754 writer_->SetWritable();
3755 connection_.OnCanWrite();
3756 EXPECT_TRUE(writer_->version_negotiation_packet() != nullptr);
3758 size_t num_versions = arraysize(kSupportedQuicVersions);
3759 ASSERT_EQ(num_versions,
3760 writer_->version_negotiation_packet()->versions.size());
3762 // We expect all versions in kSupportedQuicVersions to be
3763 // included in the packet.
3764 for (size_t i = 0; i < num_versions; ++i) {
3765 EXPECT_EQ(kSupportedQuicVersions[i],
3766 writer_->version_negotiation_packet()->versions[i]);
3770 TEST_P(QuicConnectionTest,
3771 ServerSendsVersionNegotiationPacketSocketBlockedDataBuffered) {
3772 connection_.SetSupportedVersions(QuicSupportedVersions());
3773 framer_.set_version_for_tests(QUIC_VERSION_UNSUPPORTED);
3775 QuicPacketHeader header;
3776 header.public_header.connection_id = connection_id_;
3777 header.public_header.reset_flag = false;
3778 header.public_header.version_flag = true;
3779 header.entropy_flag = false;
3780 header.fec_flag = false;
3781 header.packet_sequence_number = 12;
3782 header.fec_group = 0;
3784 QuicFrames frames;
3785 QuicFrame frame(&frame1_);
3786 frames.push_back(frame);
3787 scoped_ptr<QuicPacket> packet(
3788 BuildUnsizedDataPacket(&framer_, header, frames));
3789 scoped_ptr<QuicEncryptedPacket> encrypted(
3790 framer_.EncryptPacket(ENCRYPTION_NONE, 12, *packet));
3792 framer_.set_version(version());
3793 connection_.set_is_server(true);
3794 BlockOnNextWrite();
3795 writer_->set_is_write_blocked_data_buffered(true);
3796 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3797 EXPECT_EQ(0u, writer_->last_packet_size());
3798 EXPECT_FALSE(connection_.HasQueuedData());
3801 TEST_P(QuicConnectionTest, ClientHandlesVersionNegotiation) {
3802 // Start out with some unsupported version.
3803 QuicConnectionPeer::GetFramer(&connection_)->set_version_for_tests(
3804 QUIC_VERSION_UNSUPPORTED);
3806 QuicPacketHeader header;
3807 header.public_header.connection_id = connection_id_;
3808 header.public_header.reset_flag = false;
3809 header.public_header.version_flag = true;
3810 header.entropy_flag = false;
3811 header.fec_flag = false;
3812 header.packet_sequence_number = 12;
3813 header.fec_group = 0;
3815 QuicVersionVector supported_versions;
3816 for (size_t i = 0; i < arraysize(kSupportedQuicVersions); ++i) {
3817 supported_versions.push_back(kSupportedQuicVersions[i]);
3820 // Send a version negotiation packet.
3821 scoped_ptr<QuicEncryptedPacket> encrypted(
3822 framer_.BuildVersionNegotiationPacket(
3823 header.public_header, supported_versions));
3824 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3826 // Now force another packet. The connection should transition into
3827 // NEGOTIATED_VERSION state and tell the packet creator to StopSendingVersion.
3828 header.public_header.version_flag = false;
3829 QuicFrames frames;
3830 QuicFrame frame(&frame1_);
3831 frames.push_back(frame);
3832 scoped_ptr<QuicPacket> packet(
3833 BuildUnsizedDataPacket(&framer_, header, frames));
3834 encrypted.reset(framer_.EncryptPacket(ENCRYPTION_NONE, 12, *packet));
3835 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
3836 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3837 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3839 ASSERT_FALSE(QuicPacketCreatorPeer::SendVersionInPacket(creator_));
3842 TEST_P(QuicConnectionTest, BadVersionNegotiation) {
3843 QuicPacketHeader header;
3844 header.public_header.connection_id = connection_id_;
3845 header.public_header.reset_flag = false;
3846 header.public_header.version_flag = true;
3847 header.entropy_flag = false;
3848 header.fec_flag = false;
3849 header.packet_sequence_number = 12;
3850 header.fec_group = 0;
3852 QuicVersionVector supported_versions;
3853 for (size_t i = 0; i < arraysize(kSupportedQuicVersions); ++i) {
3854 supported_versions.push_back(kSupportedQuicVersions[i]);
3857 // Send a version negotiation packet with the version the client started with.
3858 // It should be rejected.
3859 EXPECT_CALL(visitor_,
3860 OnConnectionClosed(QUIC_INVALID_VERSION_NEGOTIATION_PACKET,
3861 false));
3862 scoped_ptr<QuicEncryptedPacket> encrypted(
3863 framer_.BuildVersionNegotiationPacket(
3864 header.public_header, supported_versions));
3865 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3868 TEST_P(QuicConnectionTest, CheckSendStats) {
3869 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3870 connection_.SendStreamDataWithString(3, "first", 0, !kFin, nullptr);
3871 size_t first_packet_size = writer_->last_packet_size();
3873 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3874 connection_.SendStreamDataWithString(5, "second", 0, !kFin, nullptr);
3875 size_t second_packet_size = writer_->last_packet_size();
3877 // 2 retransmissions due to rto, 1 due to explicit nack.
3878 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
3879 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
3881 // Retransmit due to RTO.
3882 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
3883 connection_.GetRetransmissionAlarm()->Fire();
3885 // Retransmit due to explicit nacks.
3886 QuicAckFrame nack_three = InitAckFrame(4);
3887 NackPacket(3, &nack_three);
3888 NackPacket(1, &nack_three);
3889 SequenceNumberSet lost_packets;
3890 lost_packets.insert(1);
3891 lost_packets.insert(3);
3892 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3893 .WillOnce(Return(lost_packets));
3894 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3895 EXPECT_CALL(visitor_, OnCanWrite()).Times(2);
3896 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3897 ProcessAckPacket(&nack_three);
3899 EXPECT_CALL(*send_algorithm_, BandwidthEstimate()).WillOnce(
3900 Return(QuicBandwidth::Zero()));
3902 const QuicConnectionStats& stats = connection_.GetStats();
3903 EXPECT_EQ(3 * first_packet_size + 2 * second_packet_size - kQuicVersionSize,
3904 stats.bytes_sent);
3905 EXPECT_EQ(5u, stats.packets_sent);
3906 EXPECT_EQ(2 * first_packet_size + second_packet_size - kQuicVersionSize,
3907 stats.bytes_retransmitted);
3908 EXPECT_EQ(3u, stats.packets_retransmitted);
3909 EXPECT_EQ(1u, stats.rto_count);
3910 EXPECT_EQ(kDefaultMaxPacketSize, stats.max_packet_size);
3913 TEST_P(QuicConnectionTest, CheckReceiveStats) {
3914 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3916 size_t received_bytes = 0;
3917 received_bytes += ProcessFecProtectedPacket(1, false, !kEntropyFlag);
3918 received_bytes += ProcessFecProtectedPacket(3, false, !kEntropyFlag);
3919 // Should be counted against dropped packets.
3920 received_bytes += ProcessDataPacket(3, 1, !kEntropyFlag);
3921 received_bytes += ProcessFecPacket(4, 1, true, !kEntropyFlag, nullptr);
3923 EXPECT_CALL(*send_algorithm_, BandwidthEstimate()).WillOnce(
3924 Return(QuicBandwidth::Zero()));
3926 const QuicConnectionStats& stats = connection_.GetStats();
3927 EXPECT_EQ(received_bytes, stats.bytes_received);
3928 EXPECT_EQ(4u, stats.packets_received);
3930 EXPECT_EQ(1u, stats.packets_revived);
3931 EXPECT_EQ(1u, stats.packets_dropped);
3934 TEST_P(QuicConnectionTest, TestFecGroupLimits) {
3935 // Create and return a group for 1.
3936 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 1) != nullptr);
3938 // Create and return a group for 2.
3939 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 2) != nullptr);
3941 // Create and return a group for 4. This should remove 1 but not 2.
3942 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 4) != nullptr);
3943 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 1) == nullptr);
3944 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 2) != nullptr);
3946 // Create and return a group for 3. This will kill off 2.
3947 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 3) != nullptr);
3948 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 2) == nullptr);
3950 // Verify that adding 5 kills off 3, despite 4 being created before 3.
3951 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 5) != nullptr);
3952 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 4) != nullptr);
3953 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 3) == nullptr);
3956 TEST_P(QuicConnectionTest, ProcessFramesIfPacketClosedConnection) {
3957 // Construct a packet with stream frame and connection close frame.
3958 header_.public_header.connection_id = connection_id_;
3959 header_.packet_sequence_number = 1;
3960 header_.public_header.reset_flag = false;
3961 header_.public_header.version_flag = false;
3962 header_.entropy_flag = false;
3963 header_.fec_flag = false;
3964 header_.fec_group = 0;
3966 QuicConnectionCloseFrame qccf;
3967 qccf.error_code = QUIC_PEER_GOING_AWAY;
3968 QuicFrame close_frame(&qccf);
3969 QuicFrame stream_frame(&frame1_);
3971 QuicFrames frames;
3972 frames.push_back(stream_frame);
3973 frames.push_back(close_frame);
3974 scoped_ptr<QuicPacket> packet(
3975 BuildUnsizedDataPacket(&framer_, header_, frames));
3976 EXPECT_TRUE(nullptr != packet.get());
3977 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPacket(
3978 ENCRYPTION_NONE, 1, *packet));
3980 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, true));
3981 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
3982 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3984 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3987 TEST_P(QuicConnectionTest, SelectMutualVersion) {
3988 connection_.SetSupportedVersions(QuicSupportedVersions());
3989 // Set the connection to speak the lowest quic version.
3990 connection_.set_version(QuicVersionMin());
3991 EXPECT_EQ(QuicVersionMin(), connection_.version());
3993 // Pass in available versions which includes a higher mutually supported
3994 // version. The higher mutually supported version should be selected.
3995 QuicVersionVector supported_versions;
3996 for (size_t i = 0; i < arraysize(kSupportedQuicVersions); ++i) {
3997 supported_versions.push_back(kSupportedQuicVersions[i]);
3999 EXPECT_TRUE(connection_.SelectMutualVersion(supported_versions));
4000 EXPECT_EQ(QuicVersionMax(), connection_.version());
4002 // Expect that the lowest version is selected.
4003 // Ensure the lowest supported version is less than the max, unless they're
4004 // the same.
4005 EXPECT_LE(QuicVersionMin(), QuicVersionMax());
4006 QuicVersionVector lowest_version_vector;
4007 lowest_version_vector.push_back(QuicVersionMin());
4008 EXPECT_TRUE(connection_.SelectMutualVersion(lowest_version_vector));
4009 EXPECT_EQ(QuicVersionMin(), connection_.version());
4011 // Shouldn't be able to find a mutually supported version.
4012 QuicVersionVector unsupported_version;
4013 unsupported_version.push_back(QUIC_VERSION_UNSUPPORTED);
4014 EXPECT_FALSE(connection_.SelectMutualVersion(unsupported_version));
4017 TEST_P(QuicConnectionTest, ConnectionCloseWhenWritable) {
4018 EXPECT_FALSE(writer_->IsWriteBlocked());
4020 // Send a packet.
4021 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
4022 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4023 EXPECT_EQ(1u, writer_->packets_write_attempts());
4025 TriggerConnectionClose();
4026 EXPECT_EQ(2u, writer_->packets_write_attempts());
4029 TEST_P(QuicConnectionTest, ConnectionCloseGettingWriteBlocked) {
4030 BlockOnNextWrite();
4031 TriggerConnectionClose();
4032 EXPECT_EQ(1u, writer_->packets_write_attempts());
4033 EXPECT_TRUE(writer_->IsWriteBlocked());
4036 TEST_P(QuicConnectionTest, ConnectionCloseWhenWriteBlocked) {
4037 BlockOnNextWrite();
4038 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
4039 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4040 EXPECT_EQ(1u, writer_->packets_write_attempts());
4041 EXPECT_TRUE(writer_->IsWriteBlocked());
4042 TriggerConnectionClose();
4043 EXPECT_EQ(1u, writer_->packets_write_attempts());
4046 TEST_P(QuicConnectionTest, AckNotifierTriggerCallback) {
4047 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4049 // Create a delegate which we expect to be called.
4050 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4051 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(1);
4053 // Send some data, which will register the delegate to be notified.
4054 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
4056 // Process an ACK from the server which should trigger the callback.
4057 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4058 QuicAckFrame frame = InitAckFrame(1);
4059 ProcessAckPacket(&frame);
4062 TEST_P(QuicConnectionTest, AckNotifierFailToTriggerCallback) {
4063 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4065 // Create a delegate which we don't expect to be called.
4066 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4067 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(0);
4069 // Send some data, which will register the delegate to be notified. This will
4070 // not be ACKed and so the delegate should never be called.
4071 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
4073 // Send some other data which we will ACK.
4074 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
4075 connection_.SendStreamDataWithString(1, "bar", 0, !kFin, nullptr);
4077 // Now we receive ACK for packets 2 and 3, but importantly missing packet 1
4078 // which we registered to be notified about.
4079 QuicAckFrame frame = InitAckFrame(3);
4080 NackPacket(1, &frame);
4081 SequenceNumberSet lost_packets;
4082 lost_packets.insert(1);
4083 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4084 .WillOnce(Return(lost_packets));
4085 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4086 ProcessAckPacket(&frame);
4089 TEST_P(QuicConnectionTest, AckNotifierCallbackAfterRetransmission) {
4090 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4092 // Create a delegate which we expect to be called.
4093 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4094 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(1);
4096 // Send four packets, and register to be notified on ACK of packet 2.
4097 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
4098 connection_.SendStreamDataWithString(3, "bar", 0, !kFin, delegate.get());
4099 connection_.SendStreamDataWithString(3, "baz", 0, !kFin, nullptr);
4100 connection_.SendStreamDataWithString(3, "qux", 0, !kFin, nullptr);
4102 // Now we receive ACK for packets 1, 3, and 4 and lose 2.
4103 QuicAckFrame frame = InitAckFrame(4);
4104 NackPacket(2, &frame);
4105 SequenceNumberSet lost_packets;
4106 lost_packets.insert(2);
4107 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4108 .WillOnce(Return(lost_packets));
4109 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4110 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4111 ProcessAckPacket(&frame);
4113 // Now we get an ACK for packet 5 (retransmitted packet 2), which should
4114 // trigger the callback.
4115 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4116 .WillRepeatedly(Return(SequenceNumberSet()));
4117 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4118 QuicAckFrame second_ack_frame = InitAckFrame(5);
4119 ProcessAckPacket(&second_ack_frame);
4122 // AckNotifierCallback is triggered by the ack of a packet that timed
4123 // out and was retransmitted, even though the retransmission has a
4124 // different sequence number.
4125 TEST_P(QuicConnectionTest, AckNotifierCallbackForAckAfterRTO) {
4126 InSequence s;
4128 // Create a delegate which we expect to be called.
4129 scoped_refptr<MockAckNotifierDelegate> delegate(
4130 new StrictMock<MockAckNotifierDelegate>);
4132 QuicTime default_retransmission_time = clock_.ApproximateNow().Add(
4133 DefaultRetransmissionTime());
4134 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, delegate.get());
4135 EXPECT_EQ(1u, stop_waiting()->least_unacked);
4137 EXPECT_EQ(1u, writer_->header().packet_sequence_number);
4138 EXPECT_EQ(default_retransmission_time,
4139 connection_.GetRetransmissionAlarm()->deadline());
4140 // Simulate the retransmission alarm firing.
4141 clock_.AdvanceTime(DefaultRetransmissionTime());
4142 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 2u, _, _));
4143 connection_.GetRetransmissionAlarm()->Fire();
4144 EXPECT_EQ(2u, writer_->header().packet_sequence_number);
4145 // We do not raise the high water mark yet.
4146 EXPECT_EQ(1u, stop_waiting()->least_unacked);
4148 // Ack the original packet, which will revert the RTO.
4149 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4150 EXPECT_CALL(*delegate, OnAckNotification(1, _, _));
4151 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4152 QuicAckFrame ack_frame = InitAckFrame(1);
4153 ProcessAckPacket(&ack_frame);
4155 // Delegate is not notified again when the retransmit is acked.
4156 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4157 QuicAckFrame second_ack_frame = InitAckFrame(2);
4158 ProcessAckPacket(&second_ack_frame);
4161 // AckNotifierCallback is triggered by the ack of a packet that was
4162 // previously nacked, even though the retransmission has a different
4163 // sequence number.
4164 TEST_P(QuicConnectionTest, AckNotifierCallbackForAckOfNackedPacket) {
4165 InSequence s;
4167 // Create a delegate which we expect to be called.
4168 scoped_refptr<MockAckNotifierDelegate> delegate(
4169 new StrictMock<MockAckNotifierDelegate>);
4171 // Send four packets, and register to be notified on ACK of packet 2.
4172 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
4173 connection_.SendStreamDataWithString(3, "bar", 0, !kFin, delegate.get());
4174 connection_.SendStreamDataWithString(3, "baz", 0, !kFin, nullptr);
4175 connection_.SendStreamDataWithString(3, "qux", 0, !kFin, nullptr);
4177 // Now we receive ACK for packets 1, 3, and 4 and lose 2.
4178 QuicAckFrame frame = InitAckFrame(4);
4179 NackPacket(2, &frame);
4180 SequenceNumberSet lost_packets;
4181 lost_packets.insert(2);
4182 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4183 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4184 .WillOnce(Return(lost_packets));
4185 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4186 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4187 ProcessAckPacket(&frame);
4189 // Now we get an ACK for packet 2, which was previously nacked.
4190 SequenceNumberSet no_lost_packets;
4191 EXPECT_CALL(*delegate.get(), OnAckNotification(1, _, _));
4192 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4193 .WillOnce(Return(no_lost_packets));
4194 QuicAckFrame second_ack_frame = InitAckFrame(4);
4195 ProcessAckPacket(&second_ack_frame);
4197 // Verify that the delegate is not notified again when the
4198 // retransmit is acked.
4199 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4200 .WillOnce(Return(no_lost_packets));
4201 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4202 QuicAckFrame third_ack_frame = InitAckFrame(5);
4203 ProcessAckPacket(&third_ack_frame);
4206 TEST_P(QuicConnectionTest, AckNotifierFECTriggerCallback) {
4207 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4209 // Create a delegate which we expect to be called.
4210 scoped_refptr<MockAckNotifierDelegate> delegate(
4211 new MockAckNotifierDelegate);
4212 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(1);
4214 // Send some data, which will register the delegate to be notified.
4215 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
4216 connection_.SendStreamDataWithString(2, "bar", 0, !kFin, nullptr);
4218 // Process an ACK from the server with a revived packet, which should trigger
4219 // the callback.
4220 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4221 QuicAckFrame frame = InitAckFrame(2);
4222 NackPacket(1, &frame);
4223 frame.revived_packets.insert(1);
4224 ProcessAckPacket(&frame);
4225 // If the ack is processed again, the notifier should not be called again.
4226 ProcessAckPacket(&frame);
4229 TEST_P(QuicConnectionTest, AckNotifierCallbackAfterFECRecovery) {
4230 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4231 EXPECT_CALL(visitor_, OnCanWrite());
4233 // Create a delegate which we expect to be called.
4234 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4235 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(1);
4237 // Expect ACKs for 1 packet.
4238 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4240 // Send one packet, and register to be notified on ACK.
4241 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
4243 // Ack packet gets dropped, but we receive an FEC packet that covers it.
4244 // Should recover the Ack packet and trigger the notification callback.
4245 QuicFrames frames;
4247 QuicAckFrame ack_frame = InitAckFrame(1);
4248 frames.push_back(QuicFrame(&ack_frame));
4250 // Dummy stream frame to satisfy expectations set elsewhere.
4251 frames.push_back(QuicFrame(&frame1_));
4253 QuicPacketHeader ack_header;
4254 ack_header.public_header.connection_id = connection_id_;
4255 ack_header.public_header.reset_flag = false;
4256 ack_header.public_header.version_flag = false;
4257 ack_header.entropy_flag = !kEntropyFlag;
4258 ack_header.fec_flag = true;
4259 ack_header.packet_sequence_number = 1;
4260 ack_header.is_in_fec_group = IN_FEC_GROUP;
4261 ack_header.fec_group = 1;
4263 QuicPacket* packet = BuildUnsizedDataPacket(&framer_, ack_header, frames);
4265 // Take the packet which contains the ACK frame, and construct and deliver an
4266 // FEC packet which allows the ACK packet to be recovered.
4267 ProcessFecPacket(2, 1, true, !kEntropyFlag, packet);
4270 TEST_P(QuicConnectionTest, NetworkChangeVisitorCwndCallbackChangesFecState) {
4271 size_t max_packets_per_fec_group = creator_->max_packets_per_fec_group();
4273 QuicSentPacketManager::NetworkChangeVisitor* visitor =
4274 QuicSentPacketManagerPeer::GetNetworkChangeVisitor(manager_);
4275 EXPECT_TRUE(visitor);
4277 // Increase FEC group size by increasing congestion window to a large number.
4278 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
4279 Return(1000 * kDefaultTCPMSS));
4280 visitor->OnCongestionWindowChange();
4281 EXPECT_LT(max_packets_per_fec_group, creator_->max_packets_per_fec_group());
4284 TEST_P(QuicConnectionTest, NetworkChangeVisitorConfigCallbackChangesFecState) {
4285 QuicSentPacketManager::NetworkChangeVisitor* visitor =
4286 QuicSentPacketManagerPeer::GetNetworkChangeVisitor(manager_);
4287 EXPECT_TRUE(visitor);
4288 EXPECT_EQ(QuicTime::Delta::Zero(),
4289 QuicPacketGeneratorPeer::GetFecTimeout(generator_));
4291 // Verify that sending a config with a new initial rtt changes fec timeout.
4292 // Create and process a config with a non-zero initial RTT.
4293 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _, _));
4294 QuicConfig config;
4295 config.SetInitialRoundTripTimeUsToSend(300000);
4296 connection_.SetFromConfig(config);
4297 EXPECT_LT(QuicTime::Delta::Zero(),
4298 QuicPacketGeneratorPeer::GetFecTimeout(generator_));
4301 TEST_P(QuicConnectionTest, NetworkChangeVisitorRttCallbackChangesFecState) {
4302 // Verify that sending a config with a new initial rtt changes fec timeout.
4303 QuicSentPacketManager::NetworkChangeVisitor* visitor =
4304 QuicSentPacketManagerPeer::GetNetworkChangeVisitor(manager_);
4305 EXPECT_TRUE(visitor);
4306 EXPECT_EQ(QuicTime::Delta::Zero(),
4307 QuicPacketGeneratorPeer::GetFecTimeout(generator_));
4309 // Increase FEC timeout by increasing RTT.
4310 RttStats* rtt_stats = QuicSentPacketManagerPeer::GetRttStats(manager_);
4311 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(300),
4312 QuicTime::Delta::Zero(), QuicTime::Zero());
4313 visitor->OnRttChange();
4314 EXPECT_LT(QuicTime::Delta::Zero(),
4315 QuicPacketGeneratorPeer::GetFecTimeout(generator_));
4318 class MockQuicConnectionDebugVisitor
4319 : public QuicConnectionDebugVisitor {
4320 public:
4321 MOCK_METHOD1(OnFrameAddedToPacket,
4322 void(const QuicFrame&));
4324 MOCK_METHOD6(OnPacketSent,
4325 void(const SerializedPacket&,
4326 QuicPacketSequenceNumber,
4327 EncryptionLevel,
4328 TransmissionType,
4329 const QuicEncryptedPacket&,
4330 QuicTime));
4332 MOCK_METHOD3(OnPacketReceived,
4333 void(const IPEndPoint&,
4334 const IPEndPoint&,
4335 const QuicEncryptedPacket&));
4337 MOCK_METHOD1(OnProtocolVersionMismatch,
4338 void(QuicVersion));
4340 MOCK_METHOD1(OnPacketHeader,
4341 void(const QuicPacketHeader& header));
4343 MOCK_METHOD1(OnStreamFrame,
4344 void(const QuicStreamFrame&));
4346 MOCK_METHOD1(OnAckFrame,
4347 void(const QuicAckFrame& frame));
4349 MOCK_METHOD1(OnStopWaitingFrame,
4350 void(const QuicStopWaitingFrame&));
4352 MOCK_METHOD1(OnRstStreamFrame,
4353 void(const QuicRstStreamFrame&));
4355 MOCK_METHOD1(OnConnectionCloseFrame,
4356 void(const QuicConnectionCloseFrame&));
4358 MOCK_METHOD1(OnPublicResetPacket,
4359 void(const QuicPublicResetPacket&));
4361 MOCK_METHOD1(OnVersionNegotiationPacket,
4362 void(const QuicVersionNegotiationPacket&));
4364 MOCK_METHOD2(OnRevivedPacket,
4365 void(const QuicPacketHeader&, StringPiece payload));
4368 TEST_P(QuicConnectionTest, OnPacketHeaderDebugVisitor) {
4369 QuicPacketHeader header;
4371 MockQuicConnectionDebugVisitor* debug_visitor =
4372 new MockQuicConnectionDebugVisitor();
4373 connection_.set_debug_visitor(debug_visitor);
4374 EXPECT_CALL(*debug_visitor, OnPacketHeader(Ref(header))).Times(1);
4375 connection_.OnPacketHeader(header);
4378 TEST_P(QuicConnectionTest, Pacing) {
4379 TestConnection server(connection_id_, IPEndPoint(), helper_.get(),
4380 factory_, /* is_server= */ true, version());
4381 TestConnection client(connection_id_, IPEndPoint(), helper_.get(),
4382 factory_, /* is_server= */ false, version());
4383 EXPECT_FALSE(client.sent_packet_manager().using_pacing());
4384 EXPECT_FALSE(server.sent_packet_manager().using_pacing());
4387 TEST_P(QuicConnectionTest, ControlFramesInstigateAcks) {
4388 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4390 // Send a WINDOW_UPDATE frame.
4391 QuicWindowUpdateFrame window_update;
4392 window_update.stream_id = 3;
4393 window_update.byte_offset = 1234;
4394 EXPECT_CALL(visitor_, OnWindowUpdateFrames(_));
4395 ProcessFramePacket(QuicFrame(&window_update));
4397 // Ensure that this has caused the ACK alarm to be set.
4398 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
4399 EXPECT_TRUE(ack_alarm->IsSet());
4401 // Cancel alarm, and try again with BLOCKED frame.
4402 ack_alarm->Cancel();
4403 QuicBlockedFrame blocked;
4404 blocked.stream_id = 3;
4405 EXPECT_CALL(visitor_, OnBlockedFrames(_));
4406 ProcessFramePacket(QuicFrame(&blocked));
4407 EXPECT_TRUE(ack_alarm->IsSet());
4410 TEST_P(QuicConnectionTest, NoDataNoFin) {
4411 // Make sure that a call to SendStreamWithData, with no data and no FIN, does
4412 // not result in a QuicAckNotifier being used-after-free (fail under ASAN).
4413 // Regression test for b/18594622
4414 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4415 EXPECT_DFATAL(
4416 connection_.SendStreamDataWithString(3, "", 0, !kFin, delegate.get()),
4417 "Attempt to send empty stream frame");
4420 } // namespace
4421 } // namespace test
4422 } // namespace net