Supervised user whitelists: Cleanup
[chromium-blink-merge.git] / net / quic / quic_connection_test.cc
blobafe1876b0e86d8594828f1022b32620f884c4166
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/memory/scoped_ptr.h"
10 #include "base/stl_util.h"
11 #include "net/base/net_errors.h"
12 #include "net/quic/congestion_control/loss_detection_interface.h"
13 #include "net/quic/congestion_control/send_algorithm_interface.h"
14 #include "net/quic/crypto/null_encrypter.h"
15 #include "net/quic/crypto/quic_decrypter.h"
16 #include "net/quic/crypto/quic_encrypter.h"
17 #include "net/quic/quic_ack_notifier.h"
18 #include "net/quic/quic_flags.h"
19 #include "net/quic/quic_protocol.h"
20 #include "net/quic/quic_utils.h"
21 #include "net/quic/test_tools/mock_clock.h"
22 #include "net/quic/test_tools/mock_random.h"
23 #include "net/quic/test_tools/quic_config_peer.h"
24 #include "net/quic/test_tools/quic_connection_peer.h"
25 #include "net/quic/test_tools/quic_framer_peer.h"
26 #include "net/quic/test_tools/quic_packet_creator_peer.h"
27 #include "net/quic/test_tools/quic_packet_generator_peer.h"
28 #include "net/quic/test_tools/quic_sent_packet_manager_peer.h"
29 #include "net/quic/test_tools/quic_test_utils.h"
30 #include "net/quic/test_tools/simple_quic_framer.h"
31 #include "net/test/gtest_util.h"
32 #include "testing/gmock/include/gmock/gmock.h"
33 #include "testing/gtest/include/gtest/gtest.h"
35 using base::StringPiece;
36 using std::map;
37 using std::string;
38 using std::vector;
39 using testing::AnyNumber;
40 using testing::AtLeast;
41 using testing::ContainerEq;
42 using testing::Contains;
43 using testing::DoAll;
44 using testing::InSequence;
45 using testing::InvokeWithoutArgs;
46 using testing::NiceMock;
47 using testing::Ref;
48 using testing::Return;
49 using testing::SaveArg;
50 using testing::StrictMock;
51 using testing::_;
53 namespace net {
54 namespace test {
55 namespace {
57 const char data1[] = "foo";
58 const char data2[] = "bar";
60 const bool kFin = true;
61 const bool kEntropyFlag = true;
63 const QuicPacketEntropyHash kTestEntropyHash = 76;
65 const int kDefaultRetransmissionTimeMs = 500;
67 // TaggingEncrypter appends kTagSize bytes of |tag| to the end of each message.
68 class TaggingEncrypter : public QuicEncrypter {
69 public:
70 explicit TaggingEncrypter(uint8 tag)
71 : tag_(tag) {
74 ~TaggingEncrypter() override {}
76 // QuicEncrypter interface.
77 bool SetKey(StringPiece key) override { return true; }
79 bool SetNoncePrefix(StringPiece nonce_prefix) override { return true; }
81 bool Encrypt(StringPiece nonce,
82 StringPiece associated_data,
83 StringPiece plaintext,
84 unsigned char* output) override {
85 memcpy(output, plaintext.data(), plaintext.size());
86 output += plaintext.size();
87 memset(output, tag_, kTagSize);
88 return true;
91 bool EncryptPacket(QuicPacketSequenceNumber sequence_number,
92 StringPiece associated_data,
93 StringPiece plaintext,
94 char* output,
95 size_t* output_length,
96 size_t max_output_length) override {
97 const size_t len = plaintext.size() + kTagSize;
98 if (max_output_length < len) {
99 return false;
101 Encrypt(StringPiece(), associated_data, plaintext,
102 reinterpret_cast<unsigned char*>(output));
103 *output_length = len;
104 return true;
107 size_t GetKeySize() const override { return 0; }
108 size_t GetNoncePrefixSize() const override { return 0; }
110 size_t GetMaxPlaintextSize(size_t ciphertext_size) const override {
111 return ciphertext_size - kTagSize;
114 size_t GetCiphertextSize(size_t plaintext_size) const override {
115 return plaintext_size + kTagSize;
118 StringPiece GetKey() const override { return StringPiece(); }
120 StringPiece GetNoncePrefix() const override { return StringPiece(); }
122 private:
123 enum {
124 kTagSize = 12,
127 const uint8 tag_;
129 DISALLOW_COPY_AND_ASSIGN(TaggingEncrypter);
132 // TaggingDecrypter ensures that the final kTagSize bytes of the message all
133 // have the same value and then removes them.
134 class TaggingDecrypter : public QuicDecrypter {
135 public:
136 ~TaggingDecrypter() override {}
138 // QuicDecrypter interface
139 bool SetKey(StringPiece key) override { return true; }
141 bool SetNoncePrefix(StringPiece nonce_prefix) override { return true; }
143 bool DecryptPacket(QuicPacketSequenceNumber sequence_number,
144 const StringPiece& associated_data,
145 const StringPiece& ciphertext,
146 char* output,
147 size_t* output_length,
148 size_t max_output_length) override {
149 if (ciphertext.size() < kTagSize) {
150 return false;
152 if (!CheckTag(ciphertext, GetTag(ciphertext))) {
153 return false;
155 *output_length = ciphertext.size() - kTagSize;
156 memcpy(output, ciphertext.data(), *output_length);
157 return true;
160 StringPiece GetKey() const override { return StringPiece(); }
161 StringPiece GetNoncePrefix() const override { return StringPiece(); }
163 protected:
164 virtual uint8 GetTag(StringPiece ciphertext) {
165 return ciphertext.data()[ciphertext.size()-1];
168 private:
169 enum {
170 kTagSize = 12,
173 bool CheckTag(StringPiece ciphertext, uint8 tag) {
174 for (size_t i = ciphertext.size() - kTagSize; i < ciphertext.size(); i++) {
175 if (ciphertext.data()[i] != tag) {
176 return false;
180 return true;
184 // StringTaggingDecrypter ensures that the final kTagSize bytes of the message
185 // match the expected value.
186 class StrictTaggingDecrypter : public TaggingDecrypter {
187 public:
188 explicit StrictTaggingDecrypter(uint8 tag) : tag_(tag) {}
189 ~StrictTaggingDecrypter() override {}
191 // TaggingQuicDecrypter
192 uint8 GetTag(StringPiece ciphertext) override { return tag_; }
194 private:
195 const uint8 tag_;
198 class TestConnectionHelper : public QuicConnectionHelperInterface {
199 public:
200 class TestAlarm : public QuicAlarm {
201 public:
202 explicit TestAlarm(QuicAlarm::Delegate* delegate)
203 : QuicAlarm(delegate) {
206 void SetImpl() override {}
207 void CancelImpl() override {}
208 using QuicAlarm::Fire;
211 TestConnectionHelper(MockClock* clock, MockRandom* random_generator)
212 : clock_(clock),
213 random_generator_(random_generator) {
214 clock_->AdvanceTime(QuicTime::Delta::FromSeconds(1));
217 // QuicConnectionHelperInterface
218 const QuicClock* GetClock() const override { return clock_; }
220 QuicRandom* GetRandomGenerator() override { return random_generator_; }
222 QuicAlarm* CreateAlarm(QuicAlarm::Delegate* delegate) override {
223 return new TestAlarm(delegate);
226 private:
227 MockClock* clock_;
228 MockRandom* random_generator_;
230 DISALLOW_COPY_AND_ASSIGN(TestConnectionHelper);
233 class TestPacketWriter : public QuicPacketWriter {
234 public:
235 TestPacketWriter(QuicVersion version, MockClock *clock)
236 : version_(version),
237 framer_(SupportedVersions(version_)),
238 last_packet_size_(0),
239 write_blocked_(false),
240 block_on_next_write_(false),
241 is_write_blocked_data_buffered_(false),
242 final_bytes_of_last_packet_(0),
243 final_bytes_of_previous_packet_(0),
244 use_tagging_decrypter_(false),
245 packets_write_attempts_(0),
246 clock_(clock),
247 write_pause_time_delta_(QuicTime::Delta::Zero()) {
250 // QuicPacketWriter interface
251 WriteResult WritePacket(const char* buffer,
252 size_t buf_len,
253 const IPAddressNumber& self_address,
254 const IPEndPoint& peer_address) override {
255 QuicEncryptedPacket packet(buffer, buf_len);
256 ++packets_write_attempts_;
258 if (packet.length() >= sizeof(final_bytes_of_last_packet_)) {
259 final_bytes_of_previous_packet_ = final_bytes_of_last_packet_;
260 memcpy(&final_bytes_of_last_packet_, packet.data() + packet.length() - 4,
261 sizeof(final_bytes_of_last_packet_));
264 if (use_tagging_decrypter_) {
265 framer_.framer()->SetDecrypter(new TaggingDecrypter, ENCRYPTION_NONE);
267 EXPECT_TRUE(framer_.ProcessPacket(packet));
268 if (block_on_next_write_) {
269 write_blocked_ = true;
270 block_on_next_write_ = false;
272 if (IsWriteBlocked()) {
273 return WriteResult(WRITE_STATUS_BLOCKED, -1);
275 last_packet_size_ = packet.length();
277 if (!write_pause_time_delta_.IsZero()) {
278 clock_->AdvanceTime(write_pause_time_delta_);
280 return WriteResult(WRITE_STATUS_OK, last_packet_size_);
283 bool IsWriteBlockedDataBuffered() const override {
284 return is_write_blocked_data_buffered_;
287 bool IsWriteBlocked() const override { return write_blocked_; }
289 void SetWritable() override { write_blocked_ = false; }
291 void BlockOnNextWrite() { block_on_next_write_ = true; }
293 // Sets the amount of time that the writer should before the actual write.
294 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
295 write_pause_time_delta_ = delta;
298 const QuicPacketHeader& header() { return framer_.header(); }
300 size_t frame_count() const { return framer_.num_frames(); }
302 const vector<QuicAckFrame>& ack_frames() const {
303 return framer_.ack_frames();
306 const vector<QuicStopWaitingFrame>& stop_waiting_frames() const {
307 return framer_.stop_waiting_frames();
310 const vector<QuicConnectionCloseFrame>& connection_close_frames() const {
311 return framer_.connection_close_frames();
314 const vector<QuicRstStreamFrame>& rst_stream_frames() const {
315 return framer_.rst_stream_frames();
318 const vector<QuicStreamFrame>& stream_frames() const {
319 return framer_.stream_frames();
322 const vector<QuicPingFrame>& ping_frames() const {
323 return framer_.ping_frames();
326 size_t last_packet_size() {
327 return last_packet_size_;
330 const QuicVersionNegotiationPacket* version_negotiation_packet() {
331 return framer_.version_negotiation_packet();
334 void set_is_write_blocked_data_buffered(bool buffered) {
335 is_write_blocked_data_buffered_ = buffered;
338 void set_perspective(Perspective perspective) {
339 // We invert perspective here, because the framer needs to parse packets
340 // we send.
341 perspective = perspective == Perspective::IS_CLIENT
342 ? Perspective::IS_SERVER
343 : Perspective::IS_CLIENT;
344 QuicFramerPeer::SetPerspective(framer_.framer(), perspective);
347 // final_bytes_of_last_packet_ returns the last four bytes of the previous
348 // packet as a little-endian, uint32. This is intended to be used with a
349 // TaggingEncrypter so that tests can determine which encrypter was used for
350 // a given packet.
351 uint32 final_bytes_of_last_packet() { return final_bytes_of_last_packet_; }
353 // Returns the final bytes of the second to last packet.
354 uint32 final_bytes_of_previous_packet() {
355 return final_bytes_of_previous_packet_;
358 void use_tagging_decrypter() {
359 use_tagging_decrypter_ = true;
362 uint32 packets_write_attempts() { return packets_write_attempts_; }
364 void Reset() { framer_.Reset(); }
366 void SetSupportedVersions(const QuicVersionVector& versions) {
367 framer_.SetSupportedVersions(versions);
370 private:
371 QuicVersion version_;
372 SimpleQuicFramer framer_;
373 size_t last_packet_size_;
374 bool write_blocked_;
375 bool block_on_next_write_;
376 bool is_write_blocked_data_buffered_;
377 uint32 final_bytes_of_last_packet_;
378 uint32 final_bytes_of_previous_packet_;
379 bool use_tagging_decrypter_;
380 uint32 packets_write_attempts_;
381 MockClock *clock_;
382 // If non-zero, the clock will pause during WritePacket for this amount of
383 // time.
384 QuicTime::Delta write_pause_time_delta_;
386 DISALLOW_COPY_AND_ASSIGN(TestPacketWriter);
389 class TestConnection : public QuicConnection {
390 public:
391 TestConnection(QuicConnectionId connection_id,
392 IPEndPoint address,
393 TestConnectionHelper* helper,
394 const PacketWriterFactory& factory,
395 Perspective perspective,
396 QuicVersion version)
397 : QuicConnection(connection_id,
398 address,
399 helper,
400 factory,
401 /* owns_writer= */ false,
402 perspective,
403 /* is_secure= */ false,
404 SupportedVersions(version)) {
405 // Disable tail loss probes for most tests.
406 QuicSentPacketManagerPeer::SetMaxTailLossProbes(
407 QuicConnectionPeer::GetSentPacketManager(this), 0);
408 writer()->set_perspective(perspective);
411 void SendAck() {
412 QuicConnectionPeer::SendAck(this);
415 void SetSendAlgorithm(SendAlgorithmInterface* send_algorithm) {
416 QuicConnectionPeer::SetSendAlgorithm(this, send_algorithm);
419 void SetLossAlgorithm(LossDetectionInterface* loss_algorithm) {
420 QuicSentPacketManagerPeer::SetLossAlgorithm(
421 QuicConnectionPeer::GetSentPacketManager(this), loss_algorithm);
424 void SendPacket(EncryptionLevel level,
425 QuicPacketSequenceNumber sequence_number,
426 QuicPacket* packet,
427 QuicPacketEntropyHash entropy_hash,
428 HasRetransmittableData retransmittable) {
429 RetransmittableFrames* retransmittable_frames =
430 retransmittable == HAS_RETRANSMITTABLE_DATA
431 ? new RetransmittableFrames(ENCRYPTION_NONE)
432 : nullptr;
433 QuicEncryptedPacket* encrypted =
434 QuicConnectionPeer::GetFramer(this)
435 ->EncryptPacket(ENCRYPTION_NONE, sequence_number, *packet);
436 delete packet;
437 OnSerializedPacket(SerializedPacket(sequence_number,
438 PACKET_6BYTE_SEQUENCE_NUMBER, encrypted,
439 entropy_hash, retransmittable_frames));
442 QuicConsumedData SendStreamDataWithString(
443 QuicStreamId id,
444 StringPiece data,
445 QuicStreamOffset offset,
446 bool fin,
447 QuicAckNotifier::DelegateInterface* delegate) {
448 return SendStreamDataWithStringHelper(id, data, offset, fin,
449 MAY_FEC_PROTECT, delegate);
452 QuicConsumedData SendStreamDataWithStringWithFec(
453 QuicStreamId id,
454 StringPiece data,
455 QuicStreamOffset offset,
456 bool fin,
457 QuicAckNotifier::DelegateInterface* delegate) {
458 return SendStreamDataWithStringHelper(id, data, offset, fin,
459 MUST_FEC_PROTECT, delegate);
462 QuicConsumedData SendStreamDataWithStringHelper(
463 QuicStreamId id,
464 StringPiece data,
465 QuicStreamOffset offset,
466 bool fin,
467 FecProtection fec_protection,
468 QuicAckNotifier::DelegateInterface* delegate) {
469 IOVector data_iov;
470 if (!data.empty()) {
471 data_iov.Append(const_cast<char*>(data.data()), data.size());
473 return QuicConnection::SendStreamData(id, data_iov, offset, fin,
474 fec_protection, delegate);
477 QuicConsumedData SendStreamData3() {
478 return SendStreamDataWithString(kClientDataStreamId1, "food", 0, !kFin,
479 nullptr);
482 QuicConsumedData SendStreamData3WithFec() {
483 return SendStreamDataWithStringWithFec(kClientDataStreamId1, "food", 0,
484 !kFin, nullptr);
487 QuicConsumedData SendStreamData5() {
488 return SendStreamDataWithString(kClientDataStreamId2, "food2", 0, !kFin,
489 nullptr);
492 QuicConsumedData SendStreamData5WithFec() {
493 return SendStreamDataWithStringWithFec(kClientDataStreamId2, "food2", 0,
494 !kFin, nullptr);
496 // Ensures the connection can write stream data before writing.
497 QuicConsumedData EnsureWritableAndSendStreamData5() {
498 EXPECT_TRUE(CanWriteStreamData());
499 return SendStreamData5();
502 // The crypto stream has special semantics so that it is not blocked by a
503 // congestion window limitation, and also so that it gets put into a separate
504 // packet (so that it is easier to reason about a crypto frame not being
505 // split needlessly across packet boundaries). As a result, we have separate
506 // tests for some cases for this stream.
507 QuicConsumedData SendCryptoStreamData() {
508 return SendStreamDataWithString(kCryptoStreamId, "chlo", 0, !kFin, nullptr);
511 void set_version(QuicVersion version) {
512 QuicConnectionPeer::GetFramer(this)->set_version(version);
515 void SetSupportedVersions(const QuicVersionVector& versions) {
516 QuicConnectionPeer::GetFramer(this)->SetSupportedVersions(versions);
517 writer()->SetSupportedVersions(versions);
520 void set_perspective(Perspective perspective) {
521 writer()->set_perspective(perspective);
522 QuicConnectionPeer::SetPerspective(this, perspective);
525 TestConnectionHelper::TestAlarm* GetAckAlarm() {
526 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
527 QuicConnectionPeer::GetAckAlarm(this));
530 TestConnectionHelper::TestAlarm* GetPingAlarm() {
531 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
532 QuicConnectionPeer::GetPingAlarm(this));
535 TestConnectionHelper::TestAlarm* GetFecAlarm() {
536 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
537 QuicConnectionPeer::GetFecAlarm(this));
540 TestConnectionHelper::TestAlarm* GetResumeWritesAlarm() {
541 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
542 QuicConnectionPeer::GetResumeWritesAlarm(this));
545 TestConnectionHelper::TestAlarm* GetRetransmissionAlarm() {
546 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
547 QuicConnectionPeer::GetRetransmissionAlarm(this));
550 TestConnectionHelper::TestAlarm* GetSendAlarm() {
551 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
552 QuicConnectionPeer::GetSendAlarm(this));
555 TestConnectionHelper::TestAlarm* GetTimeoutAlarm() {
556 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
557 QuicConnectionPeer::GetTimeoutAlarm(this));
560 using QuicConnection::SelectMutualVersion;
562 private:
563 TestPacketWriter* writer() {
564 return static_cast<TestPacketWriter*>(QuicConnection::writer());
567 DISALLOW_COPY_AND_ASSIGN(TestConnection);
570 // Used for testing packets revived from FEC packets.
571 class FecQuicConnectionDebugVisitor
572 : public QuicConnectionDebugVisitor {
573 public:
574 void OnRevivedPacket(const QuicPacketHeader& header,
575 StringPiece data) override {
576 revived_header_ = header;
579 // Public accessor method.
580 QuicPacketHeader revived_header() const {
581 return revived_header_;
584 private:
585 QuicPacketHeader revived_header_;
588 class MockPacketWriterFactory : public QuicConnection::PacketWriterFactory {
589 public:
590 explicit MockPacketWriterFactory(QuicPacketWriter* writer) {
591 ON_CALL(*this, Create(_)).WillByDefault(Return(writer));
593 ~MockPacketWriterFactory() override {}
595 MOCK_CONST_METHOD1(Create, QuicPacketWriter*(QuicConnection* connection));
598 class QuicConnectionTest : public ::testing::TestWithParam<QuicVersion> {
599 protected:
600 QuicConnectionTest()
601 : connection_id_(42),
602 framer_(SupportedVersions(version()),
603 QuicTime::Zero(),
604 Perspective::IS_CLIENT),
605 peer_creator_(connection_id_, &framer_, &random_generator_),
606 send_algorithm_(new StrictMock<MockSendAlgorithm>),
607 loss_algorithm_(new MockLossAlgorithm()),
608 helper_(new TestConnectionHelper(&clock_, &random_generator_)),
609 writer_(new TestPacketWriter(version(), &clock_)),
610 factory_(writer_.get()),
611 connection_(connection_id_,
612 IPEndPoint(),
613 helper_.get(),
614 factory_,
615 Perspective::IS_CLIENT,
616 version()),
617 creator_(QuicConnectionPeer::GetPacketCreator(&connection_)),
618 generator_(QuicConnectionPeer::GetPacketGenerator(&connection_)),
619 manager_(QuicConnectionPeer::GetSentPacketManager(&connection_)),
620 frame1_(1, false, 0, MakeIOVector(data1)),
621 frame2_(1, false, 3, MakeIOVector(data2)),
622 sequence_number_length_(PACKET_6BYTE_SEQUENCE_NUMBER),
623 connection_id_length_(PACKET_8BYTE_CONNECTION_ID) {
624 connection_.set_visitor(&visitor_);
625 connection_.SetSendAlgorithm(send_algorithm_);
626 connection_.SetLossAlgorithm(loss_algorithm_);
627 framer_.set_received_entropy_calculator(&entropy_calculator_);
628 EXPECT_CALL(
629 *send_algorithm_, TimeUntilSend(_, _, _)).WillRepeatedly(Return(
630 QuicTime::Delta::Zero()));
631 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
632 .Times(AnyNumber());
633 EXPECT_CALL(*send_algorithm_, RetransmissionDelay()).WillRepeatedly(
634 Return(QuicTime::Delta::Zero()));
635 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
636 Return(kMaxPacketSize));
637 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
638 .WillByDefault(Return(true));
639 EXPECT_CALL(*send_algorithm_, HasReliableBandwidthEstimate())
640 .Times(AnyNumber());
641 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
642 .Times(AnyNumber())
643 .WillRepeatedly(Return(QuicBandwidth::Zero()));
644 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
645 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
646 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).Times(AnyNumber());
647 EXPECT_CALL(visitor_, HasPendingHandshake()).Times(AnyNumber());
648 EXPECT_CALL(visitor_, OnCanWrite()).Times(AnyNumber());
649 EXPECT_CALL(visitor_, HasOpenDataStreams()).WillRepeatedly(Return(false));
650 EXPECT_CALL(visitor_, OnCongestionWindowChange(_)).Times(AnyNumber());
652 EXPECT_CALL(*loss_algorithm_, GetLossTimeout())
653 .WillRepeatedly(Return(QuicTime::Zero()));
654 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
655 .WillRepeatedly(Return(SequenceNumberSet()));
658 QuicVersion version() {
659 return GetParam();
662 QuicAckFrame* outgoing_ack() {
663 QuicConnectionPeer::PopulateAckFrame(&connection_, &ack_);
664 return &ack_;
667 QuicStopWaitingFrame* stop_waiting() {
668 QuicConnectionPeer::PopulateStopWaitingFrame(&connection_, &stop_waiting_);
669 return &stop_waiting_;
672 QuicPacketSequenceNumber least_unacked() {
673 if (writer_->stop_waiting_frames().empty()) {
674 return 0;
676 return writer_->stop_waiting_frames()[0].least_unacked;
679 void use_tagging_decrypter() {
680 writer_->use_tagging_decrypter();
683 void ProcessPacket(QuicPacketSequenceNumber number) {
684 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
685 ProcessDataPacket(number, 0, !kEntropyFlag);
688 QuicPacketEntropyHash ProcessFramePacket(QuicFrame frame) {
689 QuicFrames frames;
690 frames.push_back(QuicFrame(frame));
691 QuicPacketCreatorPeer::SetSendVersionInPacket(
692 &peer_creator_, connection_.perspective() == Perspective::IS_SERVER);
694 SerializedPacket serialized_packet =
695 peer_creator_.SerializeAllFrames(frames);
696 scoped_ptr<QuicEncryptedPacket> encrypted(serialized_packet.packet);
697 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
698 return serialized_packet.entropy_hash;
701 size_t ProcessDataPacket(QuicPacketSequenceNumber number,
702 QuicFecGroupNumber fec_group,
703 bool entropy_flag) {
704 return ProcessDataPacketAtLevel(number, fec_group, entropy_flag,
705 ENCRYPTION_NONE);
708 size_t ProcessDataPacketAtLevel(QuicPacketSequenceNumber number,
709 QuicFecGroupNumber fec_group,
710 bool entropy_flag,
711 EncryptionLevel level) {
712 scoped_ptr<QuicPacket> packet(ConstructDataPacket(number, fec_group,
713 entropy_flag));
714 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPacket(
715 level, number, *packet));
716 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
717 return encrypted->length();
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 QuicPacketHeader header;
760 header.public_header.connection_id = connection_id_;
761 header.public_header.sequence_number_length = sequence_number_length_;
762 header.public_header.connection_id_length = connection_id_length_;
763 header.packet_sequence_number = number;
764 header.entropy_flag = entropy_flag;
765 header.fec_flag = true;
766 header.is_in_fec_group = IN_FEC_GROUP;
767 header.fec_group = min_protected_packet;
768 QuicFecData fec_data;
769 fec_data.fec_group = header.fec_group;
771 // Since all data packets in this test have the same payload, the
772 // redundancy is either equal to that payload or the xor of that payload
773 // with itself, depending on the number of packets.
774 if (((number - min_protected_packet) % 2) == 0) {
775 for (size_t i = GetStartOfFecProtectedData(
776 header.public_header.connection_id_length,
777 header.public_header.version_flag,
778 header.public_header.sequence_number_length);
779 i < data_packet->length(); ++i) {
780 data_packet->mutable_data()[i] ^= data_packet->data()[i];
783 fec_data.redundancy = data_packet->FecProtectedData();
785 scoped_ptr<QuicPacket> fec_packet(framer_.BuildFecPacket(header, fec_data));
786 scoped_ptr<QuicEncryptedPacket> encrypted(
787 framer_.EncryptPacket(ENCRYPTION_NONE, number, *fec_packet));
789 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
790 return encrypted->length();
793 QuicByteCount SendStreamDataToPeer(QuicStreamId id,
794 StringPiece data,
795 QuicStreamOffset offset,
796 bool fin,
797 QuicPacketSequenceNumber* last_packet) {
798 QuicByteCount packet_size;
799 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
800 .WillOnce(DoAll(SaveArg<3>(&packet_size), Return(true)));
801 connection_.SendStreamDataWithString(id, data, offset, fin, nullptr);
802 if (last_packet != nullptr) {
803 *last_packet = creator_->sequence_number();
805 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
806 .Times(AnyNumber());
807 return packet_size;
810 void SendAckPacketToPeer() {
811 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
812 connection_.SendAck();
813 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
814 .Times(AnyNumber());
817 QuicPacketEntropyHash ProcessAckPacket(QuicAckFrame* frame) {
818 return ProcessFramePacket(QuicFrame(frame));
821 QuicPacketEntropyHash ProcessStopWaitingPacket(QuicStopWaitingFrame* frame) {
822 return ProcessFramePacket(QuicFrame(frame));
825 QuicPacketEntropyHash ProcessGoAwayPacket(QuicGoAwayFrame* frame) {
826 return ProcessFramePacket(QuicFrame(frame));
829 bool IsMissing(QuicPacketSequenceNumber number) {
830 return IsAwaitingPacket(*outgoing_ack(), number);
833 QuicPacket* ConstructPacket(QuicPacketHeader header, QuicFrames frames) {
834 QuicPacket* packet = BuildUnsizedDataPacket(&framer_, header, frames);
835 EXPECT_NE(nullptr, packet);
836 return packet;
839 QuicPacket* ConstructDataPacket(QuicPacketSequenceNumber number,
840 QuicFecGroupNumber fec_group,
841 bool entropy_flag) {
842 QuicPacketHeader header;
843 header.public_header.connection_id = connection_id_;
844 header.public_header.sequence_number_length = sequence_number_length_;
845 header.public_header.connection_id_length = connection_id_length_;
846 header.entropy_flag = entropy_flag;
847 header.packet_sequence_number = number;
848 header.is_in_fec_group = fec_group == 0u ? NOT_IN_FEC_GROUP : IN_FEC_GROUP;
849 header.fec_group = fec_group;
851 QuicFrames frames;
852 frames.push_back(QuicFrame(&frame1_));
853 return ConstructPacket(header, frames);
856 QuicPacket* ConstructClosePacket(QuicPacketSequenceNumber number,
857 QuicFecGroupNumber fec_group) {
858 QuicPacketHeader header;
859 header.public_header.connection_id = connection_id_;
860 header.packet_sequence_number = number;
861 header.is_in_fec_group = fec_group == 0u ? NOT_IN_FEC_GROUP : IN_FEC_GROUP;
862 header.fec_group = fec_group;
864 QuicConnectionCloseFrame qccf;
865 qccf.error_code = QUIC_PEER_GOING_AWAY;
867 QuicFrames frames;
868 frames.push_back(QuicFrame(&qccf));
869 return ConstructPacket(header, frames);
872 QuicTime::Delta DefaultRetransmissionTime() {
873 return QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
876 QuicTime::Delta DefaultDelayedAckTime() {
877 return QuicTime::Delta::FromMilliseconds(kMaxDelayedAckTimeMs);
880 // Initialize a frame acknowledging all packets up to largest_observed.
881 const QuicAckFrame InitAckFrame(QuicPacketSequenceNumber largest_observed) {
882 QuicAckFrame frame(MakeAckFrame(largest_observed));
883 if (largest_observed > 0) {
884 frame.entropy_hash =
885 QuicConnectionPeer::GetSentEntropyHash(&connection_,
886 largest_observed);
888 return frame;
891 const QuicStopWaitingFrame InitStopWaitingFrame(
892 QuicPacketSequenceNumber least_unacked) {
893 QuicStopWaitingFrame frame;
894 frame.least_unacked = least_unacked;
895 return frame;
898 // Explicitly nack a packet.
899 void NackPacket(QuicPacketSequenceNumber missing, QuicAckFrame* frame) {
900 frame->missing_packets.insert(missing);
901 frame->entropy_hash ^=
902 QuicConnectionPeer::PacketEntropy(&connection_, missing);
905 // Undo nacking a packet within the frame.
906 void AckPacket(QuicPacketSequenceNumber arrived, QuicAckFrame* frame) {
907 EXPECT_THAT(frame->missing_packets, Contains(arrived));
908 frame->missing_packets.erase(arrived);
909 frame->entropy_hash ^=
910 QuicConnectionPeer::PacketEntropy(&connection_, arrived);
913 void TriggerConnectionClose() {
914 // Send an erroneous packet to close the connection.
915 EXPECT_CALL(visitor_,
916 OnConnectionClosed(QUIC_INVALID_PACKET_HEADER, false));
917 // Call ProcessDataPacket rather than ProcessPacket, as we should not get a
918 // packet call to the visitor.
919 ProcessDataPacket(6000, 0, !kEntropyFlag);
920 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
921 nullptr);
924 void BlockOnNextWrite() {
925 writer_->BlockOnNextWrite();
926 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
929 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
930 writer_->SetWritePauseTimeDelta(delta);
933 void CongestionBlockWrites() {
934 EXPECT_CALL(*send_algorithm_,
935 TimeUntilSend(_, _, _)).WillRepeatedly(
936 testing::Return(QuicTime::Delta::FromSeconds(1)));
939 void CongestionUnblockWrites() {
940 EXPECT_CALL(*send_algorithm_,
941 TimeUntilSend(_, _, _)).WillRepeatedly(
942 testing::Return(QuicTime::Delta::Zero()));
945 QuicConnectionId connection_id_;
946 QuicFramer framer_;
947 QuicPacketCreator peer_creator_;
948 MockEntropyCalculator entropy_calculator_;
950 MockSendAlgorithm* send_algorithm_;
951 MockLossAlgorithm* loss_algorithm_;
952 MockClock clock_;
953 MockRandom random_generator_;
954 scoped_ptr<TestConnectionHelper> helper_;
955 scoped_ptr<TestPacketWriter> writer_;
956 NiceMock<MockPacketWriterFactory> factory_;
957 TestConnection connection_;
958 QuicPacketCreator* creator_;
959 QuicPacketGenerator* generator_;
960 QuicSentPacketManager* manager_;
961 StrictMock<MockConnectionVisitor> visitor_;
963 QuicStreamFrame frame1_;
964 QuicStreamFrame frame2_;
965 QuicAckFrame ack_;
966 QuicStopWaitingFrame stop_waiting_;
967 QuicSequenceNumberLength sequence_number_length_;
968 QuicConnectionIdLength connection_id_length_;
970 private:
971 DISALLOW_COPY_AND_ASSIGN(QuicConnectionTest);
974 // Run all end to end tests with all supported versions.
975 INSTANTIATE_TEST_CASE_P(SupportedVersion,
976 QuicConnectionTest,
977 ::testing::ValuesIn(QuicSupportedVersions()));
979 TEST_P(QuicConnectionTest, MaxPacketSize) {
980 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
981 EXPECT_EQ(1350u, connection_.max_packet_length());
984 TEST_P(QuicConnectionTest, SmallerServerMaxPacketSize) {
985 QuicConnectionId connection_id = 42;
986 TestConnection connection(connection_id, IPEndPoint(), helper_.get(),
987 factory_, Perspective::IS_SERVER, version());
988 EXPECT_EQ(Perspective::IS_SERVER, connection.perspective());
989 EXPECT_EQ(1000u, connection.max_packet_length());
992 TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSize) {
993 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
995 connection_.set_perspective(Perspective::IS_SERVER);
996 connection_.set_max_packet_length(1000);
998 QuicPacketHeader header;
999 header.public_header.connection_id = connection_id_;
1000 header.public_header.version_flag = true;
1001 header.packet_sequence_number = 1;
1003 QuicFrames frames;
1004 QuicPaddingFrame padding;
1005 frames.push_back(QuicFrame(&frame1_));
1006 frames.push_back(QuicFrame(&padding));
1007 scoped_ptr<QuicPacket> packet(ConstructPacket(header, frames));
1008 scoped_ptr<QuicEncryptedPacket> encrypted(
1009 framer_.EncryptPacket(ENCRYPTION_NONE, 12, *packet));
1010 EXPECT_EQ(kMaxPacketSize, encrypted->length());
1012 framer_.set_version(version());
1013 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
1014 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
1016 EXPECT_EQ(kMaxPacketSize, connection_.max_packet_length());
1019 TEST_P(QuicConnectionTest, PacketsInOrder) {
1020 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1022 ProcessPacket(1);
1023 EXPECT_EQ(1u, outgoing_ack()->largest_observed);
1024 EXPECT_EQ(0u, outgoing_ack()->missing_packets.size());
1026 ProcessPacket(2);
1027 EXPECT_EQ(2u, outgoing_ack()->largest_observed);
1028 EXPECT_EQ(0u, outgoing_ack()->missing_packets.size());
1030 ProcessPacket(3);
1031 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1032 EXPECT_EQ(0u, outgoing_ack()->missing_packets.size());
1035 TEST_P(QuicConnectionTest, PacketsOutOfOrder) {
1036 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1038 ProcessPacket(3);
1039 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1040 EXPECT_TRUE(IsMissing(2));
1041 EXPECT_TRUE(IsMissing(1));
1043 ProcessPacket(2);
1044 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1045 EXPECT_FALSE(IsMissing(2));
1046 EXPECT_TRUE(IsMissing(1));
1048 ProcessPacket(1);
1049 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1050 EXPECT_FALSE(IsMissing(2));
1051 EXPECT_FALSE(IsMissing(1));
1054 TEST_P(QuicConnectionTest, DuplicatePacket) {
1055 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1057 ProcessPacket(3);
1058 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1059 EXPECT_TRUE(IsMissing(2));
1060 EXPECT_TRUE(IsMissing(1));
1062 // Send packet 3 again, but do not set the expectation that
1063 // the visitor OnStreamFrames() will be called.
1064 ProcessDataPacket(3, 0, !kEntropyFlag);
1065 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1066 EXPECT_TRUE(IsMissing(2));
1067 EXPECT_TRUE(IsMissing(1));
1070 TEST_P(QuicConnectionTest, PacketsOutOfOrderWithAdditionsAndLeastAwaiting) {
1071 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1073 ProcessPacket(3);
1074 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1075 EXPECT_TRUE(IsMissing(2));
1076 EXPECT_TRUE(IsMissing(1));
1078 ProcessPacket(2);
1079 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1080 EXPECT_TRUE(IsMissing(1));
1082 ProcessPacket(5);
1083 EXPECT_EQ(5u, outgoing_ack()->largest_observed);
1084 EXPECT_TRUE(IsMissing(1));
1085 EXPECT_TRUE(IsMissing(4));
1087 // Pretend at this point the client has gotten acks for 2 and 3 and 1 is a
1088 // packet the peer will not retransmit. It indicates this by sending 'least
1089 // awaiting' is 4. The connection should then realize 1 will not be
1090 // retransmitted, and will remove it from the missing list.
1091 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 5);
1092 QuicAckFrame frame = InitAckFrame(1);
1093 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _));
1094 ProcessAckPacket(&frame);
1096 // Force an ack to be sent.
1097 SendAckPacketToPeer();
1098 EXPECT_TRUE(IsMissing(4));
1101 TEST_P(QuicConnectionTest, RejectPacketTooFarOut) {
1102 EXPECT_CALL(visitor_,
1103 OnConnectionClosed(QUIC_INVALID_PACKET_HEADER, false));
1104 // Call ProcessDataPacket rather than ProcessPacket, as we should not get a
1105 // packet call to the visitor.
1106 ProcessDataPacket(6000, 0, !kEntropyFlag);
1107 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1108 nullptr);
1111 TEST_P(QuicConnectionTest, RejectUnencryptedStreamData) {
1112 // Process an unencrypted packet from the non-crypto stream.
1113 frame1_.stream_id = 3;
1114 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1115 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_UNENCRYPTED_STREAM_DATA,
1116 false));
1117 ProcessDataPacket(1, 0, !kEntropyFlag);
1118 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1119 nullptr);
1120 const vector<QuicConnectionCloseFrame>& connection_close_frames =
1121 writer_->connection_close_frames();
1122 EXPECT_EQ(1u, connection_close_frames.size());
1123 EXPECT_EQ(QUIC_UNENCRYPTED_STREAM_DATA,
1124 connection_close_frames[0].error_code);
1127 TEST_P(QuicConnectionTest, TruncatedAck) {
1128 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1129 QuicPacketSequenceNumber num_packets = 256 * 2 + 1;
1130 for (QuicPacketSequenceNumber i = 0; i < num_packets; ++i) {
1131 SendStreamDataToPeer(3, "foo", i * 3, !kFin, nullptr);
1134 QuicAckFrame frame = InitAckFrame(num_packets);
1135 SequenceNumberSet lost_packets;
1136 // Create an ack with 256 nacks, none adjacent to one another.
1137 for (QuicPacketSequenceNumber i = 1; i <= 256; ++i) {
1138 NackPacket(i * 2, &frame);
1139 if (i < 256) { // Last packet is nacked, but not lost.
1140 lost_packets.insert(i * 2);
1143 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1144 .WillOnce(Return(lost_packets));
1145 EXPECT_CALL(entropy_calculator_, EntropyHash(511))
1146 .WillOnce(Return(static_cast<QuicPacketEntropyHash>(0)));
1147 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1148 ProcessAckPacket(&frame);
1150 // A truncated ack will not have the true largest observed.
1151 EXPECT_GT(num_packets, manager_->largest_observed());
1153 AckPacket(192, &frame);
1155 // Removing one missing packet allows us to ack 192 and one more range, but
1156 // 192 has already been declared lost, so it doesn't register as an ack.
1157 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1158 .WillOnce(Return(SequenceNumberSet()));
1159 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1160 ProcessAckPacket(&frame);
1161 EXPECT_EQ(num_packets, manager_->largest_observed());
1164 TEST_P(QuicConnectionTest, AckReceiptCausesAckSendBadEntropy) {
1165 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1167 ProcessPacket(1);
1168 // Delay sending, then queue up an ack.
1169 EXPECT_CALL(*send_algorithm_,
1170 TimeUntilSend(_, _, _)).WillOnce(
1171 testing::Return(QuicTime::Delta::FromMicroseconds(1)));
1172 QuicConnectionPeer::SendAck(&connection_);
1174 // Process an ack with a least unacked of the received ack.
1175 // This causes an ack to be sent when TimeUntilSend returns 0.
1176 EXPECT_CALL(*send_algorithm_,
1177 TimeUntilSend(_, _, _)).WillRepeatedly(
1178 testing::Return(QuicTime::Delta::Zero()));
1179 // Skip a packet and then record an ack.
1180 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 2);
1181 QuicAckFrame frame = InitAckFrame(0);
1182 ProcessAckPacket(&frame);
1185 TEST_P(QuicConnectionTest, OutOfOrderReceiptCausesAckSend) {
1186 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1188 ProcessPacket(3);
1189 // Should ack immediately since we have missing packets.
1190 EXPECT_EQ(1u, writer_->packets_write_attempts());
1192 ProcessPacket(2);
1193 // Should ack immediately since we have missing packets.
1194 EXPECT_EQ(2u, writer_->packets_write_attempts());
1196 ProcessPacket(1);
1197 // Should ack immediately, since this fills the last hole.
1198 EXPECT_EQ(3u, writer_->packets_write_attempts());
1200 ProcessPacket(4);
1201 // Should not cause an ack.
1202 EXPECT_EQ(3u, writer_->packets_write_attempts());
1205 TEST_P(QuicConnectionTest, AckReceiptCausesAckSend) {
1206 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1208 QuicPacketSequenceNumber original;
1209 QuicByteCount packet_size;
1210 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1211 .WillOnce(DoAll(SaveArg<2>(&original), SaveArg<3>(&packet_size),
1212 Return(true)));
1213 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
1214 QuicAckFrame frame = InitAckFrame(original);
1215 NackPacket(original, &frame);
1216 // First nack triggers early retransmit.
1217 SequenceNumberSet lost_packets;
1218 lost_packets.insert(1);
1219 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1220 .WillOnce(Return(lost_packets));
1221 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1222 QuicPacketSequenceNumber retransmission;
1223 EXPECT_CALL(*send_algorithm_,
1224 OnPacketSent(_, _, _, packet_size - kQuicVersionSize, _))
1225 .WillOnce(DoAll(SaveArg<2>(&retransmission), Return(true)));
1227 ProcessAckPacket(&frame);
1229 QuicAckFrame frame2 = InitAckFrame(retransmission);
1230 NackPacket(original, &frame2);
1231 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1232 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1233 .WillOnce(Return(SequenceNumberSet()));
1234 ProcessAckPacket(&frame2);
1236 // Now if the peer sends an ack which still reports the retransmitted packet
1237 // as missing, that will bundle an ack with data after two acks in a row
1238 // indicate the high water mark needs to be raised.
1239 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _,
1240 HAS_RETRANSMITTABLE_DATA));
1241 connection_.SendStreamDataWithString(3, "foo", 3, !kFin, nullptr);
1242 // No ack sent.
1243 EXPECT_EQ(1u, writer_->frame_count());
1244 EXPECT_EQ(1u, writer_->stream_frames().size());
1246 // No more packet loss for the rest of the test.
1247 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1248 .WillRepeatedly(Return(SequenceNumberSet()));
1249 ProcessAckPacket(&frame2);
1250 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _,
1251 HAS_RETRANSMITTABLE_DATA));
1252 connection_.SendStreamDataWithString(3, "foo", 3, !kFin, nullptr);
1253 // Ack bundled.
1254 EXPECT_EQ(3u, writer_->frame_count());
1255 EXPECT_EQ(1u, writer_->stream_frames().size());
1256 EXPECT_FALSE(writer_->ack_frames().empty());
1258 // But an ack with no missing packets will not send an ack.
1259 AckPacket(original, &frame2);
1260 ProcessAckPacket(&frame2);
1261 ProcessAckPacket(&frame2);
1264 TEST_P(QuicConnectionTest, 20AcksCausesAckSend) {
1265 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1267 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr);
1269 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
1270 // But an ack with no missing packets will not send an ack.
1271 QuicAckFrame frame = InitAckFrame(1);
1272 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1273 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1274 .WillRepeatedly(Return(SequenceNumberSet()));
1275 for (int i = 0; i < 20; ++i) {
1276 EXPECT_FALSE(ack_alarm->IsSet());
1277 ProcessAckPacket(&frame);
1279 EXPECT_TRUE(ack_alarm->IsSet());
1282 TEST_P(QuicConnectionTest, LeastUnackedLower) {
1283 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1285 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr);
1286 SendStreamDataToPeer(1, "bar", 3, !kFin, nullptr);
1287 SendStreamDataToPeer(1, "eep", 6, !kFin, nullptr);
1289 // Start out saying the least unacked is 2.
1290 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 5);
1291 QuicStopWaitingFrame frame = InitStopWaitingFrame(2);
1292 ProcessStopWaitingPacket(&frame);
1294 // Change it to 1, but lower the sequence number to fake out-of-order packets.
1295 // This should be fine.
1296 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 1);
1297 // The scheduler will not process out of order acks, but all packet processing
1298 // causes the connection to try to write.
1299 EXPECT_CALL(visitor_, OnCanWrite());
1300 QuicStopWaitingFrame frame2 = InitStopWaitingFrame(1);
1301 ProcessStopWaitingPacket(&frame2);
1303 // Now claim it's one, but set the ordering so it was sent "after" the first
1304 // one. This should cause a connection error.
1305 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
1306 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 7);
1307 EXPECT_CALL(visitor_,
1308 OnConnectionClosed(QUIC_INVALID_STOP_WAITING_DATA, false));
1309 QuicStopWaitingFrame frame3 = InitStopWaitingFrame(1);
1310 ProcessStopWaitingPacket(&frame3);
1313 TEST_P(QuicConnectionTest, TooManySentPackets) {
1314 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1316 for (int i = 0; i < 1100; ++i) {
1317 SendStreamDataToPeer(1, "foo", 3 * i, !kFin, nullptr);
1320 // Ack packet 1, which leaves more than the limit outstanding.
1321 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1322 EXPECT_CALL(visitor_, OnConnectionClosed(
1323 QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS, false));
1324 // We're receive buffer limited, so the connection won't try to write more.
1325 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
1327 // Nack every packet except the last one, leaving a huge gap.
1328 QuicAckFrame frame1 = InitAckFrame(1100);
1329 for (QuicPacketSequenceNumber i = 1; i < 1100; ++i) {
1330 NackPacket(i, &frame1);
1332 ProcessAckPacket(&frame1);
1335 TEST_P(QuicConnectionTest, TooManyReceivedPackets) {
1336 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1337 EXPECT_CALL(visitor_, OnConnectionClosed(
1338 QUIC_TOO_MANY_OUTSTANDING_RECEIVED_PACKETS, false));
1340 // Miss every other packet for 1000 packets.
1341 for (QuicPacketSequenceNumber i = 1; i < 1000; ++i) {
1342 ProcessPacket(i * 2);
1343 if (!connection_.connected()) {
1344 break;
1349 TEST_P(QuicConnectionTest, LargestObservedLower) {
1350 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1352 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr);
1353 SendStreamDataToPeer(1, "bar", 3, !kFin, nullptr);
1354 SendStreamDataToPeer(1, "eep", 6, !kFin, nullptr);
1355 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1357 // Start out saying the largest observed is 2.
1358 QuicAckFrame frame1 = InitAckFrame(1);
1359 QuicAckFrame frame2 = InitAckFrame(2);
1360 ProcessAckPacket(&frame2);
1362 // Now change it to 1, and it should cause a connection error.
1363 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, false));
1364 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
1365 ProcessAckPacket(&frame1);
1368 TEST_P(QuicConnectionTest, AckUnsentData) {
1369 // Ack a packet which has not been sent.
1370 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, false));
1371 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1372 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
1373 QuicAckFrame frame(MakeAckFrame(1));
1374 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
1375 ProcessAckPacket(&frame);
1378 TEST_P(QuicConnectionTest, AckAll) {
1379 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1380 ProcessPacket(1);
1382 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 1);
1383 QuicAckFrame frame1 = InitAckFrame(0);
1384 ProcessAckPacket(&frame1);
1387 TEST_P(QuicConnectionTest, SendingDifferentSequenceNumberLengthsBandwidth) {
1388 QuicPacketSequenceNumber last_packet;
1389 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet);
1390 EXPECT_EQ(1u, last_packet);
1391 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1392 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1393 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1394 writer_->header().public_header.sequence_number_length);
1396 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
1397 Return(kMaxPacketSize * 256));
1399 SendStreamDataToPeer(1, "bar", 3, !kFin, &last_packet);
1400 EXPECT_EQ(2u, last_packet);
1401 EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER,
1402 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1403 // The 1 packet lag is due to the sequence number length being recalculated in
1404 // QuicConnection after a packet is sent.
1405 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1406 writer_->header().public_header.sequence_number_length);
1408 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
1409 Return(kMaxPacketSize * 256 * 256));
1411 SendStreamDataToPeer(1, "foo", 6, !kFin, &last_packet);
1412 EXPECT_EQ(3u, last_packet);
1413 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1414 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1415 EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER,
1416 writer_->header().public_header.sequence_number_length);
1418 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
1419 Return(kMaxPacketSize * 256 * 256 * 256));
1421 SendStreamDataToPeer(1, "bar", 9, !kFin, &last_packet);
1422 EXPECT_EQ(4u, last_packet);
1423 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1424 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1425 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1426 writer_->header().public_header.sequence_number_length);
1428 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
1429 Return(kMaxPacketSize * 256 * 256 * 256 * 256));
1431 SendStreamDataToPeer(1, "foo", 12, !kFin, &last_packet);
1432 EXPECT_EQ(5u, last_packet);
1433 EXPECT_EQ(PACKET_6BYTE_SEQUENCE_NUMBER,
1434 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1435 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1436 writer_->header().public_header.sequence_number_length);
1439 // TODO(ianswett): Re-enable this test by finding a good way to test different
1440 // sequence number lengths without sending packets with giant gaps.
1441 TEST_P(QuicConnectionTest,
1442 DISABLED_SendingDifferentSequenceNumberLengthsUnackedDelta) {
1443 QuicPacketSequenceNumber last_packet;
1444 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet);
1445 EXPECT_EQ(1u, last_packet);
1446 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1447 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1448 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1449 writer_->header().public_header.sequence_number_length);
1451 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 100);
1453 SendStreamDataToPeer(1, "bar", 3, !kFin, &last_packet);
1454 EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER,
1455 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1456 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1457 writer_->header().public_header.sequence_number_length);
1459 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 100 * 256);
1461 SendStreamDataToPeer(1, "foo", 6, !kFin, &last_packet);
1462 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1463 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1464 EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER,
1465 writer_->header().public_header.sequence_number_length);
1467 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 100 * 256 * 256);
1469 SendStreamDataToPeer(1, "bar", 9, !kFin, &last_packet);
1470 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1471 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1472 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1473 writer_->header().public_header.sequence_number_length);
1475 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_,
1476 100 * 256 * 256 * 256);
1478 SendStreamDataToPeer(1, "foo", 12, !kFin, &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 TEST_P(QuicConnectionTest, BasicSending) {
1486 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1487 QuicPacketSequenceNumber last_packet;
1488 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet); // Packet 1
1489 EXPECT_EQ(1u, last_packet);
1490 SendAckPacketToPeer(); // Packet 2
1492 EXPECT_EQ(1u, least_unacked());
1494 SendAckPacketToPeer(); // Packet 3
1495 EXPECT_EQ(1u, least_unacked());
1497 SendStreamDataToPeer(1, "bar", 3, !kFin, &last_packet); // Packet 4
1498 EXPECT_EQ(4u, last_packet);
1499 SendAckPacketToPeer(); // Packet 5
1500 EXPECT_EQ(1u, least_unacked());
1502 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1504 // Peer acks up to packet 3.
1505 QuicAckFrame frame = InitAckFrame(3);
1506 ProcessAckPacket(&frame);
1507 SendAckPacketToPeer(); // Packet 6
1509 // As soon as we've acked one, we skip ack packets 2 and 3 and note lack of
1510 // ack for 4.
1511 EXPECT_EQ(4u, least_unacked());
1513 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1515 // Peer acks up to packet 4, the last packet.
1516 QuicAckFrame frame2 = InitAckFrame(6);
1517 ProcessAckPacket(&frame2); // Acks don't instigate acks.
1519 // Verify that we did not send an ack.
1520 EXPECT_EQ(6u, writer_->header().packet_sequence_number);
1522 // So the last ack has not changed.
1523 EXPECT_EQ(4u, least_unacked());
1525 // If we force an ack, we shouldn't change our retransmit state.
1526 SendAckPacketToPeer(); // Packet 7
1527 EXPECT_EQ(7u, least_unacked());
1529 // But if we send more data it should.
1530 SendStreamDataToPeer(1, "eep", 6, !kFin, &last_packet); // Packet 8
1531 EXPECT_EQ(8u, last_packet);
1532 SendAckPacketToPeer(); // Packet 9
1533 EXPECT_EQ(7u, least_unacked());
1536 // QuicConnection should record the the packet sent-time prior to sending the
1537 // packet.
1538 TEST_P(QuicConnectionTest, RecordSentTimeBeforePacketSent) {
1539 // We're using a MockClock for the tests, so we have complete control over the
1540 // time.
1541 // Our recorded timestamp for the last packet sent time will be passed in to
1542 // the send_algorithm. Make sure that it is set to the correct value.
1543 QuicTime actual_recorded_send_time = QuicTime::Zero();
1544 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1545 .WillOnce(DoAll(SaveArg<0>(&actual_recorded_send_time), Return(true)));
1547 // First send without any pause and check the result.
1548 QuicTime expected_recorded_send_time = clock_.Now();
1549 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
1550 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
1551 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
1552 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
1554 // Now pause during the write, and check the results.
1555 actual_recorded_send_time = QuicTime::Zero();
1556 const QuicTime::Delta write_pause_time_delta =
1557 QuicTime::Delta::FromMilliseconds(5000);
1558 SetWritePauseTimeDelta(write_pause_time_delta);
1559 expected_recorded_send_time = clock_.Now();
1561 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1562 .WillOnce(DoAll(SaveArg<0>(&actual_recorded_send_time), Return(true)));
1563 connection_.SendStreamDataWithString(2, "baz", 0, !kFin, nullptr);
1564 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
1565 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
1566 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
1569 TEST_P(QuicConnectionTest, FECSending) {
1570 // All packets carry version info till version is negotiated.
1571 size_t payload_length;
1572 // GetPacketLengthForOneStream() assumes a stream offset of 0 in determining
1573 // packet length. The size of the offset field in a stream frame is 0 for
1574 // offset 0, and 2 for non-zero offsets up through 64K. Increase
1575 // max_packet_length by 2 so that subsequent packets containing subsequent
1576 // stream frames with non-zero offets will fit within the packet length.
1577 size_t length = 2 + GetPacketLengthForOneStream(
1578 connection_.version(), kIncludeVersion,
1579 PACKET_8BYTE_CONNECTION_ID, PACKET_1BYTE_SEQUENCE_NUMBER,
1580 IN_FEC_GROUP, &payload_length);
1581 creator_->SetMaxPacketLength(length);
1583 // Send 4 protected data packets, which should also trigger 1 FEC packet.
1584 EXPECT_CALL(*send_algorithm_,
1585 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(5);
1586 // The first stream frame will have 2 fewer overhead bytes than the other 3.
1587 const string payload(payload_length * 4 + 2, 'a');
1588 connection_.SendStreamDataWithStringWithFec(1, payload, 0, !kFin, nullptr);
1589 // Expect the FEC group to be closed after SendStreamDataWithString.
1590 EXPECT_FALSE(creator_->IsFecGroupOpen());
1591 EXPECT_FALSE(creator_->IsFecProtected());
1594 TEST_P(QuicConnectionTest, FECQueueing) {
1595 // All packets carry version info till version is negotiated.
1596 size_t payload_length;
1597 size_t length = GetPacketLengthForOneStream(
1598 connection_.version(), kIncludeVersion,
1599 PACKET_8BYTE_CONNECTION_ID, PACKET_1BYTE_SEQUENCE_NUMBER,
1600 IN_FEC_GROUP, &payload_length);
1601 creator_->SetMaxPacketLength(length);
1602 EXPECT_TRUE(creator_->IsFecEnabled());
1604 EXPECT_EQ(0u, connection_.NumQueuedPackets());
1605 BlockOnNextWrite();
1606 const string payload(payload_length, 'a');
1607 connection_.SendStreamDataWithStringWithFec(1, payload, 0, !kFin, nullptr);
1608 EXPECT_FALSE(creator_->IsFecGroupOpen());
1609 EXPECT_FALSE(creator_->IsFecProtected());
1610 // Expect the first data packet and the fec packet to be queued.
1611 EXPECT_EQ(2u, connection_.NumQueuedPackets());
1614 TEST_P(QuicConnectionTest, FECAlarmStoppedWhenFECPacketSent) {
1615 EXPECT_TRUE(creator_->IsFecEnabled());
1616 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1617 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1619 creator_->set_max_packets_per_fec_group(2);
1621 // 1 Data packet. FEC alarm should be set.
1622 EXPECT_CALL(*send_algorithm_,
1623 OnPacketSent(_, _, 1u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1624 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, true, nullptr);
1625 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1627 // Second data packet triggers FEC packet out. FEC alarm should not be set.
1628 EXPECT_CALL(*send_algorithm_,
1629 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(2);
1630 connection_.SendStreamDataWithStringWithFec(5, "foo", 0, true, nullptr);
1631 EXPECT_TRUE(writer_->header().fec_flag);
1632 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1635 TEST_P(QuicConnectionTest, FECAlarmStoppedOnConnectionClose) {
1636 EXPECT_TRUE(creator_->IsFecEnabled());
1637 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1638 creator_->set_max_packets_per_fec_group(100);
1640 // 1 Data packet. FEC alarm should be set.
1641 EXPECT_CALL(*send_algorithm_,
1642 OnPacketSent(_, _, 1u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1643 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, kFin, nullptr);
1644 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1646 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NO_ERROR, false));
1647 // Closing connection should stop the FEC alarm.
1648 connection_.CloseConnection(QUIC_NO_ERROR, /*from_peer=*/false);
1649 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1652 TEST_P(QuicConnectionTest, RemoveFECFromInflightOnRetransmissionTimeout) {
1653 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1654 EXPECT_TRUE(creator_->IsFecEnabled());
1655 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1656 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1658 // 1 Data packet. FEC alarm should be set.
1659 EXPECT_CALL(*send_algorithm_,
1660 OnPacketSent(_, _, 1u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1661 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, !kFin, nullptr);
1662 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1663 size_t protected_packet =
1664 QuicSentPacketManagerPeer::GetBytesInFlight(manager_);
1666 // Force FEC timeout to send FEC packet out.
1667 EXPECT_CALL(*send_algorithm_,
1668 OnPacketSent(_, _, 2u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1669 connection_.GetFecAlarm()->Fire();
1670 EXPECT_TRUE(writer_->header().fec_flag);
1672 size_t fec_packet = protected_packet;
1673 EXPECT_EQ(protected_packet + fec_packet,
1674 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1675 clock_.AdvanceTime(DefaultRetransmissionTime());
1677 // On RTO, both data and FEC packets are removed from inflight, only the data
1678 // packet is retransmitted, and this retransmission (but not FEC) gets added
1679 // back into the inflight.
1680 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
1681 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1682 connection_.GetRetransmissionAlarm()->Fire();
1684 // The retransmission of packet 1 will be 3 bytes smaller than packet 1, since
1685 // the first transmission will have 1 byte for FEC group number and 2 bytes of
1686 // stream frame size, which are absent in the retransmission.
1687 size_t retransmitted_packet = protected_packet - 3;
1688 EXPECT_EQ(protected_packet + retransmitted_packet,
1689 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1690 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1692 // Receive ack for the retransmission. No data should be outstanding.
1693 QuicAckFrame ack = InitAckFrame(3);
1694 NackPacket(1, &ack);
1695 NackPacket(2, &ack);
1696 SequenceNumberSet lost_packets;
1697 lost_packets.insert(1);
1698 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1699 .WillOnce(Return(lost_packets));
1700 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1701 ProcessAckPacket(&ack);
1703 // Ensure the alarm is not set since all packets have been acked or abandoned.
1704 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
1705 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1708 TEST_P(QuicConnectionTest, RemoveFECFromInflightOnLossRetransmission) {
1709 EXPECT_TRUE(creator_->IsFecEnabled());
1710 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1712 // 1 FEC-protected data packet. FEC alarm should be set.
1713 EXPECT_CALL(*send_algorithm_,
1714 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1715 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, kFin, nullptr);
1716 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1717 size_t protected_packet =
1718 QuicSentPacketManagerPeer::GetBytesInFlight(manager_);
1720 // Force FEC timeout to send FEC packet out.
1721 EXPECT_CALL(*send_algorithm_,
1722 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1723 connection_.GetFecAlarm()->Fire();
1724 EXPECT_TRUE(writer_->header().fec_flag);
1725 size_t fec_packet = protected_packet;
1726 EXPECT_EQ(protected_packet + fec_packet,
1727 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1729 // Send more data to trigger NACKs. Note that all data starts at stream offset
1730 // 0 to ensure the same packet size, for ease of testing.
1731 EXPECT_CALL(*send_algorithm_,
1732 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(4);
1733 connection_.SendStreamDataWithString(5, "foo", 0, kFin, nullptr);
1734 connection_.SendStreamDataWithString(7, "foo", 0, kFin, nullptr);
1735 connection_.SendStreamDataWithString(9, "foo", 0, kFin, nullptr);
1736 connection_.SendStreamDataWithString(11, "foo", 0, kFin, nullptr);
1738 // An unprotected packet will be 3 bytes smaller than an FEC-protected packet,
1739 // since the protected packet will have 1 byte for FEC group number and
1740 // 2 bytes of stream frame size, which are absent in the unprotected packet.
1741 size_t unprotected_packet = protected_packet - 3;
1742 EXPECT_EQ(protected_packet + fec_packet + 4 * unprotected_packet,
1743 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1744 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1746 // Ack data packets, and NACK FEC packet and one data packet. Triggers
1747 // NACK-based loss detection of both packets, but only data packet is
1748 // retransmitted and considered oustanding.
1749 QuicAckFrame ack = InitAckFrame(6);
1750 NackPacket(2, &ack);
1751 NackPacket(3, &ack);
1752 SequenceNumberSet lost_packets;
1753 lost_packets.insert(2);
1754 lost_packets.insert(3);
1755 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1756 .WillOnce(Return(lost_packets));
1757 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1758 EXPECT_CALL(*send_algorithm_,
1759 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1760 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1761 ProcessAckPacket(&ack);
1762 // On receiving this ack from the server, the client will no longer send
1763 // version number in subsequent packets, including in this retransmission.
1764 size_t unprotected_packet_no_version = unprotected_packet - 4;
1765 EXPECT_EQ(unprotected_packet_no_version,
1766 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1768 // Receive ack for the retransmission. No data should be outstanding.
1769 QuicAckFrame ack2 = InitAckFrame(7);
1770 NackPacket(2, &ack2);
1771 NackPacket(3, &ack2);
1772 SequenceNumberSet lost_packets2;
1773 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1774 .WillOnce(Return(lost_packets2));
1775 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1776 ProcessAckPacket(&ack2);
1777 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1780 TEST_P(QuicConnectionTest, FECRemainsInflightOnTLPOfEarlierData) {
1781 // This test checks if TLP is sent correctly when a data and an FEC packet
1782 // are outstanding. TLP should be sent for the data packet when the
1783 // retransmission alarm fires.
1784 // Turn on TLP for this test.
1785 QuicSentPacketManagerPeer::SetMaxTailLossProbes(manager_, 1);
1786 EXPECT_TRUE(creator_->IsFecEnabled());
1787 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1788 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1790 // 1 Data packet. FEC alarm should be set.
1791 EXPECT_CALL(*send_algorithm_,
1792 OnPacketSent(_, _, 1u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1793 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, kFin, nullptr);
1794 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1795 size_t protected_packet =
1796 QuicSentPacketManagerPeer::GetBytesInFlight(manager_);
1797 EXPECT_LT(0u, protected_packet);
1799 // Force FEC timeout to send FEC packet out.
1800 EXPECT_CALL(*send_algorithm_,
1801 OnPacketSent(_, _, 2u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1802 connection_.GetFecAlarm()->Fire();
1803 EXPECT_TRUE(writer_->header().fec_flag);
1804 size_t fec_packet = protected_packet;
1805 EXPECT_EQ(protected_packet + fec_packet,
1806 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1808 // TLP alarm should be set.
1809 QuicTime retransmission_time =
1810 connection_.GetRetransmissionAlarm()->deadline();
1811 EXPECT_NE(QuicTime::Zero(), retransmission_time);
1812 // Simulate the retransmission alarm firing and sending a TLP, so send
1813 // algorithm's OnRetransmissionTimeout is not called.
1814 clock_.AdvanceTime(retransmission_time.Subtract(clock_.Now()));
1815 EXPECT_CALL(*send_algorithm_,
1816 OnPacketSent(_, _, 3u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1817 connection_.GetRetransmissionAlarm()->Fire();
1818 // The TLP retransmission of packet 1 will be 3 bytes smaller than packet 1,
1819 // since packet 1 will have 1 byte for FEC group number and 2 bytes of stream
1820 // frame size, which are absent in the the TLP retransmission.
1821 size_t tlp_packet = protected_packet - 3;
1822 EXPECT_EQ(protected_packet + fec_packet + tlp_packet,
1823 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1826 TEST_P(QuicConnectionTest, FECRemainsInflightOnTLPOfLaterData) {
1827 // Tests if TLP is sent correctly when data packet 1 and an FEC packet are
1828 // sent followed by data packet 2, and data packet 1 is acked. TLP should be
1829 // sent for data packet 2 when the retransmission alarm fires. Turn on TLP for
1830 // this test.
1831 QuicSentPacketManagerPeer::SetMaxTailLossProbes(manager_, 1);
1832 EXPECT_TRUE(creator_->IsFecEnabled());
1833 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1834 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1836 // 1 Data packet. FEC alarm should be set.
1837 EXPECT_CALL(*send_algorithm_,
1838 OnPacketSent(_, _, 1u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1839 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, kFin, nullptr);
1840 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1841 size_t protected_packet =
1842 QuicSentPacketManagerPeer::GetBytesInFlight(manager_);
1843 EXPECT_LT(0u, protected_packet);
1845 // Force FEC timeout to send FEC packet out.
1846 EXPECT_CALL(*send_algorithm_,
1847 OnPacketSent(_, _, 2u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1848 connection_.GetFecAlarm()->Fire();
1849 EXPECT_TRUE(writer_->header().fec_flag);
1850 // Protected data packet and FEC packet oustanding.
1851 size_t fec_packet = protected_packet;
1852 EXPECT_EQ(protected_packet + fec_packet,
1853 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1855 // Send 1 unprotected data packet. No FEC alarm should be set.
1856 EXPECT_CALL(*send_algorithm_,
1857 OnPacketSent(_, _, 3u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1858 connection_.SendStreamDataWithString(5, "foo", 0, kFin, nullptr);
1859 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1860 // Protected data packet, FEC packet, and unprotected data packet oustanding.
1861 // An unprotected packet will be 3 bytes smaller than an FEC-protected packet,
1862 // since the protected packet will have 1 byte for FEC group number and
1863 // 2 bytes of stream frame size, which are absent in the unprotected packet.
1864 size_t unprotected_packet = protected_packet - 3;
1865 EXPECT_EQ(protected_packet + fec_packet + unprotected_packet,
1866 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1868 // Receive ack for first data packet. FEC and second data packet are still
1869 // outstanding.
1870 QuicAckFrame ack = InitAckFrame(1);
1871 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1872 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1873 ProcessAckPacket(&ack);
1874 // FEC packet and unprotected data packet oustanding.
1875 EXPECT_EQ(fec_packet + unprotected_packet,
1876 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1878 // TLP alarm should be set.
1879 QuicTime retransmission_time =
1880 connection_.GetRetransmissionAlarm()->deadline();
1881 EXPECT_NE(QuicTime::Zero(), retransmission_time);
1882 // Simulate the retransmission alarm firing and sending a TLP, so send
1883 // algorithm's OnRetransmissionTimeout is not called.
1884 clock_.AdvanceTime(retransmission_time.Subtract(clock_.Now()));
1885 EXPECT_CALL(*send_algorithm_,
1886 OnPacketSent(_, _, 4u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1887 connection_.GetRetransmissionAlarm()->Fire();
1889 // Having received an ack from the server, the client will no longer send
1890 // version number in subsequent packets, including in this retransmission.
1891 size_t tlp_packet_no_version = unprotected_packet - 4;
1892 EXPECT_EQ(fec_packet + unprotected_packet + tlp_packet_no_version,
1893 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1896 TEST_P(QuicConnectionTest, NoTLPForFECPacket) {
1897 // Turn on TLP for this test.
1898 QuicSentPacketManagerPeer::SetMaxTailLossProbes(manager_, 1);
1899 EXPECT_TRUE(creator_->IsFecEnabled());
1900 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1902 // Send 1 FEC-protected data packet. FEC alarm should be set.
1903 EXPECT_CALL(*send_algorithm_,
1904 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1905 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, !kFin, nullptr);
1906 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1907 // Force FEC timeout to send FEC packet out.
1908 EXPECT_CALL(*send_algorithm_,
1909 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1910 connection_.GetFecAlarm()->Fire();
1911 EXPECT_TRUE(writer_->header().fec_flag);
1913 // Ack data packet, but not FEC packet.
1914 QuicAckFrame ack = InitAckFrame(1);
1915 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1916 ProcessAckPacket(&ack);
1918 // No TLP alarm for FEC, but retransmission alarm should be set for an RTO.
1919 EXPECT_LT(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1920 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
1921 QuicTime rto_time = connection_.GetRetransmissionAlarm()->deadline();
1922 EXPECT_NE(QuicTime::Zero(), rto_time);
1924 // Simulate the retransmission alarm firing. FEC packet is no longer
1925 // outstanding.
1926 clock_.AdvanceTime(rto_time.Subtract(clock_.Now()));
1927 connection_.GetRetransmissionAlarm()->Fire();
1929 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
1930 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1933 TEST_P(QuicConnectionTest, FramePacking) {
1934 CongestionBlockWrites();
1936 // Send an ack and two stream frames in 1 packet by queueing them.
1937 connection_.SendAck();
1938 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
1939 IgnoreResult(InvokeWithoutArgs(&connection_,
1940 &TestConnection::SendStreamData3)),
1941 IgnoreResult(InvokeWithoutArgs(&connection_,
1942 &TestConnection::SendStreamData5))));
1944 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1945 CongestionUnblockWrites();
1946 connection_.GetSendAlarm()->Fire();
1947 EXPECT_EQ(0u, connection_.NumQueuedPackets());
1948 EXPECT_FALSE(connection_.HasQueuedData());
1950 // Parse the last packet and ensure it's an ack and two stream frames from
1951 // two different streams.
1952 EXPECT_EQ(4u, writer_->frame_count());
1953 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
1954 EXPECT_FALSE(writer_->ack_frames().empty());
1955 ASSERT_EQ(2u, writer_->stream_frames().size());
1956 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id);
1957 EXPECT_EQ(kClientDataStreamId2, writer_->stream_frames()[1].stream_id);
1960 TEST_P(QuicConnectionTest, FramePackingNonCryptoThenCrypto) {
1961 CongestionBlockWrites();
1963 // Send an ack and two stream frames (one non-crypto, then one crypto) in 2
1964 // packets by queueing them.
1965 connection_.SendAck();
1966 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
1967 IgnoreResult(InvokeWithoutArgs(&connection_,
1968 &TestConnection::SendStreamData3)),
1969 IgnoreResult(InvokeWithoutArgs(&connection_,
1970 &TestConnection::SendCryptoStreamData))));
1972 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
1973 CongestionUnblockWrites();
1974 connection_.GetSendAlarm()->Fire();
1975 EXPECT_EQ(0u, connection_.NumQueuedPackets());
1976 EXPECT_FALSE(connection_.HasQueuedData());
1978 // Parse the last packet and ensure it's the crypto stream frame.
1979 EXPECT_EQ(1u, writer_->frame_count());
1980 ASSERT_EQ(1u, writer_->stream_frames().size());
1981 EXPECT_EQ(kCryptoStreamId, writer_->stream_frames()[0].stream_id);
1984 TEST_P(QuicConnectionTest, FramePackingCryptoThenNonCrypto) {
1985 CongestionBlockWrites();
1987 // Send an ack and two stream frames (one crypto, then one non-crypto) in 2
1988 // packets by queueing them.
1989 connection_.SendAck();
1990 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
1991 IgnoreResult(InvokeWithoutArgs(&connection_,
1992 &TestConnection::SendCryptoStreamData)),
1993 IgnoreResult(InvokeWithoutArgs(&connection_,
1994 &TestConnection::SendStreamData3))));
1996 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
1997 CongestionUnblockWrites();
1998 connection_.GetSendAlarm()->Fire();
1999 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2000 EXPECT_FALSE(connection_.HasQueuedData());
2002 // Parse the last packet and ensure it's the stream frame from stream 3.
2003 EXPECT_EQ(1u, writer_->frame_count());
2004 ASSERT_EQ(1u, writer_->stream_frames().size());
2005 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id);
2008 TEST_P(QuicConnectionTest, FramePackingFEC) {
2009 EXPECT_TRUE(creator_->IsFecEnabled());
2011 CongestionBlockWrites();
2013 // Queue an ack and two stream frames. Ack gets flushed when FEC is turned on
2014 // for sending protected data; two stream frames are packed in 1 packet.
2015 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
2016 IgnoreResult(InvokeWithoutArgs(
2017 &connection_, &TestConnection::SendStreamData3WithFec)),
2018 IgnoreResult(InvokeWithoutArgs(
2019 &connection_, &TestConnection::SendStreamData5WithFec))));
2020 connection_.SendAck();
2022 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
2023 CongestionUnblockWrites();
2024 connection_.GetSendAlarm()->Fire();
2025 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2026 EXPECT_FALSE(connection_.HasQueuedData());
2028 // Parse the last packet and ensure it's in an fec group.
2029 EXPECT_EQ(2u, writer_->header().fec_group);
2030 EXPECT_EQ(2u, writer_->frame_count());
2032 // FEC alarm should be set.
2033 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
2036 TEST_P(QuicConnectionTest, FramePackingAckResponse) {
2037 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2038 // Process a data packet to queue up a pending ack.
2039 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
2040 ProcessDataPacket(1, 1, kEntropyFlag);
2042 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
2043 IgnoreResult(InvokeWithoutArgs(&connection_,
2044 &TestConnection::SendStreamData3)),
2045 IgnoreResult(InvokeWithoutArgs(&connection_,
2046 &TestConnection::SendStreamData5))));
2048 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2050 // Process an ack to cause the visitor's OnCanWrite to be invoked.
2051 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 2);
2052 QuicAckFrame ack_one = InitAckFrame(0);
2053 ProcessAckPacket(&ack_one);
2055 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2056 EXPECT_FALSE(connection_.HasQueuedData());
2058 // Parse the last packet and ensure it's an ack and two stream frames from
2059 // two different streams.
2060 EXPECT_EQ(4u, writer_->frame_count());
2061 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
2062 EXPECT_FALSE(writer_->ack_frames().empty());
2063 ASSERT_EQ(2u, writer_->stream_frames().size());
2064 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id);
2065 EXPECT_EQ(kClientDataStreamId2, writer_->stream_frames()[1].stream_id);
2068 TEST_P(QuicConnectionTest, FramePackingSendv) {
2069 // Send data in 1 packet by writing multiple blocks in a single iovector
2070 // using writev.
2071 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2073 char data[] = "ABCD";
2074 IOVector data_iov;
2075 data_iov.AppendNoCoalesce(data, 2);
2076 data_iov.AppendNoCoalesce(data + 2, 2);
2077 connection_.SendStreamData(1, data_iov, 0, !kFin, MAY_FEC_PROTECT, nullptr);
2079 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2080 EXPECT_FALSE(connection_.HasQueuedData());
2082 // Parse the last packet and ensure multiple iovector blocks have
2083 // been packed into a single stream frame from one stream.
2084 EXPECT_EQ(1u, writer_->frame_count());
2085 EXPECT_EQ(1u, writer_->stream_frames().size());
2086 QuicStreamFrame frame = writer_->stream_frames()[0];
2087 EXPECT_EQ(1u, frame.stream_id);
2088 EXPECT_EQ("ABCD", string(static_cast<char*>
2089 (frame.data.iovec()[0].iov_base),
2090 (frame.data.iovec()[0].iov_len)));
2093 TEST_P(QuicConnectionTest, FramePackingSendvQueued) {
2094 // Try to send two stream frames in 1 packet by using writev.
2095 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2097 BlockOnNextWrite();
2098 char data[] = "ABCD";
2099 IOVector data_iov;
2100 data_iov.AppendNoCoalesce(data, 2);
2101 data_iov.AppendNoCoalesce(data + 2, 2);
2102 connection_.SendStreamData(1, data_iov, 0, !kFin, MAY_FEC_PROTECT, nullptr);
2104 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2105 EXPECT_TRUE(connection_.HasQueuedData());
2107 // Unblock the writes and actually send.
2108 writer_->SetWritable();
2109 connection_.OnCanWrite();
2110 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2112 // Parse the last packet and ensure it's one stream frame from one stream.
2113 EXPECT_EQ(1u, writer_->frame_count());
2114 EXPECT_EQ(1u, writer_->stream_frames().size());
2115 EXPECT_EQ(1u, writer_->stream_frames()[0].stream_id);
2118 TEST_P(QuicConnectionTest, SendingZeroBytes) {
2119 // Send a zero byte write with a fin using writev.
2120 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2121 IOVector empty_iov;
2122 connection_.SendStreamData(1, empty_iov, 0, kFin, MAY_FEC_PROTECT, nullptr);
2124 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2125 EXPECT_FALSE(connection_.HasQueuedData());
2127 // Parse the last packet and ensure it's one stream frame from one stream.
2128 EXPECT_EQ(1u, writer_->frame_count());
2129 EXPECT_EQ(1u, writer_->stream_frames().size());
2130 EXPECT_EQ(1u, writer_->stream_frames()[0].stream_id);
2131 EXPECT_TRUE(writer_->stream_frames()[0].fin);
2134 TEST_P(QuicConnectionTest, OnCanWrite) {
2135 // Visitor's OnCanWrite will send data, but will have more pending writes.
2136 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
2137 IgnoreResult(InvokeWithoutArgs(&connection_,
2138 &TestConnection::SendStreamData3)),
2139 IgnoreResult(InvokeWithoutArgs(&connection_,
2140 &TestConnection::SendStreamData5))));
2141 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillOnce(Return(true));
2142 EXPECT_CALL(*send_algorithm_,
2143 TimeUntilSend(_, _, _)).WillRepeatedly(
2144 testing::Return(QuicTime::Delta::Zero()));
2146 connection_.OnCanWrite();
2148 // Parse the last packet and ensure it's the two stream frames from
2149 // two different streams.
2150 EXPECT_EQ(2u, writer_->frame_count());
2151 EXPECT_EQ(2u, writer_->stream_frames().size());
2152 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id);
2153 EXPECT_EQ(kClientDataStreamId2, writer_->stream_frames()[1].stream_id);
2156 TEST_P(QuicConnectionTest, RetransmitOnNack) {
2157 QuicPacketSequenceNumber last_packet;
2158 QuicByteCount second_packet_size;
2159 SendStreamDataToPeer(3, "foo", 0, !kFin, &last_packet); // Packet 1
2160 second_packet_size =
2161 SendStreamDataToPeer(3, "foos", 3, !kFin, &last_packet); // Packet 2
2162 SendStreamDataToPeer(3, "fooos", 7, !kFin, &last_packet); // Packet 3
2164 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2166 // Don't lose a packet on an ack, and nothing is retransmitted.
2167 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2168 QuicAckFrame ack_one = InitAckFrame(1);
2169 ProcessAckPacket(&ack_one);
2171 // Lose a packet and ensure it triggers retransmission.
2172 QuicAckFrame nack_two = InitAckFrame(3);
2173 NackPacket(2, &nack_two);
2174 SequenceNumberSet lost_packets;
2175 lost_packets.insert(2);
2176 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2177 .WillOnce(Return(lost_packets));
2178 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2179 EXPECT_CALL(*send_algorithm_,
2180 OnPacketSent(_, _, _, second_packet_size - kQuicVersionSize, _)).
2181 Times(1);
2182 ProcessAckPacket(&nack_two);
2185 TEST_P(QuicConnectionTest, DoNotSendQueuedPacketForResetStream) {
2186 ValueRestore<bool> old_flag(&FLAGS_quic_do_not_retransmit_for_reset_streams,
2187 true);
2189 // Block the connection to queue the packet.
2190 BlockOnNextWrite();
2192 QuicStreamId stream_id = 2;
2193 connection_.SendStreamDataWithString(stream_id, "foo", 0, !kFin, nullptr);
2195 // Now that there is a queued packet, reset the stream.
2196 connection_.SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 14);
2198 // Unblock the connection and verify that only the RST_STREAM is sent.
2199 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2200 writer_->SetWritable();
2201 connection_.OnCanWrite();
2202 EXPECT_EQ(1u, writer_->frame_count());
2203 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
2206 TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnNack) {
2207 ValueRestore<bool> old_flag(&FLAGS_quic_do_not_retransmit_for_reset_streams,
2208 true);
2210 QuicStreamId stream_id = 2;
2211 QuicPacketSequenceNumber last_packet;
2212 SendStreamDataToPeer(stream_id, "foo", 0, !kFin, &last_packet);
2213 SendStreamDataToPeer(stream_id, "foos", 3, !kFin, &last_packet);
2214 SendStreamDataToPeer(stream_id, "fooos", 7, !kFin, &last_packet);
2216 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2217 connection_.SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 14);
2219 // Lose a packet and ensure it does not trigger retransmission.
2220 QuicAckFrame nack_two = InitAckFrame(last_packet);
2221 NackPacket(last_packet - 1, &nack_two);
2222 SequenceNumberSet lost_packets;
2223 lost_packets.insert(last_packet - 1);
2224 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2225 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2226 .WillOnce(Return(lost_packets));
2227 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2228 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
2229 ProcessAckPacket(&nack_two);
2232 TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnRTO) {
2233 ValueRestore<bool> old_flag(&FLAGS_quic_do_not_retransmit_for_reset_streams,
2234 true);
2236 QuicStreamId stream_id = 2;
2237 QuicPacketSequenceNumber last_packet;
2238 SendStreamDataToPeer(stream_id, "foo", 0, !kFin, &last_packet);
2240 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2241 connection_.SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 14);
2243 // Fire the RTO and verify that the RST_STREAM is resent, not stream data.
2244 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2245 clock_.AdvanceTime(DefaultRetransmissionTime());
2246 connection_.GetRetransmissionAlarm()->Fire();
2247 EXPECT_EQ(1u, writer_->frame_count());
2248 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
2249 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
2252 TEST_P(QuicConnectionTest, DoNotSendPendingRetransmissionForResetStream) {
2253 ValueRestore<bool> old_flag(&FLAGS_quic_do_not_retransmit_for_reset_streams,
2254 true);
2256 QuicStreamId stream_id = 2;
2257 QuicPacketSequenceNumber last_packet;
2258 SendStreamDataToPeer(stream_id, "foo", 0, !kFin, &last_packet);
2259 SendStreamDataToPeer(stream_id, "foos", 3, !kFin, &last_packet);
2260 BlockOnNextWrite();
2261 connection_.SendStreamDataWithString(stream_id, "fooos", 7, !kFin, nullptr);
2263 // Lose a packet which will trigger a pending retransmission.
2264 QuicAckFrame ack = InitAckFrame(last_packet);
2265 NackPacket(last_packet - 1, &ack);
2266 SequenceNumberSet lost_packets;
2267 lost_packets.insert(last_packet - 1);
2268 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2269 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2270 .WillOnce(Return(lost_packets));
2271 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2272 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
2273 ProcessAckPacket(&ack);
2275 connection_.SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 14);
2277 // Unblock the connection and verify that the RST_STREAM is sent but not the
2278 // second data packet nor a retransmit.
2279 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2280 writer_->SetWritable();
2281 connection_.OnCanWrite();
2282 EXPECT_EQ(1u, writer_->frame_count());
2283 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
2284 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
2287 TEST_P(QuicConnectionTest, DiscardRetransmit) {
2288 QuicPacketSequenceNumber last_packet;
2289 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet); // Packet 1
2290 SendStreamDataToPeer(1, "foos", 3, !kFin, &last_packet); // Packet 2
2291 SendStreamDataToPeer(1, "fooos", 7, !kFin, &last_packet); // Packet 3
2293 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2295 // Instigate a loss with an ack.
2296 QuicAckFrame nack_two = InitAckFrame(3);
2297 NackPacket(2, &nack_two);
2298 // The first nack should trigger a fast retransmission, but we'll be
2299 // write blocked, so the packet will be queued.
2300 BlockOnNextWrite();
2301 SequenceNumberSet lost_packets;
2302 lost_packets.insert(2);
2303 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2304 .WillOnce(Return(lost_packets));
2305 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2306 ProcessAckPacket(&nack_two);
2307 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2309 // Now, ack the previous transmission.
2310 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2311 .WillOnce(Return(SequenceNumberSet()));
2312 QuicAckFrame ack_all = InitAckFrame(3);
2313 ProcessAckPacket(&ack_all);
2315 // Unblock the socket and attempt to send the queued packets. However,
2316 // since the previous transmission has been acked, we will not
2317 // send the retransmission.
2318 EXPECT_CALL(*send_algorithm_,
2319 OnPacketSent(_, _, _, _, _)).Times(0);
2321 writer_->SetWritable();
2322 connection_.OnCanWrite();
2324 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2327 TEST_P(QuicConnectionTest, RetransmitNackedLargestObserved) {
2328 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2329 QuicPacketSequenceNumber largest_observed;
2330 QuicByteCount packet_size;
2331 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2332 .WillOnce(DoAll(SaveArg<2>(&largest_observed), SaveArg<3>(&packet_size),
2333 Return(true)));
2334 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
2336 QuicAckFrame frame = InitAckFrame(1);
2337 NackPacket(largest_observed, &frame);
2338 // The first nack should retransmit the largest observed packet.
2339 SequenceNumberSet lost_packets;
2340 lost_packets.insert(1);
2341 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2342 .WillOnce(Return(lost_packets));
2343 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2344 EXPECT_CALL(*send_algorithm_,
2345 OnPacketSent(_, _, _, packet_size - kQuicVersionSize, _));
2346 ProcessAckPacket(&frame);
2349 TEST_P(QuicConnectionTest, QueueAfterTwoRTOs) {
2350 for (int i = 0; i < 10; ++i) {
2351 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2352 connection_.SendStreamDataWithString(3, "foo", i * 3, !kFin, nullptr);
2355 // Block the writer and ensure they're queued.
2356 BlockOnNextWrite();
2357 clock_.AdvanceTime(DefaultRetransmissionTime());
2358 // Only one packet should be retransmitted.
2359 connection_.GetRetransmissionAlarm()->Fire();
2360 EXPECT_TRUE(connection_.HasQueuedData());
2362 // Unblock the writer.
2363 writer_->SetWritable();
2364 clock_.AdvanceTime(QuicTime::Delta::FromMicroseconds(
2365 2 * DefaultRetransmissionTime().ToMicroseconds()));
2366 // Retransmit already retransmitted packets event though the sequence number
2367 // greater than the largest observed.
2368 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
2369 connection_.GetRetransmissionAlarm()->Fire();
2370 connection_.OnCanWrite();
2373 TEST_P(QuicConnectionTest, WriteBlockedThenSent) {
2374 BlockOnNextWrite();
2375 writer_->set_is_write_blocked_data_buffered(true);
2376 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2377 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
2378 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2380 writer_->SetWritable();
2381 connection_.OnCanWrite();
2382 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2385 TEST_P(QuicConnectionTest, RetransmitWriteBlockedAckedOriginalThenSent) {
2386 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2387 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
2388 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2390 BlockOnNextWrite();
2391 writer_->set_is_write_blocked_data_buffered(true);
2392 // Simulate the retransmission alarm firing.
2393 clock_.AdvanceTime(DefaultRetransmissionTime());
2394 connection_.GetRetransmissionAlarm()->Fire();
2396 // Ack the sent packet before the callback returns, which happens in
2397 // rare circumstances with write blocked sockets.
2398 QuicAckFrame ack = InitAckFrame(1);
2399 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2400 ProcessAckPacket(&ack);
2402 writer_->SetWritable();
2403 connection_.OnCanWrite();
2404 // There is now a pending packet, but with no retransmittable frames.
2405 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2406 EXPECT_FALSE(connection_.sent_packet_manager().HasRetransmittableFrames(2));
2409 TEST_P(QuicConnectionTest, AlarmsWhenWriteBlocked) {
2410 // Block the connection.
2411 BlockOnNextWrite();
2412 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
2413 EXPECT_EQ(1u, writer_->packets_write_attempts());
2414 EXPECT_TRUE(writer_->IsWriteBlocked());
2416 // Set the send and resumption alarms. Fire the alarms and ensure they don't
2417 // attempt to write.
2418 connection_.GetResumeWritesAlarm()->Set(clock_.ApproximateNow());
2419 connection_.GetSendAlarm()->Set(clock_.ApproximateNow());
2420 connection_.GetResumeWritesAlarm()->Fire();
2421 connection_.GetSendAlarm()->Fire();
2422 EXPECT_TRUE(writer_->IsWriteBlocked());
2423 EXPECT_EQ(1u, writer_->packets_write_attempts());
2426 TEST_P(QuicConnectionTest, NoLimitPacketsPerNack) {
2427 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2428 int offset = 0;
2429 // Send packets 1 to 15.
2430 for (int i = 0; i < 15; ++i) {
2431 SendStreamDataToPeer(1, "foo", offset, !kFin, nullptr);
2432 offset += 3;
2435 // Ack 15, nack 1-14.
2436 SequenceNumberSet lost_packets;
2437 QuicAckFrame nack = InitAckFrame(15);
2438 for (int i = 1; i < 15; ++i) {
2439 NackPacket(i, &nack);
2440 lost_packets.insert(i);
2443 // 14 packets have been NACK'd and lost. In TCP cubic, PRR limits
2444 // the retransmission rate in the case of burst losses.
2445 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2446 .WillOnce(Return(lost_packets));
2447 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2448 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(14);
2449 ProcessAckPacket(&nack);
2452 // Test sending multiple acks from the connection to the session.
2453 TEST_P(QuicConnectionTest, MultipleAcks) {
2454 QuicPacketSequenceNumber last_packet;
2455 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet); // Packet 1
2456 EXPECT_EQ(1u, last_packet);
2457 SendStreamDataToPeer(3, "foo", 0, !kFin, &last_packet); // Packet 2
2458 EXPECT_EQ(2u, last_packet);
2459 SendAckPacketToPeer(); // Packet 3
2460 SendStreamDataToPeer(5, "foo", 0, !kFin, &last_packet); // Packet 4
2461 EXPECT_EQ(4u, last_packet);
2462 SendStreamDataToPeer(1, "foo", 3, !kFin, &last_packet); // Packet 5
2463 EXPECT_EQ(5u, last_packet);
2464 SendStreamDataToPeer(3, "foo", 3, !kFin, &last_packet); // Packet 6
2465 EXPECT_EQ(6u, last_packet);
2467 // Client will ack packets 1, 2, [!3], 4, 5.
2468 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2469 QuicAckFrame frame1 = InitAckFrame(5);
2470 NackPacket(3, &frame1);
2471 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2472 ProcessAckPacket(&frame1);
2474 // Now the client implicitly acks 3, and explicitly acks 6.
2475 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2476 QuicAckFrame frame2 = InitAckFrame(6);
2477 ProcessAckPacket(&frame2);
2480 TEST_P(QuicConnectionTest, DontLatchUnackedPacket) {
2481 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr); // Packet 1;
2482 // From now on, we send acks, so the send algorithm won't mark them pending.
2483 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2484 .WillByDefault(Return(false));
2485 SendAckPacketToPeer(); // Packet 2
2487 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2488 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2489 QuicAckFrame frame = InitAckFrame(1);
2490 ProcessAckPacket(&frame);
2492 // Verify that our internal state has least-unacked as 2, because we're still
2493 // waiting for a potential ack for 2.
2495 EXPECT_EQ(2u, stop_waiting()->least_unacked);
2497 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2498 frame = InitAckFrame(2);
2499 ProcessAckPacket(&frame);
2500 EXPECT_EQ(3u, stop_waiting()->least_unacked);
2502 // When we send an ack, we make sure our least-unacked makes sense. In this
2503 // case since we're not waiting on an ack for 2 and all packets are acked, we
2504 // set it to 3.
2505 SendAckPacketToPeer(); // Packet 3
2506 // Least_unacked remains at 3 until another ack is received.
2507 EXPECT_EQ(3u, stop_waiting()->least_unacked);
2508 // Check that the outgoing ack had its sequence number as least_unacked.
2509 EXPECT_EQ(3u, least_unacked());
2511 // Ack the ack, which updates the rtt and raises the least unacked.
2512 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2513 frame = InitAckFrame(3);
2514 ProcessAckPacket(&frame);
2516 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2517 .WillByDefault(Return(true));
2518 SendStreamDataToPeer(1, "bar", 3, false, nullptr); // Packet 4
2519 EXPECT_EQ(4u, stop_waiting()->least_unacked);
2520 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2521 .WillByDefault(Return(false));
2522 SendAckPacketToPeer(); // Packet 5
2523 EXPECT_EQ(4u, least_unacked());
2525 // Send two data packets at the end, and ensure if the last one is acked,
2526 // the least unacked is raised above the ack packets.
2527 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2528 .WillByDefault(Return(true));
2529 SendStreamDataToPeer(1, "bar", 6, false, nullptr); // Packet 6
2530 SendStreamDataToPeer(1, "bar", 9, false, nullptr); // Packet 7
2532 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2533 frame = InitAckFrame(7);
2534 NackPacket(5, &frame);
2535 NackPacket(6, &frame);
2536 ProcessAckPacket(&frame);
2538 EXPECT_EQ(6u, stop_waiting()->least_unacked);
2541 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterFecPacket) {
2542 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2544 // Don't send missing packet 1.
2545 ProcessFecPacket(2, 1, true, !kEntropyFlag, nullptr);
2546 // Entropy flag should be false, so entropy should be 0.
2547 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2550 TEST_P(QuicConnectionTest, ReviveMissingPacketWithVaryingSeqNumLengths) {
2551 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2553 // Set up a debug visitor to the connection.
2554 scoped_ptr<FecQuicConnectionDebugVisitor> fec_visitor(
2555 new FecQuicConnectionDebugVisitor());
2556 connection_.set_debug_visitor(fec_visitor.get());
2558 QuicPacketSequenceNumber fec_packet = 0;
2559 QuicSequenceNumberLength lengths[] = {PACKET_6BYTE_SEQUENCE_NUMBER,
2560 PACKET_4BYTE_SEQUENCE_NUMBER,
2561 PACKET_2BYTE_SEQUENCE_NUMBER,
2562 PACKET_1BYTE_SEQUENCE_NUMBER};
2563 // For each sequence number length size, revive a packet and check sequence
2564 // number length in the revived packet.
2565 for (size_t i = 0; i < arraysize(lengths); ++i) {
2566 // Set sequence_number_length_ (for data and FEC packets).
2567 sequence_number_length_ = lengths[i];
2568 fec_packet += 2;
2569 // Don't send missing packet, but send fec packet right after it.
2570 ProcessFecPacket(fec_packet, fec_packet - 1, true, !kEntropyFlag, nullptr);
2571 // Sequence number length in the revived header should be the same as
2572 // in the original data/fec packet headers.
2573 EXPECT_EQ(sequence_number_length_, fec_visitor->revived_header().
2574 public_header.sequence_number_length);
2578 TEST_P(QuicConnectionTest, ReviveMissingPacketWithVaryingConnectionIdLengths) {
2579 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2581 // Set up a debug visitor to the connection.
2582 scoped_ptr<FecQuicConnectionDebugVisitor> fec_visitor(
2583 new FecQuicConnectionDebugVisitor());
2584 connection_.set_debug_visitor(fec_visitor.get());
2586 QuicPacketSequenceNumber fec_packet = 0;
2587 QuicConnectionIdLength lengths[] = {PACKET_8BYTE_CONNECTION_ID,
2588 PACKET_4BYTE_CONNECTION_ID,
2589 PACKET_1BYTE_CONNECTION_ID,
2590 PACKET_0BYTE_CONNECTION_ID};
2591 // For each connection id length size, revive a packet and check connection
2592 // id length in the revived packet.
2593 for (size_t i = 0; i < arraysize(lengths); ++i) {
2594 // Set connection id length (for data and FEC packets).
2595 connection_id_length_ = lengths[i];
2596 fec_packet += 2;
2597 // Don't send missing packet, but send fec packet right after it.
2598 ProcessFecPacket(fec_packet, fec_packet - 1, true, !kEntropyFlag, nullptr);
2599 // Connection id length in the revived header should be the same as
2600 // in the original data/fec packet headers.
2601 EXPECT_EQ(connection_id_length_,
2602 fec_visitor->revived_header().public_header.connection_id_length);
2606 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPacketThenFecPacket) {
2607 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2609 ProcessFecProtectedPacket(1, false, kEntropyFlag);
2610 // Don't send missing packet 2.
2611 ProcessFecPacket(3, 1, true, !kEntropyFlag, nullptr);
2612 // Entropy flag should be true, so entropy should not be 0.
2613 EXPECT_NE(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2616 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPacketsThenFecPacket) {
2617 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2619 ProcessFecProtectedPacket(1, false, !kEntropyFlag);
2620 // Don't send missing packet 2.
2621 ProcessFecProtectedPacket(3, false, !kEntropyFlag);
2622 ProcessFecPacket(4, 1, true, kEntropyFlag, nullptr);
2623 // Ensure QUIC no longer revives entropy for lost packets.
2624 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2625 EXPECT_NE(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 4));
2628 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPacket) {
2629 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2631 // Don't send missing packet 1.
2632 ProcessFecPacket(3, 1, false, !kEntropyFlag, nullptr);
2633 // Out of order.
2634 ProcessFecProtectedPacket(2, true, !kEntropyFlag);
2635 // Entropy flag should be false, so entropy should be 0.
2636 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2639 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPackets) {
2640 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2642 ProcessFecProtectedPacket(1, false, !kEntropyFlag);
2643 // Don't send missing packet 2.
2644 ProcessFecPacket(6, 1, false, kEntropyFlag, nullptr);
2645 ProcessFecProtectedPacket(3, false, kEntropyFlag);
2646 ProcessFecProtectedPacket(4, false, kEntropyFlag);
2647 ProcessFecProtectedPacket(5, true, !kEntropyFlag);
2648 // Ensure entropy is not revived for the missing packet.
2649 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2650 EXPECT_NE(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 3));
2653 TEST_P(QuicConnectionTest, TLP) {
2654 QuicSentPacketManagerPeer::SetMaxTailLossProbes(manager_, 1);
2656 SendStreamDataToPeer(3, "foo", 0, !kFin, nullptr);
2657 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2658 QuicTime retransmission_time =
2659 connection_.GetRetransmissionAlarm()->deadline();
2660 EXPECT_NE(QuicTime::Zero(), retransmission_time);
2662 EXPECT_EQ(1u, writer_->header().packet_sequence_number);
2663 // Simulate the retransmission alarm firing and sending a tlp,
2664 // so send algorithm's OnRetransmissionTimeout is not called.
2665 clock_.AdvanceTime(retransmission_time.Subtract(clock_.Now()));
2666 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 2u, _, _));
2667 connection_.GetRetransmissionAlarm()->Fire();
2668 EXPECT_EQ(2u, writer_->header().packet_sequence_number);
2669 // We do not raise the high water mark yet.
2670 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2673 TEST_P(QuicConnectionTest, RTO) {
2674 QuicTime default_retransmission_time = clock_.ApproximateNow().Add(
2675 DefaultRetransmissionTime());
2676 SendStreamDataToPeer(3, "foo", 0, !kFin, nullptr);
2677 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2679 EXPECT_EQ(1u, writer_->header().packet_sequence_number);
2680 EXPECT_EQ(default_retransmission_time,
2681 connection_.GetRetransmissionAlarm()->deadline());
2682 // Simulate the retransmission alarm firing.
2683 clock_.AdvanceTime(DefaultRetransmissionTime());
2684 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 2u, _, _));
2685 connection_.GetRetransmissionAlarm()->Fire();
2686 EXPECT_EQ(2u, writer_->header().packet_sequence_number);
2687 // We do not raise the high water mark yet.
2688 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2691 TEST_P(QuicConnectionTest, RTOWithSameEncryptionLevel) {
2692 QuicTime default_retransmission_time = clock_.ApproximateNow().Add(
2693 DefaultRetransmissionTime());
2694 use_tagging_decrypter();
2696 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
2697 // the end of the packet. We can test this to check which encrypter was used.
2698 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2699 SendStreamDataToPeer(3, "foo", 0, !kFin, nullptr);
2700 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
2702 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2703 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2704 SendStreamDataToPeer(3, "foo", 0, !kFin, nullptr);
2705 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2707 EXPECT_EQ(default_retransmission_time,
2708 connection_.GetRetransmissionAlarm()->deadline());
2710 InSequence s;
2711 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 3, _, _));
2712 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 4, _, _));
2715 // Simulate the retransmission alarm firing.
2716 clock_.AdvanceTime(DefaultRetransmissionTime());
2717 connection_.GetRetransmissionAlarm()->Fire();
2719 // Packet should have been sent with ENCRYPTION_NONE.
2720 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_previous_packet());
2722 // Packet should have been sent with ENCRYPTION_INITIAL.
2723 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2726 TEST_P(QuicConnectionTest, SendHandshakeMessages) {
2727 use_tagging_decrypter();
2728 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
2729 // the end of the packet. We can test this to check which encrypter was used.
2730 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2732 // Attempt to send a handshake message and have the socket block.
2733 EXPECT_CALL(*send_algorithm_,
2734 TimeUntilSend(_, _, _)).WillRepeatedly(
2735 testing::Return(QuicTime::Delta::Zero()));
2736 BlockOnNextWrite();
2737 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
2738 // The packet should be serialized, but not queued.
2739 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2741 // Switch to the new encrypter.
2742 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2743 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2745 // Now become writeable and flush the packets.
2746 writer_->SetWritable();
2747 EXPECT_CALL(visitor_, OnCanWrite());
2748 connection_.OnCanWrite();
2749 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2751 // Verify that the handshake packet went out at the null encryption.
2752 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
2755 TEST_P(QuicConnectionTest,
2756 DropRetransmitsForNullEncryptedPacketAfterForwardSecure) {
2757 use_tagging_decrypter();
2758 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2759 QuicPacketSequenceNumber sequence_number;
2760 SendStreamDataToPeer(3, "foo", 0, !kFin, &sequence_number);
2762 // Simulate the retransmission alarm firing and the socket blocking.
2763 BlockOnNextWrite();
2764 clock_.AdvanceTime(DefaultRetransmissionTime());
2765 connection_.GetRetransmissionAlarm()->Fire();
2767 // Go forward secure.
2768 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
2769 new TaggingEncrypter(0x02));
2770 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2771 connection_.NeuterUnencryptedPackets();
2773 EXPECT_EQ(QuicTime::Zero(),
2774 connection_.GetRetransmissionAlarm()->deadline());
2775 // Unblock the socket and ensure that no packets are sent.
2776 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
2777 writer_->SetWritable();
2778 connection_.OnCanWrite();
2781 TEST_P(QuicConnectionTest, RetransmitPacketsWithInitialEncryption) {
2782 use_tagging_decrypter();
2783 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2784 connection_.SetDefaultEncryptionLevel(ENCRYPTION_NONE);
2786 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr);
2788 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2789 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2791 SendStreamDataToPeer(2, "bar", 0, !kFin, nullptr);
2792 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2794 connection_.RetransmitUnackedPackets(ALL_INITIAL_RETRANSMISSION);
2797 TEST_P(QuicConnectionTest, DelayForwardSecureEncryptionUntilClientIsReady) {
2798 // A TaggingEncrypter puts kTagSize copies of the given byte (0x02 here) at
2799 // the end of the packet. We can test this to check which encrypter was used.
2800 use_tagging_decrypter();
2801 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2802 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2803 SendAckPacketToPeer();
2804 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2806 // Set a forward-secure encrypter but do not make it the default, and verify
2807 // that it is not yet used.
2808 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
2809 new TaggingEncrypter(0x03));
2810 SendAckPacketToPeer();
2811 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2813 // Now simulate receipt of a forward-secure packet and verify that the
2814 // forward-secure encrypter is now used.
2815 connection_.OnDecryptedPacket(ENCRYPTION_FORWARD_SECURE);
2816 SendAckPacketToPeer();
2817 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
2820 TEST_P(QuicConnectionTest, DelayForwardSecureEncryptionUntilManyPacketSent) {
2821 // Set a congestion window of 10 packets.
2822 QuicPacketCount congestion_window = 10;
2823 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
2824 Return(congestion_window * kDefaultMaxPacketSize));
2826 // A TaggingEncrypter puts kTagSize copies of the given byte (0x02 here) at
2827 // the end of the packet. We can test this to check which encrypter was used.
2828 use_tagging_decrypter();
2829 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2830 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2831 SendAckPacketToPeer();
2832 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2834 // Set a forward-secure encrypter but do not make it the default, and
2835 // verify that it is not yet used.
2836 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
2837 new TaggingEncrypter(0x03));
2838 SendAckPacketToPeer();
2839 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2841 // Now send a packet "Far enough" after the encrypter was set and verify that
2842 // the forward-secure encrypter is now used.
2843 for (uint64 i = 0; i < 3 * congestion_window - 1; ++i) {
2844 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2845 SendAckPacketToPeer();
2847 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
2850 TEST_P(QuicConnectionTest, BufferNonDecryptablePackets) {
2851 // SetFromConfig is always called after construction from InitializeSession.
2852 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
2853 QuicConfig config;
2854 connection_.SetFromConfig(config);
2855 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2856 use_tagging_decrypter();
2858 const uint8 tag = 0x07;
2859 framer_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
2861 // Process an encrypted packet which can not yet be decrypted which should
2862 // result in the packet being buffered.
2863 ProcessDataPacketAtLevel(1, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2865 // Transition to the new encryption state and process another encrypted packet
2866 // which should result in the original packet being processed.
2867 connection_.SetDecrypter(new StrictTaggingDecrypter(tag),
2868 ENCRYPTION_INITIAL);
2869 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2870 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
2871 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(2);
2872 ProcessDataPacketAtLevel(2, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2874 // Finally, process a third packet and note that we do not reprocess the
2875 // buffered packet.
2876 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
2877 ProcessDataPacketAtLevel(3, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2880 TEST_P(QuicConnectionTest, Buffer100NonDecryptablePackets) {
2881 // SetFromConfig is always called after construction from InitializeSession.
2882 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
2883 QuicConfig config;
2884 config.set_max_undecryptable_packets(100);
2885 connection_.SetFromConfig(config);
2886 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2887 use_tagging_decrypter();
2889 const uint8 tag = 0x07;
2890 framer_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
2892 // Process an encrypted packet which can not yet be decrypted which should
2893 // result in the packet being buffered.
2894 for (QuicPacketSequenceNumber i = 1; i <= 100; ++i) {
2895 ProcessDataPacketAtLevel(i, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2898 // Transition to the new encryption state and process another encrypted packet
2899 // which should result in the original packets being processed.
2900 connection_.SetDecrypter(new StrictTaggingDecrypter(tag), ENCRYPTION_INITIAL);
2901 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2902 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
2903 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(101);
2904 ProcessDataPacketAtLevel(101, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2906 // Finally, process a third packet and note that we do not reprocess the
2907 // buffered packet.
2908 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
2909 ProcessDataPacketAtLevel(102, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2912 TEST_P(QuicConnectionTest, TestRetransmitOrder) {
2913 QuicByteCount first_packet_size;
2914 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).WillOnce(
2915 DoAll(SaveArg<3>(&first_packet_size), Return(true)));
2917 connection_.SendStreamDataWithString(3, "first_packet", 0, !kFin, nullptr);
2918 QuicByteCount second_packet_size;
2919 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).WillOnce(
2920 DoAll(SaveArg<3>(&second_packet_size), Return(true)));
2921 connection_.SendStreamDataWithString(3, "second_packet", 12, !kFin, nullptr);
2922 EXPECT_NE(first_packet_size, second_packet_size);
2923 // Advance the clock by huge time to make sure packets will be retransmitted.
2924 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
2926 InSequence s;
2927 EXPECT_CALL(*send_algorithm_,
2928 OnPacketSent(_, _, _, first_packet_size, _));
2929 EXPECT_CALL(*send_algorithm_,
2930 OnPacketSent(_, _, _, second_packet_size, _));
2932 connection_.GetRetransmissionAlarm()->Fire();
2934 // Advance again and expect the packets to be sent again in the same order.
2935 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(20));
2937 InSequence s;
2938 EXPECT_CALL(*send_algorithm_,
2939 OnPacketSent(_, _, _, first_packet_size, _));
2940 EXPECT_CALL(*send_algorithm_,
2941 OnPacketSent(_, _, _, second_packet_size, _));
2943 connection_.GetRetransmissionAlarm()->Fire();
2946 TEST_P(QuicConnectionTest, SetRTOAfterWritingToSocket) {
2947 BlockOnNextWrite();
2948 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
2949 // Make sure that RTO is not started when the packet is queued.
2950 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
2952 // Test that RTO is started once we write to the socket.
2953 writer_->SetWritable();
2954 connection_.OnCanWrite();
2955 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2958 TEST_P(QuicConnectionTest, DelayRTOWithAckReceipt) {
2959 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2960 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2961 .Times(2);
2962 connection_.SendStreamDataWithString(2, "foo", 0, !kFin, nullptr);
2963 connection_.SendStreamDataWithString(3, "bar", 0, !kFin, nullptr);
2964 QuicAlarm* retransmission_alarm = connection_.GetRetransmissionAlarm();
2965 EXPECT_TRUE(retransmission_alarm->IsSet());
2966 EXPECT_EQ(clock_.Now().Add(DefaultRetransmissionTime()),
2967 retransmission_alarm->deadline());
2969 // Advance the time right before the RTO, then receive an ack for the first
2970 // packet to delay the RTO.
2971 clock_.AdvanceTime(DefaultRetransmissionTime());
2972 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2973 QuicAckFrame ack = InitAckFrame(1);
2974 ProcessAckPacket(&ack);
2975 EXPECT_TRUE(retransmission_alarm->IsSet());
2976 EXPECT_GT(retransmission_alarm->deadline(), clock_.Now());
2978 // Move forward past the original RTO and ensure the RTO is still pending.
2979 clock_.AdvanceTime(DefaultRetransmissionTime().Multiply(2));
2981 // Ensure the second packet gets retransmitted when it finally fires.
2982 EXPECT_TRUE(retransmission_alarm->IsSet());
2983 EXPECT_LT(retransmission_alarm->deadline(), clock_.ApproximateNow());
2984 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2985 // Manually cancel the alarm to simulate a real test.
2986 connection_.GetRetransmissionAlarm()->Fire();
2988 // The new retransmitted sequence number should set the RTO to a larger value
2989 // than previously.
2990 EXPECT_TRUE(retransmission_alarm->IsSet());
2991 QuicTime next_rto_time = retransmission_alarm->deadline();
2992 QuicTime expected_rto_time =
2993 connection_.sent_packet_manager().GetRetransmissionTime();
2994 EXPECT_EQ(next_rto_time, expected_rto_time);
2997 TEST_P(QuicConnectionTest, TestQueued) {
2998 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2999 BlockOnNextWrite();
3000 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
3001 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3003 // Unblock the writes and actually send.
3004 writer_->SetWritable();
3005 connection_.OnCanWrite();
3006 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3009 TEST_P(QuicConnectionTest, CloseFecGroup) {
3010 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3011 // Don't send missing packet 1.
3012 // Don't send missing packet 2.
3013 ProcessFecProtectedPacket(3, false, !kEntropyFlag);
3014 // Don't send missing FEC packet 3.
3015 ASSERT_EQ(1u, connection_.NumFecGroups());
3017 // Now send non-fec protected ack packet and close the group.
3018 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 4);
3019 QuicStopWaitingFrame frame = InitStopWaitingFrame(5);
3020 ProcessStopWaitingPacket(&frame);
3021 ASSERT_EQ(0u, connection_.NumFecGroups());
3024 TEST_P(QuicConnectionTest, InitialTimeout) {
3025 EXPECT_TRUE(connection_.connected());
3026 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
3027 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3029 // SetFromConfig sets the initial timeouts before negotiation.
3030 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3031 QuicConfig config;
3032 connection_.SetFromConfig(config);
3033 // Subtract a second from the idle timeout on the client side.
3034 QuicTime default_timeout = clock_.ApproximateNow().Add(
3035 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1));
3036 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
3038 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_CONNECTION_TIMED_OUT, false));
3039 // Simulate the timeout alarm firing.
3040 clock_.AdvanceTime(
3041 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1));
3042 connection_.GetTimeoutAlarm()->Fire();
3044 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3045 EXPECT_FALSE(connection_.connected());
3047 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3048 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
3049 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
3050 EXPECT_FALSE(connection_.GetResumeWritesAlarm()->IsSet());
3051 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3052 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
3055 TEST_P(QuicConnectionTest, OverallTimeout) {
3056 // Use a shorter overall connection timeout than idle timeout for this test.
3057 const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(5);
3058 connection_.SetNetworkTimeouts(timeout, timeout);
3059 EXPECT_TRUE(connection_.connected());
3060 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
3062 QuicTime overall_timeout = clock_.ApproximateNow().Add(timeout).Subtract(
3063 QuicTime::Delta::FromSeconds(1));
3064 EXPECT_EQ(overall_timeout, connection_.GetTimeoutAlarm()->deadline());
3065 EXPECT_TRUE(connection_.connected());
3067 // Send and ack new data 3 seconds later to lengthen the idle timeout.
3068 SendStreamDataToPeer(1, "GET /", 0, kFin, nullptr);
3069 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(3));
3070 QuicAckFrame frame = InitAckFrame(1);
3071 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3072 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3073 ProcessAckPacket(&frame);
3075 // Fire early to verify it wouldn't timeout yet.
3076 connection_.GetTimeoutAlarm()->Fire();
3077 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
3078 EXPECT_TRUE(connection_.connected());
3080 clock_.AdvanceTime(timeout.Subtract(QuicTime::Delta::FromSeconds(2)));
3082 EXPECT_CALL(visitor_,
3083 OnConnectionClosed(QUIC_CONNECTION_OVERALL_TIMED_OUT, false));
3084 // Simulate the timeout alarm firing.
3085 connection_.GetTimeoutAlarm()->Fire();
3087 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3088 EXPECT_FALSE(connection_.connected());
3090 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3091 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
3092 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
3093 EXPECT_FALSE(connection_.GetResumeWritesAlarm()->IsSet());
3094 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3095 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
3098 TEST_P(QuicConnectionTest, PingAfterSend) {
3099 EXPECT_TRUE(connection_.connected());
3100 EXPECT_CALL(visitor_, HasOpenDataStreams()).WillRepeatedly(Return(true));
3101 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
3103 // Advance to 5ms, and send a packet to the peer, which will set
3104 // the ping alarm.
3105 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
3106 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3107 SendStreamDataToPeer(1, "GET /", 0, kFin, nullptr);
3108 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
3109 EXPECT_EQ(clock_.ApproximateNow().Add(QuicTime::Delta::FromSeconds(15)),
3110 connection_.GetPingAlarm()->deadline());
3112 // Now recevie and ACK of the previous packet, which will move the
3113 // ping alarm forward.
3114 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
3115 QuicAckFrame frame = InitAckFrame(1);
3116 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3117 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3118 ProcessAckPacket(&frame);
3119 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
3120 // The ping timer is set slightly less than 15 seconds in the future, because
3121 // of the 1s ping timer alarm granularity.
3122 EXPECT_EQ(clock_.ApproximateNow().Add(QuicTime::Delta::FromSeconds(15))
3123 .Subtract(QuicTime::Delta::FromMilliseconds(5)),
3124 connection_.GetPingAlarm()->deadline());
3126 writer_->Reset();
3127 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15));
3128 connection_.GetPingAlarm()->Fire();
3129 EXPECT_EQ(1u, writer_->frame_count());
3130 ASSERT_EQ(1u, writer_->ping_frames().size());
3131 writer_->Reset();
3133 EXPECT_CALL(visitor_, HasOpenDataStreams()).WillRepeatedly(Return(false));
3134 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
3135 SendAckPacketToPeer();
3137 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
3140 TEST_P(QuicConnectionTest, TimeoutAfterSend) {
3141 EXPECT_TRUE(connection_.connected());
3142 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3143 QuicConfig config;
3144 connection_.SetFromConfig(config);
3145 EXPECT_FALSE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
3147 const QuicTime::Delta initial_idle_timeout =
3148 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
3149 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
3150 QuicTime default_timeout = clock_.ApproximateNow().Add(initial_idle_timeout);
3152 // When we send a packet, the timeout will change to 5ms +
3153 // kInitialIdleTimeoutSecs.
3154 clock_.AdvanceTime(five_ms);
3156 // Send an ack so we don't set the retransmission alarm.
3157 SendAckPacketToPeer();
3158 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
3160 // The original alarm will fire. We should not time out because we had a
3161 // network event at t=5ms. The alarm will reregister.
3162 clock_.AdvanceTime(initial_idle_timeout.Subtract(five_ms));
3163 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
3164 connection_.GetTimeoutAlarm()->Fire();
3165 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
3166 EXPECT_TRUE(connection_.connected());
3167 EXPECT_EQ(default_timeout.Add(five_ms),
3168 connection_.GetTimeoutAlarm()->deadline());
3170 // This time, we should time out.
3171 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_CONNECTION_TIMED_OUT, false));
3172 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3173 clock_.AdvanceTime(five_ms);
3174 EXPECT_EQ(default_timeout.Add(five_ms), clock_.ApproximateNow());
3175 connection_.GetTimeoutAlarm()->Fire();
3176 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3177 EXPECT_FALSE(connection_.connected());
3180 TEST_P(QuicConnectionTest, TimeoutAfterSendSilentClose) {
3181 // Same test as above, but complete a handshake which enables silent close,
3182 // causing no connection close packet to be sent.
3183 EXPECT_TRUE(connection_.connected());
3184 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3185 QuicConfig config;
3187 // Create a handshake message that also enables silent close.
3188 CryptoHandshakeMessage msg;
3189 string error_details;
3190 QuicConfig client_config;
3191 client_config.SetInitialStreamFlowControlWindowToSend(
3192 kInitialStreamFlowControlWindowForTest);
3193 client_config.SetInitialSessionFlowControlWindowToSend(
3194 kInitialSessionFlowControlWindowForTest);
3195 client_config.SetIdleConnectionStateLifetime(
3196 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs),
3197 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs));
3198 client_config.ToHandshakeMessage(&msg);
3199 const QuicErrorCode error =
3200 config.ProcessPeerHello(msg, CLIENT, &error_details);
3201 EXPECT_EQ(QUIC_NO_ERROR, error);
3203 connection_.SetFromConfig(config);
3204 EXPECT_TRUE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
3206 const QuicTime::Delta default_idle_timeout =
3207 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs - 1);
3208 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
3209 QuicTime default_timeout = clock_.ApproximateNow().Add(default_idle_timeout);
3211 // When we send a packet, the timeout will change to 5ms +
3212 // kInitialIdleTimeoutSecs.
3213 clock_.AdvanceTime(five_ms);
3215 // Send an ack so we don't set the retransmission alarm.
3216 SendAckPacketToPeer();
3217 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
3219 // The original alarm will fire. We should not time out because we had a
3220 // network event at t=5ms. The alarm will reregister.
3221 clock_.AdvanceTime(default_idle_timeout.Subtract(five_ms));
3222 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
3223 connection_.GetTimeoutAlarm()->Fire();
3224 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
3225 EXPECT_TRUE(connection_.connected());
3226 EXPECT_EQ(default_timeout.Add(five_ms),
3227 connection_.GetTimeoutAlarm()->deadline());
3229 // This time, we should time out.
3230 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_CONNECTION_TIMED_OUT, false));
3231 clock_.AdvanceTime(five_ms);
3232 EXPECT_EQ(default_timeout.Add(five_ms), clock_.ApproximateNow());
3233 connection_.GetTimeoutAlarm()->Fire();
3234 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3235 EXPECT_FALSE(connection_.connected());
3238 TEST_P(QuicConnectionTest, SendScheduler) {
3239 // Test that if we send a packet without delay, it is not queued.
3240 QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
3241 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3242 connection_.SendPacket(
3243 ENCRYPTION_NONE, 1, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA);
3244 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3247 TEST_P(QuicConnectionTest, SendSchedulerEAGAIN) {
3248 QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
3249 BlockOnNextWrite();
3250 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 1, _, _)).Times(0);
3251 connection_.SendPacket(
3252 ENCRYPTION_NONE, 1, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA);
3253 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3256 TEST_P(QuicConnectionTest, TestQueueLimitsOnSendStreamData) {
3257 // All packets carry version info till version is negotiated.
3258 size_t payload_length;
3259 size_t length = GetPacketLengthForOneStream(
3260 connection_.version(), kIncludeVersion,
3261 PACKET_8BYTE_CONNECTION_ID, PACKET_1BYTE_SEQUENCE_NUMBER,
3262 NOT_IN_FEC_GROUP, &payload_length);
3263 creator_->SetMaxPacketLength(length);
3265 // Queue the first packet.
3266 EXPECT_CALL(*send_algorithm_,
3267 TimeUntilSend(_, _, _)).WillOnce(
3268 testing::Return(QuicTime::Delta::FromMicroseconds(10)));
3269 const string payload(payload_length, 'a');
3270 EXPECT_EQ(0u, connection_.SendStreamDataWithString(3, payload, 0, !kFin,
3271 nullptr).bytes_consumed);
3272 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3275 TEST_P(QuicConnectionTest, LoopThroughSendingPackets) {
3276 // All packets carry version info till version is negotiated.
3277 size_t payload_length;
3278 // GetPacketLengthForOneStream() assumes a stream offset of 0 in determining
3279 // packet length. The size of the offset field in a stream frame is 0 for
3280 // offset 0, and 2 for non-zero offsets up through 16K. Increase
3281 // max_packet_length by 2 so that subsequent packets containing subsequent
3282 // stream frames with non-zero offets will fit within the packet length.
3283 size_t length = 2 + GetPacketLengthForOneStream(
3284 connection_.version(), kIncludeVersion,
3285 PACKET_8BYTE_CONNECTION_ID, PACKET_1BYTE_SEQUENCE_NUMBER,
3286 NOT_IN_FEC_GROUP, &payload_length);
3287 creator_->SetMaxPacketLength(length);
3289 // Queue the first packet.
3290 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(7);
3291 // The first stream frame will have 2 fewer overhead bytes than the other six.
3292 const string payload(payload_length * 7 + 2, 'a');
3293 EXPECT_EQ(payload.size(),
3294 connection_.SendStreamDataWithString(1, payload, 0, !kFin, nullptr)
3295 .bytes_consumed);
3298 TEST_P(QuicConnectionTest, LoopThroughSendingPacketsWithTruncation) {
3299 // Set up a larger payload than will fit in one packet.
3300 const string payload(connection_.max_packet_length(), 'a');
3301 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
3303 // Now send some packets with no truncation.
3304 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3305 EXPECT_EQ(payload.size(),
3306 connection_.SendStreamDataWithString(
3307 3, payload, 0, !kFin, nullptr).bytes_consumed);
3308 // Track the size of the second packet here. The overhead will be the largest
3309 // we see in this test, due to the non-truncated connection id.
3310 size_t non_truncated_packet_size = writer_->last_packet_size();
3312 // Change to a 4 byte connection id.
3313 QuicConfig config;
3314 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 4);
3315 connection_.SetFromConfig(config);
3316 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3317 EXPECT_EQ(payload.size(),
3318 connection_.SendStreamDataWithString(
3319 3, payload, 0, !kFin, nullptr).bytes_consumed);
3320 // Verify that we have 8 fewer bytes than in the non-truncated case. The
3321 // first packet got 4 bytes of extra payload due to the truncation, and the
3322 // headers here are also 4 byte smaller.
3323 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() + 8);
3325 // Change to a 1 byte connection id.
3326 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 1);
3327 connection_.SetFromConfig(config);
3328 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3329 EXPECT_EQ(payload.size(),
3330 connection_.SendStreamDataWithString(
3331 3, payload, 0, !kFin, nullptr).bytes_consumed);
3332 // Just like above, we save 7 bytes on payload, and 7 on truncation.
3333 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() + 7 * 2);
3335 // Change to a 0 byte connection id.
3336 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
3337 connection_.SetFromConfig(config);
3338 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3339 EXPECT_EQ(payload.size(),
3340 connection_.SendStreamDataWithString(
3341 3, payload, 0, !kFin, nullptr).bytes_consumed);
3342 // Just like above, we save 8 bytes on payload, and 8 on truncation.
3343 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() + 8 * 2);
3346 TEST_P(QuicConnectionTest, SendDelayedAck) {
3347 QuicTime ack_time = clock_.ApproximateNow().Add(DefaultDelayedAckTime());
3348 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3349 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3350 const uint8 tag = 0x07;
3351 connection_.SetDecrypter(new StrictTaggingDecrypter(tag),
3352 ENCRYPTION_INITIAL);
3353 framer_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
3354 // Process a packet from the non-crypto stream.
3355 frame1_.stream_id = 3;
3357 // The same as ProcessPacket(1) except that ENCRYPTION_INITIAL is used
3358 // instead of ENCRYPTION_NONE.
3359 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
3360 ProcessDataPacketAtLevel(1, 0, !kEntropyFlag, ENCRYPTION_INITIAL);
3362 // Check if delayed ack timer is running for the expected interval.
3363 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3364 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
3365 // Simulate delayed ack alarm firing.
3366 connection_.GetAckAlarm()->Fire();
3367 // Check that ack is sent and that delayed ack alarm is reset.
3368 EXPECT_EQ(2u, writer_->frame_count());
3369 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3370 EXPECT_FALSE(writer_->ack_frames().empty());
3371 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3374 TEST_P(QuicConnectionTest, SendDelayedAckOnHandshakeConfirmed) {
3375 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3376 ProcessPacket(1);
3377 // Check that ack is sent and that delayed ack alarm is set.
3378 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3379 QuicTime ack_time = clock_.ApproximateNow().Add(DefaultDelayedAckTime());
3380 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
3382 // Completing the handshake as the server does nothing.
3383 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_SERVER);
3384 connection_.OnHandshakeComplete();
3385 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3386 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
3388 // Complete the handshake as the client decreases the delayed ack time to 0ms.
3389 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_CLIENT);
3390 connection_.OnHandshakeComplete();
3391 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3392 EXPECT_EQ(clock_.ApproximateNow(), connection_.GetAckAlarm()->deadline());
3395 TEST_P(QuicConnectionTest, SendDelayedAckOnSecondPacket) {
3396 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3397 ProcessPacket(1);
3398 ProcessPacket(2);
3399 // Check that ack is sent and that delayed ack alarm is reset.
3400 EXPECT_EQ(2u, writer_->frame_count());
3401 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3402 EXPECT_FALSE(writer_->ack_frames().empty());
3403 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3406 TEST_P(QuicConnectionTest, NoAckOnOldNacks) {
3407 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3408 // Drop one packet, triggering a sequence of acks.
3409 ProcessPacket(2);
3410 size_t frames_per_ack = 2;
3411 EXPECT_EQ(frames_per_ack, writer_->frame_count());
3412 EXPECT_FALSE(writer_->ack_frames().empty());
3413 writer_->Reset();
3414 ProcessPacket(3);
3415 EXPECT_EQ(frames_per_ack, writer_->frame_count());
3416 EXPECT_FALSE(writer_->ack_frames().empty());
3417 writer_->Reset();
3418 ProcessPacket(4);
3419 EXPECT_EQ(frames_per_ack, writer_->frame_count());
3420 EXPECT_FALSE(writer_->ack_frames().empty());
3421 writer_->Reset();
3422 ProcessPacket(5);
3423 EXPECT_EQ(frames_per_ack, writer_->frame_count());
3424 EXPECT_FALSE(writer_->ack_frames().empty());
3425 writer_->Reset();
3426 // Now only set the timer on the 6th packet, instead of sending another ack.
3427 ProcessPacket(6);
3428 EXPECT_EQ(0u, writer_->frame_count());
3429 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3432 TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingPacket) {
3433 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3434 ProcessPacket(1);
3435 connection_.SendStreamDataWithString(kClientDataStreamId1, "foo", 0, !kFin,
3436 nullptr);
3437 // Check that ack is bundled with outgoing data and that delayed ack
3438 // alarm is reset.
3439 EXPECT_EQ(3u, writer_->frame_count());
3440 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3441 EXPECT_FALSE(writer_->ack_frames().empty());
3442 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3445 TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingCryptoPacket) {
3446 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3447 ProcessPacket(1);
3448 connection_.SendStreamDataWithString(kCryptoStreamId, "foo", 0, !kFin,
3449 nullptr);
3450 // Check that ack is bundled with outgoing crypto data.
3451 EXPECT_EQ(3u, writer_->frame_count());
3452 EXPECT_FALSE(writer_->ack_frames().empty());
3453 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3456 TEST_P(QuicConnectionTest, BlockAndBufferOnFirstCHLOPacketOfTwo) {
3457 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3458 ProcessPacket(1);
3459 BlockOnNextWrite();
3460 writer_->set_is_write_blocked_data_buffered(true);
3461 connection_.SendStreamDataWithString(kCryptoStreamId, "foo", 0, !kFin,
3462 nullptr);
3463 EXPECT_TRUE(writer_->IsWriteBlocked());
3464 EXPECT_FALSE(connection_.HasQueuedData());
3465 connection_.SendStreamDataWithString(kCryptoStreamId, "bar", 3, !kFin,
3466 nullptr);
3467 EXPECT_TRUE(writer_->IsWriteBlocked());
3468 EXPECT_TRUE(connection_.HasQueuedData());
3471 TEST_P(QuicConnectionTest, BundleAckForSecondCHLO) {
3472 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3473 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3474 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(
3475 IgnoreResult(InvokeWithoutArgs(&connection_,
3476 &TestConnection::SendCryptoStreamData)));
3477 // Process a packet from the crypto stream, which is frame1_'s default.
3478 // Receiving the CHLO as packet 2 first will cause the connection to
3479 // immediately send an ack, due to the packet gap.
3480 ProcessPacket(2);
3481 // Check that ack is sent and that delayed ack alarm is reset.
3482 EXPECT_EQ(3u, writer_->frame_count());
3483 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3484 EXPECT_EQ(1u, writer_->stream_frames().size());
3485 EXPECT_FALSE(writer_->ack_frames().empty());
3486 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3489 TEST_P(QuicConnectionTest, BundleAckWithDataOnIncomingAck) {
3490 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3491 connection_.SendStreamDataWithString(kClientDataStreamId1, "foo", 0, !kFin,
3492 nullptr);
3493 connection_.SendStreamDataWithString(kClientDataStreamId1, "foo", 3, !kFin,
3494 nullptr);
3495 // Ack the second packet, which will retransmit the first packet.
3496 QuicAckFrame ack = InitAckFrame(2);
3497 NackPacket(1, &ack);
3498 SequenceNumberSet lost_packets;
3499 lost_packets.insert(1);
3500 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3501 .WillOnce(Return(lost_packets));
3502 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3503 ProcessAckPacket(&ack);
3504 EXPECT_EQ(1u, writer_->frame_count());
3505 EXPECT_EQ(1u, writer_->stream_frames().size());
3506 writer_->Reset();
3508 // Now ack the retransmission, which will both raise the high water mark
3509 // and see if there is more data to send.
3510 ack = InitAckFrame(3);
3511 NackPacket(1, &ack);
3512 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3513 .WillOnce(Return(SequenceNumberSet()));
3514 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3515 ProcessAckPacket(&ack);
3517 // Check that no packet is sent and the ack alarm isn't set.
3518 EXPECT_EQ(0u, writer_->frame_count());
3519 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3520 writer_->Reset();
3522 // Send the same ack, but send both data and an ack together.
3523 ack = InitAckFrame(3);
3524 NackPacket(1, &ack);
3525 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3526 .WillOnce(Return(SequenceNumberSet()));
3527 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(
3528 IgnoreResult(InvokeWithoutArgs(
3529 &connection_,
3530 &TestConnection::EnsureWritableAndSendStreamData5)));
3531 ProcessAckPacket(&ack);
3533 // Check that ack is bundled with outgoing data and the delayed ack
3534 // alarm is reset.
3535 EXPECT_EQ(3u, writer_->frame_count());
3536 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3537 EXPECT_FALSE(writer_->ack_frames().empty());
3538 EXPECT_EQ(1u, writer_->stream_frames().size());
3539 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3542 TEST_P(QuicConnectionTest, NoAckSentForClose) {
3543 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3544 ProcessPacket(1);
3545 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, true));
3546 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3547 ProcessClosePacket(2, 0);
3550 TEST_P(QuicConnectionTest, SendWhenDisconnected) {
3551 EXPECT_TRUE(connection_.connected());
3552 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, false));
3553 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, false);
3554 EXPECT_FALSE(connection_.connected());
3555 EXPECT_FALSE(connection_.CanWriteStreamData());
3556 QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
3557 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 1, _, _)).Times(0);
3558 connection_.SendPacket(
3559 ENCRYPTION_NONE, 1, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA);
3562 TEST_P(QuicConnectionTest, PublicReset) {
3563 QuicPublicResetPacket header;
3564 header.public_header.connection_id = connection_id_;
3565 header.public_header.reset_flag = true;
3566 header.public_header.version_flag = false;
3567 header.rejected_sequence_number = 10101;
3568 scoped_ptr<QuicEncryptedPacket> packet(
3569 framer_.BuildPublicResetPacket(header));
3570 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PUBLIC_RESET, true));
3571 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *packet);
3574 TEST_P(QuicConnectionTest, GoAway) {
3575 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3577 QuicGoAwayFrame goaway;
3578 goaway.last_good_stream_id = 1;
3579 goaway.error_code = QUIC_PEER_GOING_AWAY;
3580 goaway.reason_phrase = "Going away.";
3581 EXPECT_CALL(visitor_, OnGoAway(_));
3582 ProcessGoAwayPacket(&goaway);
3585 TEST_P(QuicConnectionTest, WindowUpdate) {
3586 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3588 QuicWindowUpdateFrame window_update;
3589 window_update.stream_id = 3;
3590 window_update.byte_offset = 1234;
3591 EXPECT_CALL(visitor_, OnWindowUpdateFrames(_));
3592 ProcessFramePacket(QuicFrame(&window_update));
3595 TEST_P(QuicConnectionTest, Blocked) {
3596 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3598 QuicBlockedFrame blocked;
3599 blocked.stream_id = 3;
3600 EXPECT_CALL(visitor_, OnBlockedFrames(_));
3601 ProcessFramePacket(QuicFrame(&blocked));
3604 TEST_P(QuicConnectionTest, ZeroBytePacket) {
3605 // Don't close the connection for zero byte packets.
3606 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
3607 QuicEncryptedPacket encrypted(nullptr, 0);
3608 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), encrypted);
3611 TEST_P(QuicConnectionTest, MissingPacketsBeforeLeastUnacked) {
3612 // Set the sequence number of the ack packet to be least unacked (4).
3613 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 3);
3614 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3615 QuicStopWaitingFrame frame = InitStopWaitingFrame(4);
3616 ProcessStopWaitingPacket(&frame);
3617 EXPECT_TRUE(outgoing_ack()->missing_packets.empty());
3620 TEST_P(QuicConnectionTest, ReceivedEntropyHashCalculation) {
3621 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(AtLeast(1));
3622 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3623 ProcessDataPacket(1, 1, kEntropyFlag);
3624 ProcessDataPacket(4, 1, kEntropyFlag);
3625 ProcessDataPacket(3, 1, !kEntropyFlag);
3626 ProcessDataPacket(7, 1, kEntropyFlag);
3627 EXPECT_EQ(146u, outgoing_ack()->entropy_hash);
3630 TEST_P(QuicConnectionTest, ReceivedEntropyHashCalculationHalfFEC) {
3631 // FEC packets should not change the entropy hash calculation.
3632 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(AtLeast(1));
3633 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3634 ProcessDataPacket(1, 1, kEntropyFlag);
3635 ProcessFecPacket(4, 1, false, kEntropyFlag, nullptr);
3636 ProcessDataPacket(3, 3, !kEntropyFlag);
3637 ProcessFecPacket(7, 3, false, kEntropyFlag, nullptr);
3638 EXPECT_EQ(146u, outgoing_ack()->entropy_hash);
3641 TEST_P(QuicConnectionTest, UpdateEntropyForReceivedPackets) {
3642 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(AtLeast(1));
3643 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3644 ProcessDataPacket(1, 1, kEntropyFlag);
3645 ProcessDataPacket(5, 1, kEntropyFlag);
3646 ProcessDataPacket(4, 1, !kEntropyFlag);
3647 EXPECT_EQ(34u, outgoing_ack()->entropy_hash);
3648 // Make 4th packet my least unacked, and update entropy for 2, 3 packets.
3649 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 5);
3650 QuicPacketEntropyHash six_packet_entropy_hash = 0;
3651 QuicPacketEntropyHash random_entropy_hash = 129u;
3652 QuicStopWaitingFrame frame = InitStopWaitingFrame(4);
3653 frame.entropy_hash = random_entropy_hash;
3654 if (ProcessStopWaitingPacket(&frame)) {
3655 six_packet_entropy_hash = 1 << 6;
3658 EXPECT_EQ((random_entropy_hash + (1 << 5) + six_packet_entropy_hash),
3659 outgoing_ack()->entropy_hash);
3662 TEST_P(QuicConnectionTest, UpdateEntropyHashUptoCurrentPacket) {
3663 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(AtLeast(1));
3664 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3665 ProcessDataPacket(1, 1, kEntropyFlag);
3666 ProcessDataPacket(5, 1, !kEntropyFlag);
3667 ProcessDataPacket(22, 1, kEntropyFlag);
3668 EXPECT_EQ(66u, outgoing_ack()->entropy_hash);
3669 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 22);
3670 QuicPacketEntropyHash random_entropy_hash = 85u;
3671 // Current packet is the least unacked packet.
3672 QuicPacketEntropyHash ack_entropy_hash;
3673 QuicStopWaitingFrame frame = InitStopWaitingFrame(23);
3674 frame.entropy_hash = random_entropy_hash;
3675 ack_entropy_hash = ProcessStopWaitingPacket(&frame);
3676 EXPECT_EQ((random_entropy_hash + ack_entropy_hash),
3677 outgoing_ack()->entropy_hash);
3678 ProcessDataPacket(25, 1, kEntropyFlag);
3679 EXPECT_EQ((random_entropy_hash + ack_entropy_hash + (1 << (25 % 8))),
3680 outgoing_ack()->entropy_hash);
3683 TEST_P(QuicConnectionTest, EntropyCalculationForTruncatedAck) {
3684 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(AtLeast(1));
3685 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3686 QuicPacketEntropyHash entropy[51];
3687 entropy[0] = 0;
3688 for (int i = 1; i < 51; ++i) {
3689 bool should_send = i % 10 != 1;
3690 bool entropy_flag = (i & (i - 1)) != 0;
3691 if (!should_send) {
3692 entropy[i] = entropy[i - 1];
3693 continue;
3695 if (entropy_flag) {
3696 entropy[i] = entropy[i - 1] ^ (1 << (i % 8));
3697 } else {
3698 entropy[i] = entropy[i - 1];
3700 ProcessDataPacket(i, 1, entropy_flag);
3702 for (int i = 1; i < 50; ++i) {
3703 EXPECT_EQ(entropy[i], QuicConnectionPeer::ReceivedEntropyHash(
3704 &connection_, i));
3708 TEST_P(QuicConnectionTest, ServerSendsVersionNegotiationPacket) {
3709 connection_.SetSupportedVersions(QuicSupportedVersions());
3710 framer_.set_version_for_tests(QUIC_VERSION_UNSUPPORTED);
3712 QuicPacketHeader header;
3713 header.public_header.connection_id = connection_id_;
3714 header.public_header.version_flag = true;
3715 header.packet_sequence_number = 12;
3717 QuicFrames frames;
3718 frames.push_back(QuicFrame(&frame1_));
3719 scoped_ptr<QuicPacket> packet(ConstructPacket(header, frames));
3720 scoped_ptr<QuicEncryptedPacket> encrypted(
3721 framer_.EncryptPacket(ENCRYPTION_NONE, 12, *packet));
3723 framer_.set_version(version());
3724 connection_.set_perspective(Perspective::IS_SERVER);
3725 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3726 EXPECT_TRUE(writer_->version_negotiation_packet() != nullptr);
3728 size_t num_versions = arraysize(kSupportedQuicVersions);
3729 ASSERT_EQ(num_versions,
3730 writer_->version_negotiation_packet()->versions.size());
3732 // We expect all versions in kSupportedQuicVersions to be
3733 // included in the packet.
3734 for (size_t i = 0; i < num_versions; ++i) {
3735 EXPECT_EQ(kSupportedQuicVersions[i],
3736 writer_->version_negotiation_packet()->versions[i]);
3740 TEST_P(QuicConnectionTest, ServerSendsVersionNegotiationPacketSocketBlocked) {
3741 connection_.SetSupportedVersions(QuicSupportedVersions());
3742 framer_.set_version_for_tests(QUIC_VERSION_UNSUPPORTED);
3744 QuicPacketHeader header;
3745 header.public_header.connection_id = connection_id_;
3746 header.public_header.version_flag = true;
3747 header.packet_sequence_number = 12;
3749 QuicFrames frames;
3750 frames.push_back(QuicFrame(&frame1_));
3751 scoped_ptr<QuicPacket> packet(ConstructPacket(header, frames));
3752 scoped_ptr<QuicEncryptedPacket> encrypted(
3753 framer_.EncryptPacket(ENCRYPTION_NONE, 12, *packet));
3755 framer_.set_version(version());
3756 connection_.set_perspective(Perspective::IS_SERVER);
3757 BlockOnNextWrite();
3758 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3759 EXPECT_EQ(0u, writer_->last_packet_size());
3760 EXPECT_TRUE(connection_.HasQueuedData());
3762 writer_->SetWritable();
3763 connection_.OnCanWrite();
3764 EXPECT_TRUE(writer_->version_negotiation_packet() != nullptr);
3766 size_t num_versions = arraysize(kSupportedQuicVersions);
3767 ASSERT_EQ(num_versions,
3768 writer_->version_negotiation_packet()->versions.size());
3770 // We expect all versions in kSupportedQuicVersions to be
3771 // included in the packet.
3772 for (size_t i = 0; i < num_versions; ++i) {
3773 EXPECT_EQ(kSupportedQuicVersions[i],
3774 writer_->version_negotiation_packet()->versions[i]);
3778 TEST_P(QuicConnectionTest,
3779 ServerSendsVersionNegotiationPacketSocketBlockedDataBuffered) {
3780 connection_.SetSupportedVersions(QuicSupportedVersions());
3781 framer_.set_version_for_tests(QUIC_VERSION_UNSUPPORTED);
3783 QuicPacketHeader header;
3784 header.public_header.connection_id = connection_id_;
3785 header.public_header.version_flag = true;
3786 header.packet_sequence_number = 12;
3788 QuicFrames frames;
3789 frames.push_back(QuicFrame(&frame1_));
3790 scoped_ptr<QuicPacket> packet(ConstructPacket(header, frames));
3791 scoped_ptr<QuicEncryptedPacket> encrypted(
3792 framer_.EncryptPacket(ENCRYPTION_NONE, 12, *packet));
3794 framer_.set_version(version());
3795 connection_.set_perspective(Perspective::IS_SERVER);
3796 BlockOnNextWrite();
3797 writer_->set_is_write_blocked_data_buffered(true);
3798 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3799 EXPECT_EQ(0u, writer_->last_packet_size());
3800 EXPECT_FALSE(connection_.HasQueuedData());
3803 TEST_P(QuicConnectionTest, ClientHandlesVersionNegotiation) {
3804 // Start out with some unsupported version.
3805 QuicConnectionPeer::GetFramer(&connection_)->set_version_for_tests(
3806 QUIC_VERSION_UNSUPPORTED);
3808 QuicPacketHeader header;
3809 header.public_header.connection_id = connection_id_;
3810 header.public_header.version_flag = true;
3811 header.packet_sequence_number = 12;
3813 QuicVersionVector supported_versions;
3814 for (size_t i = 0; i < arraysize(kSupportedQuicVersions); ++i) {
3815 supported_versions.push_back(kSupportedQuicVersions[i]);
3818 // Send a version negotiation packet.
3819 scoped_ptr<QuicEncryptedPacket> encrypted(
3820 framer_.BuildVersionNegotiationPacket(
3821 header.public_header, supported_versions));
3822 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3824 // Now force another packet. The connection should transition into
3825 // NEGOTIATED_VERSION state and tell the packet creator to StopSendingVersion.
3826 header.public_header.version_flag = false;
3827 QuicFrames frames;
3828 frames.push_back(QuicFrame(&frame1_));
3829 scoped_ptr<QuicPacket> packet(ConstructPacket(header, frames));
3830 encrypted.reset(framer_.EncryptPacket(ENCRYPTION_NONE, 12, *packet));
3831 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
3832 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3833 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3835 ASSERT_FALSE(QuicPacketCreatorPeer::SendVersionInPacket(creator_));
3838 TEST_P(QuicConnectionTest, BadVersionNegotiation) {
3839 QuicPacketHeader header;
3840 header.public_header.connection_id = connection_id_;
3841 header.public_header.version_flag = true;
3842 header.packet_sequence_number = 12;
3844 QuicVersionVector supported_versions;
3845 for (size_t i = 0; i < arraysize(kSupportedQuicVersions); ++i) {
3846 supported_versions.push_back(kSupportedQuicVersions[i]);
3849 // Send a version negotiation packet with the version the client started with.
3850 // It should be rejected.
3851 EXPECT_CALL(visitor_,
3852 OnConnectionClosed(QUIC_INVALID_VERSION_NEGOTIATION_PACKET,
3853 false));
3854 scoped_ptr<QuicEncryptedPacket> encrypted(
3855 framer_.BuildVersionNegotiationPacket(
3856 header.public_header, supported_versions));
3857 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3860 TEST_P(QuicConnectionTest, CheckSendStats) {
3861 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3862 connection_.SendStreamDataWithString(3, "first", 0, !kFin, nullptr);
3863 size_t first_packet_size = writer_->last_packet_size();
3865 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3866 connection_.SendStreamDataWithString(5, "second", 0, !kFin, nullptr);
3867 size_t second_packet_size = writer_->last_packet_size();
3869 // 2 retransmissions due to rto, 1 due to explicit nack.
3870 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
3871 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
3873 // Retransmit due to RTO.
3874 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
3875 connection_.GetRetransmissionAlarm()->Fire();
3877 // Retransmit due to explicit nacks.
3878 QuicAckFrame nack_three = InitAckFrame(4);
3879 NackPacket(3, &nack_three);
3880 NackPacket(1, &nack_three);
3881 SequenceNumberSet lost_packets;
3882 lost_packets.insert(1);
3883 lost_packets.insert(3);
3884 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3885 .WillOnce(Return(lost_packets));
3886 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3887 EXPECT_CALL(visitor_, OnCanWrite()).Times(2);
3888 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3889 ProcessAckPacket(&nack_three);
3891 EXPECT_CALL(*send_algorithm_, BandwidthEstimate()).WillOnce(
3892 Return(QuicBandwidth::Zero()));
3894 const QuicConnectionStats& stats = connection_.GetStats();
3895 EXPECT_EQ(3 * first_packet_size + 2 * second_packet_size - kQuicVersionSize,
3896 stats.bytes_sent);
3897 EXPECT_EQ(5u, stats.packets_sent);
3898 EXPECT_EQ(2 * first_packet_size + second_packet_size - kQuicVersionSize,
3899 stats.bytes_retransmitted);
3900 EXPECT_EQ(3u, stats.packets_retransmitted);
3901 EXPECT_EQ(1u, stats.rto_count);
3902 EXPECT_EQ(kDefaultMaxPacketSize, stats.max_packet_size);
3905 TEST_P(QuicConnectionTest, CheckReceiveStats) {
3906 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3908 size_t received_bytes = 0;
3909 received_bytes += ProcessFecProtectedPacket(1, false, !kEntropyFlag);
3910 received_bytes += ProcessFecProtectedPacket(3, false, !kEntropyFlag);
3911 // Should be counted against dropped packets.
3912 received_bytes += ProcessDataPacket(3, 1, !kEntropyFlag);
3913 received_bytes += ProcessFecPacket(4, 1, true, !kEntropyFlag, nullptr);
3915 EXPECT_CALL(*send_algorithm_, BandwidthEstimate()).WillOnce(
3916 Return(QuicBandwidth::Zero()));
3918 const QuicConnectionStats& stats = connection_.GetStats();
3919 EXPECT_EQ(received_bytes, stats.bytes_received);
3920 EXPECT_EQ(4u, stats.packets_received);
3922 EXPECT_EQ(1u, stats.packets_revived);
3923 EXPECT_EQ(1u, stats.packets_dropped);
3926 TEST_P(QuicConnectionTest, TestFecGroupLimits) {
3927 // Create and return a group for 1.
3928 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 1) != nullptr);
3930 // Create and return a group for 2.
3931 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 2) != nullptr);
3933 // Create and return a group for 4. This should remove 1 but not 2.
3934 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 4) != nullptr);
3935 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 1) == nullptr);
3936 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 2) != nullptr);
3938 // Create and return a group for 3. This will kill off 2.
3939 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 3) != nullptr);
3940 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 2) == nullptr);
3942 // Verify that adding 5 kills off 3, despite 4 being created before 3.
3943 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 5) != nullptr);
3944 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 4) != nullptr);
3945 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 3) == nullptr);
3948 TEST_P(QuicConnectionTest, ProcessFramesIfPacketClosedConnection) {
3949 // Construct a packet with stream frame and connection close frame.
3950 QuicPacketHeader header;
3951 header.public_header.connection_id = connection_id_;
3952 header.packet_sequence_number = 1;
3953 header.public_header.version_flag = false;
3955 QuicConnectionCloseFrame qccf;
3956 qccf.error_code = QUIC_PEER_GOING_AWAY;
3958 QuicFrames frames;
3959 frames.push_back(QuicFrame(&frame1_));
3960 frames.push_back(QuicFrame(&qccf));
3961 scoped_ptr<QuicPacket> packet(ConstructPacket(header, frames));
3962 EXPECT_TRUE(nullptr != packet.get());
3963 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPacket(
3964 ENCRYPTION_NONE, 1, *packet));
3966 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, true));
3967 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
3968 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3970 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3973 TEST_P(QuicConnectionTest, SelectMutualVersion) {
3974 connection_.SetSupportedVersions(QuicSupportedVersions());
3975 // Set the connection to speak the lowest quic version.
3976 connection_.set_version(QuicVersionMin());
3977 EXPECT_EQ(QuicVersionMin(), connection_.version());
3979 // Pass in available versions which includes a higher mutually supported
3980 // version. The higher mutually supported version should be selected.
3981 QuicVersionVector supported_versions;
3982 for (size_t i = 0; i < arraysize(kSupportedQuicVersions); ++i) {
3983 supported_versions.push_back(kSupportedQuicVersions[i]);
3985 EXPECT_TRUE(connection_.SelectMutualVersion(supported_versions));
3986 EXPECT_EQ(QuicVersionMax(), connection_.version());
3988 // Expect that the lowest version is selected.
3989 // Ensure the lowest supported version is less than the max, unless they're
3990 // the same.
3991 EXPECT_LE(QuicVersionMin(), QuicVersionMax());
3992 QuicVersionVector lowest_version_vector;
3993 lowest_version_vector.push_back(QuicVersionMin());
3994 EXPECT_TRUE(connection_.SelectMutualVersion(lowest_version_vector));
3995 EXPECT_EQ(QuicVersionMin(), connection_.version());
3997 // Shouldn't be able to find a mutually supported version.
3998 QuicVersionVector unsupported_version;
3999 unsupported_version.push_back(QUIC_VERSION_UNSUPPORTED);
4000 EXPECT_FALSE(connection_.SelectMutualVersion(unsupported_version));
4003 TEST_P(QuicConnectionTest, ConnectionCloseWhenWritable) {
4004 EXPECT_FALSE(writer_->IsWriteBlocked());
4006 // Send a packet.
4007 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
4008 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4009 EXPECT_EQ(1u, writer_->packets_write_attempts());
4011 TriggerConnectionClose();
4012 EXPECT_EQ(2u, writer_->packets_write_attempts());
4015 TEST_P(QuicConnectionTest, ConnectionCloseGettingWriteBlocked) {
4016 BlockOnNextWrite();
4017 TriggerConnectionClose();
4018 EXPECT_EQ(1u, writer_->packets_write_attempts());
4019 EXPECT_TRUE(writer_->IsWriteBlocked());
4022 TEST_P(QuicConnectionTest, ConnectionCloseWhenWriteBlocked) {
4023 BlockOnNextWrite();
4024 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
4025 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4026 EXPECT_EQ(1u, writer_->packets_write_attempts());
4027 EXPECT_TRUE(writer_->IsWriteBlocked());
4028 TriggerConnectionClose();
4029 EXPECT_EQ(1u, writer_->packets_write_attempts());
4032 TEST_P(QuicConnectionTest, AckNotifierTriggerCallback) {
4033 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4035 // Create a delegate which we expect to be called.
4036 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4037 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(1);
4039 // Send some data, which will register the delegate to be notified.
4040 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
4042 // Process an ACK from the server which should trigger the callback.
4043 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4044 QuicAckFrame frame = InitAckFrame(1);
4045 ProcessAckPacket(&frame);
4048 TEST_P(QuicConnectionTest, AckNotifierFailToTriggerCallback) {
4049 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4051 // Create a delegate which we don't expect to be called.
4052 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4053 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(0);
4055 // Send some data, which will register the delegate to be notified. This will
4056 // not be ACKed and so the delegate should never be called.
4057 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
4059 // Send some other data which we will ACK.
4060 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
4061 connection_.SendStreamDataWithString(1, "bar", 0, !kFin, nullptr);
4063 // Now we receive ACK for packets 2 and 3, but importantly missing packet 1
4064 // which we registered to be notified about.
4065 QuicAckFrame frame = InitAckFrame(3);
4066 NackPacket(1, &frame);
4067 SequenceNumberSet lost_packets;
4068 lost_packets.insert(1);
4069 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4070 .WillOnce(Return(lost_packets));
4071 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4072 ProcessAckPacket(&frame);
4075 TEST_P(QuicConnectionTest, AckNotifierCallbackAfterRetransmission) {
4076 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4078 // Create a delegate which we expect to be called.
4079 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4080 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(1);
4082 // Send four packets, and register to be notified on ACK of packet 2.
4083 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
4084 connection_.SendStreamDataWithString(3, "bar", 0, !kFin, delegate.get());
4085 connection_.SendStreamDataWithString(3, "baz", 0, !kFin, nullptr);
4086 connection_.SendStreamDataWithString(3, "qux", 0, !kFin, nullptr);
4088 // Now we receive ACK for packets 1, 3, and 4 and lose 2.
4089 QuicAckFrame frame = InitAckFrame(4);
4090 NackPacket(2, &frame);
4091 SequenceNumberSet lost_packets;
4092 lost_packets.insert(2);
4093 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4094 .WillOnce(Return(lost_packets));
4095 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4096 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4097 ProcessAckPacket(&frame);
4099 // Now we get an ACK for packet 5 (retransmitted packet 2), which should
4100 // trigger the callback.
4101 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4102 .WillRepeatedly(Return(SequenceNumberSet()));
4103 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4104 QuicAckFrame second_ack_frame = InitAckFrame(5);
4105 ProcessAckPacket(&second_ack_frame);
4108 // AckNotifierCallback is triggered by the ack of a packet that timed
4109 // out and was retransmitted, even though the retransmission has a
4110 // different sequence number.
4111 TEST_P(QuicConnectionTest, AckNotifierCallbackForAckAfterRTO) {
4112 InSequence s;
4114 // Create a delegate which we expect to be called.
4115 scoped_refptr<MockAckNotifierDelegate> delegate(
4116 new StrictMock<MockAckNotifierDelegate>);
4118 QuicTime default_retransmission_time = clock_.ApproximateNow().Add(
4119 DefaultRetransmissionTime());
4120 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, delegate.get());
4121 EXPECT_EQ(1u, stop_waiting()->least_unacked);
4123 EXPECT_EQ(1u, writer_->header().packet_sequence_number);
4124 EXPECT_EQ(default_retransmission_time,
4125 connection_.GetRetransmissionAlarm()->deadline());
4126 // Simulate the retransmission alarm firing.
4127 clock_.AdvanceTime(DefaultRetransmissionTime());
4128 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 2u, _, _));
4129 connection_.GetRetransmissionAlarm()->Fire();
4130 EXPECT_EQ(2u, writer_->header().packet_sequence_number);
4131 // We do not raise the high water mark yet.
4132 EXPECT_EQ(1u, stop_waiting()->least_unacked);
4134 // Ack the original packet, which will revert the RTO.
4135 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4136 EXPECT_CALL(*delegate, OnAckNotification(1, _, _));
4137 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4138 QuicAckFrame ack_frame = InitAckFrame(1);
4139 ProcessAckPacket(&ack_frame);
4141 // Delegate is not notified again when the retransmit is acked.
4142 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4143 QuicAckFrame second_ack_frame = InitAckFrame(2);
4144 ProcessAckPacket(&second_ack_frame);
4147 // AckNotifierCallback is triggered by the ack of a packet that was
4148 // previously nacked, even though the retransmission has a different
4149 // sequence number.
4150 TEST_P(QuicConnectionTest, AckNotifierCallbackForAckOfNackedPacket) {
4151 InSequence s;
4153 // Create a delegate which we expect to be called.
4154 scoped_refptr<MockAckNotifierDelegate> delegate(
4155 new StrictMock<MockAckNotifierDelegate>);
4157 // Send four packets, and register to be notified on ACK of packet 2.
4158 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
4159 connection_.SendStreamDataWithString(3, "bar", 0, !kFin, delegate.get());
4160 connection_.SendStreamDataWithString(3, "baz", 0, !kFin, nullptr);
4161 connection_.SendStreamDataWithString(3, "qux", 0, !kFin, nullptr);
4163 // Now we receive ACK for packets 1, 3, and 4 and lose 2.
4164 QuicAckFrame frame = InitAckFrame(4);
4165 NackPacket(2, &frame);
4166 SequenceNumberSet lost_packets;
4167 lost_packets.insert(2);
4168 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4169 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4170 .WillOnce(Return(lost_packets));
4171 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4172 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4173 ProcessAckPacket(&frame);
4175 // Now we get an ACK for packet 2, which was previously nacked.
4176 SequenceNumberSet no_lost_packets;
4177 EXPECT_CALL(*delegate.get(), OnAckNotification(1, _, _));
4178 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4179 .WillOnce(Return(no_lost_packets));
4180 QuicAckFrame second_ack_frame = InitAckFrame(4);
4181 ProcessAckPacket(&second_ack_frame);
4183 // Verify that the delegate is not notified again when the
4184 // retransmit is acked.
4185 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4186 .WillOnce(Return(no_lost_packets));
4187 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4188 QuicAckFrame third_ack_frame = InitAckFrame(5);
4189 ProcessAckPacket(&third_ack_frame);
4192 TEST_P(QuicConnectionTest, AckNotifierFECTriggerCallback) {
4193 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4195 // Create a delegate which we expect to be called.
4196 scoped_refptr<MockAckNotifierDelegate> delegate(
4197 new MockAckNotifierDelegate);
4198 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(1);
4200 // Send some data, which will register the delegate to be notified.
4201 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
4202 connection_.SendStreamDataWithString(2, "bar", 0, !kFin, nullptr);
4204 // Process an ACK from the server with a revived packet, which should trigger
4205 // the callback.
4206 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4207 QuicAckFrame frame = InitAckFrame(2);
4208 NackPacket(1, &frame);
4209 frame.revived_packets.insert(1);
4210 ProcessAckPacket(&frame);
4211 // If the ack is processed again, the notifier should not be called again.
4212 ProcessAckPacket(&frame);
4215 TEST_P(QuicConnectionTest, AckNotifierCallbackAfterFECRecovery) {
4216 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4217 EXPECT_CALL(visitor_, OnCanWrite());
4219 // Create a delegate which we expect to be called.
4220 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4221 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(1);
4223 // Expect ACKs for 1 packet.
4224 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4226 // Send one packet, and register to be notified on ACK.
4227 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
4229 // Ack packet gets dropped, but we receive an FEC packet that covers it.
4230 // Should recover the Ack packet and trigger the notification callback.
4231 QuicFrames frames;
4233 QuicAckFrame ack_frame = InitAckFrame(1);
4234 frames.push_back(QuicFrame(&ack_frame));
4236 // Dummy stream frame to satisfy expectations set elsewhere.
4237 frames.push_back(QuicFrame(&frame1_));
4239 QuicPacketHeader ack_header;
4240 ack_header.public_header.connection_id = connection_id_;
4241 ack_header.public_header.reset_flag = false;
4242 ack_header.public_header.version_flag = false;
4243 ack_header.entropy_flag = !kEntropyFlag;
4244 ack_header.fec_flag = true;
4245 ack_header.packet_sequence_number = 1;
4246 ack_header.is_in_fec_group = IN_FEC_GROUP;
4247 ack_header.fec_group = 1;
4249 QuicPacket* packet = BuildUnsizedDataPacket(&framer_, ack_header, frames);
4251 // Take the packet which contains the ACK frame, and construct and deliver an
4252 // FEC packet which allows the ACK packet to be recovered.
4253 ProcessFecPacket(2, 1, true, !kEntropyFlag, packet);
4256 TEST_P(QuicConnectionTest, NetworkChangeVisitorCwndCallbackChangesFecState) {
4257 size_t max_packets_per_fec_group = creator_->max_packets_per_fec_group();
4259 QuicSentPacketManager::NetworkChangeVisitor* visitor =
4260 QuicSentPacketManagerPeer::GetNetworkChangeVisitor(manager_);
4261 EXPECT_TRUE(visitor);
4263 // Increase FEC group size by increasing congestion window to a large number.
4264 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
4265 Return(1000 * kDefaultTCPMSS));
4266 visitor->OnCongestionWindowChange();
4267 EXPECT_LT(max_packets_per_fec_group, creator_->max_packets_per_fec_group());
4270 TEST_P(QuicConnectionTest, NetworkChangeVisitorConfigCallbackChangesFecState) {
4271 QuicSentPacketManager::NetworkChangeVisitor* visitor =
4272 QuicSentPacketManagerPeer::GetNetworkChangeVisitor(manager_);
4273 EXPECT_TRUE(visitor);
4274 EXPECT_EQ(QuicTime::Delta::Zero(),
4275 QuicPacketGeneratorPeer::GetFecTimeout(generator_));
4277 // Verify that sending a config with a new initial rtt changes fec timeout.
4278 // Create and process a config with a non-zero initial RTT.
4279 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4280 QuicConfig config;
4281 config.SetInitialRoundTripTimeUsToSend(300000);
4282 connection_.SetFromConfig(config);
4283 EXPECT_LT(QuicTime::Delta::Zero(),
4284 QuicPacketGeneratorPeer::GetFecTimeout(generator_));
4287 TEST_P(QuicConnectionTest, NetworkChangeVisitorRttCallbackChangesFecState) {
4288 // Verify that sending a config with a new initial rtt changes fec timeout.
4289 QuicSentPacketManager::NetworkChangeVisitor* visitor =
4290 QuicSentPacketManagerPeer::GetNetworkChangeVisitor(manager_);
4291 EXPECT_TRUE(visitor);
4292 EXPECT_EQ(QuicTime::Delta::Zero(),
4293 QuicPacketGeneratorPeer::GetFecTimeout(generator_));
4295 // Increase FEC timeout by increasing RTT.
4296 RttStats* rtt_stats = QuicSentPacketManagerPeer::GetRttStats(manager_);
4297 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(300),
4298 QuicTime::Delta::Zero(), QuicTime::Zero());
4299 visitor->OnRttChange();
4300 EXPECT_LT(QuicTime::Delta::Zero(),
4301 QuicPacketGeneratorPeer::GetFecTimeout(generator_));
4304 TEST_P(QuicConnectionTest, OnPacketHeaderDebugVisitor) {
4305 QuicPacketHeader header;
4307 scoped_ptr<MockQuicConnectionDebugVisitor> debug_visitor(
4308 new MockQuicConnectionDebugVisitor());
4309 connection_.set_debug_visitor(debug_visitor.get());
4310 EXPECT_CALL(*debug_visitor, OnPacketHeader(Ref(header))).Times(1);
4311 connection_.OnPacketHeader(header);
4314 TEST_P(QuicConnectionTest, Pacing) {
4315 TestConnection server(connection_id_, IPEndPoint(), helper_.get(), factory_,
4316 Perspective::IS_SERVER, version());
4317 TestConnection client(connection_id_, IPEndPoint(), helper_.get(), factory_,
4318 Perspective::IS_CLIENT, version());
4319 EXPECT_FALSE(client.sent_packet_manager().using_pacing());
4320 EXPECT_FALSE(server.sent_packet_manager().using_pacing());
4323 TEST_P(QuicConnectionTest, ControlFramesInstigateAcks) {
4324 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4326 // Send a WINDOW_UPDATE frame.
4327 QuicWindowUpdateFrame window_update;
4328 window_update.stream_id = 3;
4329 window_update.byte_offset = 1234;
4330 EXPECT_CALL(visitor_, OnWindowUpdateFrames(_));
4331 ProcessFramePacket(QuicFrame(&window_update));
4333 // Ensure that this has caused the ACK alarm to be set.
4334 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
4335 EXPECT_TRUE(ack_alarm->IsSet());
4337 // Cancel alarm, and try again with BLOCKED frame.
4338 ack_alarm->Cancel();
4339 QuicBlockedFrame blocked;
4340 blocked.stream_id = 3;
4341 EXPECT_CALL(visitor_, OnBlockedFrames(_));
4342 ProcessFramePacket(QuicFrame(&blocked));
4343 EXPECT_TRUE(ack_alarm->IsSet());
4346 TEST_P(QuicConnectionTest, NoDataNoFin) {
4347 // Make sure that a call to SendStreamWithData, with no data and no FIN, does
4348 // not result in a QuicAckNotifier being used-after-free (fail under ASAN).
4349 // Regression test for b/18594622
4350 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4351 EXPECT_DFATAL(
4352 connection_.SendStreamDataWithString(3, "", 0, !kFin, delegate.get()),
4353 "Attempt to send empty stream frame");
4356 } // namespace
4357 } // namespace test
4358 } // namespace net