Re-land: C++ readability review
[chromium-blink-merge.git] / net / quic / quic_connection_test.cc
blob0f983058350e5dba10d6575306e99231497e45eb
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/quic/quic_connection.h"
7 #include "base/basictypes.h"
8 #include "base/bind.h"
9 #include "base/memory/scoped_ptr.h"
10 #include "base/stl_util.h"
11 #include "net/base/net_errors.h"
12 #include "net/quic/congestion_control/loss_detection_interface.h"
13 #include "net/quic/congestion_control/send_algorithm_interface.h"
14 #include "net/quic/crypto/null_encrypter.h"
15 #include "net/quic/crypto/quic_decrypter.h"
16 #include "net/quic/crypto/quic_encrypter.h"
17 #include "net/quic/quic_ack_notifier.h"
18 #include "net/quic/quic_flags.h"
19 #include "net/quic/quic_protocol.h"
20 #include "net/quic/quic_utils.h"
21 #include "net/quic/test_tools/mock_clock.h"
22 #include "net/quic/test_tools/mock_random.h"
23 #include "net/quic/test_tools/quic_config_peer.h"
24 #include "net/quic/test_tools/quic_connection_peer.h"
25 #include "net/quic/test_tools/quic_framer_peer.h"
26 #include "net/quic/test_tools/quic_packet_creator_peer.h"
27 #include "net/quic/test_tools/quic_packet_generator_peer.h"
28 #include "net/quic/test_tools/quic_sent_packet_manager_peer.h"
29 #include "net/quic/test_tools/quic_test_utils.h"
30 #include "net/quic/test_tools/simple_quic_framer.h"
31 #include "net/test/gtest_util.h"
32 #include "testing/gmock/include/gmock/gmock.h"
33 #include "testing/gtest/include/gtest/gtest.h"
35 using base::StringPiece;
36 using std::map;
37 using std::string;
38 using std::vector;
39 using testing::AnyNumber;
40 using testing::AtLeast;
41 using testing::ContainerEq;
42 using testing::Contains;
43 using testing::DoAll;
44 using testing::InSequence;
45 using testing::InvokeWithoutArgs;
46 using testing::NiceMock;
47 using testing::Ref;
48 using testing::Return;
49 using testing::SaveArg;
50 using testing::StrictMock;
51 using testing::_;
53 namespace net {
54 namespace test {
55 namespace {
57 const char data1[] = "foo";
58 const char data2[] = "bar";
60 const bool kFin = true;
61 const bool kEntropyFlag = true;
63 const QuicPacketEntropyHash kTestEntropyHash = 76;
65 const int kDefaultRetransmissionTimeMs = 500;
67 // TaggingEncrypter appends kTagSize bytes of |tag| to the end of each message.
68 class TaggingEncrypter : public QuicEncrypter {
69 public:
70 explicit TaggingEncrypter(uint8 tag)
71 : tag_(tag) {
74 ~TaggingEncrypter() override {}
76 // QuicEncrypter interface.
77 bool SetKey(StringPiece key) override { return true; }
79 bool SetNoncePrefix(StringPiece nonce_prefix) override { return true; }
81 bool Encrypt(StringPiece nonce,
82 StringPiece associated_data,
83 StringPiece plaintext,
84 unsigned char* output) override {
85 memcpy(output, plaintext.data(), plaintext.size());
86 output += plaintext.size();
87 memset(output, tag_, kTagSize);
88 return true;
91 bool EncryptPacket(QuicPacketSequenceNumber sequence_number,
92 StringPiece associated_data,
93 StringPiece plaintext,
94 char* output,
95 size_t* output_length,
96 size_t max_output_length) override {
97 const size_t len = plaintext.size() + kTagSize;
98 if (max_output_length < len) {
99 return false;
101 Encrypt(StringPiece(), associated_data, plaintext,
102 reinterpret_cast<unsigned char*>(output));
103 *output_length = len;
104 return true;
107 size_t GetKeySize() const override { return 0; }
108 size_t GetNoncePrefixSize() const override { return 0; }
110 size_t GetMaxPlaintextSize(size_t ciphertext_size) const override {
111 return ciphertext_size - kTagSize;
114 size_t GetCiphertextSize(size_t plaintext_size) const override {
115 return plaintext_size + kTagSize;
118 StringPiece GetKey() const override { return StringPiece(); }
120 StringPiece GetNoncePrefix() const override { return StringPiece(); }
122 private:
123 enum {
124 kTagSize = 12,
127 const uint8 tag_;
129 DISALLOW_COPY_AND_ASSIGN(TaggingEncrypter);
132 // TaggingDecrypter ensures that the final kTagSize bytes of the message all
133 // have the same value and then removes them.
134 class TaggingDecrypter : public QuicDecrypter {
135 public:
136 ~TaggingDecrypter() override {}
138 // QuicDecrypter interface
139 bool SetKey(StringPiece key) override { return true; }
141 bool SetNoncePrefix(StringPiece nonce_prefix) override { return true; }
143 bool DecryptPacket(QuicPacketSequenceNumber sequence_number,
144 const StringPiece& associated_data,
145 const StringPiece& ciphertext,
146 char* output,
147 size_t* output_length,
148 size_t max_output_length) override {
149 if (ciphertext.size() < kTagSize) {
150 return false;
152 if (!CheckTag(ciphertext, GetTag(ciphertext))) {
153 return false;
155 *output_length = ciphertext.size() - kTagSize;
156 memcpy(output, ciphertext.data(), *output_length);
157 return true;
160 StringPiece GetKey() const override { return StringPiece(); }
161 StringPiece GetNoncePrefix() const override { return StringPiece(); }
163 protected:
164 virtual uint8 GetTag(StringPiece ciphertext) {
165 return ciphertext.data()[ciphertext.size()-1];
168 private:
169 enum {
170 kTagSize = 12,
173 bool CheckTag(StringPiece ciphertext, uint8 tag) {
174 for (size_t i = ciphertext.size() - kTagSize; i < ciphertext.size(); i++) {
175 if (ciphertext.data()[i] != tag) {
176 return false;
180 return true;
184 // StringTaggingDecrypter ensures that the final kTagSize bytes of the message
185 // match the expected value.
186 class StrictTaggingDecrypter : public TaggingDecrypter {
187 public:
188 explicit StrictTaggingDecrypter(uint8 tag) : tag_(tag) {}
189 ~StrictTaggingDecrypter() override {}
191 // TaggingQuicDecrypter
192 uint8 GetTag(StringPiece ciphertext) override { return tag_; }
194 private:
195 const uint8 tag_;
198 class TestConnectionHelper : public QuicConnectionHelperInterface {
199 public:
200 class TestAlarm : public QuicAlarm {
201 public:
202 explicit TestAlarm(QuicAlarm::Delegate* delegate)
203 : QuicAlarm(delegate) {
206 void SetImpl() override {}
207 void CancelImpl() override {}
208 using QuicAlarm::Fire;
211 TestConnectionHelper(MockClock* clock, MockRandom* random_generator)
212 : clock_(clock),
213 random_generator_(random_generator) {
214 clock_->AdvanceTime(QuicTime::Delta::FromSeconds(1));
217 // QuicConnectionHelperInterface
218 const QuicClock* GetClock() const override { return clock_; }
220 QuicRandom* GetRandomGenerator() override { return random_generator_; }
222 QuicAlarm* CreateAlarm(QuicAlarm::Delegate* delegate) override {
223 return new TestAlarm(delegate);
226 private:
227 MockClock* clock_;
228 MockRandom* random_generator_;
230 DISALLOW_COPY_AND_ASSIGN(TestConnectionHelper);
233 class TestPacketWriter : public QuicPacketWriter {
234 public:
235 TestPacketWriter(QuicVersion version, MockClock *clock)
236 : version_(version),
237 framer_(SupportedVersions(version_)),
238 last_packet_size_(0),
239 write_blocked_(false),
240 block_on_next_write_(false),
241 is_write_blocked_data_buffered_(false),
242 final_bytes_of_last_packet_(0),
243 final_bytes_of_previous_packet_(0),
244 use_tagging_decrypter_(false),
245 packets_write_attempts_(0),
246 clock_(clock),
247 write_pause_time_delta_(QuicTime::Delta::Zero()) {
250 // QuicPacketWriter interface
251 WriteResult WritePacket(const char* buffer,
252 size_t buf_len,
253 const IPAddressNumber& self_address,
254 const IPEndPoint& peer_address) override {
255 QuicEncryptedPacket packet(buffer, buf_len);
256 ++packets_write_attempts_;
258 if (packet.length() >= sizeof(final_bytes_of_last_packet_)) {
259 final_bytes_of_previous_packet_ = final_bytes_of_last_packet_;
260 memcpy(&final_bytes_of_last_packet_, packet.data() + packet.length() - 4,
261 sizeof(final_bytes_of_last_packet_));
264 if (use_tagging_decrypter_) {
265 framer_.framer()->SetDecrypter(new TaggingDecrypter, ENCRYPTION_NONE);
267 EXPECT_TRUE(framer_.ProcessPacket(packet));
268 if (block_on_next_write_) {
269 write_blocked_ = true;
270 block_on_next_write_ = false;
272 if (IsWriteBlocked()) {
273 return WriteResult(WRITE_STATUS_BLOCKED, -1);
275 last_packet_size_ = packet.length();
277 if (!write_pause_time_delta_.IsZero()) {
278 clock_->AdvanceTime(write_pause_time_delta_);
280 return WriteResult(WRITE_STATUS_OK, last_packet_size_);
283 bool IsWriteBlockedDataBuffered() const override {
284 return is_write_blocked_data_buffered_;
287 bool IsWriteBlocked() const override { return write_blocked_; }
289 void SetWritable() override { write_blocked_ = false; }
291 void BlockOnNextWrite() { block_on_next_write_ = true; }
293 // Sets the amount of time that the writer should before the actual write.
294 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
295 write_pause_time_delta_ = delta;
298 const QuicPacketHeader& header() { return framer_.header(); }
300 size_t frame_count() const { return framer_.num_frames(); }
302 const vector<QuicAckFrame>& ack_frames() const {
303 return framer_.ack_frames();
306 const vector<QuicStopWaitingFrame>& stop_waiting_frames() const {
307 return framer_.stop_waiting_frames();
310 const vector<QuicConnectionCloseFrame>& connection_close_frames() const {
311 return framer_.connection_close_frames();
314 const vector<QuicRstStreamFrame>& rst_stream_frames() const {
315 return framer_.rst_stream_frames();
318 const vector<QuicStreamFrame>& stream_frames() const {
319 return framer_.stream_frames();
322 const vector<QuicPingFrame>& ping_frames() const {
323 return framer_.ping_frames();
326 size_t last_packet_size() {
327 return last_packet_size_;
330 const QuicVersionNegotiationPacket* version_negotiation_packet() {
331 return framer_.version_negotiation_packet();
334 void set_is_write_blocked_data_buffered(bool buffered) {
335 is_write_blocked_data_buffered_ = buffered;
338 void set_perspective(Perspective perspective) {
339 // We invert perspective here, because the framer needs to parse packets
340 // we send.
341 perspective = perspective == Perspective::IS_CLIENT
342 ? Perspective::IS_SERVER
343 : Perspective::IS_CLIENT;
344 QuicFramerPeer::SetPerspective(framer_.framer(), perspective);
347 // final_bytes_of_last_packet_ returns the last four bytes of the previous
348 // packet as a little-endian, uint32. This is intended to be used with a
349 // TaggingEncrypter so that tests can determine which encrypter was used for
350 // a given packet.
351 uint32 final_bytes_of_last_packet() { return final_bytes_of_last_packet_; }
353 // Returns the final bytes of the second to last packet.
354 uint32 final_bytes_of_previous_packet() {
355 return final_bytes_of_previous_packet_;
358 void use_tagging_decrypter() {
359 use_tagging_decrypter_ = true;
362 uint32 packets_write_attempts() { return packets_write_attempts_; }
364 void Reset() { framer_.Reset(); }
366 void SetSupportedVersions(const QuicVersionVector& versions) {
367 framer_.SetSupportedVersions(versions);
370 private:
371 QuicVersion version_;
372 SimpleQuicFramer framer_;
373 size_t last_packet_size_;
374 bool write_blocked_;
375 bool block_on_next_write_;
376 bool is_write_blocked_data_buffered_;
377 uint32 final_bytes_of_last_packet_;
378 uint32 final_bytes_of_previous_packet_;
379 bool use_tagging_decrypter_;
380 uint32 packets_write_attempts_;
381 MockClock *clock_;
382 // If non-zero, the clock will pause during WritePacket for this amount of
383 // time.
384 QuicTime::Delta write_pause_time_delta_;
386 DISALLOW_COPY_AND_ASSIGN(TestPacketWriter);
389 class TestConnection : public QuicConnection {
390 public:
391 TestConnection(QuicConnectionId connection_id,
392 IPEndPoint address,
393 TestConnectionHelper* helper,
394 const PacketWriterFactory& factory,
395 Perspective perspective,
396 QuicVersion version)
397 : QuicConnection(connection_id,
398 address,
399 helper,
400 factory,
401 /* owns_writer= */ false,
402 perspective,
403 /* is_secure= */ false,
404 SupportedVersions(version)) {
405 // Disable tail loss probes for most tests.
406 QuicSentPacketManagerPeer::SetMaxTailLossProbes(
407 QuicConnectionPeer::GetSentPacketManager(this), 0);
408 writer()->set_perspective(perspective);
411 void SendAck() {
412 QuicConnectionPeer::SendAck(this);
415 void SetSendAlgorithm(SendAlgorithmInterface* send_algorithm) {
416 QuicConnectionPeer::SetSendAlgorithm(this, send_algorithm);
419 void SetLossAlgorithm(LossDetectionInterface* loss_algorithm) {
420 QuicSentPacketManagerPeer::SetLossAlgorithm(
421 QuicConnectionPeer::GetSentPacketManager(this), loss_algorithm);
424 void SendPacket(EncryptionLevel level,
425 QuicPacketSequenceNumber sequence_number,
426 QuicPacket* packet,
427 QuicPacketEntropyHash entropy_hash,
428 HasRetransmittableData retransmittable) {
429 RetransmittableFrames* retransmittable_frames =
430 retransmittable == HAS_RETRANSMITTABLE_DATA
431 ? new RetransmittableFrames(ENCRYPTION_NONE)
432 : nullptr;
433 QuicEncryptedPacket* encrypted =
434 QuicConnectionPeer::GetFramer(this)
435 ->EncryptPacket(ENCRYPTION_NONE, sequence_number, *packet);
436 delete packet;
437 OnSerializedPacket(SerializedPacket(sequence_number,
438 PACKET_6BYTE_SEQUENCE_NUMBER, encrypted,
439 entropy_hash, retransmittable_frames));
442 QuicConsumedData SendStreamDataWithString(
443 QuicStreamId id,
444 StringPiece data,
445 QuicStreamOffset offset,
446 bool fin,
447 QuicAckNotifier::DelegateInterface* delegate) {
448 return SendStreamDataWithStringHelper(id, data, offset, fin,
449 MAY_FEC_PROTECT, delegate);
452 QuicConsumedData SendStreamDataWithStringWithFec(
453 QuicStreamId id,
454 StringPiece data,
455 QuicStreamOffset offset,
456 bool fin,
457 QuicAckNotifier::DelegateInterface* delegate) {
458 return SendStreamDataWithStringHelper(id, data, offset, fin,
459 MUST_FEC_PROTECT, delegate);
462 QuicConsumedData SendStreamDataWithStringHelper(
463 QuicStreamId id,
464 StringPiece data,
465 QuicStreamOffset offset,
466 bool fin,
467 FecProtection fec_protection,
468 QuicAckNotifier::DelegateInterface* delegate) {
469 IOVector data_iov;
470 if (!data.empty()) {
471 data_iov.Append(const_cast<char*>(data.data()), data.size());
473 return QuicConnection::SendStreamData(id, data_iov, offset, fin,
474 fec_protection, delegate);
477 QuicConsumedData SendStreamData3() {
478 return SendStreamDataWithString(kClientDataStreamId1, "food", 0, !kFin,
479 nullptr);
482 QuicConsumedData SendStreamData3WithFec() {
483 return SendStreamDataWithStringWithFec(kClientDataStreamId1, "food", 0,
484 !kFin, nullptr);
487 QuicConsumedData SendStreamData5() {
488 return SendStreamDataWithString(kClientDataStreamId2, "food2", 0, !kFin,
489 nullptr);
492 QuicConsumedData SendStreamData5WithFec() {
493 return SendStreamDataWithStringWithFec(kClientDataStreamId2, "food2", 0,
494 !kFin, nullptr);
496 // Ensures the connection can write stream data before writing.
497 QuicConsumedData EnsureWritableAndSendStreamData5() {
498 EXPECT_TRUE(CanWriteStreamData());
499 return SendStreamData5();
502 // The crypto stream has special semantics so that it is not blocked by a
503 // congestion window limitation, and also so that it gets put into a separate
504 // packet (so that it is easier to reason about a crypto frame not being
505 // split needlessly across packet boundaries). As a result, we have separate
506 // tests for some cases for this stream.
507 QuicConsumedData SendCryptoStreamData() {
508 return SendStreamDataWithString(kCryptoStreamId, "chlo", 0, !kFin, nullptr);
511 void set_version(QuicVersion version) {
512 QuicConnectionPeer::GetFramer(this)->set_version(version);
515 void SetSupportedVersions(const QuicVersionVector& versions) {
516 QuicConnectionPeer::GetFramer(this)->SetSupportedVersions(versions);
517 writer()->SetSupportedVersions(versions);
520 void set_perspective(Perspective perspective) {
521 writer()->set_perspective(perspective);
522 QuicConnectionPeer::SetPerspective(this, perspective);
525 TestConnectionHelper::TestAlarm* GetAckAlarm() {
526 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
527 QuicConnectionPeer::GetAckAlarm(this));
530 TestConnectionHelper::TestAlarm* GetPingAlarm() {
531 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
532 QuicConnectionPeer::GetPingAlarm(this));
535 TestConnectionHelper::TestAlarm* GetFecAlarm() {
536 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
537 QuicConnectionPeer::GetFecAlarm(this));
540 TestConnectionHelper::TestAlarm* GetResumeWritesAlarm() {
541 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
542 QuicConnectionPeer::GetResumeWritesAlarm(this));
545 TestConnectionHelper::TestAlarm* GetRetransmissionAlarm() {
546 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
547 QuicConnectionPeer::GetRetransmissionAlarm(this));
550 TestConnectionHelper::TestAlarm* GetSendAlarm() {
551 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
552 QuicConnectionPeer::GetSendAlarm(this));
555 TestConnectionHelper::TestAlarm* GetTimeoutAlarm() {
556 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
557 QuicConnectionPeer::GetTimeoutAlarm(this));
560 using QuicConnection::SelectMutualVersion;
562 private:
563 TestPacketWriter* writer() {
564 return static_cast<TestPacketWriter*>(QuicConnection::writer());
567 DISALLOW_COPY_AND_ASSIGN(TestConnection);
570 // Used for testing packets revived from FEC packets.
571 class FecQuicConnectionDebugVisitor
572 : public QuicConnectionDebugVisitor {
573 public:
574 void OnRevivedPacket(const QuicPacketHeader& header,
575 StringPiece data) override {
576 revived_header_ = header;
579 // Public accessor method.
580 QuicPacketHeader revived_header() const {
581 return revived_header_;
584 private:
585 QuicPacketHeader revived_header_;
588 class MockPacketWriterFactory : public QuicConnection::PacketWriterFactory {
589 public:
590 explicit MockPacketWriterFactory(QuicPacketWriter* writer) {
591 ON_CALL(*this, Create(_)).WillByDefault(Return(writer));
593 ~MockPacketWriterFactory() override {}
595 MOCK_CONST_METHOD1(Create, QuicPacketWriter*(QuicConnection* connection));
598 class QuicConnectionTest : public ::testing::TestWithParam<QuicVersion> {
599 protected:
600 QuicConnectionTest()
601 : connection_id_(42),
602 framer_(SupportedVersions(version()),
603 QuicTime::Zero(),
604 Perspective::IS_CLIENT),
605 peer_creator_(connection_id_, &framer_, &random_generator_),
606 send_algorithm_(new StrictMock<MockSendAlgorithm>),
607 loss_algorithm_(new MockLossAlgorithm()),
608 helper_(new TestConnectionHelper(&clock_, &random_generator_)),
609 writer_(new TestPacketWriter(version(), &clock_)),
610 factory_(writer_.get()),
611 connection_(connection_id_,
612 IPEndPoint(),
613 helper_.get(),
614 factory_,
615 Perspective::IS_CLIENT,
616 version()),
617 creator_(QuicConnectionPeer::GetPacketCreator(&connection_)),
618 generator_(QuicConnectionPeer::GetPacketGenerator(&connection_)),
619 manager_(QuicConnectionPeer::GetSentPacketManager(&connection_)),
620 frame1_(1, false, 0, MakeIOVector(data1)),
621 frame2_(1, false, 3, MakeIOVector(data2)),
622 sequence_number_length_(PACKET_6BYTE_SEQUENCE_NUMBER),
623 connection_id_length_(PACKET_8BYTE_CONNECTION_ID) {
624 connection_.set_visitor(&visitor_);
625 connection_.SetSendAlgorithm(send_algorithm_);
626 connection_.SetLossAlgorithm(loss_algorithm_);
627 framer_.set_received_entropy_calculator(&entropy_calculator_);
628 EXPECT_CALL(
629 *send_algorithm_, TimeUntilSend(_, _, _)).WillRepeatedly(Return(
630 QuicTime::Delta::Zero()));
631 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
632 .Times(AnyNumber());
633 EXPECT_CALL(*send_algorithm_, RetransmissionDelay()).WillRepeatedly(
634 Return(QuicTime::Delta::Zero()));
635 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
636 Return(kMaxPacketSize));
637 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
638 .WillByDefault(Return(true));
639 EXPECT_CALL(*send_algorithm_, HasReliableBandwidthEstimate())
640 .Times(AnyNumber());
641 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
642 .Times(AnyNumber())
643 .WillRepeatedly(Return(QuicBandwidth::Zero()));
644 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
645 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
646 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).Times(AnyNumber());
647 EXPECT_CALL(visitor_, HasPendingHandshake()).Times(AnyNumber());
648 EXPECT_CALL(visitor_, OnCanWrite()).Times(AnyNumber());
649 EXPECT_CALL(visitor_, HasOpenDataStreams()).WillRepeatedly(Return(false));
650 EXPECT_CALL(visitor_, OnCongestionWindowChange(_)).Times(AnyNumber());
652 EXPECT_CALL(*loss_algorithm_, GetLossTimeout())
653 .WillRepeatedly(Return(QuicTime::Zero()));
654 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
655 .WillRepeatedly(Return(SequenceNumberSet()));
658 QuicVersion version() {
659 return GetParam();
662 QuicAckFrame* outgoing_ack() {
663 QuicConnectionPeer::PopulateAckFrame(&connection_, &ack_);
664 return &ack_;
667 QuicStopWaitingFrame* stop_waiting() {
668 QuicConnectionPeer::PopulateStopWaitingFrame(&connection_, &stop_waiting_);
669 return &stop_waiting_;
672 QuicPacketSequenceNumber least_unacked() {
673 if (writer_->stop_waiting_frames().empty()) {
674 return 0;
676 return writer_->stop_waiting_frames()[0].least_unacked;
679 void use_tagging_decrypter() {
680 writer_->use_tagging_decrypter();
683 void ProcessPacket(QuicPacketSequenceNumber number) {
684 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
685 ProcessDataPacket(number, 0, !kEntropyFlag);
688 QuicPacketEntropyHash ProcessFramePacket(QuicFrame frame) {
689 QuicFrames frames;
690 frames.push_back(QuicFrame(frame));
691 QuicPacketCreatorPeer::SetSendVersionInPacket(
692 &peer_creator_, connection_.perspective() == Perspective::IS_SERVER);
694 SerializedPacket serialized_packet =
695 peer_creator_.SerializeAllFrames(frames);
696 scoped_ptr<QuicEncryptedPacket> encrypted(serialized_packet.packet);
697 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
698 return serialized_packet.entropy_hash;
701 size_t ProcessDataPacket(QuicPacketSequenceNumber number,
702 QuicFecGroupNumber fec_group,
703 bool entropy_flag) {
704 return ProcessDataPacketAtLevel(number, fec_group, entropy_flag,
705 ENCRYPTION_NONE);
708 size_t ProcessDataPacketAtLevel(QuicPacketSequenceNumber number,
709 QuicFecGroupNumber fec_group,
710 bool entropy_flag,
711 EncryptionLevel level) {
712 scoped_ptr<QuicPacket> packet(ConstructDataPacket(number, fec_group,
713 entropy_flag));
714 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPacket(
715 level, number, *packet));
716 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
717 return encrypted->length();
720 void ProcessClosePacket(QuicPacketSequenceNumber number,
721 QuicFecGroupNumber fec_group) {
722 scoped_ptr<QuicPacket> packet(ConstructClosePacket(number, fec_group));
723 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPacket(
724 ENCRYPTION_NONE, number, *packet));
725 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
728 size_t ProcessFecProtectedPacket(QuicPacketSequenceNumber number,
729 bool expect_revival, bool entropy_flag) {
730 if (expect_revival) {
731 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
733 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1).
734 RetiresOnSaturation();
735 return ProcessDataPacket(number, 1, entropy_flag);
738 // Processes an FEC packet that covers the packets that would have been
739 // received.
740 size_t ProcessFecPacket(QuicPacketSequenceNumber number,
741 QuicPacketSequenceNumber min_protected_packet,
742 bool expect_revival,
743 bool entropy_flag,
744 QuicPacket* packet) {
745 if (expect_revival) {
746 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
749 // Construct the decrypted data packet so we can compute the correct
750 // redundancy. If |packet| has been provided then use that, otherwise
751 // construct a default data packet.
752 scoped_ptr<QuicPacket> data_packet;
753 if (packet) {
754 data_packet.reset(packet);
755 } else {
756 data_packet.reset(ConstructDataPacket(number, 1, !kEntropyFlag));
759 header_.public_header.connection_id = connection_id_;
760 header_.public_header.reset_flag = false;
761 header_.public_header.version_flag = false;
762 header_.public_header.sequence_number_length = sequence_number_length_;
763 header_.public_header.connection_id_length = connection_id_length_;
764 header_.packet_sequence_number = number;
765 header_.entropy_flag = entropy_flag;
766 header_.fec_flag = true;
767 header_.is_in_fec_group = IN_FEC_GROUP;
768 header_.fec_group = min_protected_packet;
769 QuicFecData fec_data;
770 fec_data.fec_group = header_.fec_group;
772 // Since all data packets in this test have the same payload, the
773 // redundancy is either equal to that payload or the xor of that payload
774 // with itself, depending on the number of packets.
775 if (((number - min_protected_packet) % 2) == 0) {
776 for (size_t i = GetStartOfFecProtectedData(
777 header_.public_header.connection_id_length,
778 header_.public_header.version_flag,
779 header_.public_header.sequence_number_length);
780 i < data_packet->length(); ++i) {
781 data_packet->mutable_data()[i] ^= data_packet->data()[i];
784 fec_data.redundancy = data_packet->FecProtectedData();
786 scoped_ptr<QuicPacket> fec_packet(
787 framer_.BuildFecPacket(header_, fec_data));
788 scoped_ptr<QuicEncryptedPacket> encrypted(
789 framer_.EncryptPacket(ENCRYPTION_NONE, number, *fec_packet));
791 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
792 return encrypted->length();
795 QuicByteCount SendStreamDataToPeer(QuicStreamId id,
796 StringPiece data,
797 QuicStreamOffset offset,
798 bool fin,
799 QuicPacketSequenceNumber* last_packet) {
800 QuicByteCount packet_size;
801 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
802 .WillOnce(DoAll(SaveArg<3>(&packet_size), Return(true)));
803 connection_.SendStreamDataWithString(id, data, offset, fin, nullptr);
804 if (last_packet != nullptr) {
805 *last_packet = creator_->sequence_number();
807 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
808 .Times(AnyNumber());
809 return packet_size;
812 void SendAckPacketToPeer() {
813 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
814 connection_.SendAck();
815 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
816 .Times(AnyNumber());
819 QuicPacketEntropyHash ProcessAckPacket(QuicAckFrame* frame) {
820 return ProcessFramePacket(QuicFrame(frame));
823 QuicPacketEntropyHash ProcessStopWaitingPacket(QuicStopWaitingFrame* frame) {
824 return ProcessFramePacket(QuicFrame(frame));
827 QuicPacketEntropyHash ProcessGoAwayPacket(QuicGoAwayFrame* frame) {
828 return ProcessFramePacket(QuicFrame(frame));
831 bool IsMissing(QuicPacketSequenceNumber number) {
832 return IsAwaitingPacket(*outgoing_ack(), number);
835 QuicPacket* ConstructDataPacket(QuicPacketSequenceNumber number,
836 QuicFecGroupNumber fec_group,
837 bool entropy_flag) {
838 header_.public_header.connection_id = connection_id_;
839 header_.public_header.reset_flag = false;
840 header_.public_header.version_flag = false;
841 header_.public_header.sequence_number_length = sequence_number_length_;
842 header_.public_header.connection_id_length = connection_id_length_;
843 header_.entropy_flag = entropy_flag;
844 header_.fec_flag = false;
845 header_.packet_sequence_number = number;
846 header_.is_in_fec_group = fec_group == 0u ? NOT_IN_FEC_GROUP : IN_FEC_GROUP;
847 header_.fec_group = fec_group;
849 QuicFrames frames;
850 QuicFrame frame(&frame1_);
851 frames.push_back(frame);
852 QuicPacket* packet = BuildUnsizedDataPacket(&framer_, header_, frames);
853 EXPECT_TRUE(packet != nullptr);
854 return packet;
857 QuicPacket* ConstructClosePacket(QuicPacketSequenceNumber number,
858 QuicFecGroupNumber fec_group) {
859 header_.public_header.connection_id = connection_id_;
860 header_.packet_sequence_number = number;
861 header_.public_header.reset_flag = false;
862 header_.public_header.version_flag = false;
863 header_.entropy_flag = false;
864 header_.fec_flag = false;
865 header_.is_in_fec_group = fec_group == 0u ? NOT_IN_FEC_GROUP : IN_FEC_GROUP;
866 header_.fec_group = fec_group;
868 QuicConnectionCloseFrame qccf;
869 qccf.error_code = QUIC_PEER_GOING_AWAY;
871 QuicFrames frames;
872 QuicFrame frame(&qccf);
873 frames.push_back(frame);
874 QuicPacket* packet = BuildUnsizedDataPacket(&framer_, header_, frames);
875 EXPECT_TRUE(packet != nullptr);
876 return packet;
879 QuicTime::Delta DefaultRetransmissionTime() {
880 return QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
883 QuicTime::Delta DefaultDelayedAckTime() {
884 return QuicTime::Delta::FromMilliseconds(kMaxDelayedAckTimeMs);
887 // Initialize a frame acknowledging all packets up to largest_observed.
888 const QuicAckFrame InitAckFrame(QuicPacketSequenceNumber largest_observed) {
889 QuicAckFrame frame(MakeAckFrame(largest_observed));
890 if (largest_observed > 0) {
891 frame.entropy_hash =
892 QuicConnectionPeer::GetSentEntropyHash(&connection_,
893 largest_observed);
895 return frame;
898 const QuicStopWaitingFrame InitStopWaitingFrame(
899 QuicPacketSequenceNumber least_unacked) {
900 QuicStopWaitingFrame frame;
901 frame.least_unacked = least_unacked;
902 return frame;
905 // Explicitly nack a packet.
906 void NackPacket(QuicPacketSequenceNumber missing, QuicAckFrame* frame) {
907 frame->missing_packets.insert(missing);
908 frame->entropy_hash ^=
909 QuicConnectionPeer::PacketEntropy(&connection_, missing);
912 // Undo nacking a packet within the frame.
913 void AckPacket(QuicPacketSequenceNumber arrived, QuicAckFrame* frame) {
914 EXPECT_THAT(frame->missing_packets, Contains(arrived));
915 frame->missing_packets.erase(arrived);
916 frame->entropy_hash ^=
917 QuicConnectionPeer::PacketEntropy(&connection_, arrived);
920 void TriggerConnectionClose() {
921 // Send an erroneous packet to close the connection.
922 EXPECT_CALL(visitor_,
923 OnConnectionClosed(QUIC_INVALID_PACKET_HEADER, false));
924 // Call ProcessDataPacket rather than ProcessPacket, as we should not get a
925 // packet call to the visitor.
926 ProcessDataPacket(6000, 0, !kEntropyFlag);
927 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
928 nullptr);
931 void BlockOnNextWrite() {
932 writer_->BlockOnNextWrite();
933 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
936 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
937 writer_->SetWritePauseTimeDelta(delta);
940 void CongestionBlockWrites() {
941 EXPECT_CALL(*send_algorithm_,
942 TimeUntilSend(_, _, _)).WillRepeatedly(
943 testing::Return(QuicTime::Delta::FromSeconds(1)));
946 void CongestionUnblockWrites() {
947 EXPECT_CALL(*send_algorithm_,
948 TimeUntilSend(_, _, _)).WillRepeatedly(
949 testing::Return(QuicTime::Delta::Zero()));
952 QuicConnectionId connection_id_;
953 QuicFramer framer_;
954 QuicPacketCreator peer_creator_;
955 MockEntropyCalculator entropy_calculator_;
957 MockSendAlgorithm* send_algorithm_;
958 MockLossAlgorithm* loss_algorithm_;
959 MockClock clock_;
960 MockRandom random_generator_;
961 scoped_ptr<TestConnectionHelper> helper_;
962 scoped_ptr<TestPacketWriter> writer_;
963 NiceMock<MockPacketWriterFactory> factory_;
964 TestConnection connection_;
965 QuicPacketCreator* creator_;
966 QuicPacketGenerator* generator_;
967 QuicSentPacketManager* manager_;
968 StrictMock<MockConnectionVisitor> visitor_;
970 QuicPacketHeader header_;
971 QuicStreamFrame frame1_;
972 QuicStreamFrame frame2_;
973 QuicAckFrame ack_;
974 QuicStopWaitingFrame stop_waiting_;
975 QuicSequenceNumberLength sequence_number_length_;
976 QuicConnectionIdLength connection_id_length_;
978 private:
979 DISALLOW_COPY_AND_ASSIGN(QuicConnectionTest);
982 // Run all end to end tests with all supported versions.
983 INSTANTIATE_TEST_CASE_P(SupportedVersion,
984 QuicConnectionTest,
985 ::testing::ValuesIn(QuicSupportedVersions()));
987 TEST_P(QuicConnectionTest, MaxPacketSize) {
988 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
989 EXPECT_EQ(1350u, connection_.max_packet_length());
992 TEST_P(QuicConnectionTest, SmallerServerMaxPacketSize) {
993 ValueRestore<bool> old_flag(&FLAGS_quic_small_default_packet_size, true);
994 QuicConnectionId connection_id = 42;
995 TestConnection connection(connection_id, IPEndPoint(), helper_.get(),
996 factory_, Perspective::IS_SERVER, version());
997 EXPECT_EQ(Perspective::IS_SERVER, connection.perspective());
998 EXPECT_EQ(1000u, connection.max_packet_length());
1001 TEST_P(QuicConnectionTest, ServerMaxPacketSize) {
1002 ValueRestore<bool> old_flag(&FLAGS_quic_small_default_packet_size, false);
1003 QuicConnectionId connection_id = 42;
1004 TestConnection connection(connection_id, IPEndPoint(), helper_.get(),
1005 factory_, Perspective::IS_SERVER, version());
1006 EXPECT_EQ(Perspective::IS_SERVER, connection.perspective());
1007 EXPECT_EQ(1350u, connection.max_packet_length());
1010 TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSize) {
1011 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1013 connection_.set_perspective(Perspective::IS_SERVER);
1014 connection_.set_max_packet_length(1000);
1016 QuicPacketHeader header;
1017 header.public_header.connection_id = connection_id_;
1018 header.public_header.reset_flag = false;
1019 header.public_header.version_flag = true;
1020 header.entropy_flag = false;
1021 header.fec_flag = false;
1022 header.packet_sequence_number = 1;
1023 header.fec_group = 0;
1025 QuicFrames frames;
1026 QuicPaddingFrame padding;
1027 frames.push_back(QuicFrame(&frame1_));
1028 frames.push_back(QuicFrame(&padding));
1030 scoped_ptr<QuicPacket> packet(
1031 BuildUnsizedDataPacket(&framer_, header, frames));
1032 scoped_ptr<QuicEncryptedPacket> encrypted(
1033 framer_.EncryptPacket(ENCRYPTION_NONE, 12, *packet));
1034 EXPECT_EQ(kMaxPacketSize, encrypted->length());
1036 framer_.set_version(version());
1037 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
1038 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
1040 EXPECT_EQ(kMaxPacketSize, connection_.max_packet_length());
1043 TEST_P(QuicConnectionTest, PacketsInOrder) {
1044 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1046 ProcessPacket(1);
1047 EXPECT_EQ(1u, outgoing_ack()->largest_observed);
1048 EXPECT_EQ(0u, outgoing_ack()->missing_packets.size());
1050 ProcessPacket(2);
1051 EXPECT_EQ(2u, outgoing_ack()->largest_observed);
1052 EXPECT_EQ(0u, outgoing_ack()->missing_packets.size());
1054 ProcessPacket(3);
1055 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1056 EXPECT_EQ(0u, outgoing_ack()->missing_packets.size());
1059 TEST_P(QuicConnectionTest, PacketsOutOfOrder) {
1060 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1062 ProcessPacket(3);
1063 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1064 EXPECT_TRUE(IsMissing(2));
1065 EXPECT_TRUE(IsMissing(1));
1067 ProcessPacket(2);
1068 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1069 EXPECT_FALSE(IsMissing(2));
1070 EXPECT_TRUE(IsMissing(1));
1072 ProcessPacket(1);
1073 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1074 EXPECT_FALSE(IsMissing(2));
1075 EXPECT_FALSE(IsMissing(1));
1078 TEST_P(QuicConnectionTest, DuplicatePacket) {
1079 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1081 ProcessPacket(3);
1082 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1083 EXPECT_TRUE(IsMissing(2));
1084 EXPECT_TRUE(IsMissing(1));
1086 // Send packet 3 again, but do not set the expectation that
1087 // the visitor OnStreamFrames() will be called.
1088 ProcessDataPacket(3, 0, !kEntropyFlag);
1089 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1090 EXPECT_TRUE(IsMissing(2));
1091 EXPECT_TRUE(IsMissing(1));
1094 TEST_P(QuicConnectionTest, PacketsOutOfOrderWithAdditionsAndLeastAwaiting) {
1095 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1097 ProcessPacket(3);
1098 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1099 EXPECT_TRUE(IsMissing(2));
1100 EXPECT_TRUE(IsMissing(1));
1102 ProcessPacket(2);
1103 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1104 EXPECT_TRUE(IsMissing(1));
1106 ProcessPacket(5);
1107 EXPECT_EQ(5u, outgoing_ack()->largest_observed);
1108 EXPECT_TRUE(IsMissing(1));
1109 EXPECT_TRUE(IsMissing(4));
1111 // Pretend at this point the client has gotten acks for 2 and 3 and 1 is a
1112 // packet the peer will not retransmit. It indicates this by sending 'least
1113 // awaiting' is 4. The connection should then realize 1 will not be
1114 // retransmitted, and will remove it from the missing list.
1115 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 5);
1116 QuicAckFrame frame = InitAckFrame(1);
1117 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _));
1118 ProcessAckPacket(&frame);
1120 // Force an ack to be sent.
1121 SendAckPacketToPeer();
1122 EXPECT_TRUE(IsMissing(4));
1125 TEST_P(QuicConnectionTest, RejectPacketTooFarOut) {
1126 EXPECT_CALL(visitor_,
1127 OnConnectionClosed(QUIC_INVALID_PACKET_HEADER, false));
1128 // Call ProcessDataPacket rather than ProcessPacket, as we should not get a
1129 // packet call to the visitor.
1130 ProcessDataPacket(6000, 0, !kEntropyFlag);
1131 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1132 nullptr);
1135 TEST_P(QuicConnectionTest, RejectUnencryptedStreamData) {
1136 // Process an unencrypted packet from the non-crypto stream.
1137 frame1_.stream_id = 3;
1138 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1139 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_UNENCRYPTED_STREAM_DATA,
1140 false));
1141 ProcessDataPacket(1, 0, !kEntropyFlag);
1142 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1143 nullptr);
1144 const vector<QuicConnectionCloseFrame>& connection_close_frames =
1145 writer_->connection_close_frames();
1146 EXPECT_EQ(1u, connection_close_frames.size());
1147 EXPECT_EQ(QUIC_UNENCRYPTED_STREAM_DATA,
1148 connection_close_frames[0].error_code);
1151 TEST_P(QuicConnectionTest, TruncatedAck) {
1152 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1153 QuicPacketSequenceNumber num_packets = 256 * 2 + 1;
1154 for (QuicPacketSequenceNumber i = 0; i < num_packets; ++i) {
1155 SendStreamDataToPeer(3, "foo", i * 3, !kFin, nullptr);
1158 QuicAckFrame frame = InitAckFrame(num_packets);
1159 SequenceNumberSet lost_packets;
1160 // Create an ack with 256 nacks, none adjacent to one another.
1161 for (QuicPacketSequenceNumber i = 1; i <= 256; ++i) {
1162 NackPacket(i * 2, &frame);
1163 if (i < 256) { // Last packet is nacked, but not lost.
1164 lost_packets.insert(i * 2);
1167 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1168 .WillOnce(Return(lost_packets));
1169 EXPECT_CALL(entropy_calculator_, EntropyHash(511))
1170 .WillOnce(Return(static_cast<QuicPacketEntropyHash>(0)));
1171 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1172 ProcessAckPacket(&frame);
1174 // A truncated ack will not have the true largest observed.
1175 EXPECT_GT(num_packets, manager_->largest_observed());
1177 AckPacket(192, &frame);
1179 // Removing one missing packet allows us to ack 192 and one more range, but
1180 // 192 has already been declared lost, so it doesn't register as an ack.
1181 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1182 .WillOnce(Return(SequenceNumberSet()));
1183 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1184 ProcessAckPacket(&frame);
1185 EXPECT_EQ(num_packets, manager_->largest_observed());
1188 TEST_P(QuicConnectionTest, AckReceiptCausesAckSendBadEntropy) {
1189 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1191 ProcessPacket(1);
1192 // Delay sending, then queue up an ack.
1193 EXPECT_CALL(*send_algorithm_,
1194 TimeUntilSend(_, _, _)).WillOnce(
1195 testing::Return(QuicTime::Delta::FromMicroseconds(1)));
1196 QuicConnectionPeer::SendAck(&connection_);
1198 // Process an ack with a least unacked of the received ack.
1199 // This causes an ack to be sent when TimeUntilSend returns 0.
1200 EXPECT_CALL(*send_algorithm_,
1201 TimeUntilSend(_, _, _)).WillRepeatedly(
1202 testing::Return(QuicTime::Delta::Zero()));
1203 // Skip a packet and then record an ack.
1204 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 2);
1205 QuicAckFrame frame = InitAckFrame(0);
1206 ProcessAckPacket(&frame);
1209 TEST_P(QuicConnectionTest, OutOfOrderReceiptCausesAckSend) {
1210 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1212 ProcessPacket(3);
1213 // Should ack immediately since we have missing packets.
1214 EXPECT_EQ(1u, writer_->packets_write_attempts());
1216 ProcessPacket(2);
1217 // Should ack immediately since we have missing packets.
1218 EXPECT_EQ(2u, writer_->packets_write_attempts());
1220 ProcessPacket(1);
1221 // Should ack immediately, since this fills the last hole.
1222 EXPECT_EQ(3u, writer_->packets_write_attempts());
1224 ProcessPacket(4);
1225 // Should not cause an ack.
1226 EXPECT_EQ(3u, writer_->packets_write_attempts());
1229 TEST_P(QuicConnectionTest, AckReceiptCausesAckSend) {
1230 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1232 QuicPacketSequenceNumber original;
1233 QuicByteCount packet_size;
1234 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1235 .WillOnce(DoAll(SaveArg<2>(&original), SaveArg<3>(&packet_size),
1236 Return(true)));
1237 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
1238 QuicAckFrame frame = InitAckFrame(original);
1239 NackPacket(original, &frame);
1240 // First nack triggers early retransmit.
1241 SequenceNumberSet lost_packets;
1242 lost_packets.insert(1);
1243 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1244 .WillOnce(Return(lost_packets));
1245 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1246 QuicPacketSequenceNumber retransmission;
1247 EXPECT_CALL(*send_algorithm_,
1248 OnPacketSent(_, _, _, packet_size - kQuicVersionSize, _))
1249 .WillOnce(DoAll(SaveArg<2>(&retransmission), Return(true)));
1251 ProcessAckPacket(&frame);
1253 QuicAckFrame frame2 = InitAckFrame(retransmission);
1254 NackPacket(original, &frame2);
1255 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1256 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1257 .WillOnce(Return(SequenceNumberSet()));
1258 ProcessAckPacket(&frame2);
1260 // Now if the peer sends an ack which still reports the retransmitted packet
1261 // as missing, that will bundle an ack with data after two acks in a row
1262 // indicate the high water mark needs to be raised.
1263 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _,
1264 HAS_RETRANSMITTABLE_DATA));
1265 connection_.SendStreamDataWithString(3, "foo", 3, !kFin, nullptr);
1266 // No ack sent.
1267 EXPECT_EQ(1u, writer_->frame_count());
1268 EXPECT_EQ(1u, writer_->stream_frames().size());
1270 // No more packet loss for the rest of the test.
1271 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1272 .WillRepeatedly(Return(SequenceNumberSet()));
1273 ProcessAckPacket(&frame2);
1274 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _,
1275 HAS_RETRANSMITTABLE_DATA));
1276 connection_.SendStreamDataWithString(3, "foo", 3, !kFin, nullptr);
1277 // Ack bundled.
1278 EXPECT_EQ(3u, writer_->frame_count());
1279 EXPECT_EQ(1u, writer_->stream_frames().size());
1280 EXPECT_FALSE(writer_->ack_frames().empty());
1282 // But an ack with no missing packets will not send an ack.
1283 AckPacket(original, &frame2);
1284 ProcessAckPacket(&frame2);
1285 ProcessAckPacket(&frame2);
1288 TEST_P(QuicConnectionTest, 20AcksCausesAckSend) {
1289 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1291 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr);
1293 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
1294 // But an ack with no missing packets will not send an ack.
1295 QuicAckFrame frame = InitAckFrame(1);
1296 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1297 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1298 .WillRepeatedly(Return(SequenceNumberSet()));
1299 for (int i = 0; i < 20; ++i) {
1300 EXPECT_FALSE(ack_alarm->IsSet());
1301 ProcessAckPacket(&frame);
1303 EXPECT_TRUE(ack_alarm->IsSet());
1306 TEST_P(QuicConnectionTest, LeastUnackedLower) {
1307 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1309 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr);
1310 SendStreamDataToPeer(1, "bar", 3, !kFin, nullptr);
1311 SendStreamDataToPeer(1, "eep", 6, !kFin, nullptr);
1313 // Start out saying the least unacked is 2.
1314 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 5);
1315 QuicStopWaitingFrame frame = InitStopWaitingFrame(2);
1316 ProcessStopWaitingPacket(&frame);
1318 // Change it to 1, but lower the sequence number to fake out-of-order packets.
1319 // This should be fine.
1320 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 1);
1321 // The scheduler will not process out of order acks, but all packet processing
1322 // causes the connection to try to write.
1323 EXPECT_CALL(visitor_, OnCanWrite());
1324 QuicStopWaitingFrame frame2 = InitStopWaitingFrame(1);
1325 ProcessStopWaitingPacket(&frame2);
1327 // Now claim it's one, but set the ordering so it was sent "after" the first
1328 // one. This should cause a connection error.
1329 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
1330 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 7);
1331 EXPECT_CALL(visitor_,
1332 OnConnectionClosed(QUIC_INVALID_STOP_WAITING_DATA, false));
1333 QuicStopWaitingFrame frame3 = InitStopWaitingFrame(1);
1334 ProcessStopWaitingPacket(&frame3);
1337 TEST_P(QuicConnectionTest, TooManySentPackets) {
1338 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1340 for (int i = 0; i < 1100; ++i) {
1341 SendStreamDataToPeer(1, "foo", 3 * i, !kFin, nullptr);
1344 // Ack packet 1, which leaves more than the limit outstanding.
1345 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1346 EXPECT_CALL(visitor_, OnConnectionClosed(
1347 QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS, false));
1348 // We're receive buffer limited, so the connection won't try to write more.
1349 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
1351 // Nack every packet except the last one, leaving a huge gap.
1352 QuicAckFrame frame1 = InitAckFrame(1100);
1353 for (QuicPacketSequenceNumber i = 1; i < 1100; ++i) {
1354 NackPacket(i, &frame1);
1356 ProcessAckPacket(&frame1);
1359 TEST_P(QuicConnectionTest, TooManyReceivedPackets) {
1360 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1361 EXPECT_CALL(visitor_, OnConnectionClosed(
1362 QUIC_TOO_MANY_OUTSTANDING_RECEIVED_PACKETS, false));
1364 // Miss every other packet for 1000 packets.
1365 for (QuicPacketSequenceNumber i = 1; i < 1000; ++i) {
1366 ProcessPacket(i * 2);
1367 if (!connection_.connected()) {
1368 break;
1373 TEST_P(QuicConnectionTest, LargestObservedLower) {
1374 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1376 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr);
1377 SendStreamDataToPeer(1, "bar", 3, !kFin, nullptr);
1378 SendStreamDataToPeer(1, "eep", 6, !kFin, nullptr);
1379 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1381 // Start out saying the largest observed is 2.
1382 QuicAckFrame frame1 = InitAckFrame(1);
1383 QuicAckFrame frame2 = InitAckFrame(2);
1384 ProcessAckPacket(&frame2);
1386 // Now change it to 1, and it should cause a connection error.
1387 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, false));
1388 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
1389 ProcessAckPacket(&frame1);
1392 TEST_P(QuicConnectionTest, AckUnsentData) {
1393 // Ack a packet which has not been sent.
1394 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, false));
1395 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1396 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
1397 QuicAckFrame frame(MakeAckFrame(1));
1398 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
1399 ProcessAckPacket(&frame);
1402 TEST_P(QuicConnectionTest, AckAll) {
1403 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1404 ProcessPacket(1);
1406 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 1);
1407 QuicAckFrame frame1 = InitAckFrame(0);
1408 ProcessAckPacket(&frame1);
1411 TEST_P(QuicConnectionTest, SendingDifferentSequenceNumberLengthsBandwidth) {
1412 QuicPacketSequenceNumber last_packet;
1413 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet);
1414 EXPECT_EQ(1u, last_packet);
1415 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1416 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1417 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1418 writer_->header().public_header.sequence_number_length);
1420 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
1421 Return(kMaxPacketSize * 256));
1423 SendStreamDataToPeer(1, "bar", 3, !kFin, &last_packet);
1424 EXPECT_EQ(2u, last_packet);
1425 EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER,
1426 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1427 // The 1 packet lag is due to the sequence number length being recalculated in
1428 // QuicConnection after a packet is sent.
1429 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1430 writer_->header().public_header.sequence_number_length);
1432 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
1433 Return(kMaxPacketSize * 256 * 256));
1435 SendStreamDataToPeer(1, "foo", 6, !kFin, &last_packet);
1436 EXPECT_EQ(3u, last_packet);
1437 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1438 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1439 EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER,
1440 writer_->header().public_header.sequence_number_length);
1442 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
1443 Return(kMaxPacketSize * 256 * 256 * 256));
1445 SendStreamDataToPeer(1, "bar", 9, !kFin, &last_packet);
1446 EXPECT_EQ(4u, last_packet);
1447 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1448 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1449 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1450 writer_->header().public_header.sequence_number_length);
1452 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
1453 Return(kMaxPacketSize * 256 * 256 * 256 * 256));
1455 SendStreamDataToPeer(1, "foo", 12, !kFin, &last_packet);
1456 EXPECT_EQ(5u, last_packet);
1457 EXPECT_EQ(PACKET_6BYTE_SEQUENCE_NUMBER,
1458 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1459 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1460 writer_->header().public_header.sequence_number_length);
1463 // TODO(ianswett): Re-enable this test by finding a good way to test different
1464 // sequence number lengths without sending packets with giant gaps.
1465 TEST_P(QuicConnectionTest,
1466 DISABLED_SendingDifferentSequenceNumberLengthsUnackedDelta) {
1467 QuicPacketSequenceNumber last_packet;
1468 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet);
1469 EXPECT_EQ(1u, last_packet);
1470 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1471 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1472 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1473 writer_->header().public_header.sequence_number_length);
1475 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 100);
1477 SendStreamDataToPeer(1, "bar", 3, !kFin, &last_packet);
1478 EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER,
1479 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1480 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1481 writer_->header().public_header.sequence_number_length);
1483 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 100 * 256);
1485 SendStreamDataToPeer(1, "foo", 6, !kFin, &last_packet);
1486 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1487 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1488 EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER,
1489 writer_->header().public_header.sequence_number_length);
1491 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 100 * 256 * 256);
1493 SendStreamDataToPeer(1, "bar", 9, !kFin, &last_packet);
1494 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1495 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1496 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1497 writer_->header().public_header.sequence_number_length);
1499 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_,
1500 100 * 256 * 256 * 256);
1502 SendStreamDataToPeer(1, "foo", 12, !kFin, &last_packet);
1503 EXPECT_EQ(PACKET_6BYTE_SEQUENCE_NUMBER,
1504 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1505 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1506 writer_->header().public_header.sequence_number_length);
1509 TEST_P(QuicConnectionTest, BasicSending) {
1510 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1511 QuicPacketSequenceNumber last_packet;
1512 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet); // Packet 1
1513 EXPECT_EQ(1u, last_packet);
1514 SendAckPacketToPeer(); // Packet 2
1516 EXPECT_EQ(1u, least_unacked());
1518 SendAckPacketToPeer(); // Packet 3
1519 EXPECT_EQ(1u, least_unacked());
1521 SendStreamDataToPeer(1, "bar", 3, !kFin, &last_packet); // Packet 4
1522 EXPECT_EQ(4u, last_packet);
1523 SendAckPacketToPeer(); // Packet 5
1524 EXPECT_EQ(1u, least_unacked());
1526 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1528 // Peer acks up to packet 3.
1529 QuicAckFrame frame = InitAckFrame(3);
1530 ProcessAckPacket(&frame);
1531 SendAckPacketToPeer(); // Packet 6
1533 // As soon as we've acked one, we skip ack packets 2 and 3 and note lack of
1534 // ack for 4.
1535 EXPECT_EQ(4u, least_unacked());
1537 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1539 // Peer acks up to packet 4, the last packet.
1540 QuicAckFrame frame2 = InitAckFrame(6);
1541 ProcessAckPacket(&frame2); // Acks don't instigate acks.
1543 // Verify that we did not send an ack.
1544 EXPECT_EQ(6u, writer_->header().packet_sequence_number);
1546 // So the last ack has not changed.
1547 EXPECT_EQ(4u, least_unacked());
1549 // If we force an ack, we shouldn't change our retransmit state.
1550 SendAckPacketToPeer(); // Packet 7
1551 EXPECT_EQ(7u, least_unacked());
1553 // But if we send more data it should.
1554 SendStreamDataToPeer(1, "eep", 6, !kFin, &last_packet); // Packet 8
1555 EXPECT_EQ(8u, last_packet);
1556 SendAckPacketToPeer(); // Packet 9
1557 EXPECT_EQ(7u, least_unacked());
1560 // QuicConnection should record the the packet sent-time prior to sending the
1561 // packet.
1562 TEST_P(QuicConnectionTest, RecordSentTimeBeforePacketSent) {
1563 // We're using a MockClock for the tests, so we have complete control over the
1564 // time.
1565 // Our recorded timestamp for the last packet sent time will be passed in to
1566 // the send_algorithm. Make sure that it is set to the correct value.
1567 QuicTime actual_recorded_send_time = QuicTime::Zero();
1568 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1569 .WillOnce(DoAll(SaveArg<0>(&actual_recorded_send_time), Return(true)));
1571 // First send without any pause and check the result.
1572 QuicTime expected_recorded_send_time = clock_.Now();
1573 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
1574 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
1575 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
1576 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
1578 // Now pause during the write, and check the results.
1579 actual_recorded_send_time = QuicTime::Zero();
1580 const QuicTime::Delta write_pause_time_delta =
1581 QuicTime::Delta::FromMilliseconds(5000);
1582 SetWritePauseTimeDelta(write_pause_time_delta);
1583 expected_recorded_send_time = clock_.Now();
1585 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1586 .WillOnce(DoAll(SaveArg<0>(&actual_recorded_send_time), Return(true)));
1587 connection_.SendStreamDataWithString(2, "baz", 0, !kFin, nullptr);
1588 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
1589 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
1590 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
1593 TEST_P(QuicConnectionTest, FECSending) {
1594 // All packets carry version info till version is negotiated.
1595 size_t payload_length;
1596 // GetPacketLengthForOneStream() assumes a stream offset of 0 in determining
1597 // packet length. The size of the offset field in a stream frame is 0 for
1598 // offset 0, and 2 for non-zero offsets up through 64K. Increase
1599 // max_packet_length by 2 so that subsequent packets containing subsequent
1600 // stream frames with non-zero offets will fit within the packet length.
1601 size_t length = 2 + GetPacketLengthForOneStream(
1602 connection_.version(), kIncludeVersion,
1603 PACKET_8BYTE_CONNECTION_ID, PACKET_1BYTE_SEQUENCE_NUMBER,
1604 IN_FEC_GROUP, &payload_length);
1605 creator_->SetMaxPacketLength(length);
1607 // Send 4 protected data packets, which should also trigger 1 FEC packet.
1608 EXPECT_CALL(*send_algorithm_,
1609 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(5);
1610 // The first stream frame will have 2 fewer overhead bytes than the other 3.
1611 const string payload(payload_length * 4 + 2, 'a');
1612 connection_.SendStreamDataWithStringWithFec(1, payload, 0, !kFin, nullptr);
1613 // Expect the FEC group to be closed after SendStreamDataWithString.
1614 EXPECT_FALSE(creator_->IsFecGroupOpen());
1615 EXPECT_FALSE(creator_->IsFecProtected());
1618 TEST_P(QuicConnectionTest, FECQueueing) {
1619 // All packets carry version info till version is negotiated.
1620 size_t payload_length;
1621 size_t length = GetPacketLengthForOneStream(
1622 connection_.version(), kIncludeVersion,
1623 PACKET_8BYTE_CONNECTION_ID, PACKET_1BYTE_SEQUENCE_NUMBER,
1624 IN_FEC_GROUP, &payload_length);
1625 creator_->SetMaxPacketLength(length);
1626 EXPECT_TRUE(creator_->IsFecEnabled());
1628 EXPECT_EQ(0u, connection_.NumQueuedPackets());
1629 BlockOnNextWrite();
1630 const string payload(payload_length, 'a');
1631 connection_.SendStreamDataWithStringWithFec(1, payload, 0, !kFin, nullptr);
1632 EXPECT_FALSE(creator_->IsFecGroupOpen());
1633 EXPECT_FALSE(creator_->IsFecProtected());
1634 // Expect the first data packet and the fec packet to be queued.
1635 EXPECT_EQ(2u, connection_.NumQueuedPackets());
1638 TEST_P(QuicConnectionTest, FECAlarmStoppedWhenFECPacketSent) {
1639 EXPECT_TRUE(creator_->IsFecEnabled());
1640 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1641 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1643 creator_->set_max_packets_per_fec_group(2);
1645 // 1 Data packet. FEC alarm should be set.
1646 EXPECT_CALL(*send_algorithm_,
1647 OnPacketSent(_, _, 1u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1648 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, true, nullptr);
1649 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1651 // Second data packet triggers FEC packet out. FEC alarm should not be set.
1652 EXPECT_CALL(*send_algorithm_,
1653 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(2);
1654 connection_.SendStreamDataWithStringWithFec(5, "foo", 0, true, nullptr);
1655 EXPECT_TRUE(writer_->header().fec_flag);
1656 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1659 TEST_P(QuicConnectionTest, FECAlarmStoppedOnConnectionClose) {
1660 EXPECT_TRUE(creator_->IsFecEnabled());
1661 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1662 creator_->set_max_packets_per_fec_group(100);
1664 // 1 Data packet. FEC alarm should be set.
1665 EXPECT_CALL(*send_algorithm_,
1666 OnPacketSent(_, _, 1u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1667 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, kFin, nullptr);
1668 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1670 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NO_ERROR, false));
1671 // Closing connection should stop the FEC alarm.
1672 connection_.CloseConnection(QUIC_NO_ERROR, /*from_peer=*/false);
1673 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1676 TEST_P(QuicConnectionTest, RemoveFECFromInflightOnRetransmissionTimeout) {
1677 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1678 EXPECT_TRUE(creator_->IsFecEnabled());
1679 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1680 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1682 // 1 Data packet. FEC alarm should be set.
1683 EXPECT_CALL(*send_algorithm_,
1684 OnPacketSent(_, _, 1u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1685 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, !kFin, nullptr);
1686 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1687 size_t protected_packet =
1688 QuicSentPacketManagerPeer::GetBytesInFlight(manager_);
1690 // Force FEC timeout to send FEC packet out.
1691 EXPECT_CALL(*send_algorithm_,
1692 OnPacketSent(_, _, 2u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1693 connection_.GetFecAlarm()->Fire();
1694 EXPECT_TRUE(writer_->header().fec_flag);
1696 size_t fec_packet = protected_packet;
1697 EXPECT_EQ(protected_packet + fec_packet,
1698 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1699 clock_.AdvanceTime(DefaultRetransmissionTime());
1701 // On RTO, both data and FEC packets are removed from inflight, only the data
1702 // packet is retransmitted, and this retransmission (but not FEC) gets added
1703 // back into the inflight.
1704 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
1705 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1706 connection_.GetRetransmissionAlarm()->Fire();
1708 // The retransmission of packet 1 will be 3 bytes smaller than packet 1, since
1709 // the first transmission will have 1 byte for FEC group number and 2 bytes of
1710 // stream frame size, which are absent in the retransmission.
1711 size_t retransmitted_packet = protected_packet - 3;
1712 EXPECT_EQ(protected_packet + retransmitted_packet,
1713 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1714 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1716 // Receive ack for the retransmission. No data should be outstanding.
1717 QuicAckFrame ack = InitAckFrame(3);
1718 NackPacket(1, &ack);
1719 NackPacket(2, &ack);
1720 SequenceNumberSet lost_packets;
1721 lost_packets.insert(1);
1722 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1723 .WillOnce(Return(lost_packets));
1724 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1725 ProcessAckPacket(&ack);
1727 // Ensure the alarm is not set since all packets have been acked or abandoned.
1728 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
1729 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1732 TEST_P(QuicConnectionTest, RemoveFECFromInflightOnLossRetransmission) {
1733 EXPECT_TRUE(creator_->IsFecEnabled());
1734 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1736 // 1 FEC-protected data packet. FEC alarm should be set.
1737 EXPECT_CALL(*send_algorithm_,
1738 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1739 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, kFin, nullptr);
1740 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1741 size_t protected_packet =
1742 QuicSentPacketManagerPeer::GetBytesInFlight(manager_);
1744 // Force FEC timeout to send FEC packet out.
1745 EXPECT_CALL(*send_algorithm_,
1746 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1747 connection_.GetFecAlarm()->Fire();
1748 EXPECT_TRUE(writer_->header().fec_flag);
1749 size_t fec_packet = protected_packet;
1750 EXPECT_EQ(protected_packet + fec_packet,
1751 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1753 // Send more data to trigger NACKs. Note that all data starts at stream offset
1754 // 0 to ensure the same packet size, for ease of testing.
1755 EXPECT_CALL(*send_algorithm_,
1756 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(4);
1757 connection_.SendStreamDataWithString(5, "foo", 0, kFin, nullptr);
1758 connection_.SendStreamDataWithString(7, "foo", 0, kFin, nullptr);
1759 connection_.SendStreamDataWithString(9, "foo", 0, kFin, nullptr);
1760 connection_.SendStreamDataWithString(11, "foo", 0, kFin, nullptr);
1762 // An unprotected packet will be 3 bytes smaller than an FEC-protected packet,
1763 // since the protected packet will have 1 byte for FEC group number and
1764 // 2 bytes of stream frame size, which are absent in the unprotected packet.
1765 size_t unprotected_packet = protected_packet - 3;
1766 EXPECT_EQ(protected_packet + fec_packet + 4 * unprotected_packet,
1767 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1768 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1770 // Ack data packets, and NACK FEC packet and one data packet. Triggers
1771 // NACK-based loss detection of both packets, but only data packet is
1772 // retransmitted and considered oustanding.
1773 QuicAckFrame ack = InitAckFrame(6);
1774 NackPacket(2, &ack);
1775 NackPacket(3, &ack);
1776 SequenceNumberSet lost_packets;
1777 lost_packets.insert(2);
1778 lost_packets.insert(3);
1779 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1780 .WillOnce(Return(lost_packets));
1781 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1782 EXPECT_CALL(*send_algorithm_,
1783 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1784 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1785 ProcessAckPacket(&ack);
1786 // On receiving this ack from the server, the client will no longer send
1787 // version number in subsequent packets, including in this retransmission.
1788 size_t unprotected_packet_no_version = unprotected_packet - 4;
1789 EXPECT_EQ(unprotected_packet_no_version,
1790 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1792 // Receive ack for the retransmission. No data should be outstanding.
1793 QuicAckFrame ack2 = InitAckFrame(7);
1794 NackPacket(2, &ack2);
1795 NackPacket(3, &ack2);
1796 SequenceNumberSet lost_packets2;
1797 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1798 .WillOnce(Return(lost_packets2));
1799 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1800 ProcessAckPacket(&ack2);
1801 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1804 TEST_P(QuicConnectionTest, FECRemainsInflightOnTLPOfEarlierData) {
1805 // This test checks if TLP is sent correctly when a data and an FEC packet
1806 // are outstanding. TLP should be sent for the data packet when the
1807 // retransmission alarm fires.
1808 // Turn on TLP for this test.
1809 QuicSentPacketManagerPeer::SetMaxTailLossProbes(manager_, 1);
1810 EXPECT_TRUE(creator_->IsFecEnabled());
1811 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1812 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1814 // 1 Data packet. FEC alarm should be set.
1815 EXPECT_CALL(*send_algorithm_,
1816 OnPacketSent(_, _, 1u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1817 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, kFin, nullptr);
1818 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1819 size_t protected_packet =
1820 QuicSentPacketManagerPeer::GetBytesInFlight(manager_);
1821 EXPECT_LT(0u, protected_packet);
1823 // Force FEC timeout to send FEC packet out.
1824 EXPECT_CALL(*send_algorithm_,
1825 OnPacketSent(_, _, 2u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1826 connection_.GetFecAlarm()->Fire();
1827 EXPECT_TRUE(writer_->header().fec_flag);
1828 size_t fec_packet = protected_packet;
1829 EXPECT_EQ(protected_packet + fec_packet,
1830 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1832 // TLP alarm should be set.
1833 QuicTime retransmission_time =
1834 connection_.GetRetransmissionAlarm()->deadline();
1835 EXPECT_NE(QuicTime::Zero(), retransmission_time);
1836 // Simulate the retransmission alarm firing and sending a TLP, so send
1837 // algorithm's OnRetransmissionTimeout is not called.
1838 clock_.AdvanceTime(retransmission_time.Subtract(clock_.Now()));
1839 EXPECT_CALL(*send_algorithm_,
1840 OnPacketSent(_, _, 3u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1841 connection_.GetRetransmissionAlarm()->Fire();
1842 // The TLP retransmission of packet 1 will be 3 bytes smaller than packet 1,
1843 // since packet 1 will have 1 byte for FEC group number and 2 bytes of stream
1844 // frame size, which are absent in the the TLP retransmission.
1845 size_t tlp_packet = protected_packet - 3;
1846 EXPECT_EQ(protected_packet + fec_packet + tlp_packet,
1847 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1850 TEST_P(QuicConnectionTest, FECRemainsInflightOnTLPOfLaterData) {
1851 // Tests if TLP is sent correctly when data packet 1 and an FEC packet are
1852 // sent followed by data packet 2, and data packet 1 is acked. TLP should be
1853 // sent for data packet 2 when the retransmission alarm fires. Turn on TLP for
1854 // this test.
1855 QuicSentPacketManagerPeer::SetMaxTailLossProbes(manager_, 1);
1856 EXPECT_TRUE(creator_->IsFecEnabled());
1857 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1858 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1860 // 1 Data packet. FEC alarm should be set.
1861 EXPECT_CALL(*send_algorithm_,
1862 OnPacketSent(_, _, 1u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1863 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, kFin, nullptr);
1864 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1865 size_t protected_packet =
1866 QuicSentPacketManagerPeer::GetBytesInFlight(manager_);
1867 EXPECT_LT(0u, protected_packet);
1869 // Force FEC timeout to send FEC packet out.
1870 EXPECT_CALL(*send_algorithm_,
1871 OnPacketSent(_, _, 2u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1872 connection_.GetFecAlarm()->Fire();
1873 EXPECT_TRUE(writer_->header().fec_flag);
1874 // Protected data packet and FEC packet oustanding.
1875 size_t fec_packet = protected_packet;
1876 EXPECT_EQ(protected_packet + fec_packet,
1877 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1879 // Send 1 unprotected data packet. No FEC alarm should be set.
1880 EXPECT_CALL(*send_algorithm_,
1881 OnPacketSent(_, _, 3u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1882 connection_.SendStreamDataWithString(5, "foo", 0, kFin, nullptr);
1883 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1884 // Protected data packet, FEC packet, and unprotected data packet oustanding.
1885 // An unprotected packet will be 3 bytes smaller than an FEC-protected packet,
1886 // since the protected packet will have 1 byte for FEC group number and
1887 // 2 bytes of stream frame size, which are absent in the unprotected packet.
1888 size_t unprotected_packet = protected_packet - 3;
1889 EXPECT_EQ(protected_packet + fec_packet + unprotected_packet,
1890 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1892 // Receive ack for first data packet. FEC and second data packet are still
1893 // outstanding.
1894 QuicAckFrame ack = InitAckFrame(1);
1895 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1896 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1897 ProcessAckPacket(&ack);
1898 // FEC packet and unprotected data packet oustanding.
1899 EXPECT_EQ(fec_packet + unprotected_packet,
1900 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1902 // TLP alarm should be set.
1903 QuicTime retransmission_time =
1904 connection_.GetRetransmissionAlarm()->deadline();
1905 EXPECT_NE(QuicTime::Zero(), retransmission_time);
1906 // Simulate the retransmission alarm firing and sending a TLP, so send
1907 // algorithm's OnRetransmissionTimeout is not called.
1908 clock_.AdvanceTime(retransmission_time.Subtract(clock_.Now()));
1909 EXPECT_CALL(*send_algorithm_,
1910 OnPacketSent(_, _, 4u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1911 connection_.GetRetransmissionAlarm()->Fire();
1913 // Having received an ack from the server, the client will no longer send
1914 // version number in subsequent packets, including in this retransmission.
1915 size_t tlp_packet_no_version = unprotected_packet - 4;
1916 EXPECT_EQ(fec_packet + unprotected_packet + tlp_packet_no_version,
1917 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1920 TEST_P(QuicConnectionTest, NoTLPForFECPacket) {
1921 // Turn on TLP for this test.
1922 QuicSentPacketManagerPeer::SetMaxTailLossProbes(manager_, 1);
1923 EXPECT_TRUE(creator_->IsFecEnabled());
1924 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1926 // Send 1 FEC-protected data packet. FEC alarm should be set.
1927 EXPECT_CALL(*send_algorithm_,
1928 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1929 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, !kFin, nullptr);
1930 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1931 // Force FEC timeout to send FEC packet out.
1932 EXPECT_CALL(*send_algorithm_,
1933 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1934 connection_.GetFecAlarm()->Fire();
1935 EXPECT_TRUE(writer_->header().fec_flag);
1937 // Ack data packet, but not FEC packet.
1938 QuicAckFrame ack = InitAckFrame(1);
1939 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1940 ProcessAckPacket(&ack);
1942 // No TLP alarm for FEC, but retransmission alarm should be set for an RTO.
1943 EXPECT_LT(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1944 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
1945 QuicTime rto_time = connection_.GetRetransmissionAlarm()->deadline();
1946 EXPECT_NE(QuicTime::Zero(), rto_time);
1948 // Simulate the retransmission alarm firing. FEC packet is no longer
1949 // outstanding.
1950 clock_.AdvanceTime(rto_time.Subtract(clock_.Now()));
1951 connection_.GetRetransmissionAlarm()->Fire();
1953 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
1954 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1957 TEST_P(QuicConnectionTest, FramePacking) {
1958 CongestionBlockWrites();
1960 // Send an ack and two stream frames in 1 packet by queueing them.
1961 connection_.SendAck();
1962 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
1963 IgnoreResult(InvokeWithoutArgs(&connection_,
1964 &TestConnection::SendStreamData3)),
1965 IgnoreResult(InvokeWithoutArgs(&connection_,
1966 &TestConnection::SendStreamData5))));
1968 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1969 CongestionUnblockWrites();
1970 connection_.GetSendAlarm()->Fire();
1971 EXPECT_EQ(0u, connection_.NumQueuedPackets());
1972 EXPECT_FALSE(connection_.HasQueuedData());
1974 // Parse the last packet and ensure it's an ack and two stream frames from
1975 // two different streams.
1976 EXPECT_EQ(4u, writer_->frame_count());
1977 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
1978 EXPECT_FALSE(writer_->ack_frames().empty());
1979 ASSERT_EQ(2u, writer_->stream_frames().size());
1980 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id);
1981 EXPECT_EQ(kClientDataStreamId2, writer_->stream_frames()[1].stream_id);
1984 TEST_P(QuicConnectionTest, FramePackingNonCryptoThenCrypto) {
1985 CongestionBlockWrites();
1987 // Send an ack and two stream frames (one non-crypto, then one crypto) in 2
1988 // packets by queueing them.
1989 connection_.SendAck();
1990 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
1991 IgnoreResult(InvokeWithoutArgs(&connection_,
1992 &TestConnection::SendStreamData3)),
1993 IgnoreResult(InvokeWithoutArgs(&connection_,
1994 &TestConnection::SendCryptoStreamData))));
1996 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
1997 CongestionUnblockWrites();
1998 connection_.GetSendAlarm()->Fire();
1999 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2000 EXPECT_FALSE(connection_.HasQueuedData());
2002 // Parse the last packet and ensure it's the crypto stream frame.
2003 EXPECT_EQ(1u, writer_->frame_count());
2004 ASSERT_EQ(1u, writer_->stream_frames().size());
2005 EXPECT_EQ(kCryptoStreamId, writer_->stream_frames()[0].stream_id);
2008 TEST_P(QuicConnectionTest, FramePackingCryptoThenNonCrypto) {
2009 CongestionBlockWrites();
2011 // Send an ack and two stream frames (one crypto, then one non-crypto) in 2
2012 // packets by queueing them.
2013 connection_.SendAck();
2014 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
2015 IgnoreResult(InvokeWithoutArgs(&connection_,
2016 &TestConnection::SendCryptoStreamData)),
2017 IgnoreResult(InvokeWithoutArgs(&connection_,
2018 &TestConnection::SendStreamData3))));
2020 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
2021 CongestionUnblockWrites();
2022 connection_.GetSendAlarm()->Fire();
2023 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2024 EXPECT_FALSE(connection_.HasQueuedData());
2026 // Parse the last packet and ensure it's the stream frame from stream 3.
2027 EXPECT_EQ(1u, writer_->frame_count());
2028 ASSERT_EQ(1u, writer_->stream_frames().size());
2029 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id);
2032 TEST_P(QuicConnectionTest, FramePackingFEC) {
2033 EXPECT_TRUE(creator_->IsFecEnabled());
2035 CongestionBlockWrites();
2037 // Queue an ack and two stream frames. Ack gets flushed when FEC is turned on
2038 // for sending protected data; two stream frames are packed in 1 packet.
2039 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
2040 IgnoreResult(InvokeWithoutArgs(
2041 &connection_, &TestConnection::SendStreamData3WithFec)),
2042 IgnoreResult(InvokeWithoutArgs(
2043 &connection_, &TestConnection::SendStreamData5WithFec))));
2044 connection_.SendAck();
2046 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
2047 CongestionUnblockWrites();
2048 connection_.GetSendAlarm()->Fire();
2049 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2050 EXPECT_FALSE(connection_.HasQueuedData());
2052 // Parse the last packet and ensure it's in an fec group.
2053 EXPECT_EQ(2u, writer_->header().fec_group);
2054 EXPECT_EQ(2u, writer_->frame_count());
2056 // FEC alarm should be set.
2057 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
2060 TEST_P(QuicConnectionTest, FramePackingAckResponse) {
2061 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2062 // Process a data packet to queue up a pending ack.
2063 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
2064 ProcessDataPacket(1, 1, kEntropyFlag);
2066 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
2067 IgnoreResult(InvokeWithoutArgs(&connection_,
2068 &TestConnection::SendStreamData3)),
2069 IgnoreResult(InvokeWithoutArgs(&connection_,
2070 &TestConnection::SendStreamData5))));
2072 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2074 // Process an ack to cause the visitor's OnCanWrite to be invoked.
2075 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 2);
2076 QuicAckFrame ack_one = InitAckFrame(0);
2077 ProcessAckPacket(&ack_one);
2079 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2080 EXPECT_FALSE(connection_.HasQueuedData());
2082 // Parse the last packet and ensure it's an ack and two stream frames from
2083 // two different streams.
2084 EXPECT_EQ(4u, writer_->frame_count());
2085 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
2086 EXPECT_FALSE(writer_->ack_frames().empty());
2087 ASSERT_EQ(2u, writer_->stream_frames().size());
2088 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id);
2089 EXPECT_EQ(kClientDataStreamId2, writer_->stream_frames()[1].stream_id);
2092 TEST_P(QuicConnectionTest, FramePackingSendv) {
2093 // Send data in 1 packet by writing multiple blocks in a single iovector
2094 // using writev.
2095 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2097 char data[] = "ABCD";
2098 IOVector data_iov;
2099 data_iov.AppendNoCoalesce(data, 2);
2100 data_iov.AppendNoCoalesce(data + 2, 2);
2101 connection_.SendStreamData(1, data_iov, 0, !kFin, MAY_FEC_PROTECT, nullptr);
2103 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2104 EXPECT_FALSE(connection_.HasQueuedData());
2106 // Parse the last packet and ensure multiple iovector blocks have
2107 // been packed into a single stream frame from one stream.
2108 EXPECT_EQ(1u, writer_->frame_count());
2109 EXPECT_EQ(1u, writer_->stream_frames().size());
2110 QuicStreamFrame frame = writer_->stream_frames()[0];
2111 EXPECT_EQ(1u, frame.stream_id);
2112 EXPECT_EQ("ABCD", string(static_cast<char*>
2113 (frame.data.iovec()[0].iov_base),
2114 (frame.data.iovec()[0].iov_len)));
2117 TEST_P(QuicConnectionTest, FramePackingSendvQueued) {
2118 // Try to send two stream frames in 1 packet by using writev.
2119 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2121 BlockOnNextWrite();
2122 char data[] = "ABCD";
2123 IOVector data_iov;
2124 data_iov.AppendNoCoalesce(data, 2);
2125 data_iov.AppendNoCoalesce(data + 2, 2);
2126 connection_.SendStreamData(1, data_iov, 0, !kFin, MAY_FEC_PROTECT, nullptr);
2128 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2129 EXPECT_TRUE(connection_.HasQueuedData());
2131 // Unblock the writes and actually send.
2132 writer_->SetWritable();
2133 connection_.OnCanWrite();
2134 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2136 // Parse the last packet and ensure it's one stream frame from one stream.
2137 EXPECT_EQ(1u, writer_->frame_count());
2138 EXPECT_EQ(1u, writer_->stream_frames().size());
2139 EXPECT_EQ(1u, writer_->stream_frames()[0].stream_id);
2142 TEST_P(QuicConnectionTest, SendingZeroBytes) {
2143 // Send a zero byte write with a fin using writev.
2144 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2145 IOVector empty_iov;
2146 connection_.SendStreamData(1, empty_iov, 0, kFin, MAY_FEC_PROTECT, nullptr);
2148 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2149 EXPECT_FALSE(connection_.HasQueuedData());
2151 // Parse the last packet and ensure it's one stream frame from one stream.
2152 EXPECT_EQ(1u, writer_->frame_count());
2153 EXPECT_EQ(1u, writer_->stream_frames().size());
2154 EXPECT_EQ(1u, writer_->stream_frames()[0].stream_id);
2155 EXPECT_TRUE(writer_->stream_frames()[0].fin);
2158 TEST_P(QuicConnectionTest, OnCanWrite) {
2159 // Visitor's OnCanWrite will send data, but will have more pending writes.
2160 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
2161 IgnoreResult(InvokeWithoutArgs(&connection_,
2162 &TestConnection::SendStreamData3)),
2163 IgnoreResult(InvokeWithoutArgs(&connection_,
2164 &TestConnection::SendStreamData5))));
2165 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillOnce(Return(true));
2166 EXPECT_CALL(*send_algorithm_,
2167 TimeUntilSend(_, _, _)).WillRepeatedly(
2168 testing::Return(QuicTime::Delta::Zero()));
2170 connection_.OnCanWrite();
2172 // Parse the last packet and ensure it's the two stream frames from
2173 // two different streams.
2174 EXPECT_EQ(2u, writer_->frame_count());
2175 EXPECT_EQ(2u, writer_->stream_frames().size());
2176 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id);
2177 EXPECT_EQ(kClientDataStreamId2, writer_->stream_frames()[1].stream_id);
2180 TEST_P(QuicConnectionTest, RetransmitOnNack) {
2181 QuicPacketSequenceNumber last_packet;
2182 QuicByteCount second_packet_size;
2183 SendStreamDataToPeer(3, "foo", 0, !kFin, &last_packet); // Packet 1
2184 second_packet_size =
2185 SendStreamDataToPeer(3, "foos", 3, !kFin, &last_packet); // Packet 2
2186 SendStreamDataToPeer(3, "fooos", 7, !kFin, &last_packet); // Packet 3
2188 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2190 // Don't lose a packet on an ack, and nothing is retransmitted.
2191 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2192 QuicAckFrame ack_one = InitAckFrame(1);
2193 ProcessAckPacket(&ack_one);
2195 // Lose a packet and ensure it triggers retransmission.
2196 QuicAckFrame nack_two = InitAckFrame(3);
2197 NackPacket(2, &nack_two);
2198 SequenceNumberSet lost_packets;
2199 lost_packets.insert(2);
2200 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2201 .WillOnce(Return(lost_packets));
2202 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2203 EXPECT_CALL(*send_algorithm_,
2204 OnPacketSent(_, _, _, second_packet_size - kQuicVersionSize, _)).
2205 Times(1);
2206 ProcessAckPacket(&nack_two);
2209 TEST_P(QuicConnectionTest, DoNotSendQueuedPacketForResetStream) {
2210 ValueRestore<bool> old_flag(&FLAGS_quic_do_not_retransmit_for_reset_streams,
2211 true);
2213 // Block the connection to queue the packet.
2214 BlockOnNextWrite();
2216 QuicStreamId stream_id = 2;
2217 connection_.SendStreamDataWithString(stream_id, "foo", 0, !kFin, nullptr);
2219 // Now that there is a queued packet, reset the stream.
2220 connection_.SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 14);
2222 // Unblock the connection and verify that only the RST_STREAM is sent.
2223 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2224 writer_->SetWritable();
2225 connection_.OnCanWrite();
2226 EXPECT_EQ(1u, writer_->frame_count());
2227 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
2230 TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnNack) {
2231 ValueRestore<bool> old_flag(&FLAGS_quic_do_not_retransmit_for_reset_streams,
2232 true);
2234 QuicStreamId stream_id = 2;
2235 QuicPacketSequenceNumber last_packet;
2236 SendStreamDataToPeer(stream_id, "foo", 0, !kFin, &last_packet);
2237 SendStreamDataToPeer(stream_id, "foos", 3, !kFin, &last_packet);
2238 SendStreamDataToPeer(stream_id, "fooos", 7, !kFin, &last_packet);
2240 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2241 connection_.SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 14);
2243 // Lose a packet and ensure it does not trigger retransmission.
2244 QuicAckFrame nack_two = InitAckFrame(last_packet);
2245 NackPacket(last_packet - 1, &nack_two);
2246 SequenceNumberSet lost_packets;
2247 lost_packets.insert(last_packet - 1);
2248 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2249 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2250 .WillOnce(Return(lost_packets));
2251 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2252 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
2253 ProcessAckPacket(&nack_two);
2256 TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnRTO) {
2257 ValueRestore<bool> old_flag(&FLAGS_quic_do_not_retransmit_for_reset_streams,
2258 true);
2260 QuicStreamId stream_id = 2;
2261 QuicPacketSequenceNumber last_packet;
2262 SendStreamDataToPeer(stream_id, "foo", 0, !kFin, &last_packet);
2264 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2265 connection_.SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 14);
2267 // Fire the RTO and verify that the RST_STREAM is resent, not stream data.
2268 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2269 clock_.AdvanceTime(DefaultRetransmissionTime());
2270 connection_.GetRetransmissionAlarm()->Fire();
2271 EXPECT_EQ(1u, writer_->frame_count());
2272 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
2273 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
2276 TEST_P(QuicConnectionTest, DoNotSendPendingRetransmissionForResetStream) {
2277 ValueRestore<bool> old_flag(&FLAGS_quic_do_not_retransmit_for_reset_streams,
2278 true);
2280 QuicStreamId stream_id = 2;
2281 QuicPacketSequenceNumber last_packet;
2282 SendStreamDataToPeer(stream_id, "foo", 0, !kFin, &last_packet);
2283 SendStreamDataToPeer(stream_id, "foos", 3, !kFin, &last_packet);
2284 BlockOnNextWrite();
2285 connection_.SendStreamDataWithString(stream_id, "fooos", 7, !kFin, nullptr);
2287 // Lose a packet which will trigger a pending retransmission.
2288 QuicAckFrame ack = InitAckFrame(last_packet);
2289 NackPacket(last_packet - 1, &ack);
2290 SequenceNumberSet lost_packets;
2291 lost_packets.insert(last_packet - 1);
2292 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2293 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2294 .WillOnce(Return(lost_packets));
2295 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2296 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
2297 ProcessAckPacket(&ack);
2299 connection_.SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 14);
2301 // Unblock the connection and verify that the RST_STREAM is sent but not the
2302 // second data packet nor a retransmit.
2303 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2304 writer_->SetWritable();
2305 connection_.OnCanWrite();
2306 EXPECT_EQ(1u, writer_->frame_count());
2307 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
2308 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
2311 TEST_P(QuicConnectionTest, DiscardRetransmit) {
2312 QuicPacketSequenceNumber last_packet;
2313 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet); // Packet 1
2314 SendStreamDataToPeer(1, "foos", 3, !kFin, &last_packet); // Packet 2
2315 SendStreamDataToPeer(1, "fooos", 7, !kFin, &last_packet); // Packet 3
2317 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2319 // Instigate a loss with an ack.
2320 QuicAckFrame nack_two = InitAckFrame(3);
2321 NackPacket(2, &nack_two);
2322 // The first nack should trigger a fast retransmission, but we'll be
2323 // write blocked, so the packet will be queued.
2324 BlockOnNextWrite();
2325 SequenceNumberSet lost_packets;
2326 lost_packets.insert(2);
2327 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2328 .WillOnce(Return(lost_packets));
2329 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2330 ProcessAckPacket(&nack_two);
2331 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2333 // Now, ack the previous transmission.
2334 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2335 .WillOnce(Return(SequenceNumberSet()));
2336 QuicAckFrame ack_all = InitAckFrame(3);
2337 ProcessAckPacket(&ack_all);
2339 // Unblock the socket and attempt to send the queued packets. However,
2340 // since the previous transmission has been acked, we will not
2341 // send the retransmission.
2342 EXPECT_CALL(*send_algorithm_,
2343 OnPacketSent(_, _, _, _, _)).Times(0);
2345 writer_->SetWritable();
2346 connection_.OnCanWrite();
2348 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2351 TEST_P(QuicConnectionTest, RetransmitNackedLargestObserved) {
2352 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2353 QuicPacketSequenceNumber largest_observed;
2354 QuicByteCount packet_size;
2355 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2356 .WillOnce(DoAll(SaveArg<2>(&largest_observed), SaveArg<3>(&packet_size),
2357 Return(true)));
2358 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
2360 QuicAckFrame frame = InitAckFrame(1);
2361 NackPacket(largest_observed, &frame);
2362 // The first nack should retransmit the largest observed packet.
2363 SequenceNumberSet lost_packets;
2364 lost_packets.insert(1);
2365 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2366 .WillOnce(Return(lost_packets));
2367 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2368 EXPECT_CALL(*send_algorithm_,
2369 OnPacketSent(_, _, _, packet_size - kQuicVersionSize, _));
2370 ProcessAckPacket(&frame);
2373 TEST_P(QuicConnectionTest, QueueAfterTwoRTOs) {
2374 for (int i = 0; i < 10; ++i) {
2375 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2376 connection_.SendStreamDataWithString(3, "foo", i * 3, !kFin, nullptr);
2379 // Block the writer and ensure they're queued.
2380 BlockOnNextWrite();
2381 clock_.AdvanceTime(DefaultRetransmissionTime());
2382 // Only one packet should be retransmitted.
2383 connection_.GetRetransmissionAlarm()->Fire();
2384 EXPECT_TRUE(connection_.HasQueuedData());
2386 // Unblock the writer.
2387 writer_->SetWritable();
2388 clock_.AdvanceTime(QuicTime::Delta::FromMicroseconds(
2389 2 * DefaultRetransmissionTime().ToMicroseconds()));
2390 // Retransmit already retransmitted packets event though the sequence number
2391 // greater than the largest observed.
2392 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
2393 connection_.GetRetransmissionAlarm()->Fire();
2394 connection_.OnCanWrite();
2397 TEST_P(QuicConnectionTest, WriteBlockedThenSent) {
2398 BlockOnNextWrite();
2399 writer_->set_is_write_blocked_data_buffered(true);
2400 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2401 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
2402 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2404 writer_->SetWritable();
2405 connection_.OnCanWrite();
2406 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2409 TEST_P(QuicConnectionTest, RetransmitWriteBlockedAckedOriginalThenSent) {
2410 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2411 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
2412 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2414 BlockOnNextWrite();
2415 writer_->set_is_write_blocked_data_buffered(true);
2416 // Simulate the retransmission alarm firing.
2417 clock_.AdvanceTime(DefaultRetransmissionTime());
2418 connection_.GetRetransmissionAlarm()->Fire();
2420 // Ack the sent packet before the callback returns, which happens in
2421 // rare circumstances with write blocked sockets.
2422 QuicAckFrame ack = InitAckFrame(1);
2423 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2424 ProcessAckPacket(&ack);
2426 writer_->SetWritable();
2427 connection_.OnCanWrite();
2428 // There is now a pending packet, but with no retransmittable frames.
2429 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2430 EXPECT_FALSE(connection_.sent_packet_manager().HasRetransmittableFrames(2));
2433 TEST_P(QuicConnectionTest, AlarmsWhenWriteBlocked) {
2434 // Block the connection.
2435 BlockOnNextWrite();
2436 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
2437 EXPECT_EQ(1u, writer_->packets_write_attempts());
2438 EXPECT_TRUE(writer_->IsWriteBlocked());
2440 // Set the send and resumption alarms. Fire the alarms and ensure they don't
2441 // attempt to write.
2442 connection_.GetResumeWritesAlarm()->Set(clock_.ApproximateNow());
2443 connection_.GetSendAlarm()->Set(clock_.ApproximateNow());
2444 connection_.GetResumeWritesAlarm()->Fire();
2445 connection_.GetSendAlarm()->Fire();
2446 EXPECT_TRUE(writer_->IsWriteBlocked());
2447 EXPECT_EQ(1u, writer_->packets_write_attempts());
2450 TEST_P(QuicConnectionTest, NoLimitPacketsPerNack) {
2451 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2452 int offset = 0;
2453 // Send packets 1 to 15.
2454 for (int i = 0; i < 15; ++i) {
2455 SendStreamDataToPeer(1, "foo", offset, !kFin, nullptr);
2456 offset += 3;
2459 // Ack 15, nack 1-14.
2460 SequenceNumberSet lost_packets;
2461 QuicAckFrame nack = InitAckFrame(15);
2462 for (int i = 1; i < 15; ++i) {
2463 NackPacket(i, &nack);
2464 lost_packets.insert(i);
2467 // 14 packets have been NACK'd and lost. In TCP cubic, PRR limits
2468 // the retransmission rate in the case of burst losses.
2469 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2470 .WillOnce(Return(lost_packets));
2471 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2472 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(14);
2473 ProcessAckPacket(&nack);
2476 // Test sending multiple acks from the connection to the session.
2477 TEST_P(QuicConnectionTest, MultipleAcks) {
2478 QuicPacketSequenceNumber last_packet;
2479 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet); // Packet 1
2480 EXPECT_EQ(1u, last_packet);
2481 SendStreamDataToPeer(3, "foo", 0, !kFin, &last_packet); // Packet 2
2482 EXPECT_EQ(2u, last_packet);
2483 SendAckPacketToPeer(); // Packet 3
2484 SendStreamDataToPeer(5, "foo", 0, !kFin, &last_packet); // Packet 4
2485 EXPECT_EQ(4u, last_packet);
2486 SendStreamDataToPeer(1, "foo", 3, !kFin, &last_packet); // Packet 5
2487 EXPECT_EQ(5u, last_packet);
2488 SendStreamDataToPeer(3, "foo", 3, !kFin, &last_packet); // Packet 6
2489 EXPECT_EQ(6u, last_packet);
2491 // Client will ack packets 1, 2, [!3], 4, 5.
2492 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2493 QuicAckFrame frame1 = InitAckFrame(5);
2494 NackPacket(3, &frame1);
2495 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2496 ProcessAckPacket(&frame1);
2498 // Now the client implicitly acks 3, and explicitly acks 6.
2499 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2500 QuicAckFrame frame2 = InitAckFrame(6);
2501 ProcessAckPacket(&frame2);
2504 TEST_P(QuicConnectionTest, DontLatchUnackedPacket) {
2505 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr); // Packet 1;
2506 // From now on, we send acks, so the send algorithm won't mark them pending.
2507 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2508 .WillByDefault(Return(false));
2509 SendAckPacketToPeer(); // Packet 2
2511 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2512 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2513 QuicAckFrame frame = InitAckFrame(1);
2514 ProcessAckPacket(&frame);
2516 // Verify that our internal state has least-unacked as 2, because we're still
2517 // waiting for a potential ack for 2.
2519 EXPECT_EQ(2u, stop_waiting()->least_unacked);
2521 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2522 frame = InitAckFrame(2);
2523 ProcessAckPacket(&frame);
2524 EXPECT_EQ(3u, stop_waiting()->least_unacked);
2526 // When we send an ack, we make sure our least-unacked makes sense. In this
2527 // case since we're not waiting on an ack for 2 and all packets are acked, we
2528 // set it to 3.
2529 SendAckPacketToPeer(); // Packet 3
2530 // Least_unacked remains at 3 until another ack is received.
2531 EXPECT_EQ(3u, stop_waiting()->least_unacked);
2532 // Check that the outgoing ack had its sequence number as least_unacked.
2533 EXPECT_EQ(3u, least_unacked());
2535 // Ack the ack, which updates the rtt and raises the least unacked.
2536 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2537 frame = InitAckFrame(3);
2538 ProcessAckPacket(&frame);
2540 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2541 .WillByDefault(Return(true));
2542 SendStreamDataToPeer(1, "bar", 3, false, nullptr); // Packet 4
2543 EXPECT_EQ(4u, stop_waiting()->least_unacked);
2544 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2545 .WillByDefault(Return(false));
2546 SendAckPacketToPeer(); // Packet 5
2547 EXPECT_EQ(4u, least_unacked());
2549 // Send two data packets at the end, and ensure if the last one is acked,
2550 // the least unacked is raised above the ack packets.
2551 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2552 .WillByDefault(Return(true));
2553 SendStreamDataToPeer(1, "bar", 6, false, nullptr); // Packet 6
2554 SendStreamDataToPeer(1, "bar", 9, false, nullptr); // Packet 7
2556 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2557 frame = InitAckFrame(7);
2558 NackPacket(5, &frame);
2559 NackPacket(6, &frame);
2560 ProcessAckPacket(&frame);
2562 EXPECT_EQ(6u, stop_waiting()->least_unacked);
2565 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterFecPacket) {
2566 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2568 // Don't send missing packet 1.
2569 ProcessFecPacket(2, 1, true, !kEntropyFlag, nullptr);
2570 // Entropy flag should be false, so entropy should be 0.
2571 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2574 TEST_P(QuicConnectionTest, ReviveMissingPacketWithVaryingSeqNumLengths) {
2575 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2577 // Set up a debug visitor to the connection.
2578 scoped_ptr<FecQuicConnectionDebugVisitor> fec_visitor(
2579 new FecQuicConnectionDebugVisitor());
2580 connection_.set_debug_visitor(fec_visitor.get());
2582 QuicPacketSequenceNumber fec_packet = 0;
2583 QuicSequenceNumberLength lengths[] = {PACKET_6BYTE_SEQUENCE_NUMBER,
2584 PACKET_4BYTE_SEQUENCE_NUMBER,
2585 PACKET_2BYTE_SEQUENCE_NUMBER,
2586 PACKET_1BYTE_SEQUENCE_NUMBER};
2587 // For each sequence number length size, revive a packet and check sequence
2588 // number length in the revived packet.
2589 for (size_t i = 0; i < arraysize(lengths); ++i) {
2590 // Set sequence_number_length_ (for data and FEC packets).
2591 sequence_number_length_ = lengths[i];
2592 fec_packet += 2;
2593 // Don't send missing packet, but send fec packet right after it.
2594 ProcessFecPacket(fec_packet, fec_packet - 1, true, !kEntropyFlag, nullptr);
2595 // Sequence number length in the revived header should be the same as
2596 // in the original data/fec packet headers.
2597 EXPECT_EQ(sequence_number_length_, fec_visitor->revived_header().
2598 public_header.sequence_number_length);
2602 TEST_P(QuicConnectionTest, ReviveMissingPacketWithVaryingConnectionIdLengths) {
2603 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2605 // Set up a debug visitor to the connection.
2606 scoped_ptr<FecQuicConnectionDebugVisitor> fec_visitor(
2607 new FecQuicConnectionDebugVisitor());
2608 connection_.set_debug_visitor(fec_visitor.get());
2610 QuicPacketSequenceNumber fec_packet = 0;
2611 QuicConnectionIdLength lengths[] = {PACKET_8BYTE_CONNECTION_ID,
2612 PACKET_4BYTE_CONNECTION_ID,
2613 PACKET_1BYTE_CONNECTION_ID,
2614 PACKET_0BYTE_CONNECTION_ID};
2615 // For each connection id length size, revive a packet and check connection
2616 // id length in the revived packet.
2617 for (size_t i = 0; i < arraysize(lengths); ++i) {
2618 // Set connection id length (for data and FEC packets).
2619 connection_id_length_ = lengths[i];
2620 fec_packet += 2;
2621 // Don't send missing packet, but send fec packet right after it.
2622 ProcessFecPacket(fec_packet, fec_packet - 1, true, !kEntropyFlag, nullptr);
2623 // Connection id length in the revived header should be the same as
2624 // in the original data/fec packet headers.
2625 EXPECT_EQ(connection_id_length_,
2626 fec_visitor->revived_header().public_header.connection_id_length);
2630 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPacketThenFecPacket) {
2631 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2633 ProcessFecProtectedPacket(1, false, kEntropyFlag);
2634 // Don't send missing packet 2.
2635 ProcessFecPacket(3, 1, true, !kEntropyFlag, nullptr);
2636 // Entropy flag should be true, so entropy should not be 0.
2637 EXPECT_NE(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2640 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPacketsThenFecPacket) {
2641 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2643 ProcessFecProtectedPacket(1, false, !kEntropyFlag);
2644 // Don't send missing packet 2.
2645 ProcessFecProtectedPacket(3, false, !kEntropyFlag);
2646 ProcessFecPacket(4, 1, true, kEntropyFlag, nullptr);
2647 // Ensure QUIC no longer revives entropy for lost packets.
2648 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2649 EXPECT_NE(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 4));
2652 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPacket) {
2653 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2655 // Don't send missing packet 1.
2656 ProcessFecPacket(3, 1, false, !kEntropyFlag, nullptr);
2657 // Out of order.
2658 ProcessFecProtectedPacket(2, true, !kEntropyFlag);
2659 // Entropy flag should be false, so entropy should be 0.
2660 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2663 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPackets) {
2664 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2666 ProcessFecProtectedPacket(1, false, !kEntropyFlag);
2667 // Don't send missing packet 2.
2668 ProcessFecPacket(6, 1, false, kEntropyFlag, nullptr);
2669 ProcessFecProtectedPacket(3, false, kEntropyFlag);
2670 ProcessFecProtectedPacket(4, false, kEntropyFlag);
2671 ProcessFecProtectedPacket(5, true, !kEntropyFlag);
2672 // Ensure entropy is not revived for the missing packet.
2673 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2674 EXPECT_NE(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 3));
2677 TEST_P(QuicConnectionTest, TLP) {
2678 QuicSentPacketManagerPeer::SetMaxTailLossProbes(manager_, 1);
2680 SendStreamDataToPeer(3, "foo", 0, !kFin, nullptr);
2681 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2682 QuicTime retransmission_time =
2683 connection_.GetRetransmissionAlarm()->deadline();
2684 EXPECT_NE(QuicTime::Zero(), retransmission_time);
2686 EXPECT_EQ(1u, writer_->header().packet_sequence_number);
2687 // Simulate the retransmission alarm firing and sending a tlp,
2688 // so send algorithm's OnRetransmissionTimeout is not called.
2689 clock_.AdvanceTime(retransmission_time.Subtract(clock_.Now()));
2690 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 2u, _, _));
2691 connection_.GetRetransmissionAlarm()->Fire();
2692 EXPECT_EQ(2u, writer_->header().packet_sequence_number);
2693 // We do not raise the high water mark yet.
2694 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2697 TEST_P(QuicConnectionTest, RTO) {
2698 QuicTime default_retransmission_time = clock_.ApproximateNow().Add(
2699 DefaultRetransmissionTime());
2700 SendStreamDataToPeer(3, "foo", 0, !kFin, nullptr);
2701 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2703 EXPECT_EQ(1u, writer_->header().packet_sequence_number);
2704 EXPECT_EQ(default_retransmission_time,
2705 connection_.GetRetransmissionAlarm()->deadline());
2706 // Simulate the retransmission alarm firing.
2707 clock_.AdvanceTime(DefaultRetransmissionTime());
2708 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 2u, _, _));
2709 connection_.GetRetransmissionAlarm()->Fire();
2710 EXPECT_EQ(2u, writer_->header().packet_sequence_number);
2711 // We do not raise the high water mark yet.
2712 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2715 TEST_P(QuicConnectionTest, RTOWithSameEncryptionLevel) {
2716 QuicTime default_retransmission_time = clock_.ApproximateNow().Add(
2717 DefaultRetransmissionTime());
2718 use_tagging_decrypter();
2720 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
2721 // the end of the packet. We can test this to check which encrypter was used.
2722 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2723 SendStreamDataToPeer(3, "foo", 0, !kFin, nullptr);
2724 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
2726 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2727 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2728 SendStreamDataToPeer(3, "foo", 0, !kFin, nullptr);
2729 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2731 EXPECT_EQ(default_retransmission_time,
2732 connection_.GetRetransmissionAlarm()->deadline());
2734 InSequence s;
2735 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 3, _, _));
2736 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 4, _, _));
2739 // Simulate the retransmission alarm firing.
2740 clock_.AdvanceTime(DefaultRetransmissionTime());
2741 connection_.GetRetransmissionAlarm()->Fire();
2743 // Packet should have been sent with ENCRYPTION_NONE.
2744 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_previous_packet());
2746 // Packet should have been sent with ENCRYPTION_INITIAL.
2747 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2750 TEST_P(QuicConnectionTest, SendHandshakeMessages) {
2751 use_tagging_decrypter();
2752 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
2753 // the end of the packet. We can test this to check which encrypter was used.
2754 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2756 // Attempt to send a handshake message and have the socket block.
2757 EXPECT_CALL(*send_algorithm_,
2758 TimeUntilSend(_, _, _)).WillRepeatedly(
2759 testing::Return(QuicTime::Delta::Zero()));
2760 BlockOnNextWrite();
2761 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
2762 // The packet should be serialized, but not queued.
2763 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2765 // Switch to the new encrypter.
2766 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2767 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2769 // Now become writeable and flush the packets.
2770 writer_->SetWritable();
2771 EXPECT_CALL(visitor_, OnCanWrite());
2772 connection_.OnCanWrite();
2773 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2775 // Verify that the handshake packet went out at the null encryption.
2776 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
2779 TEST_P(QuicConnectionTest,
2780 DropRetransmitsForNullEncryptedPacketAfterForwardSecure) {
2781 use_tagging_decrypter();
2782 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2783 QuicPacketSequenceNumber sequence_number;
2784 SendStreamDataToPeer(3, "foo", 0, !kFin, &sequence_number);
2786 // Simulate the retransmission alarm firing and the socket blocking.
2787 BlockOnNextWrite();
2788 clock_.AdvanceTime(DefaultRetransmissionTime());
2789 connection_.GetRetransmissionAlarm()->Fire();
2791 // Go forward secure.
2792 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
2793 new TaggingEncrypter(0x02));
2794 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2795 connection_.NeuterUnencryptedPackets();
2797 EXPECT_EQ(QuicTime::Zero(),
2798 connection_.GetRetransmissionAlarm()->deadline());
2799 // Unblock the socket and ensure that no packets are sent.
2800 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
2801 writer_->SetWritable();
2802 connection_.OnCanWrite();
2805 TEST_P(QuicConnectionTest, RetransmitPacketsWithInitialEncryption) {
2806 use_tagging_decrypter();
2807 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2808 connection_.SetDefaultEncryptionLevel(ENCRYPTION_NONE);
2810 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr);
2812 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2813 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2815 SendStreamDataToPeer(2, "bar", 0, !kFin, nullptr);
2816 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2818 connection_.RetransmitUnackedPackets(ALL_INITIAL_RETRANSMISSION);
2821 TEST_P(QuicConnectionTest, DelayForwardSecureEncryptionUntilClientIsReady) {
2822 // A TaggingEncrypter puts kTagSize copies of the given byte (0x02 here) at
2823 // the end of the packet. We can test this to check which encrypter was used.
2824 use_tagging_decrypter();
2825 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2826 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2827 SendAckPacketToPeer();
2828 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2830 // Set a forward-secure encrypter but do not make it the default, and verify
2831 // that it is not yet used.
2832 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
2833 new TaggingEncrypter(0x03));
2834 SendAckPacketToPeer();
2835 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2837 // Now simulate receipt of a forward-secure packet and verify that the
2838 // forward-secure encrypter is now used.
2839 connection_.OnDecryptedPacket(ENCRYPTION_FORWARD_SECURE);
2840 SendAckPacketToPeer();
2841 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
2844 TEST_P(QuicConnectionTest, DelayForwardSecureEncryptionUntilManyPacketSent) {
2845 // Set a congestion window of 10 packets.
2846 QuicPacketCount congestion_window = 10;
2847 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
2848 Return(congestion_window * kDefaultMaxPacketSize));
2850 // A TaggingEncrypter puts kTagSize copies of the given byte (0x02 here) at
2851 // the end of the packet. We can test this to check which encrypter was used.
2852 use_tagging_decrypter();
2853 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2854 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2855 SendAckPacketToPeer();
2856 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2858 // Set a forward-secure encrypter but do not make it the default, and
2859 // verify that it is not yet used.
2860 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
2861 new TaggingEncrypter(0x03));
2862 SendAckPacketToPeer();
2863 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2865 // Now send a packet "Far enough" after the encrypter was set and verify that
2866 // the forward-secure encrypter is now used.
2867 for (uint64 i = 0; i < 3 * congestion_window - 1; ++i) {
2868 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2869 SendAckPacketToPeer();
2871 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
2874 TEST_P(QuicConnectionTest, BufferNonDecryptablePackets) {
2875 // SetFromConfig is always called after construction from InitializeSession.
2876 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
2877 QuicConfig config;
2878 connection_.SetFromConfig(config);
2879 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2880 use_tagging_decrypter();
2882 const uint8 tag = 0x07;
2883 framer_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
2885 // Process an encrypted packet which can not yet be decrypted which should
2886 // result in the packet being buffered.
2887 ProcessDataPacketAtLevel(1, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2889 // Transition to the new encryption state and process another encrypted packet
2890 // which should result in the original packet being processed.
2891 connection_.SetDecrypter(new StrictTaggingDecrypter(tag),
2892 ENCRYPTION_INITIAL);
2893 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2894 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
2895 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(2);
2896 ProcessDataPacketAtLevel(2, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2898 // Finally, process a third packet and note that we do not reprocess the
2899 // buffered packet.
2900 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
2901 ProcessDataPacketAtLevel(3, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2904 TEST_P(QuicConnectionTest, Buffer100NonDecryptablePackets) {
2905 // SetFromConfig is always called after construction from InitializeSession.
2906 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
2907 QuicConfig config;
2908 config.set_max_undecryptable_packets(100);
2909 connection_.SetFromConfig(config);
2910 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2911 use_tagging_decrypter();
2913 const uint8 tag = 0x07;
2914 framer_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
2916 // Process an encrypted packet which can not yet be decrypted which should
2917 // result in the packet being buffered.
2918 for (QuicPacketSequenceNumber i = 1; i <= 100; ++i) {
2919 ProcessDataPacketAtLevel(i, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2922 // Transition to the new encryption state and process another encrypted packet
2923 // which should result in the original packets being processed.
2924 connection_.SetDecrypter(new StrictTaggingDecrypter(tag), ENCRYPTION_INITIAL);
2925 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2926 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
2927 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(101);
2928 ProcessDataPacketAtLevel(101, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2930 // Finally, process a third packet and note that we do not reprocess the
2931 // buffered packet.
2932 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
2933 ProcessDataPacketAtLevel(102, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2936 TEST_P(QuicConnectionTest, TestRetransmitOrder) {
2937 QuicByteCount first_packet_size;
2938 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).WillOnce(
2939 DoAll(SaveArg<3>(&first_packet_size), Return(true)));
2941 connection_.SendStreamDataWithString(3, "first_packet", 0, !kFin, nullptr);
2942 QuicByteCount second_packet_size;
2943 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).WillOnce(
2944 DoAll(SaveArg<3>(&second_packet_size), Return(true)));
2945 connection_.SendStreamDataWithString(3, "second_packet", 12, !kFin, nullptr);
2946 EXPECT_NE(first_packet_size, second_packet_size);
2947 // Advance the clock by huge time to make sure packets will be retransmitted.
2948 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
2950 InSequence s;
2951 EXPECT_CALL(*send_algorithm_,
2952 OnPacketSent(_, _, _, first_packet_size, _));
2953 EXPECT_CALL(*send_algorithm_,
2954 OnPacketSent(_, _, _, second_packet_size, _));
2956 connection_.GetRetransmissionAlarm()->Fire();
2958 // Advance again and expect the packets to be sent again in the same order.
2959 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(20));
2961 InSequence s;
2962 EXPECT_CALL(*send_algorithm_,
2963 OnPacketSent(_, _, _, first_packet_size, _));
2964 EXPECT_CALL(*send_algorithm_,
2965 OnPacketSent(_, _, _, second_packet_size, _));
2967 connection_.GetRetransmissionAlarm()->Fire();
2970 TEST_P(QuicConnectionTest, SetRTOAfterWritingToSocket) {
2971 BlockOnNextWrite();
2972 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
2973 // Make sure that RTO is not started when the packet is queued.
2974 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
2976 // Test that RTO is started once we write to the socket.
2977 writer_->SetWritable();
2978 connection_.OnCanWrite();
2979 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2982 TEST_P(QuicConnectionTest, DelayRTOWithAckReceipt) {
2983 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2984 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2985 .Times(2);
2986 connection_.SendStreamDataWithString(2, "foo", 0, !kFin, nullptr);
2987 connection_.SendStreamDataWithString(3, "bar", 0, !kFin, nullptr);
2988 QuicAlarm* retransmission_alarm = connection_.GetRetransmissionAlarm();
2989 EXPECT_TRUE(retransmission_alarm->IsSet());
2990 EXPECT_EQ(clock_.Now().Add(DefaultRetransmissionTime()),
2991 retransmission_alarm->deadline());
2993 // Advance the time right before the RTO, then receive an ack for the first
2994 // packet to delay the RTO.
2995 clock_.AdvanceTime(DefaultRetransmissionTime());
2996 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2997 QuicAckFrame ack = InitAckFrame(1);
2998 ProcessAckPacket(&ack);
2999 EXPECT_TRUE(retransmission_alarm->IsSet());
3000 EXPECT_GT(retransmission_alarm->deadline(), clock_.Now());
3002 // Move forward past the original RTO and ensure the RTO is still pending.
3003 clock_.AdvanceTime(DefaultRetransmissionTime().Multiply(2));
3005 // Ensure the second packet gets retransmitted when it finally fires.
3006 EXPECT_TRUE(retransmission_alarm->IsSet());
3007 EXPECT_LT(retransmission_alarm->deadline(), clock_.ApproximateNow());
3008 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3009 // Manually cancel the alarm to simulate a real test.
3010 connection_.GetRetransmissionAlarm()->Fire();
3012 // The new retransmitted sequence number should set the RTO to a larger value
3013 // than previously.
3014 EXPECT_TRUE(retransmission_alarm->IsSet());
3015 QuicTime next_rto_time = retransmission_alarm->deadline();
3016 QuicTime expected_rto_time =
3017 connection_.sent_packet_manager().GetRetransmissionTime();
3018 EXPECT_EQ(next_rto_time, expected_rto_time);
3021 TEST_P(QuicConnectionTest, TestQueued) {
3022 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3023 BlockOnNextWrite();
3024 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
3025 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3027 // Unblock the writes and actually send.
3028 writer_->SetWritable();
3029 connection_.OnCanWrite();
3030 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3033 TEST_P(QuicConnectionTest, CloseFecGroup) {
3034 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3035 // Don't send missing packet 1.
3036 // Don't send missing packet 2.
3037 ProcessFecProtectedPacket(3, false, !kEntropyFlag);
3038 // Don't send missing FEC packet 3.
3039 ASSERT_EQ(1u, connection_.NumFecGroups());
3041 // Now send non-fec protected ack packet and close the group.
3042 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 4);
3043 QuicStopWaitingFrame frame = InitStopWaitingFrame(5);
3044 ProcessStopWaitingPacket(&frame);
3045 ASSERT_EQ(0u, connection_.NumFecGroups());
3048 TEST_P(QuicConnectionTest, InitialTimeout) {
3049 EXPECT_TRUE(connection_.connected());
3050 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
3051 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3053 // SetFromConfig sets the initial timeouts before negotiation.
3054 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3055 QuicConfig config;
3056 connection_.SetFromConfig(config);
3057 // Subtract a second from the idle timeout on the client side.
3058 QuicTime default_timeout = clock_.ApproximateNow().Add(
3059 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1));
3060 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
3062 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_CONNECTION_TIMED_OUT, false));
3063 // Simulate the timeout alarm firing.
3064 clock_.AdvanceTime(
3065 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1));
3066 connection_.GetTimeoutAlarm()->Fire();
3068 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3069 EXPECT_FALSE(connection_.connected());
3071 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3072 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
3073 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
3074 EXPECT_FALSE(connection_.GetResumeWritesAlarm()->IsSet());
3075 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3076 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
3079 TEST_P(QuicConnectionTest, OverallTimeout) {
3080 // Use a shorter overall connection timeout than idle timeout for this test.
3081 const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(5);
3082 connection_.SetNetworkTimeouts(timeout, timeout);
3083 EXPECT_TRUE(connection_.connected());
3084 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
3086 QuicTime overall_timeout = clock_.ApproximateNow().Add(timeout).Subtract(
3087 QuicTime::Delta::FromSeconds(1));
3088 EXPECT_EQ(overall_timeout, connection_.GetTimeoutAlarm()->deadline());
3089 EXPECT_TRUE(connection_.connected());
3091 // Send and ack new data 3 seconds later to lengthen the idle timeout.
3092 SendStreamDataToPeer(1, "GET /", 0, kFin, nullptr);
3093 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(3));
3094 QuicAckFrame frame = InitAckFrame(1);
3095 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3096 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3097 ProcessAckPacket(&frame);
3099 // Fire early to verify it wouldn't timeout yet.
3100 connection_.GetTimeoutAlarm()->Fire();
3101 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
3102 EXPECT_TRUE(connection_.connected());
3104 clock_.AdvanceTime(timeout.Subtract(QuicTime::Delta::FromSeconds(2)));
3106 EXPECT_CALL(visitor_,
3107 OnConnectionClosed(QUIC_CONNECTION_OVERALL_TIMED_OUT, false));
3108 // Simulate the timeout alarm firing.
3109 connection_.GetTimeoutAlarm()->Fire();
3111 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3112 EXPECT_FALSE(connection_.connected());
3114 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3115 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
3116 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
3117 EXPECT_FALSE(connection_.GetResumeWritesAlarm()->IsSet());
3118 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3119 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
3122 TEST_P(QuicConnectionTest, PingAfterSend) {
3123 EXPECT_TRUE(connection_.connected());
3124 EXPECT_CALL(visitor_, HasOpenDataStreams()).WillRepeatedly(Return(true));
3125 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
3127 // Advance to 5ms, and send a packet to the peer, which will set
3128 // the ping alarm.
3129 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
3130 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3131 SendStreamDataToPeer(1, "GET /", 0, kFin, nullptr);
3132 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
3133 EXPECT_EQ(clock_.ApproximateNow().Add(QuicTime::Delta::FromSeconds(15)),
3134 connection_.GetPingAlarm()->deadline());
3136 // Now recevie and ACK of the previous packet, which will move the
3137 // ping alarm forward.
3138 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
3139 QuicAckFrame frame = InitAckFrame(1);
3140 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3141 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3142 ProcessAckPacket(&frame);
3143 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
3144 // The ping timer is set slightly less than 15 seconds in the future, because
3145 // of the 1s ping timer alarm granularity.
3146 EXPECT_EQ(clock_.ApproximateNow().Add(QuicTime::Delta::FromSeconds(15))
3147 .Subtract(QuicTime::Delta::FromMilliseconds(5)),
3148 connection_.GetPingAlarm()->deadline());
3150 writer_->Reset();
3151 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15));
3152 connection_.GetPingAlarm()->Fire();
3153 EXPECT_EQ(1u, writer_->frame_count());
3154 ASSERT_EQ(1u, writer_->ping_frames().size());
3155 writer_->Reset();
3157 EXPECT_CALL(visitor_, HasOpenDataStreams()).WillRepeatedly(Return(false));
3158 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
3159 SendAckPacketToPeer();
3161 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
3164 TEST_P(QuicConnectionTest, TimeoutAfterSend) {
3165 EXPECT_TRUE(connection_.connected());
3166 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3167 QuicConfig config;
3168 connection_.SetFromConfig(config);
3169 EXPECT_FALSE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
3171 const QuicTime::Delta initial_idle_timeout =
3172 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
3173 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
3174 QuicTime default_timeout = clock_.ApproximateNow().Add(initial_idle_timeout);
3176 // When we send a packet, the timeout will change to 5ms +
3177 // kInitialIdleTimeoutSecs.
3178 clock_.AdvanceTime(five_ms);
3180 // Send an ack so we don't set the retransmission alarm.
3181 SendAckPacketToPeer();
3182 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
3184 // The original alarm will fire. We should not time out because we had a
3185 // network event at t=5ms. The alarm will reregister.
3186 clock_.AdvanceTime(initial_idle_timeout.Subtract(five_ms));
3187 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
3188 connection_.GetTimeoutAlarm()->Fire();
3189 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
3190 EXPECT_TRUE(connection_.connected());
3191 EXPECT_EQ(default_timeout.Add(five_ms),
3192 connection_.GetTimeoutAlarm()->deadline());
3194 // This time, we should time out.
3195 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_CONNECTION_TIMED_OUT, false));
3196 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3197 clock_.AdvanceTime(five_ms);
3198 EXPECT_EQ(default_timeout.Add(five_ms), clock_.ApproximateNow());
3199 connection_.GetTimeoutAlarm()->Fire();
3200 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3201 EXPECT_FALSE(connection_.connected());
3204 TEST_P(QuicConnectionTest, TimeoutAfterSendSilentClose) {
3205 // Same test as above, but complete a handshake which enables silent close,
3206 // causing no connection close packet to be sent.
3207 EXPECT_TRUE(connection_.connected());
3208 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3209 QuicConfig config;
3211 // Create a handshake message that also enables silent close.
3212 CryptoHandshakeMessage msg;
3213 string error_details;
3214 QuicConfig client_config;
3215 client_config.SetInitialStreamFlowControlWindowToSend(
3216 kInitialStreamFlowControlWindowForTest);
3217 client_config.SetInitialSessionFlowControlWindowToSend(
3218 kInitialSessionFlowControlWindowForTest);
3219 client_config.SetIdleConnectionStateLifetime(
3220 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs),
3221 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs));
3222 client_config.ToHandshakeMessage(&msg);
3223 const QuicErrorCode error =
3224 config.ProcessPeerHello(msg, CLIENT, &error_details);
3225 EXPECT_EQ(QUIC_NO_ERROR, error);
3227 connection_.SetFromConfig(config);
3228 EXPECT_TRUE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
3230 const QuicTime::Delta default_idle_timeout =
3231 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs - 1);
3232 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
3233 QuicTime default_timeout = clock_.ApproximateNow().Add(default_idle_timeout);
3235 // When we send a packet, the timeout will change to 5ms +
3236 // kInitialIdleTimeoutSecs.
3237 clock_.AdvanceTime(five_ms);
3239 // Send an ack so we don't set the retransmission alarm.
3240 SendAckPacketToPeer();
3241 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
3243 // The original alarm will fire. We should not time out because we had a
3244 // network event at t=5ms. The alarm will reregister.
3245 clock_.AdvanceTime(default_idle_timeout.Subtract(five_ms));
3246 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
3247 connection_.GetTimeoutAlarm()->Fire();
3248 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
3249 EXPECT_TRUE(connection_.connected());
3250 EXPECT_EQ(default_timeout.Add(five_ms),
3251 connection_.GetTimeoutAlarm()->deadline());
3253 // This time, we should time out.
3254 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_CONNECTION_TIMED_OUT, false));
3255 clock_.AdvanceTime(five_ms);
3256 EXPECT_EQ(default_timeout.Add(five_ms), clock_.ApproximateNow());
3257 connection_.GetTimeoutAlarm()->Fire();
3258 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3259 EXPECT_FALSE(connection_.connected());
3262 TEST_P(QuicConnectionTest, SendScheduler) {
3263 // Test that if we send a packet without delay, it is not queued.
3264 QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
3265 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3266 connection_.SendPacket(
3267 ENCRYPTION_NONE, 1, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA);
3268 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3271 TEST_P(QuicConnectionTest, SendSchedulerEAGAIN) {
3272 QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
3273 BlockOnNextWrite();
3274 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 1, _, _)).Times(0);
3275 connection_.SendPacket(
3276 ENCRYPTION_NONE, 1, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA);
3277 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3280 TEST_P(QuicConnectionTest, TestQueueLimitsOnSendStreamData) {
3281 // All packets carry version info till version is negotiated.
3282 size_t payload_length;
3283 size_t length = GetPacketLengthForOneStream(
3284 connection_.version(), kIncludeVersion,
3285 PACKET_8BYTE_CONNECTION_ID, PACKET_1BYTE_SEQUENCE_NUMBER,
3286 NOT_IN_FEC_GROUP, &payload_length);
3287 creator_->SetMaxPacketLength(length);
3289 // Queue the first packet.
3290 EXPECT_CALL(*send_algorithm_,
3291 TimeUntilSend(_, _, _)).WillOnce(
3292 testing::Return(QuicTime::Delta::FromMicroseconds(10)));
3293 const string payload(payload_length, 'a');
3294 EXPECT_EQ(0u, connection_.SendStreamDataWithString(3, payload, 0, !kFin,
3295 nullptr).bytes_consumed);
3296 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3299 TEST_P(QuicConnectionTest, LoopThroughSendingPackets) {
3300 // All packets carry version info till version is negotiated.
3301 size_t payload_length;
3302 // GetPacketLengthForOneStream() assumes a stream offset of 0 in determining
3303 // packet length. The size of the offset field in a stream frame is 0 for
3304 // offset 0, and 2 for non-zero offsets up through 16K. Increase
3305 // max_packet_length by 2 so that subsequent packets containing subsequent
3306 // stream frames with non-zero offets will fit within the packet length.
3307 size_t length = 2 + GetPacketLengthForOneStream(
3308 connection_.version(), kIncludeVersion,
3309 PACKET_8BYTE_CONNECTION_ID, PACKET_1BYTE_SEQUENCE_NUMBER,
3310 NOT_IN_FEC_GROUP, &payload_length);
3311 creator_->SetMaxPacketLength(length);
3313 // Queue the first packet.
3314 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(7);
3315 // The first stream frame will have 2 fewer overhead bytes than the other six.
3316 const string payload(payload_length * 7 + 2, 'a');
3317 EXPECT_EQ(payload.size(),
3318 connection_.SendStreamDataWithString(1, payload, 0, !kFin, nullptr)
3319 .bytes_consumed);
3322 TEST_P(QuicConnectionTest, LoopThroughSendingPacketsWithTruncation) {
3323 // Set up a larger payload than will fit in one packet.
3324 const string payload(connection_.max_packet_length(), 'a');
3325 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
3327 // Now send some packets with no truncation.
3328 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3329 EXPECT_EQ(payload.size(),
3330 connection_.SendStreamDataWithString(
3331 3, payload, 0, !kFin, nullptr).bytes_consumed);
3332 // Track the size of the second packet here. The overhead will be the largest
3333 // we see in this test, due to the non-truncated connection id.
3334 size_t non_truncated_packet_size = writer_->last_packet_size();
3336 // Change to a 4 byte connection id.
3337 QuicConfig config;
3338 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 4);
3339 connection_.SetFromConfig(config);
3340 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3341 EXPECT_EQ(payload.size(),
3342 connection_.SendStreamDataWithString(
3343 3, payload, 0, !kFin, nullptr).bytes_consumed);
3344 // Verify that we have 8 fewer bytes than in the non-truncated case. The
3345 // first packet got 4 bytes of extra payload due to the truncation, and the
3346 // headers here are also 4 byte smaller.
3347 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() + 8);
3349 // Change to a 1 byte connection id.
3350 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 1);
3351 connection_.SetFromConfig(config);
3352 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3353 EXPECT_EQ(payload.size(),
3354 connection_.SendStreamDataWithString(
3355 3, payload, 0, !kFin, nullptr).bytes_consumed);
3356 // Just like above, we save 7 bytes on payload, and 7 on truncation.
3357 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() + 7 * 2);
3359 // Change to a 0 byte connection id.
3360 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
3361 connection_.SetFromConfig(config);
3362 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3363 EXPECT_EQ(payload.size(),
3364 connection_.SendStreamDataWithString(
3365 3, payload, 0, !kFin, nullptr).bytes_consumed);
3366 // Just like above, we save 8 bytes on payload, and 8 on truncation.
3367 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() + 8 * 2);
3370 TEST_P(QuicConnectionTest, SendDelayedAck) {
3371 QuicTime ack_time = clock_.ApproximateNow().Add(DefaultDelayedAckTime());
3372 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3373 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3374 const uint8 tag = 0x07;
3375 connection_.SetDecrypter(new StrictTaggingDecrypter(tag),
3376 ENCRYPTION_INITIAL);
3377 framer_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
3378 // Process a packet from the non-crypto stream.
3379 frame1_.stream_id = 3;
3381 // The same as ProcessPacket(1) except that ENCRYPTION_INITIAL is used
3382 // instead of ENCRYPTION_NONE.
3383 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
3384 ProcessDataPacketAtLevel(1, 0, !kEntropyFlag, ENCRYPTION_INITIAL);
3386 // Check if delayed ack timer is running for the expected interval.
3387 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3388 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
3389 // Simulate delayed ack alarm firing.
3390 connection_.GetAckAlarm()->Fire();
3391 // Check that ack is sent and that delayed ack alarm is reset.
3392 EXPECT_EQ(2u, writer_->frame_count());
3393 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3394 EXPECT_FALSE(writer_->ack_frames().empty());
3395 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3398 TEST_P(QuicConnectionTest, SendDelayedAckOnHandshakeConfirmed) {
3399 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3400 ProcessPacket(1);
3401 // Check that ack is sent and that delayed ack alarm is set.
3402 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3403 QuicTime ack_time = clock_.ApproximateNow().Add(DefaultDelayedAckTime());
3404 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
3406 // Completing the handshake as the server does nothing.
3407 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_SERVER);
3408 connection_.OnHandshakeComplete();
3409 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3410 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
3412 // Complete the handshake as the client decreases the delayed ack time to 0ms.
3413 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_CLIENT);
3414 connection_.OnHandshakeComplete();
3415 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3416 EXPECT_EQ(clock_.ApproximateNow(), connection_.GetAckAlarm()->deadline());
3419 TEST_P(QuicConnectionTest, SendDelayedAckOnSecondPacket) {
3420 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3421 ProcessPacket(1);
3422 ProcessPacket(2);
3423 // Check that ack is sent and that delayed ack alarm is reset.
3424 EXPECT_EQ(2u, writer_->frame_count());
3425 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3426 EXPECT_FALSE(writer_->ack_frames().empty());
3427 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3430 TEST_P(QuicConnectionTest, NoAckOnOldNacks) {
3431 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3432 // Drop one packet, triggering a sequence of acks.
3433 ProcessPacket(2);
3434 size_t frames_per_ack = 2;
3435 EXPECT_EQ(frames_per_ack, writer_->frame_count());
3436 EXPECT_FALSE(writer_->ack_frames().empty());
3437 writer_->Reset();
3438 ProcessPacket(3);
3439 EXPECT_EQ(frames_per_ack, writer_->frame_count());
3440 EXPECT_FALSE(writer_->ack_frames().empty());
3441 writer_->Reset();
3442 ProcessPacket(4);
3443 EXPECT_EQ(frames_per_ack, writer_->frame_count());
3444 EXPECT_FALSE(writer_->ack_frames().empty());
3445 writer_->Reset();
3446 ProcessPacket(5);
3447 EXPECT_EQ(frames_per_ack, writer_->frame_count());
3448 EXPECT_FALSE(writer_->ack_frames().empty());
3449 writer_->Reset();
3450 // Now only set the timer on the 6th packet, instead of sending another ack.
3451 ProcessPacket(6);
3452 EXPECT_EQ(0u, writer_->frame_count());
3453 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3456 TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingPacket) {
3457 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3458 ProcessPacket(1);
3459 connection_.SendStreamDataWithString(kClientDataStreamId1, "foo", 0, !kFin,
3460 nullptr);
3461 // Check that ack is bundled with outgoing data and that delayed ack
3462 // alarm is reset.
3463 EXPECT_EQ(3u, writer_->frame_count());
3464 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3465 EXPECT_FALSE(writer_->ack_frames().empty());
3466 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3469 TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingCryptoPacket) {
3470 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3471 ProcessPacket(1);
3472 connection_.SendStreamDataWithString(kCryptoStreamId, "foo", 0, !kFin,
3473 nullptr);
3474 // Check that ack is bundled with outgoing crypto data.
3475 EXPECT_EQ(3u, writer_->frame_count());
3476 EXPECT_FALSE(writer_->ack_frames().empty());
3477 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3480 TEST_P(QuicConnectionTest, BlockAndBufferOnFirstCHLOPacketOfTwo) {
3481 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3482 ProcessPacket(1);
3483 BlockOnNextWrite();
3484 writer_->set_is_write_blocked_data_buffered(true);
3485 connection_.SendStreamDataWithString(kCryptoStreamId, "foo", 0, !kFin,
3486 nullptr);
3487 EXPECT_TRUE(writer_->IsWriteBlocked());
3488 EXPECT_FALSE(connection_.HasQueuedData());
3489 connection_.SendStreamDataWithString(kCryptoStreamId, "bar", 3, !kFin,
3490 nullptr);
3491 EXPECT_TRUE(writer_->IsWriteBlocked());
3492 EXPECT_TRUE(connection_.HasQueuedData());
3495 TEST_P(QuicConnectionTest, BundleAckForSecondCHLO) {
3496 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3497 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3498 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(
3499 IgnoreResult(InvokeWithoutArgs(&connection_,
3500 &TestConnection::SendCryptoStreamData)));
3501 // Process a packet from the crypto stream, which is frame1_'s default.
3502 // Receiving the CHLO as packet 2 first will cause the connection to
3503 // immediately send an ack, due to the packet gap.
3504 ProcessPacket(2);
3505 // Check that ack is sent and that delayed ack alarm is reset.
3506 EXPECT_EQ(3u, writer_->frame_count());
3507 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3508 EXPECT_EQ(1u, writer_->stream_frames().size());
3509 EXPECT_FALSE(writer_->ack_frames().empty());
3510 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3513 TEST_P(QuicConnectionTest, BundleAckWithDataOnIncomingAck) {
3514 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3515 connection_.SendStreamDataWithString(kClientDataStreamId1, "foo", 0, !kFin,
3516 nullptr);
3517 connection_.SendStreamDataWithString(kClientDataStreamId1, "foo", 3, !kFin,
3518 nullptr);
3519 // Ack the second packet, which will retransmit the first packet.
3520 QuicAckFrame ack = InitAckFrame(2);
3521 NackPacket(1, &ack);
3522 SequenceNumberSet lost_packets;
3523 lost_packets.insert(1);
3524 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3525 .WillOnce(Return(lost_packets));
3526 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3527 ProcessAckPacket(&ack);
3528 EXPECT_EQ(1u, writer_->frame_count());
3529 EXPECT_EQ(1u, writer_->stream_frames().size());
3530 writer_->Reset();
3532 // Now ack the retransmission, which will both raise the high water mark
3533 // and see if there is more data to send.
3534 ack = InitAckFrame(3);
3535 NackPacket(1, &ack);
3536 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3537 .WillOnce(Return(SequenceNumberSet()));
3538 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3539 ProcessAckPacket(&ack);
3541 // Check that no packet is sent and the ack alarm isn't set.
3542 EXPECT_EQ(0u, writer_->frame_count());
3543 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3544 writer_->Reset();
3546 // Send the same ack, but send both data and an ack together.
3547 ack = InitAckFrame(3);
3548 NackPacket(1, &ack);
3549 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3550 .WillOnce(Return(SequenceNumberSet()));
3551 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(
3552 IgnoreResult(InvokeWithoutArgs(
3553 &connection_,
3554 &TestConnection::EnsureWritableAndSendStreamData5)));
3555 ProcessAckPacket(&ack);
3557 // Check that ack is bundled with outgoing data and the delayed ack
3558 // alarm is reset.
3559 EXPECT_EQ(3u, writer_->frame_count());
3560 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3561 EXPECT_FALSE(writer_->ack_frames().empty());
3562 EXPECT_EQ(1u, writer_->stream_frames().size());
3563 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3566 TEST_P(QuicConnectionTest, NoAckSentForClose) {
3567 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3568 ProcessPacket(1);
3569 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, true));
3570 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3571 ProcessClosePacket(2, 0);
3574 TEST_P(QuicConnectionTest, SendWhenDisconnected) {
3575 EXPECT_TRUE(connection_.connected());
3576 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, false));
3577 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, false);
3578 EXPECT_FALSE(connection_.connected());
3579 EXPECT_FALSE(connection_.CanWriteStreamData());
3580 QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
3581 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 1, _, _)).Times(0);
3582 connection_.SendPacket(
3583 ENCRYPTION_NONE, 1, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA);
3586 TEST_P(QuicConnectionTest, PublicReset) {
3587 QuicPublicResetPacket header;
3588 header.public_header.connection_id = connection_id_;
3589 header.public_header.reset_flag = true;
3590 header.public_header.version_flag = false;
3591 header.rejected_sequence_number = 10101;
3592 scoped_ptr<QuicEncryptedPacket> packet(
3593 framer_.BuildPublicResetPacket(header));
3594 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PUBLIC_RESET, true));
3595 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *packet);
3598 TEST_P(QuicConnectionTest, GoAway) {
3599 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3601 QuicGoAwayFrame goaway;
3602 goaway.last_good_stream_id = 1;
3603 goaway.error_code = QUIC_PEER_GOING_AWAY;
3604 goaway.reason_phrase = "Going away.";
3605 EXPECT_CALL(visitor_, OnGoAway(_));
3606 ProcessGoAwayPacket(&goaway);
3609 TEST_P(QuicConnectionTest, WindowUpdate) {
3610 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3612 QuicWindowUpdateFrame window_update;
3613 window_update.stream_id = 3;
3614 window_update.byte_offset = 1234;
3615 EXPECT_CALL(visitor_, OnWindowUpdateFrames(_));
3616 ProcessFramePacket(QuicFrame(&window_update));
3619 TEST_P(QuicConnectionTest, Blocked) {
3620 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3622 QuicBlockedFrame blocked;
3623 blocked.stream_id = 3;
3624 EXPECT_CALL(visitor_, OnBlockedFrames(_));
3625 ProcessFramePacket(QuicFrame(&blocked));
3628 TEST_P(QuicConnectionTest, ZeroBytePacket) {
3629 // Don't close the connection for zero byte packets.
3630 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
3631 QuicEncryptedPacket encrypted(nullptr, 0);
3632 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), encrypted);
3635 TEST_P(QuicConnectionTest, MissingPacketsBeforeLeastUnacked) {
3636 // Set the sequence number of the ack packet to be least unacked (4).
3637 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 3);
3638 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3639 QuicStopWaitingFrame frame = InitStopWaitingFrame(4);
3640 ProcessStopWaitingPacket(&frame);
3641 EXPECT_TRUE(outgoing_ack()->missing_packets.empty());
3644 TEST_P(QuicConnectionTest, ReceivedEntropyHashCalculation) {
3645 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(AtLeast(1));
3646 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3647 ProcessDataPacket(1, 1, kEntropyFlag);
3648 ProcessDataPacket(4, 1, kEntropyFlag);
3649 ProcessDataPacket(3, 1, !kEntropyFlag);
3650 ProcessDataPacket(7, 1, kEntropyFlag);
3651 EXPECT_EQ(146u, outgoing_ack()->entropy_hash);
3654 TEST_P(QuicConnectionTest, ReceivedEntropyHashCalculationHalfFEC) {
3655 // FEC packets should not change the entropy hash calculation.
3656 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(AtLeast(1));
3657 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3658 ProcessDataPacket(1, 1, kEntropyFlag);
3659 ProcessFecPacket(4, 1, false, kEntropyFlag, nullptr);
3660 ProcessDataPacket(3, 3, !kEntropyFlag);
3661 ProcessFecPacket(7, 3, false, kEntropyFlag, nullptr);
3662 EXPECT_EQ(146u, outgoing_ack()->entropy_hash);
3665 TEST_P(QuicConnectionTest, UpdateEntropyForReceivedPackets) {
3666 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(AtLeast(1));
3667 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3668 ProcessDataPacket(1, 1, kEntropyFlag);
3669 ProcessDataPacket(5, 1, kEntropyFlag);
3670 ProcessDataPacket(4, 1, !kEntropyFlag);
3671 EXPECT_EQ(34u, outgoing_ack()->entropy_hash);
3672 // Make 4th packet my least unacked, and update entropy for 2, 3 packets.
3673 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 5);
3674 QuicPacketEntropyHash six_packet_entropy_hash = 0;
3675 QuicPacketEntropyHash random_entropy_hash = 129u;
3676 QuicStopWaitingFrame frame = InitStopWaitingFrame(4);
3677 frame.entropy_hash = random_entropy_hash;
3678 if (ProcessStopWaitingPacket(&frame)) {
3679 six_packet_entropy_hash = 1 << 6;
3682 EXPECT_EQ((random_entropy_hash + (1 << 5) + six_packet_entropy_hash),
3683 outgoing_ack()->entropy_hash);
3686 TEST_P(QuicConnectionTest, UpdateEntropyHashUptoCurrentPacket) {
3687 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(AtLeast(1));
3688 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3689 ProcessDataPacket(1, 1, kEntropyFlag);
3690 ProcessDataPacket(5, 1, !kEntropyFlag);
3691 ProcessDataPacket(22, 1, kEntropyFlag);
3692 EXPECT_EQ(66u, outgoing_ack()->entropy_hash);
3693 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 22);
3694 QuicPacketEntropyHash random_entropy_hash = 85u;
3695 // Current packet is the least unacked packet.
3696 QuicPacketEntropyHash ack_entropy_hash;
3697 QuicStopWaitingFrame frame = InitStopWaitingFrame(23);
3698 frame.entropy_hash = random_entropy_hash;
3699 ack_entropy_hash = ProcessStopWaitingPacket(&frame);
3700 EXPECT_EQ((random_entropy_hash + ack_entropy_hash),
3701 outgoing_ack()->entropy_hash);
3702 ProcessDataPacket(25, 1, kEntropyFlag);
3703 EXPECT_EQ((random_entropy_hash + ack_entropy_hash + (1 << (25 % 8))),
3704 outgoing_ack()->entropy_hash);
3707 TEST_P(QuicConnectionTest, EntropyCalculationForTruncatedAck) {
3708 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(AtLeast(1));
3709 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3710 QuicPacketEntropyHash entropy[51];
3711 entropy[0] = 0;
3712 for (int i = 1; i < 51; ++i) {
3713 bool should_send = i % 10 != 1;
3714 bool entropy_flag = (i & (i - 1)) != 0;
3715 if (!should_send) {
3716 entropy[i] = entropy[i - 1];
3717 continue;
3719 if (entropy_flag) {
3720 entropy[i] = entropy[i - 1] ^ (1 << (i % 8));
3721 } else {
3722 entropy[i] = entropy[i - 1];
3724 ProcessDataPacket(i, 1, entropy_flag);
3726 for (int i = 1; i < 50; ++i) {
3727 EXPECT_EQ(entropy[i], QuicConnectionPeer::ReceivedEntropyHash(
3728 &connection_, i));
3732 TEST_P(QuicConnectionTest, ServerSendsVersionNegotiationPacket) {
3733 connection_.SetSupportedVersions(QuicSupportedVersions());
3734 framer_.set_version_for_tests(QUIC_VERSION_UNSUPPORTED);
3736 QuicPacketHeader header;
3737 header.public_header.connection_id = connection_id_;
3738 header.public_header.reset_flag = false;
3739 header.public_header.version_flag = true;
3740 header.entropy_flag = false;
3741 header.fec_flag = false;
3742 header.packet_sequence_number = 12;
3743 header.fec_group = 0;
3745 QuicFrames frames;
3746 QuicFrame frame(&frame1_);
3747 frames.push_back(frame);
3748 scoped_ptr<QuicPacket> packet(
3749 BuildUnsizedDataPacket(&framer_, header, frames));
3750 scoped_ptr<QuicEncryptedPacket> encrypted(
3751 framer_.EncryptPacket(ENCRYPTION_NONE, 12, *packet));
3753 framer_.set_version(version());
3754 connection_.set_perspective(Perspective::IS_SERVER);
3755 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3756 EXPECT_TRUE(writer_->version_negotiation_packet() != nullptr);
3758 size_t num_versions = arraysize(kSupportedQuicVersions);
3759 ASSERT_EQ(num_versions,
3760 writer_->version_negotiation_packet()->versions.size());
3762 // We expect all versions in kSupportedQuicVersions to be
3763 // included in the packet.
3764 for (size_t i = 0; i < num_versions; ++i) {
3765 EXPECT_EQ(kSupportedQuicVersions[i],
3766 writer_->version_negotiation_packet()->versions[i]);
3770 TEST_P(QuicConnectionTest, ServerSendsVersionNegotiationPacketSocketBlocked) {
3771 connection_.SetSupportedVersions(QuicSupportedVersions());
3772 framer_.set_version_for_tests(QUIC_VERSION_UNSUPPORTED);
3774 QuicPacketHeader header;
3775 header.public_header.connection_id = connection_id_;
3776 header.public_header.reset_flag = false;
3777 header.public_header.version_flag = true;
3778 header.entropy_flag = false;
3779 header.fec_flag = false;
3780 header.packet_sequence_number = 12;
3781 header.fec_group = 0;
3783 QuicFrames frames;
3784 QuicFrame frame(&frame1_);
3785 frames.push_back(frame);
3786 scoped_ptr<QuicPacket> packet(
3787 BuildUnsizedDataPacket(&framer_, header, frames));
3788 scoped_ptr<QuicEncryptedPacket> encrypted(
3789 framer_.EncryptPacket(ENCRYPTION_NONE, 12, *packet));
3791 framer_.set_version(version());
3792 connection_.set_perspective(Perspective::IS_SERVER);
3793 BlockOnNextWrite();
3794 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3795 EXPECT_EQ(0u, writer_->last_packet_size());
3796 EXPECT_TRUE(connection_.HasQueuedData());
3798 writer_->SetWritable();
3799 connection_.OnCanWrite();
3800 EXPECT_TRUE(writer_->version_negotiation_packet() != nullptr);
3802 size_t num_versions = arraysize(kSupportedQuicVersions);
3803 ASSERT_EQ(num_versions,
3804 writer_->version_negotiation_packet()->versions.size());
3806 // We expect all versions in kSupportedQuicVersions to be
3807 // included in the packet.
3808 for (size_t i = 0; i < num_versions; ++i) {
3809 EXPECT_EQ(kSupportedQuicVersions[i],
3810 writer_->version_negotiation_packet()->versions[i]);
3814 TEST_P(QuicConnectionTest,
3815 ServerSendsVersionNegotiationPacketSocketBlockedDataBuffered) {
3816 connection_.SetSupportedVersions(QuicSupportedVersions());
3817 framer_.set_version_for_tests(QUIC_VERSION_UNSUPPORTED);
3819 QuicPacketHeader header;
3820 header.public_header.connection_id = connection_id_;
3821 header.public_header.reset_flag = false;
3822 header.public_header.version_flag = true;
3823 header.entropy_flag = false;
3824 header.fec_flag = false;
3825 header.packet_sequence_number = 12;
3826 header.fec_group = 0;
3828 QuicFrames frames;
3829 QuicFrame frame(&frame1_);
3830 frames.push_back(frame);
3831 scoped_ptr<QuicPacket> packet(
3832 BuildUnsizedDataPacket(&framer_, header, frames));
3833 scoped_ptr<QuicEncryptedPacket> encrypted(
3834 framer_.EncryptPacket(ENCRYPTION_NONE, 12, *packet));
3836 framer_.set_version(version());
3837 connection_.set_perspective(Perspective::IS_SERVER);
3838 BlockOnNextWrite();
3839 writer_->set_is_write_blocked_data_buffered(true);
3840 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3841 EXPECT_EQ(0u, writer_->last_packet_size());
3842 EXPECT_FALSE(connection_.HasQueuedData());
3845 TEST_P(QuicConnectionTest, ClientHandlesVersionNegotiation) {
3846 // Start out with some unsupported version.
3847 QuicConnectionPeer::GetFramer(&connection_)->set_version_for_tests(
3848 QUIC_VERSION_UNSUPPORTED);
3850 QuicPacketHeader header;
3851 header.public_header.connection_id = connection_id_;
3852 header.public_header.reset_flag = false;
3853 header.public_header.version_flag = true;
3854 header.entropy_flag = false;
3855 header.fec_flag = false;
3856 header.packet_sequence_number = 12;
3857 header.fec_group = 0;
3859 QuicVersionVector supported_versions;
3860 for (size_t i = 0; i < arraysize(kSupportedQuicVersions); ++i) {
3861 supported_versions.push_back(kSupportedQuicVersions[i]);
3864 // Send a version negotiation packet.
3865 scoped_ptr<QuicEncryptedPacket> encrypted(
3866 framer_.BuildVersionNegotiationPacket(
3867 header.public_header, supported_versions));
3868 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3870 // Now force another packet. The connection should transition into
3871 // NEGOTIATED_VERSION state and tell the packet creator to StopSendingVersion.
3872 header.public_header.version_flag = false;
3873 QuicFrames frames;
3874 QuicFrame frame(&frame1_);
3875 frames.push_back(frame);
3876 scoped_ptr<QuicPacket> packet(
3877 BuildUnsizedDataPacket(&framer_, header, frames));
3878 encrypted.reset(framer_.EncryptPacket(ENCRYPTION_NONE, 12, *packet));
3879 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
3880 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3881 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3883 ASSERT_FALSE(QuicPacketCreatorPeer::SendVersionInPacket(creator_));
3886 TEST_P(QuicConnectionTest, BadVersionNegotiation) {
3887 QuicPacketHeader header;
3888 header.public_header.connection_id = connection_id_;
3889 header.public_header.reset_flag = false;
3890 header.public_header.version_flag = true;
3891 header.entropy_flag = false;
3892 header.fec_flag = false;
3893 header.packet_sequence_number = 12;
3894 header.fec_group = 0;
3896 QuicVersionVector supported_versions;
3897 for (size_t i = 0; i < arraysize(kSupportedQuicVersions); ++i) {
3898 supported_versions.push_back(kSupportedQuicVersions[i]);
3901 // Send a version negotiation packet with the version the client started with.
3902 // It should be rejected.
3903 EXPECT_CALL(visitor_,
3904 OnConnectionClosed(QUIC_INVALID_VERSION_NEGOTIATION_PACKET,
3905 false));
3906 scoped_ptr<QuicEncryptedPacket> encrypted(
3907 framer_.BuildVersionNegotiationPacket(
3908 header.public_header, supported_versions));
3909 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3912 TEST_P(QuicConnectionTest, CheckSendStats) {
3913 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3914 connection_.SendStreamDataWithString(3, "first", 0, !kFin, nullptr);
3915 size_t first_packet_size = writer_->last_packet_size();
3917 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3918 connection_.SendStreamDataWithString(5, "second", 0, !kFin, nullptr);
3919 size_t second_packet_size = writer_->last_packet_size();
3921 // 2 retransmissions due to rto, 1 due to explicit nack.
3922 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
3923 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
3925 // Retransmit due to RTO.
3926 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
3927 connection_.GetRetransmissionAlarm()->Fire();
3929 // Retransmit due to explicit nacks.
3930 QuicAckFrame nack_three = InitAckFrame(4);
3931 NackPacket(3, &nack_three);
3932 NackPacket(1, &nack_three);
3933 SequenceNumberSet lost_packets;
3934 lost_packets.insert(1);
3935 lost_packets.insert(3);
3936 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3937 .WillOnce(Return(lost_packets));
3938 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3939 EXPECT_CALL(visitor_, OnCanWrite()).Times(2);
3940 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3941 ProcessAckPacket(&nack_three);
3943 EXPECT_CALL(*send_algorithm_, BandwidthEstimate()).WillOnce(
3944 Return(QuicBandwidth::Zero()));
3946 const QuicConnectionStats& stats = connection_.GetStats();
3947 EXPECT_EQ(3 * first_packet_size + 2 * second_packet_size - kQuicVersionSize,
3948 stats.bytes_sent);
3949 EXPECT_EQ(5u, stats.packets_sent);
3950 EXPECT_EQ(2 * first_packet_size + second_packet_size - kQuicVersionSize,
3951 stats.bytes_retransmitted);
3952 EXPECT_EQ(3u, stats.packets_retransmitted);
3953 EXPECT_EQ(1u, stats.rto_count);
3954 EXPECT_EQ(kDefaultMaxPacketSize, stats.max_packet_size);
3957 TEST_P(QuicConnectionTest, CheckReceiveStats) {
3958 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3960 size_t received_bytes = 0;
3961 received_bytes += ProcessFecProtectedPacket(1, false, !kEntropyFlag);
3962 received_bytes += ProcessFecProtectedPacket(3, false, !kEntropyFlag);
3963 // Should be counted against dropped packets.
3964 received_bytes += ProcessDataPacket(3, 1, !kEntropyFlag);
3965 received_bytes += ProcessFecPacket(4, 1, true, !kEntropyFlag, nullptr);
3967 EXPECT_CALL(*send_algorithm_, BandwidthEstimate()).WillOnce(
3968 Return(QuicBandwidth::Zero()));
3970 const QuicConnectionStats& stats = connection_.GetStats();
3971 EXPECT_EQ(received_bytes, stats.bytes_received);
3972 EXPECT_EQ(4u, stats.packets_received);
3974 EXPECT_EQ(1u, stats.packets_revived);
3975 EXPECT_EQ(1u, stats.packets_dropped);
3978 TEST_P(QuicConnectionTest, TestFecGroupLimits) {
3979 // Create and return a group for 1.
3980 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 1) != nullptr);
3982 // Create and return a group for 2.
3983 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 2) != nullptr);
3985 // Create and return a group for 4. This should remove 1 but not 2.
3986 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 4) != nullptr);
3987 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 1) == nullptr);
3988 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 2) != nullptr);
3990 // Create and return a group for 3. This will kill off 2.
3991 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 3) != nullptr);
3992 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 2) == nullptr);
3994 // Verify that adding 5 kills off 3, despite 4 being created before 3.
3995 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 5) != nullptr);
3996 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 4) != nullptr);
3997 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 3) == nullptr);
4000 TEST_P(QuicConnectionTest, ProcessFramesIfPacketClosedConnection) {
4001 // Construct a packet with stream frame and connection close frame.
4002 header_.public_header.connection_id = connection_id_;
4003 header_.packet_sequence_number = 1;
4004 header_.public_header.reset_flag = false;
4005 header_.public_header.version_flag = false;
4006 header_.entropy_flag = false;
4007 header_.fec_flag = false;
4008 header_.fec_group = 0;
4010 QuicConnectionCloseFrame qccf;
4011 qccf.error_code = QUIC_PEER_GOING_AWAY;
4012 QuicFrame close_frame(&qccf);
4013 QuicFrame stream_frame(&frame1_);
4015 QuicFrames frames;
4016 frames.push_back(stream_frame);
4017 frames.push_back(close_frame);
4018 scoped_ptr<QuicPacket> packet(
4019 BuildUnsizedDataPacket(&framer_, header_, frames));
4020 EXPECT_TRUE(nullptr != packet.get());
4021 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPacket(
4022 ENCRYPTION_NONE, 1, *packet));
4024 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, true));
4025 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
4026 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4028 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
4031 TEST_P(QuicConnectionTest, SelectMutualVersion) {
4032 connection_.SetSupportedVersions(QuicSupportedVersions());
4033 // Set the connection to speak the lowest quic version.
4034 connection_.set_version(QuicVersionMin());
4035 EXPECT_EQ(QuicVersionMin(), connection_.version());
4037 // Pass in available versions which includes a higher mutually supported
4038 // version. The higher mutually supported version should be selected.
4039 QuicVersionVector supported_versions;
4040 for (size_t i = 0; i < arraysize(kSupportedQuicVersions); ++i) {
4041 supported_versions.push_back(kSupportedQuicVersions[i]);
4043 EXPECT_TRUE(connection_.SelectMutualVersion(supported_versions));
4044 EXPECT_EQ(QuicVersionMax(), connection_.version());
4046 // Expect that the lowest version is selected.
4047 // Ensure the lowest supported version is less than the max, unless they're
4048 // the same.
4049 EXPECT_LE(QuicVersionMin(), QuicVersionMax());
4050 QuicVersionVector lowest_version_vector;
4051 lowest_version_vector.push_back(QuicVersionMin());
4052 EXPECT_TRUE(connection_.SelectMutualVersion(lowest_version_vector));
4053 EXPECT_EQ(QuicVersionMin(), connection_.version());
4055 // Shouldn't be able to find a mutually supported version.
4056 QuicVersionVector unsupported_version;
4057 unsupported_version.push_back(QUIC_VERSION_UNSUPPORTED);
4058 EXPECT_FALSE(connection_.SelectMutualVersion(unsupported_version));
4061 TEST_P(QuicConnectionTest, ConnectionCloseWhenWritable) {
4062 EXPECT_FALSE(writer_->IsWriteBlocked());
4064 // Send a packet.
4065 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
4066 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4067 EXPECT_EQ(1u, writer_->packets_write_attempts());
4069 TriggerConnectionClose();
4070 EXPECT_EQ(2u, writer_->packets_write_attempts());
4073 TEST_P(QuicConnectionTest, ConnectionCloseGettingWriteBlocked) {
4074 BlockOnNextWrite();
4075 TriggerConnectionClose();
4076 EXPECT_EQ(1u, writer_->packets_write_attempts());
4077 EXPECT_TRUE(writer_->IsWriteBlocked());
4080 TEST_P(QuicConnectionTest, ConnectionCloseWhenWriteBlocked) {
4081 BlockOnNextWrite();
4082 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
4083 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4084 EXPECT_EQ(1u, writer_->packets_write_attempts());
4085 EXPECT_TRUE(writer_->IsWriteBlocked());
4086 TriggerConnectionClose();
4087 EXPECT_EQ(1u, writer_->packets_write_attempts());
4090 TEST_P(QuicConnectionTest, AckNotifierTriggerCallback) {
4091 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4093 // Create a delegate which we expect to be called.
4094 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4095 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(1);
4097 // Send some data, which will register the delegate to be notified.
4098 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
4100 // Process an ACK from the server which should trigger the callback.
4101 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4102 QuicAckFrame frame = InitAckFrame(1);
4103 ProcessAckPacket(&frame);
4106 TEST_P(QuicConnectionTest, AckNotifierFailToTriggerCallback) {
4107 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4109 // Create a delegate which we don't expect to be called.
4110 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4111 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(0);
4113 // Send some data, which will register the delegate to be notified. This will
4114 // not be ACKed and so the delegate should never be called.
4115 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
4117 // Send some other data which we will ACK.
4118 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
4119 connection_.SendStreamDataWithString(1, "bar", 0, !kFin, nullptr);
4121 // Now we receive ACK for packets 2 and 3, but importantly missing packet 1
4122 // which we registered to be notified about.
4123 QuicAckFrame frame = InitAckFrame(3);
4124 NackPacket(1, &frame);
4125 SequenceNumberSet lost_packets;
4126 lost_packets.insert(1);
4127 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4128 .WillOnce(Return(lost_packets));
4129 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4130 ProcessAckPacket(&frame);
4133 TEST_P(QuicConnectionTest, AckNotifierCallbackAfterRetransmission) {
4134 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4136 // Create a delegate which we expect to be called.
4137 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4138 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(1);
4140 // Send four packets, and register to be notified on ACK of packet 2.
4141 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
4142 connection_.SendStreamDataWithString(3, "bar", 0, !kFin, delegate.get());
4143 connection_.SendStreamDataWithString(3, "baz", 0, !kFin, nullptr);
4144 connection_.SendStreamDataWithString(3, "qux", 0, !kFin, nullptr);
4146 // Now we receive ACK for packets 1, 3, and 4 and lose 2.
4147 QuicAckFrame frame = InitAckFrame(4);
4148 NackPacket(2, &frame);
4149 SequenceNumberSet lost_packets;
4150 lost_packets.insert(2);
4151 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4152 .WillOnce(Return(lost_packets));
4153 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4154 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4155 ProcessAckPacket(&frame);
4157 // Now we get an ACK for packet 5 (retransmitted packet 2), which should
4158 // trigger the callback.
4159 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4160 .WillRepeatedly(Return(SequenceNumberSet()));
4161 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4162 QuicAckFrame second_ack_frame = InitAckFrame(5);
4163 ProcessAckPacket(&second_ack_frame);
4166 // AckNotifierCallback is triggered by the ack of a packet that timed
4167 // out and was retransmitted, even though the retransmission has a
4168 // different sequence number.
4169 TEST_P(QuicConnectionTest, AckNotifierCallbackForAckAfterRTO) {
4170 InSequence s;
4172 // Create a delegate which we expect to be called.
4173 scoped_refptr<MockAckNotifierDelegate> delegate(
4174 new StrictMock<MockAckNotifierDelegate>);
4176 QuicTime default_retransmission_time = clock_.ApproximateNow().Add(
4177 DefaultRetransmissionTime());
4178 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, delegate.get());
4179 EXPECT_EQ(1u, stop_waiting()->least_unacked);
4181 EXPECT_EQ(1u, writer_->header().packet_sequence_number);
4182 EXPECT_EQ(default_retransmission_time,
4183 connection_.GetRetransmissionAlarm()->deadline());
4184 // Simulate the retransmission alarm firing.
4185 clock_.AdvanceTime(DefaultRetransmissionTime());
4186 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 2u, _, _));
4187 connection_.GetRetransmissionAlarm()->Fire();
4188 EXPECT_EQ(2u, writer_->header().packet_sequence_number);
4189 // We do not raise the high water mark yet.
4190 EXPECT_EQ(1u, stop_waiting()->least_unacked);
4192 // Ack the original packet, which will revert the RTO.
4193 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4194 EXPECT_CALL(*delegate, OnAckNotification(1, _, _));
4195 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4196 QuicAckFrame ack_frame = InitAckFrame(1);
4197 ProcessAckPacket(&ack_frame);
4199 // Delegate is not notified again when the retransmit is acked.
4200 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4201 QuicAckFrame second_ack_frame = InitAckFrame(2);
4202 ProcessAckPacket(&second_ack_frame);
4205 // AckNotifierCallback is triggered by the ack of a packet that was
4206 // previously nacked, even though the retransmission has a different
4207 // sequence number.
4208 TEST_P(QuicConnectionTest, AckNotifierCallbackForAckOfNackedPacket) {
4209 InSequence s;
4211 // Create a delegate which we expect to be called.
4212 scoped_refptr<MockAckNotifierDelegate> delegate(
4213 new StrictMock<MockAckNotifierDelegate>);
4215 // Send four packets, and register to be notified on ACK of packet 2.
4216 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
4217 connection_.SendStreamDataWithString(3, "bar", 0, !kFin, delegate.get());
4218 connection_.SendStreamDataWithString(3, "baz", 0, !kFin, nullptr);
4219 connection_.SendStreamDataWithString(3, "qux", 0, !kFin, nullptr);
4221 // Now we receive ACK for packets 1, 3, and 4 and lose 2.
4222 QuicAckFrame frame = InitAckFrame(4);
4223 NackPacket(2, &frame);
4224 SequenceNumberSet lost_packets;
4225 lost_packets.insert(2);
4226 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4227 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4228 .WillOnce(Return(lost_packets));
4229 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4230 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4231 ProcessAckPacket(&frame);
4233 // Now we get an ACK for packet 2, which was previously nacked.
4234 SequenceNumberSet no_lost_packets;
4235 EXPECT_CALL(*delegate.get(), OnAckNotification(1, _, _));
4236 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4237 .WillOnce(Return(no_lost_packets));
4238 QuicAckFrame second_ack_frame = InitAckFrame(4);
4239 ProcessAckPacket(&second_ack_frame);
4241 // Verify that the delegate is not notified again when the
4242 // retransmit is acked.
4243 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4244 .WillOnce(Return(no_lost_packets));
4245 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4246 QuicAckFrame third_ack_frame = InitAckFrame(5);
4247 ProcessAckPacket(&third_ack_frame);
4250 TEST_P(QuicConnectionTest, AckNotifierFECTriggerCallback) {
4251 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4253 // Create a delegate which we expect to be called.
4254 scoped_refptr<MockAckNotifierDelegate> delegate(
4255 new MockAckNotifierDelegate);
4256 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(1);
4258 // Send some data, which will register the delegate to be notified.
4259 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
4260 connection_.SendStreamDataWithString(2, "bar", 0, !kFin, nullptr);
4262 // Process an ACK from the server with a revived packet, which should trigger
4263 // the callback.
4264 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4265 QuicAckFrame frame = InitAckFrame(2);
4266 NackPacket(1, &frame);
4267 frame.revived_packets.insert(1);
4268 ProcessAckPacket(&frame);
4269 // If the ack is processed again, the notifier should not be called again.
4270 ProcessAckPacket(&frame);
4273 TEST_P(QuicConnectionTest, AckNotifierCallbackAfterFECRecovery) {
4274 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4275 EXPECT_CALL(visitor_, OnCanWrite());
4277 // Create a delegate which we expect to be called.
4278 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4279 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(1);
4281 // Expect ACKs for 1 packet.
4282 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4284 // Send one packet, and register to be notified on ACK.
4285 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
4287 // Ack packet gets dropped, but we receive an FEC packet that covers it.
4288 // Should recover the Ack packet and trigger the notification callback.
4289 QuicFrames frames;
4291 QuicAckFrame ack_frame = InitAckFrame(1);
4292 frames.push_back(QuicFrame(&ack_frame));
4294 // Dummy stream frame to satisfy expectations set elsewhere.
4295 frames.push_back(QuicFrame(&frame1_));
4297 QuicPacketHeader ack_header;
4298 ack_header.public_header.connection_id = connection_id_;
4299 ack_header.public_header.reset_flag = false;
4300 ack_header.public_header.version_flag = false;
4301 ack_header.entropy_flag = !kEntropyFlag;
4302 ack_header.fec_flag = true;
4303 ack_header.packet_sequence_number = 1;
4304 ack_header.is_in_fec_group = IN_FEC_GROUP;
4305 ack_header.fec_group = 1;
4307 QuicPacket* packet = BuildUnsizedDataPacket(&framer_, ack_header, frames);
4309 // Take the packet which contains the ACK frame, and construct and deliver an
4310 // FEC packet which allows the ACK packet to be recovered.
4311 ProcessFecPacket(2, 1, true, !kEntropyFlag, packet);
4314 TEST_P(QuicConnectionTest, NetworkChangeVisitorCwndCallbackChangesFecState) {
4315 size_t max_packets_per_fec_group = creator_->max_packets_per_fec_group();
4317 QuicSentPacketManager::NetworkChangeVisitor* visitor =
4318 QuicSentPacketManagerPeer::GetNetworkChangeVisitor(manager_);
4319 EXPECT_TRUE(visitor);
4321 // Increase FEC group size by increasing congestion window to a large number.
4322 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
4323 Return(1000 * kDefaultTCPMSS));
4324 visitor->OnCongestionWindowChange();
4325 EXPECT_LT(max_packets_per_fec_group, creator_->max_packets_per_fec_group());
4328 TEST_P(QuicConnectionTest, NetworkChangeVisitorConfigCallbackChangesFecState) {
4329 QuicSentPacketManager::NetworkChangeVisitor* visitor =
4330 QuicSentPacketManagerPeer::GetNetworkChangeVisitor(manager_);
4331 EXPECT_TRUE(visitor);
4332 EXPECT_EQ(QuicTime::Delta::Zero(),
4333 QuicPacketGeneratorPeer::GetFecTimeout(generator_));
4335 // Verify that sending a config with a new initial rtt changes fec timeout.
4336 // Create and process a config with a non-zero initial RTT.
4337 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4338 QuicConfig config;
4339 config.SetInitialRoundTripTimeUsToSend(300000);
4340 connection_.SetFromConfig(config);
4341 EXPECT_LT(QuicTime::Delta::Zero(),
4342 QuicPacketGeneratorPeer::GetFecTimeout(generator_));
4345 TEST_P(QuicConnectionTest, NetworkChangeVisitorRttCallbackChangesFecState) {
4346 // Verify that sending a config with a new initial rtt changes fec timeout.
4347 QuicSentPacketManager::NetworkChangeVisitor* visitor =
4348 QuicSentPacketManagerPeer::GetNetworkChangeVisitor(manager_);
4349 EXPECT_TRUE(visitor);
4350 EXPECT_EQ(QuicTime::Delta::Zero(),
4351 QuicPacketGeneratorPeer::GetFecTimeout(generator_));
4353 // Increase FEC timeout by increasing RTT.
4354 RttStats* rtt_stats = QuicSentPacketManagerPeer::GetRttStats(manager_);
4355 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(300),
4356 QuicTime::Delta::Zero(), QuicTime::Zero());
4357 visitor->OnRttChange();
4358 EXPECT_LT(QuicTime::Delta::Zero(),
4359 QuicPacketGeneratorPeer::GetFecTimeout(generator_));
4362 TEST_P(QuicConnectionTest, OnPacketHeaderDebugVisitor) {
4363 QuicPacketHeader header;
4365 scoped_ptr<MockQuicConnectionDebugVisitor> debug_visitor(
4366 new MockQuicConnectionDebugVisitor());
4367 connection_.set_debug_visitor(debug_visitor.get());
4368 EXPECT_CALL(*debug_visitor, OnPacketHeader(Ref(header))).Times(1);
4369 connection_.OnPacketHeader(header);
4372 TEST_P(QuicConnectionTest, Pacing) {
4373 TestConnection server(connection_id_, IPEndPoint(), helper_.get(), factory_,
4374 Perspective::IS_SERVER, version());
4375 TestConnection client(connection_id_, IPEndPoint(), helper_.get(), factory_,
4376 Perspective::IS_CLIENT, version());
4377 EXPECT_FALSE(client.sent_packet_manager().using_pacing());
4378 EXPECT_FALSE(server.sent_packet_manager().using_pacing());
4381 TEST_P(QuicConnectionTest, ControlFramesInstigateAcks) {
4382 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4384 // Send a WINDOW_UPDATE frame.
4385 QuicWindowUpdateFrame window_update;
4386 window_update.stream_id = 3;
4387 window_update.byte_offset = 1234;
4388 EXPECT_CALL(visitor_, OnWindowUpdateFrames(_));
4389 ProcessFramePacket(QuicFrame(&window_update));
4391 // Ensure that this has caused the ACK alarm to be set.
4392 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
4393 EXPECT_TRUE(ack_alarm->IsSet());
4395 // Cancel alarm, and try again with BLOCKED frame.
4396 ack_alarm->Cancel();
4397 QuicBlockedFrame blocked;
4398 blocked.stream_id = 3;
4399 EXPECT_CALL(visitor_, OnBlockedFrames(_));
4400 ProcessFramePacket(QuicFrame(&blocked));
4401 EXPECT_TRUE(ack_alarm->IsSet());
4404 TEST_P(QuicConnectionTest, NoDataNoFin) {
4405 // Make sure that a call to SendStreamWithData, with no data and no FIN, does
4406 // not result in a QuicAckNotifier being used-after-free (fail under ASAN).
4407 // Regression test for b/18594622
4408 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4409 EXPECT_DFATAL(
4410 connection_.SendStreamDataWithString(3, "", 0, !kFin, delegate.get()),
4411 "Attempt to send empty stream frame");
4414 } // namespace
4415 } // namespace test
4416 } // namespace net