Add missing mandoline dependencies.
[chromium-blink-merge.git] / net / quic / quic_connection_test.cc
blob9276f4433387d81fd0df009db1b091f5a081ae74
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 EncryptPacket(QuicPacketSequenceNumber sequence_number,
82 StringPiece associated_data,
83 StringPiece plaintext,
84 char* output,
85 size_t* output_length,
86 size_t max_output_length) override {
87 const size_t len = plaintext.size() + kTagSize;
88 if (max_output_length < len) {
89 return false;
91 memcpy(output, plaintext.data(), plaintext.size());
92 output += plaintext.size();
93 memset(output, tag_, kTagSize);
94 *output_length = len;
95 return true;
98 size_t GetKeySize() const override { return 0; }
99 size_t GetNoncePrefixSize() const override { return 0; }
101 size_t GetMaxPlaintextSize(size_t ciphertext_size) const override {
102 return ciphertext_size - kTagSize;
105 size_t GetCiphertextSize(size_t plaintext_size) const override {
106 return plaintext_size + kTagSize;
109 StringPiece GetKey() const override { return StringPiece(); }
111 StringPiece GetNoncePrefix() const override { return StringPiece(); }
113 private:
114 enum {
115 kTagSize = 12,
118 const uint8 tag_;
120 DISALLOW_COPY_AND_ASSIGN(TaggingEncrypter);
123 // TaggingDecrypter ensures that the final kTagSize bytes of the message all
124 // have the same value and then removes them.
125 class TaggingDecrypter : public QuicDecrypter {
126 public:
127 ~TaggingDecrypter() override {}
129 // QuicDecrypter interface
130 bool SetKey(StringPiece key) override { return true; }
132 bool SetNoncePrefix(StringPiece nonce_prefix) override { return true; }
134 bool DecryptPacket(QuicPacketSequenceNumber sequence_number,
135 const StringPiece& associated_data,
136 const StringPiece& ciphertext,
137 char* output,
138 size_t* output_length,
139 size_t max_output_length) override {
140 if (ciphertext.size() < kTagSize) {
141 return false;
143 if (!CheckTag(ciphertext, GetTag(ciphertext))) {
144 return false;
146 *output_length = ciphertext.size() - kTagSize;
147 memcpy(output, ciphertext.data(), *output_length);
148 return true;
151 StringPiece GetKey() const override { return StringPiece(); }
152 StringPiece GetNoncePrefix() const override { return StringPiece(); }
154 protected:
155 virtual uint8 GetTag(StringPiece ciphertext) {
156 return ciphertext.data()[ciphertext.size()-1];
159 private:
160 enum {
161 kTagSize = 12,
164 bool CheckTag(StringPiece ciphertext, uint8 tag) {
165 for (size_t i = ciphertext.size() - kTagSize; i < ciphertext.size(); i++) {
166 if (ciphertext.data()[i] != tag) {
167 return false;
171 return true;
175 // StringTaggingDecrypter ensures that the final kTagSize bytes of the message
176 // match the expected value.
177 class StrictTaggingDecrypter : public TaggingDecrypter {
178 public:
179 explicit StrictTaggingDecrypter(uint8 tag) : tag_(tag) {}
180 ~StrictTaggingDecrypter() override {}
182 // TaggingQuicDecrypter
183 uint8 GetTag(StringPiece ciphertext) override { return tag_; }
185 private:
186 const uint8 tag_;
189 class TestConnectionHelper : public QuicConnectionHelperInterface {
190 public:
191 class TestAlarm : public QuicAlarm {
192 public:
193 explicit TestAlarm(QuicAlarm::Delegate* delegate)
194 : QuicAlarm(delegate) {
197 void SetImpl() override {}
198 void CancelImpl() override {}
199 using QuicAlarm::Fire;
202 TestConnectionHelper(MockClock* clock, MockRandom* random_generator)
203 : clock_(clock),
204 random_generator_(random_generator) {
205 clock_->AdvanceTime(QuicTime::Delta::FromSeconds(1));
208 // QuicConnectionHelperInterface
209 const QuicClock* GetClock() const override { return clock_; }
211 QuicRandom* GetRandomGenerator() override { return random_generator_; }
213 QuicAlarm* CreateAlarm(QuicAlarm::Delegate* delegate) override {
214 return new TestAlarm(delegate);
217 private:
218 MockClock* clock_;
219 MockRandom* random_generator_;
221 DISALLOW_COPY_AND_ASSIGN(TestConnectionHelper);
224 class TestPacketWriter : public QuicPacketWriter {
225 public:
226 TestPacketWriter(QuicVersion version, MockClock *clock)
227 : version_(version),
228 framer_(SupportedVersions(version_)),
229 last_packet_size_(0),
230 write_blocked_(false),
231 block_on_next_write_(false),
232 is_write_blocked_data_buffered_(false),
233 final_bytes_of_last_packet_(0),
234 final_bytes_of_previous_packet_(0),
235 use_tagging_decrypter_(false),
236 packets_write_attempts_(0),
237 clock_(clock),
238 write_pause_time_delta_(QuicTime::Delta::Zero()) {
241 // QuicPacketWriter interface
242 WriteResult WritePacket(const char* buffer,
243 size_t buf_len,
244 const IPAddressNumber& self_address,
245 const IPEndPoint& peer_address) override {
246 QuicEncryptedPacket packet(buffer, buf_len);
247 ++packets_write_attempts_;
249 if (packet.length() >= sizeof(final_bytes_of_last_packet_)) {
250 final_bytes_of_previous_packet_ = final_bytes_of_last_packet_;
251 memcpy(&final_bytes_of_last_packet_, packet.data() + packet.length() - 4,
252 sizeof(final_bytes_of_last_packet_));
255 if (use_tagging_decrypter_) {
256 framer_.framer()->SetDecrypter(new TaggingDecrypter, ENCRYPTION_NONE);
258 EXPECT_TRUE(framer_.ProcessPacket(packet));
259 if (block_on_next_write_) {
260 write_blocked_ = true;
261 block_on_next_write_ = false;
263 if (IsWriteBlocked()) {
264 return WriteResult(WRITE_STATUS_BLOCKED, -1);
266 last_packet_size_ = packet.length();
268 if (!write_pause_time_delta_.IsZero()) {
269 clock_->AdvanceTime(write_pause_time_delta_);
271 return WriteResult(WRITE_STATUS_OK, last_packet_size_);
274 bool IsWriteBlockedDataBuffered() const override {
275 return is_write_blocked_data_buffered_;
278 bool IsWriteBlocked() const override { return write_blocked_; }
280 void SetWritable() override { write_blocked_ = false; }
282 void BlockOnNextWrite() { block_on_next_write_ = true; }
284 // Sets the amount of time that the writer should before the actual write.
285 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
286 write_pause_time_delta_ = delta;
289 const QuicPacketHeader& header() { return framer_.header(); }
291 size_t frame_count() const { return framer_.num_frames(); }
293 const vector<QuicAckFrame>& ack_frames() const {
294 return framer_.ack_frames();
297 const vector<QuicStopWaitingFrame>& stop_waiting_frames() const {
298 return framer_.stop_waiting_frames();
301 const vector<QuicConnectionCloseFrame>& connection_close_frames() const {
302 return framer_.connection_close_frames();
305 const vector<QuicRstStreamFrame>& rst_stream_frames() const {
306 return framer_.rst_stream_frames();
309 const vector<QuicStreamFrame>& stream_frames() const {
310 return framer_.stream_frames();
313 const vector<QuicPingFrame>& ping_frames() const {
314 return framer_.ping_frames();
317 size_t last_packet_size() {
318 return last_packet_size_;
321 const QuicVersionNegotiationPacket* version_negotiation_packet() {
322 return framer_.version_negotiation_packet();
325 void set_is_write_blocked_data_buffered(bool buffered) {
326 is_write_blocked_data_buffered_ = buffered;
329 void set_perspective(Perspective perspective) {
330 // We invert perspective here, because the framer needs to parse packets
331 // we send.
332 perspective = perspective == Perspective::IS_CLIENT
333 ? Perspective::IS_SERVER
334 : Perspective::IS_CLIENT;
335 QuicFramerPeer::SetPerspective(framer_.framer(), perspective);
338 // final_bytes_of_last_packet_ returns the last four bytes of the previous
339 // packet as a little-endian, uint32. This is intended to be used with a
340 // TaggingEncrypter so that tests can determine which encrypter was used for
341 // a given packet.
342 uint32 final_bytes_of_last_packet() { return final_bytes_of_last_packet_; }
344 // Returns the final bytes of the second to last packet.
345 uint32 final_bytes_of_previous_packet() {
346 return final_bytes_of_previous_packet_;
349 void use_tagging_decrypter() {
350 use_tagging_decrypter_ = true;
353 uint32 packets_write_attempts() { return packets_write_attempts_; }
355 void Reset() { framer_.Reset(); }
357 void SetSupportedVersions(const QuicVersionVector& versions) {
358 framer_.SetSupportedVersions(versions);
361 private:
362 QuicVersion version_;
363 SimpleQuicFramer framer_;
364 size_t last_packet_size_;
365 bool write_blocked_;
366 bool block_on_next_write_;
367 bool is_write_blocked_data_buffered_;
368 uint32 final_bytes_of_last_packet_;
369 uint32 final_bytes_of_previous_packet_;
370 bool use_tagging_decrypter_;
371 uint32 packets_write_attempts_;
372 MockClock *clock_;
373 // If non-zero, the clock will pause during WritePacket for this amount of
374 // time.
375 QuicTime::Delta write_pause_time_delta_;
377 DISALLOW_COPY_AND_ASSIGN(TestPacketWriter);
380 class TestConnection : public QuicConnection {
381 public:
382 TestConnection(QuicConnectionId connection_id,
383 IPEndPoint address,
384 TestConnectionHelper* helper,
385 const PacketWriterFactory& factory,
386 Perspective perspective,
387 QuicVersion version)
388 : QuicConnection(connection_id,
389 address,
390 helper,
391 factory,
392 /* owns_writer= */ false,
393 perspective,
394 /* is_secure= */ false,
395 SupportedVersions(version)) {
396 // Disable tail loss probes for most tests.
397 QuicSentPacketManagerPeer::SetMaxTailLossProbes(
398 QuicConnectionPeer::GetSentPacketManager(this), 0);
399 writer()->set_perspective(perspective);
402 void SendAck() {
403 QuicConnectionPeer::SendAck(this);
406 void SetSendAlgorithm(SendAlgorithmInterface* send_algorithm) {
407 QuicConnectionPeer::SetSendAlgorithm(this, send_algorithm);
410 void SetLossAlgorithm(LossDetectionInterface* loss_algorithm) {
411 QuicSentPacketManagerPeer::SetLossAlgorithm(
412 QuicConnectionPeer::GetSentPacketManager(this), loss_algorithm);
415 void SendPacket(EncryptionLevel level,
416 QuicPacketSequenceNumber sequence_number,
417 QuicPacket* packet,
418 QuicPacketEntropyHash entropy_hash,
419 HasRetransmittableData retransmittable) {
420 RetransmittableFrames* retransmittable_frames =
421 retransmittable == HAS_RETRANSMITTABLE_DATA
422 ? new RetransmittableFrames(ENCRYPTION_NONE)
423 : nullptr;
424 char buffer[kMaxPacketSize];
425 QuicEncryptedPacket* encrypted =
426 QuicConnectionPeer::GetFramer(this)->EncryptPacket(
427 ENCRYPTION_NONE, sequence_number, *packet, buffer, kMaxPacketSize);
428 delete packet;
429 OnSerializedPacket(SerializedPacket(sequence_number,
430 PACKET_6BYTE_SEQUENCE_NUMBER, encrypted,
431 entropy_hash, retransmittable_frames));
434 QuicConsumedData SendStreamDataWithString(
435 QuicStreamId id,
436 StringPiece data,
437 QuicStreamOffset offset,
438 bool fin,
439 QuicAckNotifier::DelegateInterface* delegate) {
440 return SendStreamDataWithStringHelper(id, data, offset, fin,
441 MAY_FEC_PROTECT, delegate);
444 QuicConsumedData SendStreamDataWithStringWithFec(
445 QuicStreamId id,
446 StringPiece data,
447 QuicStreamOffset offset,
448 bool fin,
449 QuicAckNotifier::DelegateInterface* delegate) {
450 return SendStreamDataWithStringHelper(id, data, offset, fin,
451 MUST_FEC_PROTECT, delegate);
454 QuicConsumedData SendStreamDataWithStringHelper(
455 QuicStreamId id,
456 StringPiece data,
457 QuicStreamOffset offset,
458 bool fin,
459 FecProtection fec_protection,
460 QuicAckNotifier::DelegateInterface* delegate) {
461 IOVector data_iov;
462 if (!data.empty()) {
463 data_iov.Append(const_cast<char*>(data.data()), data.size());
465 return QuicConnection::SendStreamData(id, data_iov, offset, fin,
466 fec_protection, delegate);
469 QuicConsumedData SendStreamData3() {
470 return SendStreamDataWithString(kClientDataStreamId1, "food", 0, !kFin,
471 nullptr);
474 QuicConsumedData SendStreamData3WithFec() {
475 return SendStreamDataWithStringWithFec(kClientDataStreamId1, "food", 0,
476 !kFin, nullptr);
479 QuicConsumedData SendStreamData5() {
480 return SendStreamDataWithString(kClientDataStreamId2, "food2", 0, !kFin,
481 nullptr);
484 QuicConsumedData SendStreamData5WithFec() {
485 return SendStreamDataWithStringWithFec(kClientDataStreamId2, "food2", 0,
486 !kFin, nullptr);
488 // Ensures the connection can write stream data before writing.
489 QuicConsumedData EnsureWritableAndSendStreamData5() {
490 EXPECT_TRUE(CanWriteStreamData());
491 return SendStreamData5();
494 // The crypto stream has special semantics so that it is not blocked by a
495 // congestion window limitation, and also so that it gets put into a separate
496 // packet (so that it is easier to reason about a crypto frame not being
497 // split needlessly across packet boundaries). As a result, we have separate
498 // tests for some cases for this stream.
499 QuicConsumedData SendCryptoStreamData() {
500 return SendStreamDataWithString(kCryptoStreamId, "chlo", 0, !kFin, nullptr);
503 void set_version(QuicVersion version) {
504 QuicConnectionPeer::GetFramer(this)->set_version(version);
507 void SetSupportedVersions(const QuicVersionVector& versions) {
508 QuicConnectionPeer::GetFramer(this)->SetSupportedVersions(versions);
509 writer()->SetSupportedVersions(versions);
512 void set_perspective(Perspective perspective) {
513 writer()->set_perspective(perspective);
514 QuicConnectionPeer::SetPerspective(this, perspective);
517 TestConnectionHelper::TestAlarm* GetAckAlarm() {
518 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
519 QuicConnectionPeer::GetAckAlarm(this));
522 TestConnectionHelper::TestAlarm* GetPingAlarm() {
523 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
524 QuicConnectionPeer::GetPingAlarm(this));
527 TestConnectionHelper::TestAlarm* GetFecAlarm() {
528 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
529 QuicConnectionPeer::GetFecAlarm(this));
532 TestConnectionHelper::TestAlarm* GetResumeWritesAlarm() {
533 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
534 QuicConnectionPeer::GetResumeWritesAlarm(this));
537 TestConnectionHelper::TestAlarm* GetRetransmissionAlarm() {
538 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
539 QuicConnectionPeer::GetRetransmissionAlarm(this));
542 TestConnectionHelper::TestAlarm* GetSendAlarm() {
543 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
544 QuicConnectionPeer::GetSendAlarm(this));
547 TestConnectionHelper::TestAlarm* GetTimeoutAlarm() {
548 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
549 QuicConnectionPeer::GetTimeoutAlarm(this));
552 using QuicConnection::SelectMutualVersion;
554 private:
555 TestPacketWriter* writer() {
556 return static_cast<TestPacketWriter*>(QuicConnection::writer());
559 DISALLOW_COPY_AND_ASSIGN(TestConnection);
562 // Used for testing packets revived from FEC packets.
563 class FecQuicConnectionDebugVisitor
564 : public QuicConnectionDebugVisitor {
565 public:
566 void OnRevivedPacket(const QuicPacketHeader& header,
567 StringPiece data) override {
568 revived_header_ = header;
571 // Public accessor method.
572 QuicPacketHeader revived_header() const {
573 return revived_header_;
576 private:
577 QuicPacketHeader revived_header_;
580 class MockPacketWriterFactory : public QuicConnection::PacketWriterFactory {
581 public:
582 explicit MockPacketWriterFactory(QuicPacketWriter* writer) {
583 ON_CALL(*this, Create(_)).WillByDefault(Return(writer));
585 ~MockPacketWriterFactory() override {}
587 MOCK_CONST_METHOD1(Create, QuicPacketWriter*(QuicConnection* connection));
590 class QuicConnectionTest : public ::testing::TestWithParam<QuicVersion> {
591 protected:
592 QuicConnectionTest()
593 : connection_id_(42),
594 framer_(SupportedVersions(version()),
595 QuicTime::Zero(),
596 Perspective::IS_CLIENT),
597 peer_creator_(connection_id_, &framer_, &random_generator_),
598 send_algorithm_(new StrictMock<MockSendAlgorithm>),
599 loss_algorithm_(new MockLossAlgorithm()),
600 helper_(new TestConnectionHelper(&clock_, &random_generator_)),
601 writer_(new TestPacketWriter(version(), &clock_)),
602 factory_(writer_.get()),
603 connection_(connection_id_,
604 IPEndPoint(),
605 helper_.get(),
606 factory_,
607 Perspective::IS_CLIENT,
608 version()),
609 creator_(QuicConnectionPeer::GetPacketCreator(&connection_)),
610 generator_(QuicConnectionPeer::GetPacketGenerator(&connection_)),
611 manager_(QuicConnectionPeer::GetSentPacketManager(&connection_)),
612 frame1_(1, false, 0, StringPiece(data1)),
613 frame2_(1, false, 3, StringPiece(data2)),
614 sequence_number_length_(PACKET_6BYTE_SEQUENCE_NUMBER),
615 connection_id_length_(PACKET_8BYTE_CONNECTION_ID) {
616 connection_.set_visitor(&visitor_);
617 connection_.SetSendAlgorithm(send_algorithm_);
618 connection_.SetLossAlgorithm(loss_algorithm_);
619 framer_.set_received_entropy_calculator(&entropy_calculator_);
620 EXPECT_CALL(
621 *send_algorithm_, TimeUntilSend(_, _, _)).WillRepeatedly(Return(
622 QuicTime::Delta::Zero()));
623 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
624 .Times(AnyNumber());
625 EXPECT_CALL(*send_algorithm_, RetransmissionDelay()).WillRepeatedly(
626 Return(QuicTime::Delta::Zero()));
627 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
628 Return(kMaxPacketSize));
629 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
630 .WillByDefault(Return(true));
631 EXPECT_CALL(*send_algorithm_, HasReliableBandwidthEstimate())
632 .Times(AnyNumber());
633 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
634 .Times(AnyNumber())
635 .WillRepeatedly(Return(QuicBandwidth::Zero()));
636 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
637 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
638 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).Times(AnyNumber());
639 EXPECT_CALL(visitor_, HasPendingHandshake()).Times(AnyNumber());
640 EXPECT_CALL(visitor_, OnCanWrite()).Times(AnyNumber());
641 EXPECT_CALL(visitor_, HasOpenDataStreams()).WillRepeatedly(Return(false));
642 EXPECT_CALL(visitor_, OnCongestionWindowChange(_)).Times(AnyNumber());
644 EXPECT_CALL(*loss_algorithm_, GetLossTimeout())
645 .WillRepeatedly(Return(QuicTime::Zero()));
646 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
647 .WillRepeatedly(Return(SequenceNumberSet()));
650 QuicVersion version() {
651 return GetParam();
654 QuicAckFrame* outgoing_ack() {
655 QuicConnectionPeer::PopulateAckFrame(&connection_, &ack_);
656 return &ack_;
659 QuicStopWaitingFrame* stop_waiting() {
660 QuicConnectionPeer::PopulateStopWaitingFrame(&connection_, &stop_waiting_);
661 return &stop_waiting_;
664 QuicPacketSequenceNumber least_unacked() {
665 if (writer_->stop_waiting_frames().empty()) {
666 return 0;
668 return writer_->stop_waiting_frames()[0].least_unacked;
671 void use_tagging_decrypter() {
672 writer_->use_tagging_decrypter();
675 void ProcessPacket(QuicPacketSequenceNumber number) {
676 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
677 ProcessDataPacket(number, 0, !kEntropyFlag);
680 QuicPacketEntropyHash ProcessFramePacket(QuicFrame frame) {
681 QuicFrames frames;
682 frames.push_back(QuicFrame(frame));
683 QuicPacketCreatorPeer::SetSendVersionInPacket(
684 &peer_creator_, connection_.perspective() == Perspective::IS_SERVER);
686 char buffer[kMaxPacketSize];
687 SerializedPacket serialized_packet =
688 peer_creator_.SerializeAllFrames(frames, buffer, kMaxPacketSize);
689 scoped_ptr<QuicEncryptedPacket> encrypted(serialized_packet.packet);
690 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
691 return serialized_packet.entropy_hash;
694 size_t ProcessDataPacket(QuicPacketSequenceNumber number,
695 QuicFecGroupNumber fec_group,
696 bool entropy_flag) {
697 return ProcessDataPacketAtLevel(number, fec_group, entropy_flag,
698 ENCRYPTION_NONE);
701 size_t ProcessDataPacketAtLevel(QuicPacketSequenceNumber number,
702 QuicFecGroupNumber fec_group,
703 bool entropy_flag,
704 EncryptionLevel level) {
705 scoped_ptr<QuicPacket> packet(ConstructDataPacket(number, fec_group,
706 entropy_flag));
707 char buffer[kMaxPacketSize];
708 scoped_ptr<QuicEncryptedPacket> encrypted(
709 framer_.EncryptPacket(level, number, *packet, buffer, kMaxPacketSize));
710 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
711 return encrypted->length();
714 void ProcessClosePacket(QuicPacketSequenceNumber number,
715 QuicFecGroupNumber fec_group) {
716 scoped_ptr<QuicPacket> packet(ConstructClosePacket(number, fec_group));
717 char buffer[kMaxPacketSize];
718 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPacket(
719 ENCRYPTION_NONE, number, *packet, buffer, kMaxPacketSize));
720 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
723 size_t ProcessFecProtectedPacket(QuicPacketSequenceNumber number,
724 bool expect_revival, bool entropy_flag) {
725 if (expect_revival) {
726 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
728 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1).
729 RetiresOnSaturation();
730 return ProcessDataPacket(number, 1, entropy_flag);
733 // Processes an FEC packet that covers the packets that would have been
734 // received.
735 size_t ProcessFecPacket(QuicPacketSequenceNumber number,
736 QuicPacketSequenceNumber min_protected_packet,
737 bool expect_revival,
738 bool entropy_flag,
739 QuicPacket* packet) {
740 if (expect_revival) {
741 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
744 // Construct the decrypted data packet so we can compute the correct
745 // redundancy. If |packet| has been provided then use that, otherwise
746 // construct a default data packet.
747 scoped_ptr<QuicPacket> data_packet;
748 if (packet) {
749 data_packet.reset(packet);
750 } else {
751 data_packet.reset(ConstructDataPacket(number, 1, !kEntropyFlag));
754 QuicPacketHeader header;
755 header.public_header.connection_id = connection_id_;
756 header.public_header.sequence_number_length = sequence_number_length_;
757 header.public_header.connection_id_length = connection_id_length_;
758 header.packet_sequence_number = number;
759 header.entropy_flag = entropy_flag;
760 header.fec_flag = true;
761 header.is_in_fec_group = IN_FEC_GROUP;
762 header.fec_group = min_protected_packet;
763 QuicFecData fec_data;
764 fec_data.fec_group = header.fec_group;
766 // Since all data packets in this test have the same payload, the
767 // redundancy is either equal to that payload or the xor of that payload
768 // with itself, depending on the number of packets.
769 if (((number - min_protected_packet) % 2) == 0) {
770 for (size_t i = GetStartOfFecProtectedData(
771 header.public_header.connection_id_length,
772 header.public_header.version_flag,
773 header.public_header.sequence_number_length);
774 i < data_packet->length(); ++i) {
775 data_packet->mutable_data()[i] ^= data_packet->data()[i];
778 fec_data.redundancy = data_packet->FecProtectedData();
780 scoped_ptr<QuicPacket> fec_packet(framer_.BuildFecPacket(header, fec_data));
781 char buffer[kMaxPacketSize];
782 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPacket(
783 ENCRYPTION_NONE, number, *fec_packet, buffer, kMaxPacketSize));
785 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
786 return encrypted->length();
789 QuicByteCount SendStreamDataToPeer(QuicStreamId id,
790 StringPiece data,
791 QuicStreamOffset offset,
792 bool fin,
793 QuicPacketSequenceNumber* last_packet) {
794 QuicByteCount packet_size;
795 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
796 .WillOnce(DoAll(SaveArg<3>(&packet_size), Return(true)));
797 connection_.SendStreamDataWithString(id, data, offset, fin, nullptr);
798 if (last_packet != nullptr) {
799 *last_packet = creator_->sequence_number();
801 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
802 .Times(AnyNumber());
803 return packet_size;
806 void SendAckPacketToPeer() {
807 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
808 connection_.SendAck();
809 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
810 .Times(AnyNumber());
813 QuicPacketEntropyHash ProcessAckPacket(QuicAckFrame* frame) {
814 return ProcessFramePacket(QuicFrame(frame));
817 QuicPacketEntropyHash ProcessStopWaitingPacket(QuicStopWaitingFrame* frame) {
818 return ProcessFramePacket(QuicFrame(frame));
821 QuicPacketEntropyHash ProcessGoAwayPacket(QuicGoAwayFrame* frame) {
822 return ProcessFramePacket(QuicFrame(frame));
825 bool IsMissing(QuicPacketSequenceNumber number) {
826 return IsAwaitingPacket(*outgoing_ack(), number);
829 QuicPacket* ConstructPacket(QuicPacketHeader header, QuicFrames frames) {
830 QuicPacket* packet = BuildUnsizedDataPacket(&framer_, header, frames);
831 EXPECT_NE(nullptr, packet);
832 return packet;
835 QuicPacket* ConstructDataPacket(QuicPacketSequenceNumber number,
836 QuicFecGroupNumber fec_group,
837 bool entropy_flag) {
838 QuicPacketHeader header;
839 header.public_header.connection_id = connection_id_;
840 header.public_header.sequence_number_length = sequence_number_length_;
841 header.public_header.connection_id_length = connection_id_length_;
842 header.entropy_flag = entropy_flag;
843 header.packet_sequence_number = number;
844 header.is_in_fec_group = fec_group == 0u ? NOT_IN_FEC_GROUP : IN_FEC_GROUP;
845 header.fec_group = fec_group;
847 QuicFrames frames;
848 frames.push_back(QuicFrame(&frame1_));
849 return ConstructPacket(header, frames);
852 QuicPacket* ConstructClosePacket(QuicPacketSequenceNumber number,
853 QuicFecGroupNumber fec_group) {
854 QuicPacketHeader header;
855 header.public_header.connection_id = connection_id_;
856 header.packet_sequence_number = number;
857 header.is_in_fec_group = fec_group == 0u ? NOT_IN_FEC_GROUP : IN_FEC_GROUP;
858 header.fec_group = fec_group;
860 QuicConnectionCloseFrame qccf;
861 qccf.error_code = QUIC_PEER_GOING_AWAY;
863 QuicFrames frames;
864 frames.push_back(QuicFrame(&qccf));
865 return ConstructPacket(header, frames);
868 QuicTime::Delta DefaultRetransmissionTime() {
869 return QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
872 QuicTime::Delta DefaultDelayedAckTime() {
873 return QuicTime::Delta::FromMilliseconds(kMaxDelayedAckTimeMs);
876 // Initialize a frame acknowledging all packets up to largest_observed.
877 const QuicAckFrame InitAckFrame(QuicPacketSequenceNumber largest_observed) {
878 QuicAckFrame frame(MakeAckFrame(largest_observed));
879 if (largest_observed > 0) {
880 frame.entropy_hash =
881 QuicConnectionPeer::GetSentEntropyHash(&connection_,
882 largest_observed);
884 return frame;
887 const QuicStopWaitingFrame InitStopWaitingFrame(
888 QuicPacketSequenceNumber least_unacked) {
889 QuicStopWaitingFrame frame;
890 frame.least_unacked = least_unacked;
891 return frame;
894 // Explicitly nack a packet.
895 void NackPacket(QuicPacketSequenceNumber missing, QuicAckFrame* frame) {
896 frame->missing_packets.insert(missing);
897 frame->entropy_hash ^=
898 QuicConnectionPeer::PacketEntropy(&connection_, missing);
901 // Undo nacking a packet within the frame.
902 void AckPacket(QuicPacketSequenceNumber arrived, QuicAckFrame* frame) {
903 EXPECT_THAT(frame->missing_packets, Contains(arrived));
904 frame->missing_packets.erase(arrived);
905 frame->entropy_hash ^=
906 QuicConnectionPeer::PacketEntropy(&connection_, arrived);
909 void TriggerConnectionClose() {
910 // Send an erroneous packet to close the connection.
911 EXPECT_CALL(visitor_,
912 OnConnectionClosed(QUIC_INVALID_PACKET_HEADER, false));
913 // Call ProcessDataPacket rather than ProcessPacket, as we should not get a
914 // packet call to the visitor.
915 ProcessDataPacket(6000, 0, !kEntropyFlag);
916 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
917 nullptr);
920 void BlockOnNextWrite() {
921 writer_->BlockOnNextWrite();
922 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
925 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
926 writer_->SetWritePauseTimeDelta(delta);
929 void CongestionBlockWrites() {
930 EXPECT_CALL(*send_algorithm_,
931 TimeUntilSend(_, _, _)).WillRepeatedly(
932 testing::Return(QuicTime::Delta::FromSeconds(1)));
935 void CongestionUnblockWrites() {
936 EXPECT_CALL(*send_algorithm_,
937 TimeUntilSend(_, _, _)).WillRepeatedly(
938 testing::Return(QuicTime::Delta::Zero()));
941 QuicConnectionId connection_id_;
942 QuicFramer framer_;
943 QuicPacketCreator peer_creator_;
944 MockEntropyCalculator entropy_calculator_;
946 MockSendAlgorithm* send_algorithm_;
947 MockLossAlgorithm* loss_algorithm_;
948 MockClock clock_;
949 MockRandom random_generator_;
950 scoped_ptr<TestConnectionHelper> helper_;
951 scoped_ptr<TestPacketWriter> writer_;
952 NiceMock<MockPacketWriterFactory> factory_;
953 TestConnection connection_;
954 QuicPacketCreator* creator_;
955 QuicPacketGenerator* generator_;
956 QuicSentPacketManager* manager_;
957 StrictMock<MockConnectionVisitor> visitor_;
959 QuicStreamFrame frame1_;
960 QuicStreamFrame frame2_;
961 QuicAckFrame ack_;
962 QuicStopWaitingFrame stop_waiting_;
963 QuicSequenceNumberLength sequence_number_length_;
964 QuicConnectionIdLength connection_id_length_;
966 private:
967 DISALLOW_COPY_AND_ASSIGN(QuicConnectionTest);
970 // Run all end to end tests with all supported versions.
971 INSTANTIATE_TEST_CASE_P(SupportedVersion,
972 QuicConnectionTest,
973 ::testing::ValuesIn(QuicSupportedVersions()));
975 TEST_P(QuicConnectionTest, MaxPacketSize) {
976 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
977 EXPECT_EQ(1350u, connection_.max_packet_length());
980 TEST_P(QuicConnectionTest, SmallerServerMaxPacketSize) {
981 QuicConnectionId connection_id = 42;
982 TestConnection connection(connection_id, IPEndPoint(), helper_.get(),
983 factory_, Perspective::IS_SERVER, version());
984 EXPECT_EQ(Perspective::IS_SERVER, connection.perspective());
985 EXPECT_EQ(1000u, connection.max_packet_length());
988 TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSize) {
989 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
991 connection_.set_perspective(Perspective::IS_SERVER);
992 connection_.set_max_packet_length(1000);
994 QuicPacketHeader header;
995 header.public_header.connection_id = connection_id_;
996 header.public_header.version_flag = true;
997 header.packet_sequence_number = 1;
999 QuicFrames frames;
1000 QuicPaddingFrame padding;
1001 frames.push_back(QuicFrame(&frame1_));
1002 frames.push_back(QuicFrame(&padding));
1003 scoped_ptr<QuicPacket> packet(ConstructPacket(header, frames));
1004 char buffer[kMaxPacketSize];
1005 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPacket(
1006 ENCRYPTION_NONE, 12, *packet, buffer, kMaxPacketSize));
1007 EXPECT_EQ(kMaxPacketSize, encrypted->length());
1009 framer_.set_version(version());
1010 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
1011 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
1013 EXPECT_EQ(kMaxPacketSize, connection_.max_packet_length());
1016 TEST_P(QuicConnectionTest, PacketsInOrder) {
1017 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1019 ProcessPacket(1);
1020 EXPECT_EQ(1u, outgoing_ack()->largest_observed);
1021 EXPECT_EQ(0u, outgoing_ack()->missing_packets.size());
1023 ProcessPacket(2);
1024 EXPECT_EQ(2u, outgoing_ack()->largest_observed);
1025 EXPECT_EQ(0u, outgoing_ack()->missing_packets.size());
1027 ProcessPacket(3);
1028 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1029 EXPECT_EQ(0u, outgoing_ack()->missing_packets.size());
1032 TEST_P(QuicConnectionTest, PacketsOutOfOrder) {
1033 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1035 ProcessPacket(3);
1036 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1037 EXPECT_TRUE(IsMissing(2));
1038 EXPECT_TRUE(IsMissing(1));
1040 ProcessPacket(2);
1041 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1042 EXPECT_FALSE(IsMissing(2));
1043 EXPECT_TRUE(IsMissing(1));
1045 ProcessPacket(1);
1046 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1047 EXPECT_FALSE(IsMissing(2));
1048 EXPECT_FALSE(IsMissing(1));
1051 TEST_P(QuicConnectionTest, DuplicatePacket) {
1052 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1054 ProcessPacket(3);
1055 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1056 EXPECT_TRUE(IsMissing(2));
1057 EXPECT_TRUE(IsMissing(1));
1059 // Send packet 3 again, but do not set the expectation that
1060 // the visitor OnStreamFrames() will be called.
1061 ProcessDataPacket(3, 0, !kEntropyFlag);
1062 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1063 EXPECT_TRUE(IsMissing(2));
1064 EXPECT_TRUE(IsMissing(1));
1067 TEST_P(QuicConnectionTest, PacketsOutOfOrderWithAdditionsAndLeastAwaiting) {
1068 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1070 ProcessPacket(3);
1071 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1072 EXPECT_TRUE(IsMissing(2));
1073 EXPECT_TRUE(IsMissing(1));
1075 ProcessPacket(2);
1076 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1077 EXPECT_TRUE(IsMissing(1));
1079 ProcessPacket(5);
1080 EXPECT_EQ(5u, outgoing_ack()->largest_observed);
1081 EXPECT_TRUE(IsMissing(1));
1082 EXPECT_TRUE(IsMissing(4));
1084 // Pretend at this point the client has gotten acks for 2 and 3 and 1 is a
1085 // packet the peer will not retransmit. It indicates this by sending 'least
1086 // awaiting' is 4. The connection should then realize 1 will not be
1087 // retransmitted, and will remove it from the missing list.
1088 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 5);
1089 QuicAckFrame frame = InitAckFrame(1);
1090 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _));
1091 ProcessAckPacket(&frame);
1093 // Force an ack to be sent.
1094 SendAckPacketToPeer();
1095 EXPECT_TRUE(IsMissing(4));
1098 TEST_P(QuicConnectionTest, RejectPacketTooFarOut) {
1099 EXPECT_CALL(visitor_,
1100 OnConnectionClosed(QUIC_INVALID_PACKET_HEADER, false));
1101 // Call ProcessDataPacket rather than ProcessPacket, as we should not get a
1102 // packet call to the visitor.
1103 ProcessDataPacket(6000, 0, !kEntropyFlag);
1104 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1105 nullptr);
1108 TEST_P(QuicConnectionTest, RejectUnencryptedStreamData) {
1109 // Process an unencrypted packet from the non-crypto stream.
1110 frame1_.stream_id = 3;
1111 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1112 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_UNENCRYPTED_STREAM_DATA,
1113 false));
1114 ProcessDataPacket(1, 0, !kEntropyFlag);
1115 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1116 nullptr);
1117 const vector<QuicConnectionCloseFrame>& connection_close_frames =
1118 writer_->connection_close_frames();
1119 EXPECT_EQ(1u, connection_close_frames.size());
1120 EXPECT_EQ(QUIC_UNENCRYPTED_STREAM_DATA,
1121 connection_close_frames[0].error_code);
1124 TEST_P(QuicConnectionTest, TruncatedAck) {
1125 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1126 QuicPacketSequenceNumber num_packets = 256 * 2 + 1;
1127 for (QuicPacketSequenceNumber i = 0; i < num_packets; ++i) {
1128 SendStreamDataToPeer(3, "foo", i * 3, !kFin, nullptr);
1131 QuicAckFrame frame = InitAckFrame(num_packets);
1132 SequenceNumberSet lost_packets;
1133 // Create an ack with 256 nacks, none adjacent to one another.
1134 for (QuicPacketSequenceNumber i = 1; i <= 256; ++i) {
1135 NackPacket(i * 2, &frame);
1136 if (i < 256) { // Last packet is nacked, but not lost.
1137 lost_packets.insert(i * 2);
1140 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1141 .WillOnce(Return(lost_packets));
1142 EXPECT_CALL(entropy_calculator_, EntropyHash(511))
1143 .WillOnce(Return(static_cast<QuicPacketEntropyHash>(0)));
1144 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1145 ProcessAckPacket(&frame);
1147 // A truncated ack will not have the true largest observed.
1148 EXPECT_GT(num_packets, manager_->largest_observed());
1150 AckPacket(192, &frame);
1152 // Removing one missing packet allows us to ack 192 and one more range, but
1153 // 192 has already been declared lost, so it doesn't register as an ack.
1154 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1155 .WillOnce(Return(SequenceNumberSet()));
1156 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1157 ProcessAckPacket(&frame);
1158 EXPECT_EQ(num_packets, manager_->largest_observed());
1161 TEST_P(QuicConnectionTest, AckReceiptCausesAckSendBadEntropy) {
1162 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1164 ProcessPacket(1);
1165 // Delay sending, then queue up an ack.
1166 EXPECT_CALL(*send_algorithm_,
1167 TimeUntilSend(_, _, _)).WillOnce(
1168 testing::Return(QuicTime::Delta::FromMicroseconds(1)));
1169 QuicConnectionPeer::SendAck(&connection_);
1171 // Process an ack with a least unacked of the received ack.
1172 // This causes an ack to be sent when TimeUntilSend returns 0.
1173 EXPECT_CALL(*send_algorithm_,
1174 TimeUntilSend(_, _, _)).WillRepeatedly(
1175 testing::Return(QuicTime::Delta::Zero()));
1176 // Skip a packet and then record an ack.
1177 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 2);
1178 QuicAckFrame frame = InitAckFrame(0);
1179 ProcessAckPacket(&frame);
1182 TEST_P(QuicConnectionTest, OutOfOrderReceiptCausesAckSend) {
1183 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1185 ProcessPacket(3);
1186 // Should ack immediately since we have missing packets.
1187 EXPECT_EQ(1u, writer_->packets_write_attempts());
1189 ProcessPacket(2);
1190 // Should ack immediately since we have missing packets.
1191 EXPECT_EQ(2u, writer_->packets_write_attempts());
1193 ProcessPacket(1);
1194 // Should ack immediately, since this fills the last hole.
1195 EXPECT_EQ(3u, writer_->packets_write_attempts());
1197 ProcessPacket(4);
1198 // Should not cause an ack.
1199 EXPECT_EQ(3u, writer_->packets_write_attempts());
1202 TEST_P(QuicConnectionTest, AckReceiptCausesAckSend) {
1203 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1205 QuicPacketSequenceNumber original;
1206 QuicByteCount packet_size;
1207 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1208 .WillOnce(DoAll(SaveArg<2>(&original), SaveArg<3>(&packet_size),
1209 Return(true)));
1210 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
1211 QuicAckFrame frame = InitAckFrame(original);
1212 NackPacket(original, &frame);
1213 // First nack triggers early retransmit.
1214 SequenceNumberSet lost_packets;
1215 lost_packets.insert(1);
1216 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1217 .WillOnce(Return(lost_packets));
1218 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1219 QuicPacketSequenceNumber retransmission;
1220 EXPECT_CALL(*send_algorithm_,
1221 OnPacketSent(_, _, _, packet_size - kQuicVersionSize, _))
1222 .WillOnce(DoAll(SaveArg<2>(&retransmission), Return(true)));
1224 ProcessAckPacket(&frame);
1226 QuicAckFrame frame2 = InitAckFrame(retransmission);
1227 NackPacket(original, &frame2);
1228 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1229 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1230 .WillOnce(Return(SequenceNumberSet()));
1231 ProcessAckPacket(&frame2);
1233 // Now if the peer sends an ack which still reports the retransmitted packet
1234 // as missing, that will bundle an ack with data after two acks in a row
1235 // indicate the high water mark needs to be raised.
1236 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _,
1237 HAS_RETRANSMITTABLE_DATA));
1238 connection_.SendStreamDataWithString(3, "foo", 3, !kFin, nullptr);
1239 // No ack sent.
1240 EXPECT_EQ(1u, writer_->frame_count());
1241 EXPECT_EQ(1u, writer_->stream_frames().size());
1243 // No more packet loss for the rest of the test.
1244 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1245 .WillRepeatedly(Return(SequenceNumberSet()));
1246 ProcessAckPacket(&frame2);
1247 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _,
1248 HAS_RETRANSMITTABLE_DATA));
1249 connection_.SendStreamDataWithString(3, "foo", 3, !kFin, nullptr);
1250 // Ack bundled.
1251 EXPECT_EQ(3u, writer_->frame_count());
1252 EXPECT_EQ(1u, writer_->stream_frames().size());
1253 EXPECT_FALSE(writer_->ack_frames().empty());
1255 // But an ack with no missing packets will not send an ack.
1256 AckPacket(original, &frame2);
1257 ProcessAckPacket(&frame2);
1258 ProcessAckPacket(&frame2);
1261 TEST_P(QuicConnectionTest, 20AcksCausesAckSend) {
1262 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1264 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr);
1266 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
1267 // But an ack with no missing packets will not send an ack.
1268 QuicAckFrame frame = InitAckFrame(1);
1269 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1270 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1271 .WillRepeatedly(Return(SequenceNumberSet()));
1272 for (int i = 0; i < 20; ++i) {
1273 EXPECT_FALSE(ack_alarm->IsSet());
1274 ProcessAckPacket(&frame);
1276 EXPECT_TRUE(ack_alarm->IsSet());
1279 TEST_P(QuicConnectionTest, LeastUnackedLower) {
1280 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1282 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr);
1283 SendStreamDataToPeer(1, "bar", 3, !kFin, nullptr);
1284 SendStreamDataToPeer(1, "eep", 6, !kFin, nullptr);
1286 // Start out saying the least unacked is 2.
1287 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 5);
1288 QuicStopWaitingFrame frame = InitStopWaitingFrame(2);
1289 ProcessStopWaitingPacket(&frame);
1291 // Change it to 1, but lower the sequence number to fake out-of-order packets.
1292 // This should be fine.
1293 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 1);
1294 // The scheduler will not process out of order acks, but all packet processing
1295 // causes the connection to try to write.
1296 EXPECT_CALL(visitor_, OnCanWrite());
1297 QuicStopWaitingFrame frame2 = InitStopWaitingFrame(1);
1298 ProcessStopWaitingPacket(&frame2);
1300 // Now claim it's one, but set the ordering so it was sent "after" the first
1301 // one. This should cause a connection error.
1302 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
1303 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 7);
1304 EXPECT_CALL(visitor_,
1305 OnConnectionClosed(QUIC_INVALID_STOP_WAITING_DATA, false));
1306 QuicStopWaitingFrame frame3 = InitStopWaitingFrame(1);
1307 ProcessStopWaitingPacket(&frame3);
1310 TEST_P(QuicConnectionTest, TooManySentPackets) {
1311 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1313 for (int i = 0; i < 1100; ++i) {
1314 SendStreamDataToPeer(1, "foo", 3 * i, !kFin, nullptr);
1317 // Ack packet 1, which leaves more than the limit outstanding.
1318 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1319 EXPECT_CALL(visitor_, OnConnectionClosed(
1320 QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS, false));
1321 // We're receive buffer limited, so the connection won't try to write more.
1322 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
1324 // Nack every packet except the last one, leaving a huge gap.
1325 QuicAckFrame frame1 = InitAckFrame(1100);
1326 for (QuicPacketSequenceNumber i = 1; i < 1100; ++i) {
1327 NackPacket(i, &frame1);
1329 ProcessAckPacket(&frame1);
1332 TEST_P(QuicConnectionTest, TooManyReceivedPackets) {
1333 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1334 EXPECT_CALL(visitor_, OnConnectionClosed(
1335 QUIC_TOO_MANY_OUTSTANDING_RECEIVED_PACKETS, false));
1337 // Miss every other packet for 1000 packets.
1338 for (QuicPacketSequenceNumber i = 1; i < 1000; ++i) {
1339 ProcessPacket(i * 2);
1340 if (!connection_.connected()) {
1341 break;
1346 TEST_P(QuicConnectionTest, LargestObservedLower) {
1347 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1349 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr);
1350 SendStreamDataToPeer(1, "bar", 3, !kFin, nullptr);
1351 SendStreamDataToPeer(1, "eep", 6, !kFin, nullptr);
1352 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1354 // Start out saying the largest observed is 2.
1355 QuicAckFrame frame1 = InitAckFrame(1);
1356 QuicAckFrame frame2 = InitAckFrame(2);
1357 ProcessAckPacket(&frame2);
1359 // Now change it to 1, and it should cause a connection error.
1360 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, false));
1361 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
1362 ProcessAckPacket(&frame1);
1365 TEST_P(QuicConnectionTest, AckUnsentData) {
1366 // Ack a packet which has not been sent.
1367 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, false));
1368 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1369 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
1370 QuicAckFrame frame(MakeAckFrame(1));
1371 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
1372 ProcessAckPacket(&frame);
1375 TEST_P(QuicConnectionTest, AckAll) {
1376 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1377 ProcessPacket(1);
1379 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 1);
1380 QuicAckFrame frame1 = InitAckFrame(0);
1381 ProcessAckPacket(&frame1);
1384 TEST_P(QuicConnectionTest, SendingDifferentSequenceNumberLengthsBandwidth) {
1385 QuicPacketSequenceNumber last_packet;
1386 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet);
1387 EXPECT_EQ(1u, last_packet);
1388 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1389 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1390 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1391 writer_->header().public_header.sequence_number_length);
1393 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
1394 Return(kMaxPacketSize * 256));
1396 SendStreamDataToPeer(1, "bar", 3, !kFin, &last_packet);
1397 EXPECT_EQ(2u, last_packet);
1398 EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER,
1399 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1400 // The 1 packet lag is due to the sequence number length being recalculated in
1401 // QuicConnection after a packet is sent.
1402 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1403 writer_->header().public_header.sequence_number_length);
1405 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
1406 Return(kMaxPacketSize * 256 * 256));
1408 SendStreamDataToPeer(1, "foo", 6, !kFin, &last_packet);
1409 EXPECT_EQ(3u, last_packet);
1410 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1411 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1412 EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER,
1413 writer_->header().public_header.sequence_number_length);
1415 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
1416 Return(kMaxPacketSize * 256 * 256 * 256));
1418 SendStreamDataToPeer(1, "bar", 9, !kFin, &last_packet);
1419 EXPECT_EQ(4u, last_packet);
1420 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1421 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1422 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1423 writer_->header().public_header.sequence_number_length);
1425 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
1426 Return(kMaxPacketSize * 256 * 256 * 256 * 256));
1428 SendStreamDataToPeer(1, "foo", 12, !kFin, &last_packet);
1429 EXPECT_EQ(5u, last_packet);
1430 EXPECT_EQ(PACKET_6BYTE_SEQUENCE_NUMBER,
1431 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1432 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1433 writer_->header().public_header.sequence_number_length);
1436 // TODO(ianswett): Re-enable this test by finding a good way to test different
1437 // sequence number lengths without sending packets with giant gaps.
1438 TEST_P(QuicConnectionTest,
1439 DISABLED_SendingDifferentSequenceNumberLengthsUnackedDelta) {
1440 QuicPacketSequenceNumber last_packet;
1441 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet);
1442 EXPECT_EQ(1u, last_packet);
1443 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1444 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1445 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1446 writer_->header().public_header.sequence_number_length);
1448 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 100);
1450 SendStreamDataToPeer(1, "bar", 3, !kFin, &last_packet);
1451 EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER,
1452 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1453 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1454 writer_->header().public_header.sequence_number_length);
1456 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 100 * 256);
1458 SendStreamDataToPeer(1, "foo", 6, !kFin, &last_packet);
1459 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1460 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1461 EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER,
1462 writer_->header().public_header.sequence_number_length);
1464 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 100 * 256 * 256);
1466 SendStreamDataToPeer(1, "bar", 9, !kFin, &last_packet);
1467 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1468 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1469 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1470 writer_->header().public_header.sequence_number_length);
1472 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_,
1473 100 * 256 * 256 * 256);
1475 SendStreamDataToPeer(1, "foo", 12, !kFin, &last_packet);
1476 EXPECT_EQ(PACKET_6BYTE_SEQUENCE_NUMBER,
1477 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1478 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1479 writer_->header().public_header.sequence_number_length);
1482 TEST_P(QuicConnectionTest, BasicSending) {
1483 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1484 QuicPacketSequenceNumber last_packet;
1485 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet); // Packet 1
1486 EXPECT_EQ(1u, last_packet);
1487 SendAckPacketToPeer(); // Packet 2
1489 EXPECT_EQ(1u, least_unacked());
1491 SendAckPacketToPeer(); // Packet 3
1492 EXPECT_EQ(1u, least_unacked());
1494 SendStreamDataToPeer(1, "bar", 3, !kFin, &last_packet); // Packet 4
1495 EXPECT_EQ(4u, last_packet);
1496 SendAckPacketToPeer(); // Packet 5
1497 EXPECT_EQ(1u, least_unacked());
1499 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1501 // Peer acks up to packet 3.
1502 QuicAckFrame frame = InitAckFrame(3);
1503 ProcessAckPacket(&frame);
1504 SendAckPacketToPeer(); // Packet 6
1506 // As soon as we've acked one, we skip ack packets 2 and 3 and note lack of
1507 // ack for 4.
1508 EXPECT_EQ(4u, least_unacked());
1510 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1512 // Peer acks up to packet 4, the last packet.
1513 QuicAckFrame frame2 = InitAckFrame(6);
1514 ProcessAckPacket(&frame2); // Acks don't instigate acks.
1516 // Verify that we did not send an ack.
1517 EXPECT_EQ(6u, writer_->header().packet_sequence_number);
1519 // So the last ack has not changed.
1520 EXPECT_EQ(4u, least_unacked());
1522 // If we force an ack, we shouldn't change our retransmit state.
1523 SendAckPacketToPeer(); // Packet 7
1524 EXPECT_EQ(7u, least_unacked());
1526 // But if we send more data it should.
1527 SendStreamDataToPeer(1, "eep", 6, !kFin, &last_packet); // Packet 8
1528 EXPECT_EQ(8u, last_packet);
1529 SendAckPacketToPeer(); // Packet 9
1530 EXPECT_EQ(7u, least_unacked());
1533 // QuicConnection should record the the packet sent-time prior to sending the
1534 // packet.
1535 TEST_P(QuicConnectionTest, RecordSentTimeBeforePacketSent) {
1536 // We're using a MockClock for the tests, so we have complete control over the
1537 // time.
1538 // Our recorded timestamp for the last packet sent time will be passed in to
1539 // the send_algorithm. Make sure that it is set to the correct value.
1540 QuicTime actual_recorded_send_time = QuicTime::Zero();
1541 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1542 .WillOnce(DoAll(SaveArg<0>(&actual_recorded_send_time), Return(true)));
1544 // First send without any pause and check the result.
1545 QuicTime expected_recorded_send_time = clock_.Now();
1546 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
1547 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
1548 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
1549 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
1551 // Now pause during the write, and check the results.
1552 actual_recorded_send_time = QuicTime::Zero();
1553 const QuicTime::Delta write_pause_time_delta =
1554 QuicTime::Delta::FromMilliseconds(5000);
1555 SetWritePauseTimeDelta(write_pause_time_delta);
1556 expected_recorded_send_time = clock_.Now();
1558 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1559 .WillOnce(DoAll(SaveArg<0>(&actual_recorded_send_time), Return(true)));
1560 connection_.SendStreamDataWithString(2, "baz", 0, !kFin, nullptr);
1561 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
1562 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
1563 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
1566 TEST_P(QuicConnectionTest, FECSending) {
1567 // All packets carry version info till version is negotiated.
1568 size_t payload_length;
1569 // GetPacketLengthForOneStream() assumes a stream offset of 0 in determining
1570 // packet length. The size of the offset field in a stream frame is 0 for
1571 // offset 0, and 2 for non-zero offsets up through 64K. Increase
1572 // max_packet_length by 2 so that subsequent packets containing subsequent
1573 // stream frames with non-zero offets will fit within the packet length.
1574 size_t length = 2 + GetPacketLengthForOneStream(
1575 connection_.version(), kIncludeVersion,
1576 PACKET_8BYTE_CONNECTION_ID, PACKET_1BYTE_SEQUENCE_NUMBER,
1577 IN_FEC_GROUP, &payload_length);
1578 creator_->SetMaxPacketLength(length);
1580 // Send 4 protected data packets, which should also trigger 1 FEC packet.
1581 EXPECT_CALL(*send_algorithm_,
1582 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(5);
1583 // The first stream frame will have 2 fewer overhead bytes than the other 3.
1584 const string payload(payload_length * 4 + 2, 'a');
1585 connection_.SendStreamDataWithStringWithFec(1, payload, 0, !kFin, nullptr);
1586 // Expect the FEC group to be closed after SendStreamDataWithString.
1587 EXPECT_FALSE(creator_->IsFecGroupOpen());
1588 EXPECT_FALSE(creator_->IsFecProtected());
1591 TEST_P(QuicConnectionTest, FECQueueing) {
1592 // All packets carry version info till version is negotiated.
1593 size_t payload_length;
1594 size_t length = GetPacketLengthForOneStream(
1595 connection_.version(), kIncludeVersion,
1596 PACKET_8BYTE_CONNECTION_ID, PACKET_1BYTE_SEQUENCE_NUMBER,
1597 IN_FEC_GROUP, &payload_length);
1598 creator_->SetMaxPacketLength(length);
1599 EXPECT_TRUE(creator_->IsFecEnabled());
1601 EXPECT_EQ(0u, connection_.NumQueuedPackets());
1602 BlockOnNextWrite();
1603 const string payload(payload_length, 'a');
1604 connection_.SendStreamDataWithStringWithFec(1, payload, 0, !kFin, nullptr);
1605 EXPECT_FALSE(creator_->IsFecGroupOpen());
1606 EXPECT_FALSE(creator_->IsFecProtected());
1607 // Expect the first data packet and the fec packet to be queued.
1608 EXPECT_EQ(2u, connection_.NumQueuedPackets());
1611 TEST_P(QuicConnectionTest, FECAlarmStoppedWhenFECPacketSent) {
1612 EXPECT_TRUE(creator_->IsFecEnabled());
1613 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1614 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1616 creator_->set_max_packets_per_fec_group(2);
1618 // 1 Data packet. FEC alarm should be set.
1619 EXPECT_CALL(*send_algorithm_,
1620 OnPacketSent(_, _, 1u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1621 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, true, nullptr);
1622 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1624 // Second data packet triggers FEC packet out. FEC alarm should not be set.
1625 EXPECT_CALL(*send_algorithm_,
1626 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(2);
1627 connection_.SendStreamDataWithStringWithFec(5, "foo", 0, true, nullptr);
1628 EXPECT_TRUE(writer_->header().fec_flag);
1629 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1632 TEST_P(QuicConnectionTest, FECAlarmStoppedOnConnectionClose) {
1633 EXPECT_TRUE(creator_->IsFecEnabled());
1634 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1635 creator_->set_max_packets_per_fec_group(100);
1637 // 1 Data packet. FEC alarm should be set.
1638 EXPECT_CALL(*send_algorithm_,
1639 OnPacketSent(_, _, 1u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1640 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, kFin, nullptr);
1641 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1643 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NO_ERROR, false));
1644 // Closing connection should stop the FEC alarm.
1645 connection_.CloseConnection(QUIC_NO_ERROR, /*from_peer=*/false);
1646 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1649 TEST_P(QuicConnectionTest, RemoveFECFromInflightOnRetransmissionTimeout) {
1650 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1651 EXPECT_TRUE(creator_->IsFecEnabled());
1652 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1653 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1655 // 1 Data packet. FEC alarm should be set.
1656 EXPECT_CALL(*send_algorithm_,
1657 OnPacketSent(_, _, 1u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1658 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, !kFin, nullptr);
1659 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1660 size_t protected_packet =
1661 QuicSentPacketManagerPeer::GetBytesInFlight(manager_);
1663 // Force FEC timeout to send FEC packet out.
1664 EXPECT_CALL(*send_algorithm_,
1665 OnPacketSent(_, _, 2u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1666 connection_.GetFecAlarm()->Fire();
1667 EXPECT_TRUE(writer_->header().fec_flag);
1669 size_t fec_packet = protected_packet;
1670 EXPECT_EQ(protected_packet + fec_packet,
1671 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1672 clock_.AdvanceTime(DefaultRetransmissionTime());
1674 // On RTO, both data and FEC packets are removed from inflight, only the data
1675 // packet is retransmitted, and this retransmission (but not FEC) gets added
1676 // back into the inflight.
1677 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
1678 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1679 connection_.GetRetransmissionAlarm()->Fire();
1681 // The retransmission of packet 1 will be 3 bytes smaller than packet 1, since
1682 // the first transmission will have 1 byte for FEC group number and 2 bytes of
1683 // stream frame size, which are absent in the retransmission.
1684 size_t retransmitted_packet = protected_packet - 3;
1685 EXPECT_EQ(protected_packet + retransmitted_packet,
1686 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1687 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1689 // Receive ack for the retransmission. No data should be outstanding.
1690 QuicAckFrame ack = InitAckFrame(3);
1691 NackPacket(1, &ack);
1692 NackPacket(2, &ack);
1693 SequenceNumberSet lost_packets;
1694 lost_packets.insert(1);
1695 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1696 .WillOnce(Return(lost_packets));
1697 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1698 ProcessAckPacket(&ack);
1700 // Ensure the alarm is not set since all packets have been acked or abandoned.
1701 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
1702 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1705 TEST_P(QuicConnectionTest, RemoveFECFromInflightOnLossRetransmission) {
1706 EXPECT_TRUE(creator_->IsFecEnabled());
1707 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1709 // 1 FEC-protected data packet. FEC alarm should be set.
1710 EXPECT_CALL(*send_algorithm_,
1711 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1712 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, kFin, nullptr);
1713 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1714 size_t protected_packet =
1715 QuicSentPacketManagerPeer::GetBytesInFlight(manager_);
1717 // Force FEC timeout to send FEC packet out.
1718 EXPECT_CALL(*send_algorithm_,
1719 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1720 connection_.GetFecAlarm()->Fire();
1721 EXPECT_TRUE(writer_->header().fec_flag);
1722 size_t fec_packet = protected_packet;
1723 EXPECT_EQ(protected_packet + fec_packet,
1724 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1726 // Send more data to trigger NACKs. Note that all data starts at stream offset
1727 // 0 to ensure the same packet size, for ease of testing.
1728 EXPECT_CALL(*send_algorithm_,
1729 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(4);
1730 connection_.SendStreamDataWithString(5, "foo", 0, kFin, nullptr);
1731 connection_.SendStreamDataWithString(7, "foo", 0, kFin, nullptr);
1732 connection_.SendStreamDataWithString(9, "foo", 0, kFin, nullptr);
1733 connection_.SendStreamDataWithString(11, "foo", 0, kFin, nullptr);
1735 // An unprotected packet will be 3 bytes smaller than an FEC-protected packet,
1736 // since the protected packet will have 1 byte for FEC group number and
1737 // 2 bytes of stream frame size, which are absent in the unprotected packet.
1738 size_t unprotected_packet = protected_packet - 3;
1739 EXPECT_EQ(protected_packet + fec_packet + 4 * unprotected_packet,
1740 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1741 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1743 // Ack data packets, and NACK FEC packet and one data packet. Triggers
1744 // NACK-based loss detection of both packets, but only data packet is
1745 // retransmitted and considered oustanding.
1746 QuicAckFrame ack = InitAckFrame(6);
1747 NackPacket(2, &ack);
1748 NackPacket(3, &ack);
1749 SequenceNumberSet lost_packets;
1750 lost_packets.insert(2);
1751 lost_packets.insert(3);
1752 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1753 .WillOnce(Return(lost_packets));
1754 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1755 EXPECT_CALL(*send_algorithm_,
1756 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1757 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1758 ProcessAckPacket(&ack);
1759 // On receiving this ack from the server, the client will no longer send
1760 // version number in subsequent packets, including in this retransmission.
1761 size_t unprotected_packet_no_version = unprotected_packet - 4;
1762 EXPECT_EQ(unprotected_packet_no_version,
1763 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1765 // Receive ack for the retransmission. No data should be outstanding.
1766 QuicAckFrame ack2 = InitAckFrame(7);
1767 NackPacket(2, &ack2);
1768 NackPacket(3, &ack2);
1769 SequenceNumberSet lost_packets2;
1770 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1771 .WillOnce(Return(lost_packets2));
1772 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1773 ProcessAckPacket(&ack2);
1774 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1777 TEST_P(QuicConnectionTest, FECRemainsInflightOnTLPOfEarlierData) {
1778 // This test checks if TLP is sent correctly when a data and an FEC packet
1779 // are outstanding. TLP should be sent for the data packet when the
1780 // retransmission alarm fires.
1781 // Turn on TLP for this test.
1782 QuicSentPacketManagerPeer::SetMaxTailLossProbes(manager_, 1);
1783 EXPECT_TRUE(creator_->IsFecEnabled());
1784 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1785 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1787 // 1 Data packet. FEC alarm should be set.
1788 EXPECT_CALL(*send_algorithm_,
1789 OnPacketSent(_, _, 1u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1790 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, kFin, nullptr);
1791 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1792 size_t protected_packet =
1793 QuicSentPacketManagerPeer::GetBytesInFlight(manager_);
1794 EXPECT_LT(0u, protected_packet);
1796 // Force FEC timeout to send FEC packet out.
1797 EXPECT_CALL(*send_algorithm_,
1798 OnPacketSent(_, _, 2u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1799 connection_.GetFecAlarm()->Fire();
1800 EXPECT_TRUE(writer_->header().fec_flag);
1801 size_t fec_packet = protected_packet;
1802 EXPECT_EQ(protected_packet + fec_packet,
1803 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1805 // TLP alarm should be set.
1806 QuicTime retransmission_time =
1807 connection_.GetRetransmissionAlarm()->deadline();
1808 EXPECT_NE(QuicTime::Zero(), retransmission_time);
1809 // Simulate the retransmission alarm firing and sending a TLP, so send
1810 // algorithm's OnRetransmissionTimeout is not called.
1811 clock_.AdvanceTime(retransmission_time.Subtract(clock_.Now()));
1812 EXPECT_CALL(*send_algorithm_,
1813 OnPacketSent(_, _, 3u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1814 connection_.GetRetransmissionAlarm()->Fire();
1815 // The TLP retransmission of packet 1 will be 3 bytes smaller than packet 1,
1816 // since packet 1 will have 1 byte for FEC group number and 2 bytes of stream
1817 // frame size, which are absent in the the TLP retransmission.
1818 size_t tlp_packet = protected_packet - 3;
1819 EXPECT_EQ(protected_packet + fec_packet + tlp_packet,
1820 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1823 TEST_P(QuicConnectionTest, FECRemainsInflightOnTLPOfLaterData) {
1824 // Tests if TLP is sent correctly when data packet 1 and an FEC packet are
1825 // sent followed by data packet 2, and data packet 1 is acked. TLP should be
1826 // sent for data packet 2 when the retransmission alarm fires. Turn on TLP for
1827 // this test.
1828 QuicSentPacketManagerPeer::SetMaxTailLossProbes(manager_, 1);
1829 EXPECT_TRUE(creator_->IsFecEnabled());
1830 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1831 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1833 // 1 Data packet. FEC alarm should be set.
1834 EXPECT_CALL(*send_algorithm_,
1835 OnPacketSent(_, _, 1u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1836 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, kFin, nullptr);
1837 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1838 size_t protected_packet =
1839 QuicSentPacketManagerPeer::GetBytesInFlight(manager_);
1840 EXPECT_LT(0u, protected_packet);
1842 // Force FEC timeout to send FEC packet out.
1843 EXPECT_CALL(*send_algorithm_,
1844 OnPacketSent(_, _, 2u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1845 connection_.GetFecAlarm()->Fire();
1846 EXPECT_TRUE(writer_->header().fec_flag);
1847 // Protected data packet and FEC packet oustanding.
1848 size_t fec_packet = protected_packet;
1849 EXPECT_EQ(protected_packet + fec_packet,
1850 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1852 // Send 1 unprotected data packet. No FEC alarm should be set.
1853 EXPECT_CALL(*send_algorithm_,
1854 OnPacketSent(_, _, 3u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1855 connection_.SendStreamDataWithString(5, "foo", 0, kFin, nullptr);
1856 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1857 // Protected data packet, FEC packet, and unprotected data packet oustanding.
1858 // An unprotected packet will be 3 bytes smaller than an FEC-protected packet,
1859 // since the protected packet will have 1 byte for FEC group number and
1860 // 2 bytes of stream frame size, which are absent in the unprotected packet.
1861 size_t unprotected_packet = protected_packet - 3;
1862 EXPECT_EQ(protected_packet + fec_packet + unprotected_packet,
1863 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1865 // Receive ack for first data packet. FEC and second data packet are still
1866 // outstanding.
1867 QuicAckFrame ack = InitAckFrame(1);
1868 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1869 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1870 ProcessAckPacket(&ack);
1871 // FEC packet and unprotected data packet oustanding.
1872 EXPECT_EQ(fec_packet + unprotected_packet,
1873 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1875 // TLP alarm should be set.
1876 QuicTime retransmission_time =
1877 connection_.GetRetransmissionAlarm()->deadline();
1878 EXPECT_NE(QuicTime::Zero(), retransmission_time);
1879 // Simulate the retransmission alarm firing and sending a TLP, so send
1880 // algorithm's OnRetransmissionTimeout is not called.
1881 clock_.AdvanceTime(retransmission_time.Subtract(clock_.Now()));
1882 EXPECT_CALL(*send_algorithm_,
1883 OnPacketSent(_, _, 4u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1884 connection_.GetRetransmissionAlarm()->Fire();
1886 // Having received an ack from the server, the client will no longer send
1887 // version number in subsequent packets, including in this retransmission.
1888 size_t tlp_packet_no_version = unprotected_packet - 4;
1889 EXPECT_EQ(fec_packet + unprotected_packet + tlp_packet_no_version,
1890 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1893 TEST_P(QuicConnectionTest, NoTLPForFECPacket) {
1894 // Turn on TLP for this test.
1895 QuicSentPacketManagerPeer::SetMaxTailLossProbes(manager_, 1);
1896 EXPECT_TRUE(creator_->IsFecEnabled());
1897 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1899 // Send 1 FEC-protected data packet. FEC alarm should be set.
1900 EXPECT_CALL(*send_algorithm_,
1901 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1902 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, !kFin, nullptr);
1903 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1904 // Force FEC timeout to send FEC packet out.
1905 EXPECT_CALL(*send_algorithm_,
1906 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1907 connection_.GetFecAlarm()->Fire();
1908 EXPECT_TRUE(writer_->header().fec_flag);
1910 // Ack data packet, but not FEC packet.
1911 QuicAckFrame ack = InitAckFrame(1);
1912 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1913 ProcessAckPacket(&ack);
1915 // No TLP alarm for FEC, but retransmission alarm should be set for an RTO.
1916 EXPECT_LT(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1917 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
1918 QuicTime rto_time = connection_.GetRetransmissionAlarm()->deadline();
1919 EXPECT_NE(QuicTime::Zero(), rto_time);
1921 // Simulate the retransmission alarm firing. FEC packet is no longer
1922 // outstanding.
1923 clock_.AdvanceTime(rto_time.Subtract(clock_.Now()));
1924 connection_.GetRetransmissionAlarm()->Fire();
1926 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
1927 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1930 TEST_P(QuicConnectionTest, FramePacking) {
1931 CongestionBlockWrites();
1933 // Send an ack and two stream frames in 1 packet by queueing them.
1934 connection_.SendAck();
1935 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
1936 IgnoreResult(InvokeWithoutArgs(&connection_,
1937 &TestConnection::SendStreamData3)),
1938 IgnoreResult(InvokeWithoutArgs(&connection_,
1939 &TestConnection::SendStreamData5))));
1941 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1942 CongestionUnblockWrites();
1943 connection_.GetSendAlarm()->Fire();
1944 EXPECT_EQ(0u, connection_.NumQueuedPackets());
1945 EXPECT_FALSE(connection_.HasQueuedData());
1947 // Parse the last packet and ensure it's an ack and two stream frames from
1948 // two different streams.
1949 EXPECT_EQ(4u, writer_->frame_count());
1950 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
1951 EXPECT_FALSE(writer_->ack_frames().empty());
1952 ASSERT_EQ(2u, writer_->stream_frames().size());
1953 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id);
1954 EXPECT_EQ(kClientDataStreamId2, writer_->stream_frames()[1].stream_id);
1957 TEST_P(QuicConnectionTest, FramePackingNonCryptoThenCrypto) {
1958 CongestionBlockWrites();
1960 // Send an ack and two stream frames (one non-crypto, then one crypto) in 2
1961 // packets by queueing them.
1962 connection_.SendAck();
1963 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
1964 IgnoreResult(InvokeWithoutArgs(&connection_,
1965 &TestConnection::SendStreamData3)),
1966 IgnoreResult(InvokeWithoutArgs(&connection_,
1967 &TestConnection::SendCryptoStreamData))));
1969 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
1970 CongestionUnblockWrites();
1971 connection_.GetSendAlarm()->Fire();
1972 EXPECT_EQ(0u, connection_.NumQueuedPackets());
1973 EXPECT_FALSE(connection_.HasQueuedData());
1975 // Parse the last packet and ensure it's the crypto stream frame.
1976 EXPECT_EQ(1u, writer_->frame_count());
1977 ASSERT_EQ(1u, writer_->stream_frames().size());
1978 EXPECT_EQ(kCryptoStreamId, writer_->stream_frames()[0].stream_id);
1981 TEST_P(QuicConnectionTest, FramePackingCryptoThenNonCrypto) {
1982 CongestionBlockWrites();
1984 // Send an ack and two stream frames (one crypto, then one non-crypto) in 2
1985 // packets by queueing them.
1986 connection_.SendAck();
1987 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
1988 IgnoreResult(InvokeWithoutArgs(&connection_,
1989 &TestConnection::SendCryptoStreamData)),
1990 IgnoreResult(InvokeWithoutArgs(&connection_,
1991 &TestConnection::SendStreamData3))));
1993 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
1994 CongestionUnblockWrites();
1995 connection_.GetSendAlarm()->Fire();
1996 EXPECT_EQ(0u, connection_.NumQueuedPackets());
1997 EXPECT_FALSE(connection_.HasQueuedData());
1999 // Parse the last packet and ensure it's the stream frame from stream 3.
2000 EXPECT_EQ(1u, writer_->frame_count());
2001 ASSERT_EQ(1u, writer_->stream_frames().size());
2002 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id);
2005 TEST_P(QuicConnectionTest, FramePackingFEC) {
2006 EXPECT_TRUE(creator_->IsFecEnabled());
2008 CongestionBlockWrites();
2010 // Queue an ack and two stream frames. Ack gets flushed when FEC is turned on
2011 // for sending protected data; two stream frames are packed in 1 packet.
2012 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
2013 IgnoreResult(InvokeWithoutArgs(
2014 &connection_, &TestConnection::SendStreamData3WithFec)),
2015 IgnoreResult(InvokeWithoutArgs(
2016 &connection_, &TestConnection::SendStreamData5WithFec))));
2017 connection_.SendAck();
2019 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
2020 CongestionUnblockWrites();
2021 connection_.GetSendAlarm()->Fire();
2022 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2023 EXPECT_FALSE(connection_.HasQueuedData());
2025 // Parse the last packet and ensure it's in an fec group.
2026 EXPECT_EQ(2u, writer_->header().fec_group);
2027 EXPECT_EQ(2u, writer_->frame_count());
2029 // FEC alarm should be set.
2030 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
2033 TEST_P(QuicConnectionTest, FramePackingAckResponse) {
2034 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2035 // Process a data packet to queue up a pending ack.
2036 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
2037 ProcessDataPacket(1, 1, kEntropyFlag);
2039 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
2040 IgnoreResult(InvokeWithoutArgs(&connection_,
2041 &TestConnection::SendStreamData3)),
2042 IgnoreResult(InvokeWithoutArgs(&connection_,
2043 &TestConnection::SendStreamData5))));
2045 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2047 // Process an ack to cause the visitor's OnCanWrite to be invoked.
2048 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 2);
2049 QuicAckFrame ack_one = InitAckFrame(0);
2050 ProcessAckPacket(&ack_one);
2052 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2053 EXPECT_FALSE(connection_.HasQueuedData());
2055 // Parse the last packet and ensure it's an ack and two stream frames from
2056 // two different streams.
2057 EXPECT_EQ(4u, writer_->frame_count());
2058 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
2059 EXPECT_FALSE(writer_->ack_frames().empty());
2060 ASSERT_EQ(2u, writer_->stream_frames().size());
2061 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id);
2062 EXPECT_EQ(kClientDataStreamId2, writer_->stream_frames()[1].stream_id);
2065 TEST_P(QuicConnectionTest, FramePackingSendv) {
2066 // Send data in 1 packet by writing multiple blocks in a single iovector
2067 // using writev.
2068 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2070 char data[] = "ABCD";
2071 IOVector data_iov;
2072 data_iov.AppendNoCoalesce(data, 2);
2073 data_iov.AppendNoCoalesce(data + 2, 2);
2074 connection_.SendStreamData(1, data_iov, 0, !kFin, MAY_FEC_PROTECT, nullptr);
2076 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2077 EXPECT_FALSE(connection_.HasQueuedData());
2079 // Parse the last packet and ensure multiple iovector blocks have
2080 // been packed into a single stream frame from one stream.
2081 EXPECT_EQ(1u, writer_->frame_count());
2082 EXPECT_EQ(1u, writer_->stream_frames().size());
2083 QuicStreamFrame frame = writer_->stream_frames()[0];
2084 EXPECT_EQ(1u, frame.stream_id);
2085 EXPECT_EQ("ABCD", frame.data);
2088 TEST_P(QuicConnectionTest, FramePackingSendvQueued) {
2089 // Try to send two stream frames in 1 packet by using writev.
2090 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2092 BlockOnNextWrite();
2093 char data[] = "ABCD";
2094 IOVector data_iov;
2095 data_iov.AppendNoCoalesce(data, 2);
2096 data_iov.AppendNoCoalesce(data + 2, 2);
2097 connection_.SendStreamData(1, data_iov, 0, !kFin, MAY_FEC_PROTECT, nullptr);
2099 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2100 EXPECT_TRUE(connection_.HasQueuedData());
2102 // Unblock the writes and actually send.
2103 writer_->SetWritable();
2104 connection_.OnCanWrite();
2105 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2107 // Parse the last packet and ensure it's one stream frame from one stream.
2108 EXPECT_EQ(1u, writer_->frame_count());
2109 EXPECT_EQ(1u, writer_->stream_frames().size());
2110 EXPECT_EQ(1u, writer_->stream_frames()[0].stream_id);
2113 TEST_P(QuicConnectionTest, SendingZeroBytes) {
2114 // Send a zero byte write with a fin using writev.
2115 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2116 IOVector empty_iov;
2117 connection_.SendStreamData(1, empty_iov, 0, kFin, MAY_FEC_PROTECT, nullptr);
2119 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2120 EXPECT_FALSE(connection_.HasQueuedData());
2122 // Parse the last packet and ensure it's one stream frame from one stream.
2123 EXPECT_EQ(1u, writer_->frame_count());
2124 EXPECT_EQ(1u, writer_->stream_frames().size());
2125 EXPECT_EQ(1u, writer_->stream_frames()[0].stream_id);
2126 EXPECT_TRUE(writer_->stream_frames()[0].fin);
2129 TEST_P(QuicConnectionTest, OnCanWrite) {
2130 // Visitor's OnCanWrite will send data, but will have more pending writes.
2131 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
2132 IgnoreResult(InvokeWithoutArgs(&connection_,
2133 &TestConnection::SendStreamData3)),
2134 IgnoreResult(InvokeWithoutArgs(&connection_,
2135 &TestConnection::SendStreamData5))));
2136 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillOnce(Return(true));
2137 EXPECT_CALL(*send_algorithm_,
2138 TimeUntilSend(_, _, _)).WillRepeatedly(
2139 testing::Return(QuicTime::Delta::Zero()));
2141 connection_.OnCanWrite();
2143 // Parse the last packet and ensure it's the two stream frames from
2144 // two different streams.
2145 EXPECT_EQ(2u, writer_->frame_count());
2146 EXPECT_EQ(2u, writer_->stream_frames().size());
2147 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id);
2148 EXPECT_EQ(kClientDataStreamId2, writer_->stream_frames()[1].stream_id);
2151 TEST_P(QuicConnectionTest, RetransmitOnNack) {
2152 QuicPacketSequenceNumber last_packet;
2153 QuicByteCount second_packet_size;
2154 SendStreamDataToPeer(3, "foo", 0, !kFin, &last_packet); // Packet 1
2155 second_packet_size =
2156 SendStreamDataToPeer(3, "foos", 3, !kFin, &last_packet); // Packet 2
2157 SendStreamDataToPeer(3, "fooos", 7, !kFin, &last_packet); // Packet 3
2159 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2161 // Don't lose a packet on an ack, and nothing is retransmitted.
2162 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2163 QuicAckFrame ack_one = InitAckFrame(1);
2164 ProcessAckPacket(&ack_one);
2166 // Lose a packet and ensure it triggers retransmission.
2167 QuicAckFrame nack_two = InitAckFrame(3);
2168 NackPacket(2, &nack_two);
2169 SequenceNumberSet lost_packets;
2170 lost_packets.insert(2);
2171 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2172 .WillOnce(Return(lost_packets));
2173 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2174 EXPECT_CALL(*send_algorithm_,
2175 OnPacketSent(_, _, _, second_packet_size - kQuicVersionSize, _)).
2176 Times(1);
2177 ProcessAckPacket(&nack_two);
2180 TEST_P(QuicConnectionTest, DoNotSendQueuedPacketForResetStream) {
2181 // Block the connection to queue the packet.
2182 BlockOnNextWrite();
2184 QuicStreamId stream_id = 2;
2185 connection_.SendStreamDataWithString(stream_id, "foo", 0, !kFin, nullptr);
2187 // Now that there is a queued packet, reset the stream.
2188 connection_.SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 14);
2190 // Unblock the connection and verify that only the RST_STREAM is sent.
2191 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2192 writer_->SetWritable();
2193 connection_.OnCanWrite();
2194 EXPECT_EQ(1u, writer_->frame_count());
2195 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
2198 TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnNack) {
2199 QuicStreamId stream_id = 2;
2200 QuicPacketSequenceNumber last_packet;
2201 SendStreamDataToPeer(stream_id, "foo", 0, !kFin, &last_packet);
2202 SendStreamDataToPeer(stream_id, "foos", 3, !kFin, &last_packet);
2203 SendStreamDataToPeer(stream_id, "fooos", 7, !kFin, &last_packet);
2205 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2206 connection_.SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 14);
2208 // Lose a packet and ensure it does not trigger retransmission.
2209 QuicAckFrame nack_two = InitAckFrame(last_packet);
2210 NackPacket(last_packet - 1, &nack_two);
2211 SequenceNumberSet lost_packets;
2212 lost_packets.insert(last_packet - 1);
2213 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2214 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2215 .WillOnce(Return(lost_packets));
2216 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2217 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
2218 ProcessAckPacket(&nack_two);
2221 TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnRTO) {
2222 QuicStreamId stream_id = 2;
2223 QuicPacketSequenceNumber last_packet;
2224 SendStreamDataToPeer(stream_id, "foo", 0, !kFin, &last_packet);
2226 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2227 connection_.SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 14);
2229 // Fire the RTO and verify that the RST_STREAM is resent, not stream data.
2230 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2231 clock_.AdvanceTime(DefaultRetransmissionTime());
2232 connection_.GetRetransmissionAlarm()->Fire();
2233 EXPECT_EQ(1u, writer_->frame_count());
2234 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
2235 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
2238 TEST_P(QuicConnectionTest, DoNotSendPendingRetransmissionForResetStream) {
2239 QuicStreamId stream_id = 2;
2240 QuicPacketSequenceNumber last_packet;
2241 SendStreamDataToPeer(stream_id, "foo", 0, !kFin, &last_packet);
2242 SendStreamDataToPeer(stream_id, "foos", 3, !kFin, &last_packet);
2243 BlockOnNextWrite();
2244 connection_.SendStreamDataWithString(stream_id, "fooos", 7, !kFin, nullptr);
2246 // Lose a packet which will trigger a pending retransmission.
2247 QuicAckFrame ack = InitAckFrame(last_packet);
2248 NackPacket(last_packet - 1, &ack);
2249 SequenceNumberSet lost_packets;
2250 lost_packets.insert(last_packet - 1);
2251 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2252 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2253 .WillOnce(Return(lost_packets));
2254 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2255 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
2256 ProcessAckPacket(&ack);
2258 connection_.SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 14);
2260 // Unblock the connection and verify that the RST_STREAM is sent but not the
2261 // second data packet nor a retransmit.
2262 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2263 writer_->SetWritable();
2264 connection_.OnCanWrite();
2265 EXPECT_EQ(1u, writer_->frame_count());
2266 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
2267 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
2270 TEST_P(QuicConnectionTest, DiscardRetransmit) {
2271 QuicPacketSequenceNumber last_packet;
2272 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet); // Packet 1
2273 SendStreamDataToPeer(1, "foos", 3, !kFin, &last_packet); // Packet 2
2274 SendStreamDataToPeer(1, "fooos", 7, !kFin, &last_packet); // Packet 3
2276 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2278 // Instigate a loss with an ack.
2279 QuicAckFrame nack_two = InitAckFrame(3);
2280 NackPacket(2, &nack_two);
2281 // The first nack should trigger a fast retransmission, but we'll be
2282 // write blocked, so the packet will be queued.
2283 BlockOnNextWrite();
2284 SequenceNumberSet lost_packets;
2285 lost_packets.insert(2);
2286 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2287 .WillOnce(Return(lost_packets));
2288 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2289 ProcessAckPacket(&nack_two);
2290 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2292 // Now, ack the previous transmission.
2293 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2294 .WillOnce(Return(SequenceNumberSet()));
2295 QuicAckFrame ack_all = InitAckFrame(3);
2296 ProcessAckPacket(&ack_all);
2298 // Unblock the socket and attempt to send the queued packets. However,
2299 // since the previous transmission has been acked, we will not
2300 // send the retransmission.
2301 EXPECT_CALL(*send_algorithm_,
2302 OnPacketSent(_, _, _, _, _)).Times(0);
2304 writer_->SetWritable();
2305 connection_.OnCanWrite();
2307 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2310 TEST_P(QuicConnectionTest, RetransmitNackedLargestObserved) {
2311 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2312 QuicPacketSequenceNumber largest_observed;
2313 QuicByteCount packet_size;
2314 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2315 .WillOnce(DoAll(SaveArg<2>(&largest_observed), SaveArg<3>(&packet_size),
2316 Return(true)));
2317 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
2319 QuicAckFrame frame = InitAckFrame(1);
2320 NackPacket(largest_observed, &frame);
2321 // The first nack should retransmit the largest observed packet.
2322 SequenceNumberSet lost_packets;
2323 lost_packets.insert(1);
2324 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2325 .WillOnce(Return(lost_packets));
2326 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2327 EXPECT_CALL(*send_algorithm_,
2328 OnPacketSent(_, _, _, packet_size - kQuicVersionSize, _));
2329 ProcessAckPacket(&frame);
2332 TEST_P(QuicConnectionTest, QueueAfterTwoRTOs) {
2333 for (int i = 0; i < 10; ++i) {
2334 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2335 connection_.SendStreamDataWithString(3, "foo", i * 3, !kFin, nullptr);
2338 // Block the writer and ensure they're queued.
2339 BlockOnNextWrite();
2340 clock_.AdvanceTime(DefaultRetransmissionTime());
2341 // Only one packet should be retransmitted.
2342 connection_.GetRetransmissionAlarm()->Fire();
2343 EXPECT_TRUE(connection_.HasQueuedData());
2345 // Unblock the writer.
2346 writer_->SetWritable();
2347 clock_.AdvanceTime(QuicTime::Delta::FromMicroseconds(
2348 2 * DefaultRetransmissionTime().ToMicroseconds()));
2349 // Retransmit already retransmitted packets event though the sequence number
2350 // greater than the largest observed.
2351 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
2352 connection_.GetRetransmissionAlarm()->Fire();
2353 connection_.OnCanWrite();
2356 TEST_P(QuicConnectionTest, WriteBlockedThenSent) {
2357 BlockOnNextWrite();
2358 writer_->set_is_write_blocked_data_buffered(true);
2359 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2360 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
2361 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2363 writer_->SetWritable();
2364 connection_.OnCanWrite();
2365 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2368 TEST_P(QuicConnectionTest, RetransmitWriteBlockedAckedOriginalThenSent) {
2369 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2370 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
2371 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2373 BlockOnNextWrite();
2374 writer_->set_is_write_blocked_data_buffered(true);
2375 // Simulate the retransmission alarm firing.
2376 clock_.AdvanceTime(DefaultRetransmissionTime());
2377 connection_.GetRetransmissionAlarm()->Fire();
2379 // Ack the sent packet before the callback returns, which happens in
2380 // rare circumstances with write blocked sockets.
2381 QuicAckFrame ack = InitAckFrame(1);
2382 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2383 ProcessAckPacket(&ack);
2385 writer_->SetWritable();
2386 connection_.OnCanWrite();
2387 // There is now a pending packet, but with no retransmittable frames.
2388 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2389 EXPECT_FALSE(connection_.sent_packet_manager().HasRetransmittableFrames(2));
2392 TEST_P(QuicConnectionTest, AlarmsWhenWriteBlocked) {
2393 // Block the connection.
2394 BlockOnNextWrite();
2395 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
2396 EXPECT_EQ(1u, writer_->packets_write_attempts());
2397 EXPECT_TRUE(writer_->IsWriteBlocked());
2399 // Set the send and resumption alarms. Fire the alarms and ensure they don't
2400 // attempt to write.
2401 connection_.GetResumeWritesAlarm()->Set(clock_.ApproximateNow());
2402 connection_.GetSendAlarm()->Set(clock_.ApproximateNow());
2403 connection_.GetResumeWritesAlarm()->Fire();
2404 connection_.GetSendAlarm()->Fire();
2405 EXPECT_TRUE(writer_->IsWriteBlocked());
2406 EXPECT_EQ(1u, writer_->packets_write_attempts());
2409 TEST_P(QuicConnectionTest, NoLimitPacketsPerNack) {
2410 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2411 int offset = 0;
2412 // Send packets 1 to 15.
2413 for (int i = 0; i < 15; ++i) {
2414 SendStreamDataToPeer(1, "foo", offset, !kFin, nullptr);
2415 offset += 3;
2418 // Ack 15, nack 1-14.
2419 SequenceNumberSet lost_packets;
2420 QuicAckFrame nack = InitAckFrame(15);
2421 for (int i = 1; i < 15; ++i) {
2422 NackPacket(i, &nack);
2423 lost_packets.insert(i);
2426 // 14 packets have been NACK'd and lost. In TCP cubic, PRR limits
2427 // the retransmission rate in the case of burst losses.
2428 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2429 .WillOnce(Return(lost_packets));
2430 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2431 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(14);
2432 ProcessAckPacket(&nack);
2435 // Test sending multiple acks from the connection to the session.
2436 TEST_P(QuicConnectionTest, MultipleAcks) {
2437 QuicPacketSequenceNumber last_packet;
2438 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet); // Packet 1
2439 EXPECT_EQ(1u, last_packet);
2440 SendStreamDataToPeer(3, "foo", 0, !kFin, &last_packet); // Packet 2
2441 EXPECT_EQ(2u, last_packet);
2442 SendAckPacketToPeer(); // Packet 3
2443 SendStreamDataToPeer(5, "foo", 0, !kFin, &last_packet); // Packet 4
2444 EXPECT_EQ(4u, last_packet);
2445 SendStreamDataToPeer(1, "foo", 3, !kFin, &last_packet); // Packet 5
2446 EXPECT_EQ(5u, last_packet);
2447 SendStreamDataToPeer(3, "foo", 3, !kFin, &last_packet); // Packet 6
2448 EXPECT_EQ(6u, last_packet);
2450 // Client will ack packets 1, 2, [!3], 4, 5.
2451 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2452 QuicAckFrame frame1 = InitAckFrame(5);
2453 NackPacket(3, &frame1);
2454 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2455 ProcessAckPacket(&frame1);
2457 // Now the client implicitly acks 3, and explicitly acks 6.
2458 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2459 QuicAckFrame frame2 = InitAckFrame(6);
2460 ProcessAckPacket(&frame2);
2463 TEST_P(QuicConnectionTest, DontLatchUnackedPacket) {
2464 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr); // Packet 1;
2465 // From now on, we send acks, so the send algorithm won't mark them pending.
2466 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2467 .WillByDefault(Return(false));
2468 SendAckPacketToPeer(); // Packet 2
2470 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2471 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2472 QuicAckFrame frame = InitAckFrame(1);
2473 ProcessAckPacket(&frame);
2475 // Verify that our internal state has least-unacked as 2, because we're still
2476 // waiting for a potential ack for 2.
2478 EXPECT_EQ(2u, stop_waiting()->least_unacked);
2480 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2481 frame = InitAckFrame(2);
2482 ProcessAckPacket(&frame);
2483 EXPECT_EQ(3u, stop_waiting()->least_unacked);
2485 // When we send an ack, we make sure our least-unacked makes sense. In this
2486 // case since we're not waiting on an ack for 2 and all packets are acked, we
2487 // set it to 3.
2488 SendAckPacketToPeer(); // Packet 3
2489 // Least_unacked remains at 3 until another ack is received.
2490 EXPECT_EQ(3u, stop_waiting()->least_unacked);
2491 // Check that the outgoing ack had its sequence number as least_unacked.
2492 EXPECT_EQ(3u, least_unacked());
2494 // Ack the ack, which updates the rtt and raises the least unacked.
2495 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2496 frame = InitAckFrame(3);
2497 ProcessAckPacket(&frame);
2499 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2500 .WillByDefault(Return(true));
2501 SendStreamDataToPeer(1, "bar", 3, false, nullptr); // Packet 4
2502 EXPECT_EQ(4u, stop_waiting()->least_unacked);
2503 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2504 .WillByDefault(Return(false));
2505 SendAckPacketToPeer(); // Packet 5
2506 EXPECT_EQ(4u, least_unacked());
2508 // Send two data packets at the end, and ensure if the last one is acked,
2509 // the least unacked is raised above the ack packets.
2510 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2511 .WillByDefault(Return(true));
2512 SendStreamDataToPeer(1, "bar", 6, false, nullptr); // Packet 6
2513 SendStreamDataToPeer(1, "bar", 9, false, nullptr); // Packet 7
2515 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2516 frame = InitAckFrame(7);
2517 NackPacket(5, &frame);
2518 NackPacket(6, &frame);
2519 ProcessAckPacket(&frame);
2521 EXPECT_EQ(6u, stop_waiting()->least_unacked);
2524 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterFecPacket) {
2525 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2527 // Don't send missing packet 1.
2528 ProcessFecPacket(2, 1, true, !kEntropyFlag, nullptr);
2529 // Entropy flag should be false, so entropy should be 0.
2530 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2533 TEST_P(QuicConnectionTest, ReviveMissingPacketWithVaryingSeqNumLengths) {
2534 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2536 // Set up a debug visitor to the connection.
2537 scoped_ptr<FecQuicConnectionDebugVisitor> fec_visitor(
2538 new FecQuicConnectionDebugVisitor());
2539 connection_.set_debug_visitor(fec_visitor.get());
2541 QuicPacketSequenceNumber fec_packet = 0;
2542 QuicSequenceNumberLength lengths[] = {PACKET_6BYTE_SEQUENCE_NUMBER,
2543 PACKET_4BYTE_SEQUENCE_NUMBER,
2544 PACKET_2BYTE_SEQUENCE_NUMBER,
2545 PACKET_1BYTE_SEQUENCE_NUMBER};
2546 // For each sequence number length size, revive a packet and check sequence
2547 // number length in the revived packet.
2548 for (size_t i = 0; i < arraysize(lengths); ++i) {
2549 // Set sequence_number_length_ (for data and FEC packets).
2550 sequence_number_length_ = lengths[i];
2551 fec_packet += 2;
2552 // Don't send missing packet, but send fec packet right after it.
2553 ProcessFecPacket(fec_packet, fec_packet - 1, true, !kEntropyFlag, nullptr);
2554 // Sequence number length in the revived header should be the same as
2555 // in the original data/fec packet headers.
2556 EXPECT_EQ(sequence_number_length_, fec_visitor->revived_header().
2557 public_header.sequence_number_length);
2561 TEST_P(QuicConnectionTest, ReviveMissingPacketWithVaryingConnectionIdLengths) {
2562 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2564 // Set up a debug visitor to the connection.
2565 scoped_ptr<FecQuicConnectionDebugVisitor> fec_visitor(
2566 new FecQuicConnectionDebugVisitor());
2567 connection_.set_debug_visitor(fec_visitor.get());
2569 QuicPacketSequenceNumber fec_packet = 0;
2570 QuicConnectionIdLength lengths[] = {PACKET_8BYTE_CONNECTION_ID,
2571 PACKET_4BYTE_CONNECTION_ID,
2572 PACKET_1BYTE_CONNECTION_ID,
2573 PACKET_0BYTE_CONNECTION_ID};
2574 // For each connection id length size, revive a packet and check connection
2575 // id length in the revived packet.
2576 for (size_t i = 0; i < arraysize(lengths); ++i) {
2577 // Set connection id length (for data and FEC packets).
2578 connection_id_length_ = lengths[i];
2579 fec_packet += 2;
2580 // Don't send missing packet, but send fec packet right after it.
2581 ProcessFecPacket(fec_packet, fec_packet - 1, true, !kEntropyFlag, nullptr);
2582 // Connection id length in the revived header should be the same as
2583 // in the original data/fec packet headers.
2584 EXPECT_EQ(connection_id_length_,
2585 fec_visitor->revived_header().public_header.connection_id_length);
2589 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPacketThenFecPacket) {
2590 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2592 ProcessFecProtectedPacket(1, false, kEntropyFlag);
2593 // Don't send missing packet 2.
2594 ProcessFecPacket(3, 1, true, !kEntropyFlag, nullptr);
2595 // Entropy flag should be true, so entropy should not be 0.
2596 EXPECT_NE(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2599 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPacketsThenFecPacket) {
2600 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2602 ProcessFecProtectedPacket(1, false, !kEntropyFlag);
2603 // Don't send missing packet 2.
2604 ProcessFecProtectedPacket(3, false, !kEntropyFlag);
2605 ProcessFecPacket(4, 1, true, kEntropyFlag, nullptr);
2606 // Ensure QUIC no longer revives entropy for lost packets.
2607 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2608 EXPECT_NE(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 4));
2611 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPacket) {
2612 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2614 // Don't send missing packet 1.
2615 ProcessFecPacket(3, 1, false, !kEntropyFlag, nullptr);
2616 // Out of order.
2617 ProcessFecProtectedPacket(2, true, !kEntropyFlag);
2618 // Entropy flag should be false, so entropy should be 0.
2619 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2622 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPackets) {
2623 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2625 ProcessFecProtectedPacket(1, false, !kEntropyFlag);
2626 // Don't send missing packet 2.
2627 ProcessFecPacket(6, 1, false, kEntropyFlag, nullptr);
2628 ProcessFecProtectedPacket(3, false, kEntropyFlag);
2629 ProcessFecProtectedPacket(4, false, kEntropyFlag);
2630 ProcessFecProtectedPacket(5, true, !kEntropyFlag);
2631 // Ensure entropy is not revived for the missing packet.
2632 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2633 EXPECT_NE(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 3));
2636 TEST_P(QuicConnectionTest, TLP) {
2637 QuicSentPacketManagerPeer::SetMaxTailLossProbes(manager_, 1);
2639 SendStreamDataToPeer(3, "foo", 0, !kFin, nullptr);
2640 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2641 QuicTime retransmission_time =
2642 connection_.GetRetransmissionAlarm()->deadline();
2643 EXPECT_NE(QuicTime::Zero(), retransmission_time);
2645 EXPECT_EQ(1u, writer_->header().packet_sequence_number);
2646 // Simulate the retransmission alarm firing and sending a tlp,
2647 // so send algorithm's OnRetransmissionTimeout is not called.
2648 clock_.AdvanceTime(retransmission_time.Subtract(clock_.Now()));
2649 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 2u, _, _));
2650 connection_.GetRetransmissionAlarm()->Fire();
2651 EXPECT_EQ(2u, writer_->header().packet_sequence_number);
2652 // We do not raise the high water mark yet.
2653 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2656 TEST_P(QuicConnectionTest, RTO) {
2657 QuicTime default_retransmission_time = clock_.ApproximateNow().Add(
2658 DefaultRetransmissionTime());
2659 SendStreamDataToPeer(3, "foo", 0, !kFin, nullptr);
2660 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2662 EXPECT_EQ(1u, writer_->header().packet_sequence_number);
2663 EXPECT_EQ(default_retransmission_time,
2664 connection_.GetRetransmissionAlarm()->deadline());
2665 // Simulate the retransmission alarm firing.
2666 clock_.AdvanceTime(DefaultRetransmissionTime());
2667 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 2u, _, _));
2668 connection_.GetRetransmissionAlarm()->Fire();
2669 EXPECT_EQ(2u, writer_->header().packet_sequence_number);
2670 // We do not raise the high water mark yet.
2671 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2674 TEST_P(QuicConnectionTest, RTOWithSameEncryptionLevel) {
2675 QuicTime default_retransmission_time = clock_.ApproximateNow().Add(
2676 DefaultRetransmissionTime());
2677 use_tagging_decrypter();
2679 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
2680 // the end of the packet. We can test this to check which encrypter was used.
2681 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2682 SendStreamDataToPeer(3, "foo", 0, !kFin, nullptr);
2683 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
2685 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2686 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2687 SendStreamDataToPeer(3, "foo", 0, !kFin, nullptr);
2688 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2690 EXPECT_EQ(default_retransmission_time,
2691 connection_.GetRetransmissionAlarm()->deadline());
2693 InSequence s;
2694 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 3, _, _));
2695 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 4, _, _));
2698 // Simulate the retransmission alarm firing.
2699 clock_.AdvanceTime(DefaultRetransmissionTime());
2700 connection_.GetRetransmissionAlarm()->Fire();
2702 // Packet should have been sent with ENCRYPTION_NONE.
2703 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_previous_packet());
2705 // Packet should have been sent with ENCRYPTION_INITIAL.
2706 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2709 TEST_P(QuicConnectionTest, SendHandshakeMessages) {
2710 use_tagging_decrypter();
2711 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
2712 // the end of the packet. We can test this to check which encrypter was used.
2713 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2715 // Attempt to send a handshake message and have the socket block.
2716 EXPECT_CALL(*send_algorithm_,
2717 TimeUntilSend(_, _, _)).WillRepeatedly(
2718 testing::Return(QuicTime::Delta::Zero()));
2719 BlockOnNextWrite();
2720 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
2721 // The packet should be serialized, but not queued.
2722 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2724 // Switch to the new encrypter.
2725 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2726 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2728 // Now become writeable and flush the packets.
2729 writer_->SetWritable();
2730 EXPECT_CALL(visitor_, OnCanWrite());
2731 connection_.OnCanWrite();
2732 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2734 // Verify that the handshake packet went out at the null encryption.
2735 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
2738 TEST_P(QuicConnectionTest,
2739 DropRetransmitsForNullEncryptedPacketAfterForwardSecure) {
2740 use_tagging_decrypter();
2741 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2742 QuicPacketSequenceNumber sequence_number;
2743 SendStreamDataToPeer(3, "foo", 0, !kFin, &sequence_number);
2745 // Simulate the retransmission alarm firing and the socket blocking.
2746 BlockOnNextWrite();
2747 clock_.AdvanceTime(DefaultRetransmissionTime());
2748 connection_.GetRetransmissionAlarm()->Fire();
2750 // Go forward secure.
2751 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
2752 new TaggingEncrypter(0x02));
2753 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2754 connection_.NeuterUnencryptedPackets();
2756 EXPECT_EQ(QuicTime::Zero(),
2757 connection_.GetRetransmissionAlarm()->deadline());
2758 // Unblock the socket and ensure that no packets are sent.
2759 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
2760 writer_->SetWritable();
2761 connection_.OnCanWrite();
2764 TEST_P(QuicConnectionTest, RetransmitPacketsWithInitialEncryption) {
2765 use_tagging_decrypter();
2766 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2767 connection_.SetDefaultEncryptionLevel(ENCRYPTION_NONE);
2769 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr);
2771 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2772 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2774 SendStreamDataToPeer(2, "bar", 0, !kFin, nullptr);
2775 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2777 connection_.RetransmitUnackedPackets(ALL_INITIAL_RETRANSMISSION);
2780 TEST_P(QuicConnectionTest, DelayForwardSecureEncryptionUntilClientIsReady) {
2781 // A TaggingEncrypter puts kTagSize copies of the given byte (0x02 here) at
2782 // the end of the packet. We can test this to check which encrypter was used.
2783 use_tagging_decrypter();
2784 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2785 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2786 SendAckPacketToPeer();
2787 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2789 // Set a forward-secure encrypter but do not make it the default, and verify
2790 // that it is not yet used.
2791 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
2792 new TaggingEncrypter(0x03));
2793 SendAckPacketToPeer();
2794 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2796 // Now simulate receipt of a forward-secure packet and verify that the
2797 // forward-secure encrypter is now used.
2798 connection_.OnDecryptedPacket(ENCRYPTION_FORWARD_SECURE);
2799 SendAckPacketToPeer();
2800 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
2803 TEST_P(QuicConnectionTest, DelayForwardSecureEncryptionUntilManyPacketSent) {
2804 // Set a congestion window of 10 packets.
2805 QuicPacketCount congestion_window = 10;
2806 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
2807 Return(congestion_window * kDefaultMaxPacketSize));
2809 // A TaggingEncrypter puts kTagSize copies of the given byte (0x02 here) at
2810 // the end of the packet. We can test this to check which encrypter was used.
2811 use_tagging_decrypter();
2812 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2813 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2814 SendAckPacketToPeer();
2815 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2817 // Set a forward-secure encrypter but do not make it the default, and
2818 // verify that it is not yet used.
2819 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
2820 new TaggingEncrypter(0x03));
2821 SendAckPacketToPeer();
2822 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2824 // Now send a packet "Far enough" after the encrypter was set and verify that
2825 // the forward-secure encrypter is now used.
2826 for (uint64 i = 0; i < 3 * congestion_window - 1; ++i) {
2827 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2828 SendAckPacketToPeer();
2830 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
2833 TEST_P(QuicConnectionTest, BufferNonDecryptablePackets) {
2834 // SetFromConfig is always called after construction from InitializeSession.
2835 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
2836 QuicConfig config;
2837 connection_.SetFromConfig(config);
2838 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2839 use_tagging_decrypter();
2841 const uint8 tag = 0x07;
2842 framer_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
2844 // Process an encrypted packet which can not yet be decrypted which should
2845 // result in the packet being buffered.
2846 ProcessDataPacketAtLevel(1, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2848 // Transition to the new encryption state and process another encrypted packet
2849 // which should result in the original packet being processed.
2850 connection_.SetDecrypter(new StrictTaggingDecrypter(tag),
2851 ENCRYPTION_INITIAL);
2852 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2853 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
2854 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(2);
2855 ProcessDataPacketAtLevel(2, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2857 // Finally, process a third packet and note that we do not reprocess the
2858 // buffered packet.
2859 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
2860 ProcessDataPacketAtLevel(3, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2863 TEST_P(QuicConnectionTest, Buffer100NonDecryptablePackets) {
2864 // SetFromConfig is always called after construction from InitializeSession.
2865 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
2866 QuicConfig config;
2867 config.set_max_undecryptable_packets(100);
2868 connection_.SetFromConfig(config);
2869 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2870 use_tagging_decrypter();
2872 const uint8 tag = 0x07;
2873 framer_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
2875 // Process an encrypted packet which can not yet be decrypted which should
2876 // result in the packet being buffered.
2877 for (QuicPacketSequenceNumber i = 1; i <= 100; ++i) {
2878 ProcessDataPacketAtLevel(i, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2881 // Transition to the new encryption state and process another encrypted packet
2882 // which should result in the original packets being processed.
2883 connection_.SetDecrypter(new StrictTaggingDecrypter(tag), ENCRYPTION_INITIAL);
2884 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2885 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
2886 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(101);
2887 ProcessDataPacketAtLevel(101, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2889 // Finally, process a third packet and note that we do not reprocess the
2890 // buffered packet.
2891 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
2892 ProcessDataPacketAtLevel(102, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2895 TEST_P(QuicConnectionTest, TestRetransmitOrder) {
2896 QuicByteCount first_packet_size;
2897 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).WillOnce(
2898 DoAll(SaveArg<3>(&first_packet_size), Return(true)));
2900 connection_.SendStreamDataWithString(3, "first_packet", 0, !kFin, nullptr);
2901 QuicByteCount second_packet_size;
2902 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).WillOnce(
2903 DoAll(SaveArg<3>(&second_packet_size), Return(true)));
2904 connection_.SendStreamDataWithString(3, "second_packet", 12, !kFin, nullptr);
2905 EXPECT_NE(first_packet_size, second_packet_size);
2906 // Advance the clock by huge time to make sure packets will be retransmitted.
2907 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
2909 InSequence s;
2910 EXPECT_CALL(*send_algorithm_,
2911 OnPacketSent(_, _, _, first_packet_size, _));
2912 EXPECT_CALL(*send_algorithm_,
2913 OnPacketSent(_, _, _, second_packet_size, _));
2915 connection_.GetRetransmissionAlarm()->Fire();
2917 // Advance again and expect the packets to be sent again in the same order.
2918 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(20));
2920 InSequence s;
2921 EXPECT_CALL(*send_algorithm_,
2922 OnPacketSent(_, _, _, first_packet_size, _));
2923 EXPECT_CALL(*send_algorithm_,
2924 OnPacketSent(_, _, _, second_packet_size, _));
2926 connection_.GetRetransmissionAlarm()->Fire();
2929 TEST_P(QuicConnectionTest, SetRTOAfterWritingToSocket) {
2930 BlockOnNextWrite();
2931 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
2932 // Make sure that RTO is not started when the packet is queued.
2933 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
2935 // Test that RTO is started once we write to the socket.
2936 writer_->SetWritable();
2937 connection_.OnCanWrite();
2938 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2941 TEST_P(QuicConnectionTest, DelayRTOWithAckReceipt) {
2942 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2943 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2944 .Times(2);
2945 connection_.SendStreamDataWithString(2, "foo", 0, !kFin, nullptr);
2946 connection_.SendStreamDataWithString(3, "bar", 0, !kFin, nullptr);
2947 QuicAlarm* retransmission_alarm = connection_.GetRetransmissionAlarm();
2948 EXPECT_TRUE(retransmission_alarm->IsSet());
2949 EXPECT_EQ(clock_.Now().Add(DefaultRetransmissionTime()),
2950 retransmission_alarm->deadline());
2952 // Advance the time right before the RTO, then receive an ack for the first
2953 // packet to delay the RTO.
2954 clock_.AdvanceTime(DefaultRetransmissionTime());
2955 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2956 QuicAckFrame ack = InitAckFrame(1);
2957 ProcessAckPacket(&ack);
2958 EXPECT_TRUE(retransmission_alarm->IsSet());
2959 EXPECT_GT(retransmission_alarm->deadline(), clock_.Now());
2961 // Move forward past the original RTO and ensure the RTO is still pending.
2962 clock_.AdvanceTime(DefaultRetransmissionTime().Multiply(2));
2964 // Ensure the second packet gets retransmitted when it finally fires.
2965 EXPECT_TRUE(retransmission_alarm->IsSet());
2966 EXPECT_LT(retransmission_alarm->deadline(), clock_.ApproximateNow());
2967 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2968 // Manually cancel the alarm to simulate a real test.
2969 connection_.GetRetransmissionAlarm()->Fire();
2971 // The new retransmitted sequence number should set the RTO to a larger value
2972 // than previously.
2973 EXPECT_TRUE(retransmission_alarm->IsSet());
2974 QuicTime next_rto_time = retransmission_alarm->deadline();
2975 QuicTime expected_rto_time =
2976 connection_.sent_packet_manager().GetRetransmissionTime();
2977 EXPECT_EQ(next_rto_time, expected_rto_time);
2980 TEST_P(QuicConnectionTest, TestQueued) {
2981 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2982 BlockOnNextWrite();
2983 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
2984 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2986 // Unblock the writes and actually send.
2987 writer_->SetWritable();
2988 connection_.OnCanWrite();
2989 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2992 TEST_P(QuicConnectionTest, CloseFecGroup) {
2993 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2994 // Don't send missing packet 1.
2995 // Don't send missing packet 2.
2996 ProcessFecProtectedPacket(3, false, !kEntropyFlag);
2997 // Don't send missing FEC packet 3.
2998 ASSERT_EQ(1u, connection_.NumFecGroups());
3000 // Now send non-fec protected ack packet and close the group.
3001 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 4);
3002 QuicStopWaitingFrame frame = InitStopWaitingFrame(5);
3003 ProcessStopWaitingPacket(&frame);
3004 ASSERT_EQ(0u, connection_.NumFecGroups());
3007 TEST_P(QuicConnectionTest, InitialTimeout) {
3008 EXPECT_TRUE(connection_.connected());
3009 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
3010 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3012 // SetFromConfig sets the initial timeouts before negotiation.
3013 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3014 QuicConfig config;
3015 connection_.SetFromConfig(config);
3016 // Subtract a second from the idle timeout on the client side.
3017 QuicTime default_timeout = clock_.ApproximateNow().Add(
3018 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1));
3019 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
3021 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_CONNECTION_TIMED_OUT, false));
3022 // Simulate the timeout alarm firing.
3023 clock_.AdvanceTime(
3024 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1));
3025 connection_.GetTimeoutAlarm()->Fire();
3027 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3028 EXPECT_FALSE(connection_.connected());
3030 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3031 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
3032 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
3033 EXPECT_FALSE(connection_.GetResumeWritesAlarm()->IsSet());
3034 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3035 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
3038 TEST_P(QuicConnectionTest, OverallTimeout) {
3039 // Use a shorter overall connection timeout than idle timeout for this test.
3040 const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(5);
3041 connection_.SetNetworkTimeouts(timeout, timeout);
3042 EXPECT_TRUE(connection_.connected());
3043 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
3045 QuicTime overall_timeout = clock_.ApproximateNow().Add(timeout).Subtract(
3046 QuicTime::Delta::FromSeconds(1));
3047 EXPECT_EQ(overall_timeout, connection_.GetTimeoutAlarm()->deadline());
3048 EXPECT_TRUE(connection_.connected());
3050 // Send and ack new data 3 seconds later to lengthen the idle timeout.
3051 SendStreamDataToPeer(1, "GET /", 0, kFin, nullptr);
3052 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(3));
3053 QuicAckFrame frame = InitAckFrame(1);
3054 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3055 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3056 ProcessAckPacket(&frame);
3058 // Fire early to verify it wouldn't timeout yet.
3059 connection_.GetTimeoutAlarm()->Fire();
3060 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
3061 EXPECT_TRUE(connection_.connected());
3063 clock_.AdvanceTime(timeout.Subtract(QuicTime::Delta::FromSeconds(2)));
3065 EXPECT_CALL(visitor_,
3066 OnConnectionClosed(QUIC_CONNECTION_OVERALL_TIMED_OUT, false));
3067 // Simulate the timeout alarm firing.
3068 connection_.GetTimeoutAlarm()->Fire();
3070 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3071 EXPECT_FALSE(connection_.connected());
3073 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3074 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
3075 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
3076 EXPECT_FALSE(connection_.GetResumeWritesAlarm()->IsSet());
3077 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3078 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
3081 TEST_P(QuicConnectionTest, PingAfterSend) {
3082 EXPECT_TRUE(connection_.connected());
3083 EXPECT_CALL(visitor_, HasOpenDataStreams()).WillRepeatedly(Return(true));
3084 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
3086 // Advance to 5ms, and send a packet to the peer, which will set
3087 // the ping alarm.
3088 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
3089 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3090 SendStreamDataToPeer(1, "GET /", 0, kFin, nullptr);
3091 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
3092 EXPECT_EQ(clock_.ApproximateNow().Add(QuicTime::Delta::FromSeconds(15)),
3093 connection_.GetPingAlarm()->deadline());
3095 // Now recevie and ACK of the previous packet, which will move the
3096 // ping alarm forward.
3097 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
3098 QuicAckFrame frame = InitAckFrame(1);
3099 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3100 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3101 ProcessAckPacket(&frame);
3102 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
3103 // The ping timer is set slightly less than 15 seconds in the future, because
3104 // of the 1s ping timer alarm granularity.
3105 EXPECT_EQ(clock_.ApproximateNow().Add(QuicTime::Delta::FromSeconds(15))
3106 .Subtract(QuicTime::Delta::FromMilliseconds(5)),
3107 connection_.GetPingAlarm()->deadline());
3109 writer_->Reset();
3110 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15));
3111 connection_.GetPingAlarm()->Fire();
3112 EXPECT_EQ(1u, writer_->frame_count());
3113 ASSERT_EQ(1u, writer_->ping_frames().size());
3114 writer_->Reset();
3116 EXPECT_CALL(visitor_, HasOpenDataStreams()).WillRepeatedly(Return(false));
3117 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
3118 SendAckPacketToPeer();
3120 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
3123 TEST_P(QuicConnectionTest, TimeoutAfterSend) {
3124 EXPECT_TRUE(connection_.connected());
3125 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3126 QuicConfig config;
3127 connection_.SetFromConfig(config);
3128 EXPECT_FALSE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
3130 const QuicTime::Delta initial_idle_timeout =
3131 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
3132 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
3133 QuicTime default_timeout = clock_.ApproximateNow().Add(initial_idle_timeout);
3135 // When we send a packet, the timeout will change to 5ms +
3136 // kInitialIdleTimeoutSecs.
3137 clock_.AdvanceTime(five_ms);
3139 // Send an ack so we don't set the retransmission alarm.
3140 SendAckPacketToPeer();
3141 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
3143 // The original alarm will fire. We should not time out because we had a
3144 // network event at t=5ms. The alarm will reregister.
3145 clock_.AdvanceTime(initial_idle_timeout.Subtract(five_ms));
3146 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
3147 connection_.GetTimeoutAlarm()->Fire();
3148 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
3149 EXPECT_TRUE(connection_.connected());
3150 EXPECT_EQ(default_timeout.Add(five_ms),
3151 connection_.GetTimeoutAlarm()->deadline());
3153 // This time, we should time out.
3154 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_CONNECTION_TIMED_OUT, false));
3155 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3156 clock_.AdvanceTime(five_ms);
3157 EXPECT_EQ(default_timeout.Add(five_ms), clock_.ApproximateNow());
3158 connection_.GetTimeoutAlarm()->Fire();
3159 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3160 EXPECT_FALSE(connection_.connected());
3163 TEST_P(QuicConnectionTest, TimeoutAfterSendSilentClose) {
3164 // Same test as above, but complete a handshake which enables silent close,
3165 // causing no connection close packet to be sent.
3166 EXPECT_TRUE(connection_.connected());
3167 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3168 QuicConfig config;
3170 // Create a handshake message that also enables silent close.
3171 CryptoHandshakeMessage msg;
3172 string error_details;
3173 QuicConfig client_config;
3174 client_config.SetInitialStreamFlowControlWindowToSend(
3175 kInitialStreamFlowControlWindowForTest);
3176 client_config.SetInitialSessionFlowControlWindowToSend(
3177 kInitialSessionFlowControlWindowForTest);
3178 client_config.SetIdleConnectionStateLifetime(
3179 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs),
3180 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs));
3181 client_config.ToHandshakeMessage(&msg);
3182 const QuicErrorCode error =
3183 config.ProcessPeerHello(msg, CLIENT, &error_details);
3184 EXPECT_EQ(QUIC_NO_ERROR, error);
3186 connection_.SetFromConfig(config);
3187 EXPECT_TRUE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
3189 const QuicTime::Delta default_idle_timeout =
3190 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs - 1);
3191 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
3192 QuicTime default_timeout = clock_.ApproximateNow().Add(default_idle_timeout);
3194 // When we send a packet, the timeout will change to 5ms +
3195 // kInitialIdleTimeoutSecs.
3196 clock_.AdvanceTime(five_ms);
3198 // Send an ack so we don't set the retransmission alarm.
3199 SendAckPacketToPeer();
3200 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
3202 // The original alarm will fire. We should not time out because we had a
3203 // network event at t=5ms. The alarm will reregister.
3204 clock_.AdvanceTime(default_idle_timeout.Subtract(five_ms));
3205 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
3206 connection_.GetTimeoutAlarm()->Fire();
3207 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
3208 EXPECT_TRUE(connection_.connected());
3209 EXPECT_EQ(default_timeout.Add(five_ms),
3210 connection_.GetTimeoutAlarm()->deadline());
3212 // This time, we should time out.
3213 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_CONNECTION_TIMED_OUT, false));
3214 clock_.AdvanceTime(five_ms);
3215 EXPECT_EQ(default_timeout.Add(five_ms), clock_.ApproximateNow());
3216 connection_.GetTimeoutAlarm()->Fire();
3217 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3218 EXPECT_FALSE(connection_.connected());
3221 TEST_P(QuicConnectionTest, SendScheduler) {
3222 // Test that if we send a packet without delay, it is not queued.
3223 QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
3224 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3225 connection_.SendPacket(
3226 ENCRYPTION_NONE, 1, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA);
3227 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3230 TEST_P(QuicConnectionTest, SendSchedulerEAGAIN) {
3231 QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
3232 BlockOnNextWrite();
3233 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 1, _, _)).Times(0);
3234 connection_.SendPacket(
3235 ENCRYPTION_NONE, 1, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA);
3236 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3239 TEST_P(QuicConnectionTest, TestQueueLimitsOnSendStreamData) {
3240 // All packets carry version info till version is negotiated.
3241 size_t payload_length;
3242 size_t length = GetPacketLengthForOneStream(
3243 connection_.version(), kIncludeVersion,
3244 PACKET_8BYTE_CONNECTION_ID, PACKET_1BYTE_SEQUENCE_NUMBER,
3245 NOT_IN_FEC_GROUP, &payload_length);
3246 creator_->SetMaxPacketLength(length);
3248 // Queue the first packet.
3249 EXPECT_CALL(*send_algorithm_,
3250 TimeUntilSend(_, _, _)).WillOnce(
3251 testing::Return(QuicTime::Delta::FromMicroseconds(10)));
3252 const string payload(payload_length, 'a');
3253 EXPECT_EQ(0u, connection_.SendStreamDataWithString(3, payload, 0, !kFin,
3254 nullptr).bytes_consumed);
3255 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3258 TEST_P(QuicConnectionTest, LoopThroughSendingPackets) {
3259 // All packets carry version info till version is negotiated.
3260 size_t payload_length;
3261 // GetPacketLengthForOneStream() assumes a stream offset of 0 in determining
3262 // packet length. The size of the offset field in a stream frame is 0 for
3263 // offset 0, and 2 for non-zero offsets up through 16K. Increase
3264 // max_packet_length by 2 so that subsequent packets containing subsequent
3265 // stream frames with non-zero offets will fit within the packet length.
3266 size_t length = 2 + GetPacketLengthForOneStream(
3267 connection_.version(), kIncludeVersion,
3268 PACKET_8BYTE_CONNECTION_ID, PACKET_1BYTE_SEQUENCE_NUMBER,
3269 NOT_IN_FEC_GROUP, &payload_length);
3270 creator_->SetMaxPacketLength(length);
3272 // Queue the first packet.
3273 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(7);
3274 // The first stream frame will have 2 fewer overhead bytes than the other six.
3275 const string payload(payload_length * 7 + 2, 'a');
3276 EXPECT_EQ(payload.size(),
3277 connection_.SendStreamDataWithString(1, payload, 0, !kFin, nullptr)
3278 .bytes_consumed);
3281 TEST_P(QuicConnectionTest, LoopThroughSendingPacketsWithTruncation) {
3282 // Set up a larger payload than will fit in one packet.
3283 const string payload(connection_.max_packet_length(), 'a');
3284 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
3286 // Now send some packets with no truncation.
3287 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3288 EXPECT_EQ(payload.size(),
3289 connection_.SendStreamDataWithString(
3290 3, payload, 0, !kFin, nullptr).bytes_consumed);
3291 // Track the size of the second packet here. The overhead will be the largest
3292 // we see in this test, due to the non-truncated connection id.
3293 size_t non_truncated_packet_size = writer_->last_packet_size();
3295 // Change to a 4 byte connection id.
3296 QuicConfig config;
3297 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 4);
3298 connection_.SetFromConfig(config);
3299 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3300 EXPECT_EQ(payload.size(),
3301 connection_.SendStreamDataWithString(
3302 3, payload, 0, !kFin, nullptr).bytes_consumed);
3303 // Verify that we have 8 fewer bytes than in the non-truncated case. The
3304 // first packet got 4 bytes of extra payload due to the truncation, and the
3305 // headers here are also 4 byte smaller.
3306 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() + 8);
3308 // Change to a 1 byte connection id.
3309 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 1);
3310 connection_.SetFromConfig(config);
3311 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3312 EXPECT_EQ(payload.size(),
3313 connection_.SendStreamDataWithString(
3314 3, payload, 0, !kFin, nullptr).bytes_consumed);
3315 // Just like above, we save 7 bytes on payload, and 7 on truncation.
3316 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() + 7 * 2);
3318 // Change to a 0 byte connection id.
3319 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
3320 connection_.SetFromConfig(config);
3321 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3322 EXPECT_EQ(payload.size(),
3323 connection_.SendStreamDataWithString(
3324 3, payload, 0, !kFin, nullptr).bytes_consumed);
3325 // Just like above, we save 8 bytes on payload, and 8 on truncation.
3326 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() + 8 * 2);
3329 TEST_P(QuicConnectionTest, SendDelayedAck) {
3330 QuicTime ack_time = clock_.ApproximateNow().Add(DefaultDelayedAckTime());
3331 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3332 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3333 const uint8 tag = 0x07;
3334 connection_.SetDecrypter(new StrictTaggingDecrypter(tag),
3335 ENCRYPTION_INITIAL);
3336 framer_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
3337 // Process a packet from the non-crypto stream.
3338 frame1_.stream_id = 3;
3340 // The same as ProcessPacket(1) except that ENCRYPTION_INITIAL is used
3341 // instead of ENCRYPTION_NONE.
3342 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
3343 ProcessDataPacketAtLevel(1, 0, !kEntropyFlag, ENCRYPTION_INITIAL);
3345 // Check if delayed ack timer is running for the expected interval.
3346 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3347 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
3348 // Simulate delayed ack alarm firing.
3349 connection_.GetAckAlarm()->Fire();
3350 // Check that ack is sent and that delayed ack alarm is reset.
3351 EXPECT_EQ(2u, writer_->frame_count());
3352 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3353 EXPECT_FALSE(writer_->ack_frames().empty());
3354 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3357 TEST_P(QuicConnectionTest, SendDelayedAckOnHandshakeConfirmed) {
3358 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3359 ProcessPacket(1);
3360 // Check that ack is sent and that delayed ack alarm is set.
3361 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3362 QuicTime ack_time = clock_.ApproximateNow().Add(DefaultDelayedAckTime());
3363 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
3365 // Completing the handshake as the server does nothing.
3366 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_SERVER);
3367 connection_.OnHandshakeComplete();
3368 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3369 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
3371 // Complete the handshake as the client decreases the delayed ack time to 0ms.
3372 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_CLIENT);
3373 connection_.OnHandshakeComplete();
3374 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3375 EXPECT_EQ(clock_.ApproximateNow(), connection_.GetAckAlarm()->deadline());
3378 TEST_P(QuicConnectionTest, SendDelayedAckOnSecondPacket) {
3379 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3380 ProcessPacket(1);
3381 ProcessPacket(2);
3382 // Check that ack is sent and that delayed ack alarm is reset.
3383 EXPECT_EQ(2u, writer_->frame_count());
3384 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3385 EXPECT_FALSE(writer_->ack_frames().empty());
3386 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3389 TEST_P(QuicConnectionTest, NoAckOnOldNacks) {
3390 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3391 // Drop one packet, triggering a sequence of acks.
3392 ProcessPacket(2);
3393 size_t frames_per_ack = 2;
3394 EXPECT_EQ(frames_per_ack, writer_->frame_count());
3395 EXPECT_FALSE(writer_->ack_frames().empty());
3396 writer_->Reset();
3397 ProcessPacket(3);
3398 EXPECT_EQ(frames_per_ack, writer_->frame_count());
3399 EXPECT_FALSE(writer_->ack_frames().empty());
3400 writer_->Reset();
3401 ProcessPacket(4);
3402 EXPECT_EQ(frames_per_ack, writer_->frame_count());
3403 EXPECT_FALSE(writer_->ack_frames().empty());
3404 writer_->Reset();
3405 ProcessPacket(5);
3406 EXPECT_EQ(frames_per_ack, writer_->frame_count());
3407 EXPECT_FALSE(writer_->ack_frames().empty());
3408 writer_->Reset();
3409 // Now only set the timer on the 6th packet, instead of sending another ack.
3410 ProcessPacket(6);
3411 EXPECT_EQ(0u, writer_->frame_count());
3412 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3415 TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingPacket) {
3416 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3417 ProcessPacket(1);
3418 connection_.SendStreamDataWithString(kClientDataStreamId1, "foo", 0, !kFin,
3419 nullptr);
3420 // Check that ack is bundled with outgoing data and that delayed ack
3421 // alarm is reset.
3422 EXPECT_EQ(3u, writer_->frame_count());
3423 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3424 EXPECT_FALSE(writer_->ack_frames().empty());
3425 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3428 TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingCryptoPacket) {
3429 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3430 ProcessPacket(1);
3431 connection_.SendStreamDataWithString(kCryptoStreamId, "foo", 0, !kFin,
3432 nullptr);
3433 // Check that ack is bundled with outgoing crypto data.
3434 EXPECT_EQ(3u, writer_->frame_count());
3435 EXPECT_FALSE(writer_->ack_frames().empty());
3436 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3439 TEST_P(QuicConnectionTest, BlockAndBufferOnFirstCHLOPacketOfTwo) {
3440 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3441 ProcessPacket(1);
3442 BlockOnNextWrite();
3443 writer_->set_is_write_blocked_data_buffered(true);
3444 connection_.SendStreamDataWithString(kCryptoStreamId, "foo", 0, !kFin,
3445 nullptr);
3446 EXPECT_TRUE(writer_->IsWriteBlocked());
3447 EXPECT_FALSE(connection_.HasQueuedData());
3448 connection_.SendStreamDataWithString(kCryptoStreamId, "bar", 3, !kFin,
3449 nullptr);
3450 EXPECT_TRUE(writer_->IsWriteBlocked());
3451 EXPECT_TRUE(connection_.HasQueuedData());
3454 TEST_P(QuicConnectionTest, BundleAckForSecondCHLO) {
3455 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3456 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3457 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(
3458 IgnoreResult(InvokeWithoutArgs(&connection_,
3459 &TestConnection::SendCryptoStreamData)));
3460 // Process a packet from the crypto stream, which is frame1_'s default.
3461 // Receiving the CHLO as packet 2 first will cause the connection to
3462 // immediately send an ack, due to the packet gap.
3463 ProcessPacket(2);
3464 // Check that ack is sent and that delayed ack alarm is reset.
3465 EXPECT_EQ(3u, writer_->frame_count());
3466 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3467 EXPECT_EQ(1u, writer_->stream_frames().size());
3468 EXPECT_FALSE(writer_->ack_frames().empty());
3469 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3472 TEST_P(QuicConnectionTest, BundleAckWithDataOnIncomingAck) {
3473 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3474 connection_.SendStreamDataWithString(kClientDataStreamId1, "foo", 0, !kFin,
3475 nullptr);
3476 connection_.SendStreamDataWithString(kClientDataStreamId1, "foo", 3, !kFin,
3477 nullptr);
3478 // Ack the second packet, which will retransmit the first packet.
3479 QuicAckFrame ack = InitAckFrame(2);
3480 NackPacket(1, &ack);
3481 SequenceNumberSet lost_packets;
3482 lost_packets.insert(1);
3483 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3484 .WillOnce(Return(lost_packets));
3485 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3486 ProcessAckPacket(&ack);
3487 EXPECT_EQ(1u, writer_->frame_count());
3488 EXPECT_EQ(1u, writer_->stream_frames().size());
3489 writer_->Reset();
3491 // Now ack the retransmission, which will both raise the high water mark
3492 // and see if there is more data to send.
3493 ack = InitAckFrame(3);
3494 NackPacket(1, &ack);
3495 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3496 .WillOnce(Return(SequenceNumberSet()));
3497 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3498 ProcessAckPacket(&ack);
3500 // Check that no packet is sent and the ack alarm isn't set.
3501 EXPECT_EQ(0u, writer_->frame_count());
3502 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3503 writer_->Reset();
3505 // Send the same ack, but send both data and an ack together.
3506 ack = InitAckFrame(3);
3507 NackPacket(1, &ack);
3508 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3509 .WillOnce(Return(SequenceNumberSet()));
3510 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(
3511 IgnoreResult(InvokeWithoutArgs(
3512 &connection_,
3513 &TestConnection::EnsureWritableAndSendStreamData5)));
3514 ProcessAckPacket(&ack);
3516 // Check that ack is bundled with outgoing data and the delayed ack
3517 // alarm is reset.
3518 EXPECT_EQ(3u, writer_->frame_count());
3519 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3520 EXPECT_FALSE(writer_->ack_frames().empty());
3521 EXPECT_EQ(1u, writer_->stream_frames().size());
3522 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3525 TEST_P(QuicConnectionTest, NoAckSentForClose) {
3526 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3527 ProcessPacket(1);
3528 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, true));
3529 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3530 ProcessClosePacket(2, 0);
3533 TEST_P(QuicConnectionTest, SendWhenDisconnected) {
3534 EXPECT_TRUE(connection_.connected());
3535 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, false));
3536 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, false);
3537 EXPECT_FALSE(connection_.connected());
3538 EXPECT_FALSE(connection_.CanWriteStreamData());
3539 QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
3540 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 1, _, _)).Times(0);
3541 connection_.SendPacket(
3542 ENCRYPTION_NONE, 1, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA);
3545 TEST_P(QuicConnectionTest, PublicReset) {
3546 QuicPublicResetPacket header;
3547 header.public_header.connection_id = connection_id_;
3548 header.public_header.reset_flag = true;
3549 header.public_header.version_flag = false;
3550 header.rejected_sequence_number = 10101;
3551 scoped_ptr<QuicEncryptedPacket> packet(
3552 framer_.BuildPublicResetPacket(header));
3553 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PUBLIC_RESET, true));
3554 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *packet);
3557 TEST_P(QuicConnectionTest, GoAway) {
3558 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3560 QuicGoAwayFrame goaway;
3561 goaway.last_good_stream_id = 1;
3562 goaway.error_code = QUIC_PEER_GOING_AWAY;
3563 goaway.reason_phrase = "Going away.";
3564 EXPECT_CALL(visitor_, OnGoAway(_));
3565 ProcessGoAwayPacket(&goaway);
3568 TEST_P(QuicConnectionTest, WindowUpdate) {
3569 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3571 QuicWindowUpdateFrame window_update;
3572 window_update.stream_id = 3;
3573 window_update.byte_offset = 1234;
3574 EXPECT_CALL(visitor_, OnWindowUpdateFrames(_));
3575 ProcessFramePacket(QuicFrame(&window_update));
3578 TEST_P(QuicConnectionTest, Blocked) {
3579 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3581 QuicBlockedFrame blocked;
3582 blocked.stream_id = 3;
3583 EXPECT_CALL(visitor_, OnBlockedFrames(_));
3584 ProcessFramePacket(QuicFrame(&blocked));
3587 TEST_P(QuicConnectionTest, ZeroBytePacket) {
3588 // Don't close the connection for zero byte packets.
3589 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
3590 QuicEncryptedPacket encrypted(nullptr, 0);
3591 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), encrypted);
3594 TEST_P(QuicConnectionTest, MissingPacketsBeforeLeastUnacked) {
3595 // Set the sequence number of the ack packet to be least unacked (4).
3596 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 3);
3597 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3598 QuicStopWaitingFrame frame = InitStopWaitingFrame(4);
3599 ProcessStopWaitingPacket(&frame);
3600 EXPECT_TRUE(outgoing_ack()->missing_packets.empty());
3603 TEST_P(QuicConnectionTest, ReceivedEntropyHashCalculation) {
3604 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(AtLeast(1));
3605 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3606 ProcessDataPacket(1, 1, kEntropyFlag);
3607 ProcessDataPacket(4, 1, kEntropyFlag);
3608 ProcessDataPacket(3, 1, !kEntropyFlag);
3609 ProcessDataPacket(7, 1, kEntropyFlag);
3610 EXPECT_EQ(146u, outgoing_ack()->entropy_hash);
3613 TEST_P(QuicConnectionTest, ReceivedEntropyHashCalculationHalfFEC) {
3614 // FEC packets should not change the entropy hash calculation.
3615 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(AtLeast(1));
3616 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3617 ProcessDataPacket(1, 1, kEntropyFlag);
3618 ProcessFecPacket(4, 1, false, kEntropyFlag, nullptr);
3619 ProcessDataPacket(3, 3, !kEntropyFlag);
3620 ProcessFecPacket(7, 3, false, kEntropyFlag, nullptr);
3621 EXPECT_EQ(146u, outgoing_ack()->entropy_hash);
3624 TEST_P(QuicConnectionTest, UpdateEntropyForReceivedPackets) {
3625 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(AtLeast(1));
3626 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3627 ProcessDataPacket(1, 1, kEntropyFlag);
3628 ProcessDataPacket(5, 1, kEntropyFlag);
3629 ProcessDataPacket(4, 1, !kEntropyFlag);
3630 EXPECT_EQ(34u, outgoing_ack()->entropy_hash);
3631 // Make 4th packet my least unacked, and update entropy for 2, 3 packets.
3632 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 5);
3633 QuicPacketEntropyHash six_packet_entropy_hash = 0;
3634 QuicPacketEntropyHash random_entropy_hash = 129u;
3635 QuicStopWaitingFrame frame = InitStopWaitingFrame(4);
3636 frame.entropy_hash = random_entropy_hash;
3637 if (ProcessStopWaitingPacket(&frame)) {
3638 six_packet_entropy_hash = 1 << 6;
3641 EXPECT_EQ((random_entropy_hash + (1 << 5) + six_packet_entropy_hash),
3642 outgoing_ack()->entropy_hash);
3645 TEST_P(QuicConnectionTest, UpdateEntropyHashUptoCurrentPacket) {
3646 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(AtLeast(1));
3647 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3648 ProcessDataPacket(1, 1, kEntropyFlag);
3649 ProcessDataPacket(5, 1, !kEntropyFlag);
3650 ProcessDataPacket(22, 1, kEntropyFlag);
3651 EXPECT_EQ(66u, outgoing_ack()->entropy_hash);
3652 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 22);
3653 QuicPacketEntropyHash random_entropy_hash = 85u;
3654 // Current packet is the least unacked packet.
3655 QuicPacketEntropyHash ack_entropy_hash;
3656 QuicStopWaitingFrame frame = InitStopWaitingFrame(23);
3657 frame.entropy_hash = random_entropy_hash;
3658 ack_entropy_hash = ProcessStopWaitingPacket(&frame);
3659 EXPECT_EQ((random_entropy_hash + ack_entropy_hash),
3660 outgoing_ack()->entropy_hash);
3661 ProcessDataPacket(25, 1, kEntropyFlag);
3662 EXPECT_EQ((random_entropy_hash + ack_entropy_hash + (1 << (25 % 8))),
3663 outgoing_ack()->entropy_hash);
3666 TEST_P(QuicConnectionTest, EntropyCalculationForTruncatedAck) {
3667 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(AtLeast(1));
3668 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3669 QuicPacketEntropyHash entropy[51];
3670 entropy[0] = 0;
3671 for (int i = 1; i < 51; ++i) {
3672 bool should_send = i % 10 != 1;
3673 bool entropy_flag = (i & (i - 1)) != 0;
3674 if (!should_send) {
3675 entropy[i] = entropy[i - 1];
3676 continue;
3678 if (entropy_flag) {
3679 entropy[i] = entropy[i - 1] ^ (1 << (i % 8));
3680 } else {
3681 entropy[i] = entropy[i - 1];
3683 ProcessDataPacket(i, 1, entropy_flag);
3685 for (int i = 1; i < 50; ++i) {
3686 EXPECT_EQ(entropy[i], QuicConnectionPeer::ReceivedEntropyHash(
3687 &connection_, i));
3691 TEST_P(QuicConnectionTest, ServerSendsVersionNegotiationPacket) {
3692 connection_.SetSupportedVersions(QuicSupportedVersions());
3693 framer_.set_version_for_tests(QUIC_VERSION_UNSUPPORTED);
3695 QuicPacketHeader header;
3696 header.public_header.connection_id = connection_id_;
3697 header.public_header.version_flag = true;
3698 header.packet_sequence_number = 12;
3700 QuicFrames frames;
3701 frames.push_back(QuicFrame(&frame1_));
3702 scoped_ptr<QuicPacket> packet(ConstructPacket(header, frames));
3703 char buffer[kMaxPacketSize];
3704 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPacket(
3705 ENCRYPTION_NONE, 12, *packet, buffer, kMaxPacketSize));
3707 framer_.set_version(version());
3708 connection_.set_perspective(Perspective::IS_SERVER);
3709 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3710 EXPECT_TRUE(writer_->version_negotiation_packet() != nullptr);
3712 size_t num_versions = arraysize(kSupportedQuicVersions);
3713 ASSERT_EQ(num_versions,
3714 writer_->version_negotiation_packet()->versions.size());
3716 // We expect all versions in kSupportedQuicVersions to be
3717 // included in the packet.
3718 for (size_t i = 0; i < num_versions; ++i) {
3719 EXPECT_EQ(kSupportedQuicVersions[i],
3720 writer_->version_negotiation_packet()->versions[i]);
3724 TEST_P(QuicConnectionTest, ServerSendsVersionNegotiationPacketSocketBlocked) {
3725 connection_.SetSupportedVersions(QuicSupportedVersions());
3726 framer_.set_version_for_tests(QUIC_VERSION_UNSUPPORTED);
3728 QuicPacketHeader header;
3729 header.public_header.connection_id = connection_id_;
3730 header.public_header.version_flag = true;
3731 header.packet_sequence_number = 12;
3733 QuicFrames frames;
3734 frames.push_back(QuicFrame(&frame1_));
3735 scoped_ptr<QuicPacket> packet(ConstructPacket(header, frames));
3736 char buffer[kMaxPacketSize];
3737 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPacket(
3738 ENCRYPTION_NONE, 12, *packet, buffer, kMaxPacketSize));
3740 framer_.set_version(version());
3741 connection_.set_perspective(Perspective::IS_SERVER);
3742 BlockOnNextWrite();
3743 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3744 EXPECT_EQ(0u, writer_->last_packet_size());
3745 EXPECT_TRUE(connection_.HasQueuedData());
3747 writer_->SetWritable();
3748 connection_.OnCanWrite();
3749 EXPECT_TRUE(writer_->version_negotiation_packet() != nullptr);
3751 size_t num_versions = arraysize(kSupportedQuicVersions);
3752 ASSERT_EQ(num_versions,
3753 writer_->version_negotiation_packet()->versions.size());
3755 // We expect all versions in kSupportedQuicVersions to be
3756 // included in the packet.
3757 for (size_t i = 0; i < num_versions; ++i) {
3758 EXPECT_EQ(kSupportedQuicVersions[i],
3759 writer_->version_negotiation_packet()->versions[i]);
3763 TEST_P(QuicConnectionTest,
3764 ServerSendsVersionNegotiationPacketSocketBlockedDataBuffered) {
3765 connection_.SetSupportedVersions(QuicSupportedVersions());
3766 framer_.set_version_for_tests(QUIC_VERSION_UNSUPPORTED);
3768 QuicPacketHeader header;
3769 header.public_header.connection_id = connection_id_;
3770 header.public_header.version_flag = true;
3771 header.packet_sequence_number = 12;
3773 QuicFrames frames;
3774 frames.push_back(QuicFrame(&frame1_));
3775 scoped_ptr<QuicPacket> packet(ConstructPacket(header, frames));
3776 char buffer[kMaxPacketSize];
3777 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPacket(
3778 ENCRYPTION_NONE, 12, *packet, buffer, kMaxPacketSize));
3780 framer_.set_version(version());
3781 connection_.set_perspective(Perspective::IS_SERVER);
3782 BlockOnNextWrite();
3783 writer_->set_is_write_blocked_data_buffered(true);
3784 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3785 EXPECT_EQ(0u, writer_->last_packet_size());
3786 EXPECT_FALSE(connection_.HasQueuedData());
3789 TEST_P(QuicConnectionTest, ClientHandlesVersionNegotiation) {
3790 // Start out with some unsupported version.
3791 QuicConnectionPeer::GetFramer(&connection_)->set_version_for_tests(
3792 QUIC_VERSION_UNSUPPORTED);
3794 QuicPacketHeader header;
3795 header.public_header.connection_id = connection_id_;
3796 header.public_header.version_flag = true;
3797 header.packet_sequence_number = 12;
3799 QuicVersionVector supported_versions;
3800 for (size_t i = 0; i < arraysize(kSupportedQuicVersions); ++i) {
3801 supported_versions.push_back(kSupportedQuicVersions[i]);
3804 // Send a version negotiation packet.
3805 scoped_ptr<QuicEncryptedPacket> encrypted(
3806 framer_.BuildVersionNegotiationPacket(
3807 header.public_header, supported_versions));
3808 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3810 // Now force another packet. The connection should transition into
3811 // NEGOTIATED_VERSION state and tell the packet creator to StopSendingVersion.
3812 header.public_header.version_flag = false;
3813 QuicFrames frames;
3814 frames.push_back(QuicFrame(&frame1_));
3815 scoped_ptr<QuicPacket> packet(ConstructPacket(header, frames));
3816 char buffer[kMaxPacketSize];
3817 encrypted.reset(framer_.EncryptPacket(ENCRYPTION_NONE, 12, *packet, buffer,
3818 kMaxPacketSize));
3819 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
3820 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3821 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3823 ASSERT_FALSE(QuicPacketCreatorPeer::SendVersionInPacket(creator_));
3826 TEST_P(QuicConnectionTest, BadVersionNegotiation) {
3827 QuicPacketHeader header;
3828 header.public_header.connection_id = connection_id_;
3829 header.public_header.version_flag = true;
3830 header.packet_sequence_number = 12;
3832 QuicVersionVector supported_versions;
3833 for (size_t i = 0; i < arraysize(kSupportedQuicVersions); ++i) {
3834 supported_versions.push_back(kSupportedQuicVersions[i]);
3837 // Send a version negotiation packet with the version the client started with.
3838 // It should be rejected.
3839 EXPECT_CALL(visitor_,
3840 OnConnectionClosed(QUIC_INVALID_VERSION_NEGOTIATION_PACKET,
3841 false));
3842 scoped_ptr<QuicEncryptedPacket> encrypted(
3843 framer_.BuildVersionNegotiationPacket(
3844 header.public_header, supported_versions));
3845 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3848 TEST_P(QuicConnectionTest, CheckSendStats) {
3849 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3850 connection_.SendStreamDataWithString(3, "first", 0, !kFin, nullptr);
3851 size_t first_packet_size = writer_->last_packet_size();
3853 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3854 connection_.SendStreamDataWithString(5, "second", 0, !kFin, nullptr);
3855 size_t second_packet_size = writer_->last_packet_size();
3857 // 2 retransmissions due to rto, 1 due to explicit nack.
3858 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
3859 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
3861 // Retransmit due to RTO.
3862 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
3863 connection_.GetRetransmissionAlarm()->Fire();
3865 // Retransmit due to explicit nacks.
3866 QuicAckFrame nack_three = InitAckFrame(4);
3867 NackPacket(3, &nack_three);
3868 NackPacket(1, &nack_three);
3869 SequenceNumberSet lost_packets;
3870 lost_packets.insert(1);
3871 lost_packets.insert(3);
3872 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3873 .WillOnce(Return(lost_packets));
3874 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3875 EXPECT_CALL(visitor_, OnCanWrite()).Times(2);
3876 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3877 ProcessAckPacket(&nack_three);
3879 EXPECT_CALL(*send_algorithm_, BandwidthEstimate()).WillOnce(
3880 Return(QuicBandwidth::Zero()));
3882 const QuicConnectionStats& stats = connection_.GetStats();
3883 EXPECT_EQ(3 * first_packet_size + 2 * second_packet_size - kQuicVersionSize,
3884 stats.bytes_sent);
3885 EXPECT_EQ(5u, stats.packets_sent);
3886 EXPECT_EQ(2 * first_packet_size + second_packet_size - kQuicVersionSize,
3887 stats.bytes_retransmitted);
3888 EXPECT_EQ(3u, stats.packets_retransmitted);
3889 EXPECT_EQ(1u, stats.rto_count);
3890 EXPECT_EQ(kDefaultMaxPacketSize, stats.max_packet_size);
3893 TEST_P(QuicConnectionTest, CheckReceiveStats) {
3894 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3896 size_t received_bytes = 0;
3897 received_bytes += ProcessFecProtectedPacket(1, false, !kEntropyFlag);
3898 received_bytes += ProcessFecProtectedPacket(3, false, !kEntropyFlag);
3899 // Should be counted against dropped packets.
3900 received_bytes += ProcessDataPacket(3, 1, !kEntropyFlag);
3901 received_bytes += ProcessFecPacket(4, 1, true, !kEntropyFlag, nullptr);
3903 EXPECT_CALL(*send_algorithm_, BandwidthEstimate()).WillOnce(
3904 Return(QuicBandwidth::Zero()));
3906 const QuicConnectionStats& stats = connection_.GetStats();
3907 EXPECT_EQ(received_bytes, stats.bytes_received);
3908 EXPECT_EQ(4u, stats.packets_received);
3910 EXPECT_EQ(1u, stats.packets_revived);
3911 EXPECT_EQ(1u, stats.packets_dropped);
3914 TEST_P(QuicConnectionTest, TestFecGroupLimits) {
3915 // Create and return a group for 1.
3916 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 1) != nullptr);
3918 // Create and return a group for 2.
3919 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 2) != nullptr);
3921 // Create and return a group for 4. This should remove 1 but not 2.
3922 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 4) != nullptr);
3923 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 1) == nullptr);
3924 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 2) != nullptr);
3926 // Create and return a group for 3. This will kill off 2.
3927 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 3) != nullptr);
3928 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 2) == nullptr);
3930 // Verify that adding 5 kills off 3, despite 4 being created before 3.
3931 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 5) != nullptr);
3932 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 4) != nullptr);
3933 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 3) == nullptr);
3936 TEST_P(QuicConnectionTest, ProcessFramesIfPacketClosedConnection) {
3937 // Construct a packet with stream frame and connection close frame.
3938 QuicPacketHeader header;
3939 header.public_header.connection_id = connection_id_;
3940 header.packet_sequence_number = 1;
3941 header.public_header.version_flag = false;
3943 QuicConnectionCloseFrame qccf;
3944 qccf.error_code = QUIC_PEER_GOING_AWAY;
3946 QuicFrames frames;
3947 frames.push_back(QuicFrame(&frame1_));
3948 frames.push_back(QuicFrame(&qccf));
3949 scoped_ptr<QuicPacket> packet(ConstructPacket(header, frames));
3950 EXPECT_TRUE(nullptr != packet.get());
3951 char buffer[kMaxPacketSize];
3952 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPacket(
3953 ENCRYPTION_NONE, 1, *packet, buffer, kMaxPacketSize));
3955 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, true));
3956 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
3957 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3959 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3962 TEST_P(QuicConnectionTest, SelectMutualVersion) {
3963 connection_.SetSupportedVersions(QuicSupportedVersions());
3964 // Set the connection to speak the lowest quic version.
3965 connection_.set_version(QuicVersionMin());
3966 EXPECT_EQ(QuicVersionMin(), connection_.version());
3968 // Pass in available versions which includes a higher mutually supported
3969 // version. The higher mutually supported version should be selected.
3970 QuicVersionVector supported_versions;
3971 for (size_t i = 0; i < arraysize(kSupportedQuicVersions); ++i) {
3972 supported_versions.push_back(kSupportedQuicVersions[i]);
3974 EXPECT_TRUE(connection_.SelectMutualVersion(supported_versions));
3975 EXPECT_EQ(QuicVersionMax(), connection_.version());
3977 // Expect that the lowest version is selected.
3978 // Ensure the lowest supported version is less than the max, unless they're
3979 // the same.
3980 EXPECT_LE(QuicVersionMin(), QuicVersionMax());
3981 QuicVersionVector lowest_version_vector;
3982 lowest_version_vector.push_back(QuicVersionMin());
3983 EXPECT_TRUE(connection_.SelectMutualVersion(lowest_version_vector));
3984 EXPECT_EQ(QuicVersionMin(), connection_.version());
3986 // Shouldn't be able to find a mutually supported version.
3987 QuicVersionVector unsupported_version;
3988 unsupported_version.push_back(QUIC_VERSION_UNSUPPORTED);
3989 EXPECT_FALSE(connection_.SelectMutualVersion(unsupported_version));
3992 TEST_P(QuicConnectionTest, ConnectionCloseWhenWritable) {
3993 EXPECT_FALSE(writer_->IsWriteBlocked());
3995 // Send a packet.
3996 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
3997 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3998 EXPECT_EQ(1u, writer_->packets_write_attempts());
4000 TriggerConnectionClose();
4001 EXPECT_EQ(2u, writer_->packets_write_attempts());
4004 TEST_P(QuicConnectionTest, ConnectionCloseGettingWriteBlocked) {
4005 BlockOnNextWrite();
4006 TriggerConnectionClose();
4007 EXPECT_EQ(1u, writer_->packets_write_attempts());
4008 EXPECT_TRUE(writer_->IsWriteBlocked());
4011 TEST_P(QuicConnectionTest, ConnectionCloseWhenWriteBlocked) {
4012 BlockOnNextWrite();
4013 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
4014 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4015 EXPECT_EQ(1u, writer_->packets_write_attempts());
4016 EXPECT_TRUE(writer_->IsWriteBlocked());
4017 TriggerConnectionClose();
4018 EXPECT_EQ(1u, writer_->packets_write_attempts());
4021 TEST_P(QuicConnectionTest, AckNotifierTriggerCallback) {
4022 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4024 // Create a delegate which we expect to be called.
4025 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4026 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(1);
4028 // Send some data, which will register the delegate to be notified.
4029 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
4031 // Process an ACK from the server which should trigger the callback.
4032 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4033 QuicAckFrame frame = InitAckFrame(1);
4034 ProcessAckPacket(&frame);
4037 TEST_P(QuicConnectionTest, AckNotifierFailToTriggerCallback) {
4038 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4040 // Create a delegate which we don't expect to be called.
4041 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4042 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(0);
4044 // Send some data, which will register the delegate to be notified. This will
4045 // not be ACKed and so the delegate should never be called.
4046 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
4048 // Send some other data which we will ACK.
4049 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
4050 connection_.SendStreamDataWithString(1, "bar", 0, !kFin, nullptr);
4052 // Now we receive ACK for packets 2 and 3, but importantly missing packet 1
4053 // which we registered to be notified about.
4054 QuicAckFrame frame = InitAckFrame(3);
4055 NackPacket(1, &frame);
4056 SequenceNumberSet lost_packets;
4057 lost_packets.insert(1);
4058 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4059 .WillOnce(Return(lost_packets));
4060 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4061 ProcessAckPacket(&frame);
4064 TEST_P(QuicConnectionTest, AckNotifierCallbackAfterRetransmission) {
4065 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4067 // Create a delegate which we expect to be called.
4068 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4069 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(1);
4071 // Send four packets, and register to be notified on ACK of packet 2.
4072 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
4073 connection_.SendStreamDataWithString(3, "bar", 0, !kFin, delegate.get());
4074 connection_.SendStreamDataWithString(3, "baz", 0, !kFin, nullptr);
4075 connection_.SendStreamDataWithString(3, "qux", 0, !kFin, nullptr);
4077 // Now we receive ACK for packets 1, 3, and 4 and lose 2.
4078 QuicAckFrame frame = InitAckFrame(4);
4079 NackPacket(2, &frame);
4080 SequenceNumberSet lost_packets;
4081 lost_packets.insert(2);
4082 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4083 .WillOnce(Return(lost_packets));
4084 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4085 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4086 ProcessAckPacket(&frame);
4088 // Now we get an ACK for packet 5 (retransmitted packet 2), which should
4089 // trigger the callback.
4090 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4091 .WillRepeatedly(Return(SequenceNumberSet()));
4092 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4093 QuicAckFrame second_ack_frame = InitAckFrame(5);
4094 ProcessAckPacket(&second_ack_frame);
4097 // AckNotifierCallback is triggered by the ack of a packet that timed
4098 // out and was retransmitted, even though the retransmission has a
4099 // different sequence number.
4100 TEST_P(QuicConnectionTest, AckNotifierCallbackForAckAfterRTO) {
4101 InSequence s;
4103 // Create a delegate which we expect to be called.
4104 scoped_refptr<MockAckNotifierDelegate> delegate(
4105 new StrictMock<MockAckNotifierDelegate>);
4107 QuicTime default_retransmission_time = clock_.ApproximateNow().Add(
4108 DefaultRetransmissionTime());
4109 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, delegate.get());
4110 EXPECT_EQ(1u, stop_waiting()->least_unacked);
4112 EXPECT_EQ(1u, writer_->header().packet_sequence_number);
4113 EXPECT_EQ(default_retransmission_time,
4114 connection_.GetRetransmissionAlarm()->deadline());
4115 // Simulate the retransmission alarm firing.
4116 clock_.AdvanceTime(DefaultRetransmissionTime());
4117 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 2u, _, _));
4118 connection_.GetRetransmissionAlarm()->Fire();
4119 EXPECT_EQ(2u, writer_->header().packet_sequence_number);
4120 // We do not raise the high water mark yet.
4121 EXPECT_EQ(1u, stop_waiting()->least_unacked);
4123 // Ack the original packet, which will revert the RTO.
4124 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4125 EXPECT_CALL(*delegate, OnAckNotification(1, _, _));
4126 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4127 QuicAckFrame ack_frame = InitAckFrame(1);
4128 ProcessAckPacket(&ack_frame);
4130 // Delegate is not notified again when the retransmit is acked.
4131 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4132 QuicAckFrame second_ack_frame = InitAckFrame(2);
4133 ProcessAckPacket(&second_ack_frame);
4136 // AckNotifierCallback is triggered by the ack of a packet that was
4137 // previously nacked, even though the retransmission has a different
4138 // sequence number.
4139 TEST_P(QuicConnectionTest, AckNotifierCallbackForAckOfNackedPacket) {
4140 InSequence s;
4142 // Create a delegate which we expect to be called.
4143 scoped_refptr<MockAckNotifierDelegate> delegate(
4144 new StrictMock<MockAckNotifierDelegate>);
4146 // Send four packets, and register to be notified on ACK of packet 2.
4147 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
4148 connection_.SendStreamDataWithString(3, "bar", 0, !kFin, delegate.get());
4149 connection_.SendStreamDataWithString(3, "baz", 0, !kFin, nullptr);
4150 connection_.SendStreamDataWithString(3, "qux", 0, !kFin, nullptr);
4152 // Now we receive ACK for packets 1, 3, and 4 and lose 2.
4153 QuicAckFrame frame = InitAckFrame(4);
4154 NackPacket(2, &frame);
4155 SequenceNumberSet lost_packets;
4156 lost_packets.insert(2);
4157 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4158 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4159 .WillOnce(Return(lost_packets));
4160 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4161 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4162 ProcessAckPacket(&frame);
4164 // Now we get an ACK for packet 2, which was previously nacked.
4165 SequenceNumberSet no_lost_packets;
4166 EXPECT_CALL(*delegate.get(), OnAckNotification(1, _, _));
4167 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4168 .WillOnce(Return(no_lost_packets));
4169 QuicAckFrame second_ack_frame = InitAckFrame(4);
4170 ProcessAckPacket(&second_ack_frame);
4172 // Verify that the delegate is not notified again when the
4173 // retransmit is acked.
4174 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4175 .WillOnce(Return(no_lost_packets));
4176 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4177 QuicAckFrame third_ack_frame = InitAckFrame(5);
4178 ProcessAckPacket(&third_ack_frame);
4181 TEST_P(QuicConnectionTest, AckNotifierFECTriggerCallback) {
4182 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4184 // Create a delegate which we expect to be called.
4185 scoped_refptr<MockAckNotifierDelegate> delegate(
4186 new MockAckNotifierDelegate);
4187 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(1);
4189 // Send some data, which will register the delegate to be notified.
4190 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
4191 connection_.SendStreamDataWithString(2, "bar", 0, !kFin, nullptr);
4193 // Process an ACK from the server with a revived packet, which should trigger
4194 // the callback.
4195 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4196 QuicAckFrame frame = InitAckFrame(2);
4197 NackPacket(1, &frame);
4198 frame.revived_packets.insert(1);
4199 ProcessAckPacket(&frame);
4200 // If the ack is processed again, the notifier should not be called again.
4201 ProcessAckPacket(&frame);
4204 TEST_P(QuicConnectionTest, AckNotifierCallbackAfterFECRecovery) {
4205 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4206 EXPECT_CALL(visitor_, OnCanWrite());
4208 // Create a delegate which we expect to be called.
4209 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4210 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(1);
4212 // Expect ACKs for 1 packet.
4213 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4215 // Send one packet, and register to be notified on ACK.
4216 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
4218 // Ack packet gets dropped, but we receive an FEC packet that covers it.
4219 // Should recover the Ack packet and trigger the notification callback.
4220 QuicFrames frames;
4222 QuicAckFrame ack_frame = InitAckFrame(1);
4223 frames.push_back(QuicFrame(&ack_frame));
4225 // Dummy stream frame to satisfy expectations set elsewhere.
4226 frames.push_back(QuicFrame(&frame1_));
4228 QuicPacketHeader ack_header;
4229 ack_header.public_header.connection_id = connection_id_;
4230 ack_header.public_header.reset_flag = false;
4231 ack_header.public_header.version_flag = false;
4232 ack_header.entropy_flag = !kEntropyFlag;
4233 ack_header.fec_flag = true;
4234 ack_header.packet_sequence_number = 1;
4235 ack_header.is_in_fec_group = IN_FEC_GROUP;
4236 ack_header.fec_group = 1;
4238 QuicPacket* packet = BuildUnsizedDataPacket(&framer_, ack_header, frames);
4240 // Take the packet which contains the ACK frame, and construct and deliver an
4241 // FEC packet which allows the ACK packet to be recovered.
4242 ProcessFecPacket(2, 1, true, !kEntropyFlag, packet);
4245 TEST_P(QuicConnectionTest, NetworkChangeVisitorCwndCallbackChangesFecState) {
4246 size_t max_packets_per_fec_group = creator_->max_packets_per_fec_group();
4248 QuicSentPacketManager::NetworkChangeVisitor* visitor =
4249 QuicSentPacketManagerPeer::GetNetworkChangeVisitor(manager_);
4250 EXPECT_TRUE(visitor);
4252 // Increase FEC group size by increasing congestion window to a large number.
4253 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
4254 Return(1000 * kDefaultTCPMSS));
4255 visitor->OnCongestionWindowChange();
4256 EXPECT_LT(max_packets_per_fec_group, creator_->max_packets_per_fec_group());
4259 TEST_P(QuicConnectionTest, NetworkChangeVisitorConfigCallbackChangesFecState) {
4260 QuicSentPacketManager::NetworkChangeVisitor* visitor =
4261 QuicSentPacketManagerPeer::GetNetworkChangeVisitor(manager_);
4262 EXPECT_TRUE(visitor);
4263 EXPECT_EQ(QuicTime::Delta::Zero(),
4264 QuicPacketGeneratorPeer::GetFecTimeout(generator_));
4266 // Verify that sending a config with a new initial rtt changes fec timeout.
4267 // Create and process a config with a non-zero initial RTT.
4268 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4269 QuicConfig config;
4270 config.SetInitialRoundTripTimeUsToSend(300000);
4271 connection_.SetFromConfig(config);
4272 EXPECT_LT(QuicTime::Delta::Zero(),
4273 QuicPacketGeneratorPeer::GetFecTimeout(generator_));
4276 TEST_P(QuicConnectionTest, NetworkChangeVisitorRttCallbackChangesFecState) {
4277 // Verify that sending a config with a new initial rtt changes fec timeout.
4278 QuicSentPacketManager::NetworkChangeVisitor* visitor =
4279 QuicSentPacketManagerPeer::GetNetworkChangeVisitor(manager_);
4280 EXPECT_TRUE(visitor);
4281 EXPECT_EQ(QuicTime::Delta::Zero(),
4282 QuicPacketGeneratorPeer::GetFecTimeout(generator_));
4284 // Increase FEC timeout by increasing RTT.
4285 RttStats* rtt_stats = QuicSentPacketManagerPeer::GetRttStats(manager_);
4286 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(300),
4287 QuicTime::Delta::Zero(), QuicTime::Zero());
4288 visitor->OnRttChange();
4289 EXPECT_LT(QuicTime::Delta::Zero(),
4290 QuicPacketGeneratorPeer::GetFecTimeout(generator_));
4293 TEST_P(QuicConnectionTest, OnPacketHeaderDebugVisitor) {
4294 QuicPacketHeader header;
4296 scoped_ptr<MockQuicConnectionDebugVisitor> debug_visitor(
4297 new MockQuicConnectionDebugVisitor());
4298 connection_.set_debug_visitor(debug_visitor.get());
4299 EXPECT_CALL(*debug_visitor, OnPacketHeader(Ref(header))).Times(1);
4300 connection_.OnPacketHeader(header);
4303 TEST_P(QuicConnectionTest, Pacing) {
4304 TestConnection server(connection_id_, IPEndPoint(), helper_.get(), factory_,
4305 Perspective::IS_SERVER, version());
4306 TestConnection client(connection_id_, IPEndPoint(), helper_.get(), factory_,
4307 Perspective::IS_CLIENT, version());
4308 EXPECT_FALSE(client.sent_packet_manager().using_pacing());
4309 EXPECT_FALSE(server.sent_packet_manager().using_pacing());
4312 TEST_P(QuicConnectionTest, ControlFramesInstigateAcks) {
4313 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4315 // Send a WINDOW_UPDATE frame.
4316 QuicWindowUpdateFrame window_update;
4317 window_update.stream_id = 3;
4318 window_update.byte_offset = 1234;
4319 EXPECT_CALL(visitor_, OnWindowUpdateFrames(_));
4320 ProcessFramePacket(QuicFrame(&window_update));
4322 // Ensure that this has caused the ACK alarm to be set.
4323 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
4324 EXPECT_TRUE(ack_alarm->IsSet());
4326 // Cancel alarm, and try again with BLOCKED frame.
4327 ack_alarm->Cancel();
4328 QuicBlockedFrame blocked;
4329 blocked.stream_id = 3;
4330 EXPECT_CALL(visitor_, OnBlockedFrames(_));
4331 ProcessFramePacket(QuicFrame(&blocked));
4332 EXPECT_TRUE(ack_alarm->IsSet());
4335 TEST_P(QuicConnectionTest, NoDataNoFin) {
4336 // Make sure that a call to SendStreamWithData, with no data and no FIN, does
4337 // not result in a QuicAckNotifier being used-after-free (fail under ASAN).
4338 // Regression test for b/18594622
4339 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4340 EXPECT_DFATAL(
4341 connection_.SendStreamDataWithString(3, "", 0, !kFin, delegate.get()),
4342 "Attempt to send empty stream frame");
4345 } // namespace
4346 } // namespace test
4347 } // namespace net