ozone: evdev: Sync caps lock LED state to evdev
[chromium-blink-merge.git] / net / quic / quic_connection_test.cc
blobc23ea738605849b373b603165be9919babe85b80
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<QuicStreamFrame>& stream_frames() const {
315 return framer_.stream_frames();
318 const vector<QuicPingFrame>& ping_frames() const {
319 return framer_.ping_frames();
322 size_t last_packet_size() {
323 return last_packet_size_;
326 const QuicVersionNegotiationPacket* version_negotiation_packet() {
327 return framer_.version_negotiation_packet();
330 void set_is_write_blocked_data_buffered(bool buffered) {
331 is_write_blocked_data_buffered_ = buffered;
334 void set_is_server(bool is_server) {
335 // We invert is_server here, because the framer needs to parse packets
336 // we send.
337 QuicFramerPeer::SetIsServer(framer_.framer(), !is_server);
340 // final_bytes_of_last_packet_ returns the last four bytes of the previous
341 // packet as a little-endian, uint32. This is intended to be used with a
342 // TaggingEncrypter so that tests can determine which encrypter was used for
343 // a given packet.
344 uint32 final_bytes_of_last_packet() { return final_bytes_of_last_packet_; }
346 // Returns the final bytes of the second to last packet.
347 uint32 final_bytes_of_previous_packet() {
348 return final_bytes_of_previous_packet_;
351 void use_tagging_decrypter() {
352 use_tagging_decrypter_ = true;
355 uint32 packets_write_attempts() { return packets_write_attempts_; }
357 void Reset() { framer_.Reset(); }
359 void SetSupportedVersions(const QuicVersionVector& versions) {
360 framer_.SetSupportedVersions(versions);
363 private:
364 QuicVersion version_;
365 SimpleQuicFramer framer_;
366 size_t last_packet_size_;
367 bool write_blocked_;
368 bool block_on_next_write_;
369 bool is_write_blocked_data_buffered_;
370 uint32 final_bytes_of_last_packet_;
371 uint32 final_bytes_of_previous_packet_;
372 bool use_tagging_decrypter_;
373 uint32 packets_write_attempts_;
374 MockClock *clock_;
375 // If non-zero, the clock will pause during WritePacket for this amount of
376 // time.
377 QuicTime::Delta write_pause_time_delta_;
379 DISALLOW_COPY_AND_ASSIGN(TestPacketWriter);
382 class TestConnection : public QuicConnection {
383 public:
384 TestConnection(QuicConnectionId connection_id,
385 IPEndPoint address,
386 TestConnectionHelper* helper,
387 const PacketWriterFactory& factory,
388 bool is_server,
389 QuicVersion version)
390 : QuicConnection(connection_id,
391 address,
392 helper,
393 factory,
394 /* owns_writer= */ false,
395 is_server,
396 /* is_secure= */ false,
397 SupportedVersions(version)) {
398 // Disable tail loss probes for most tests.
399 QuicSentPacketManagerPeer::SetMaxTailLossProbes(
400 QuicConnectionPeer::GetSentPacketManager(this), 0);
401 writer()->set_is_server(is_server);
404 void SendAck() {
405 QuicConnectionPeer::SendAck(this);
408 void SetSendAlgorithm(SendAlgorithmInterface* send_algorithm) {
409 QuicConnectionPeer::SetSendAlgorithm(this, send_algorithm);
412 void SetLossAlgorithm(LossDetectionInterface* loss_algorithm) {
413 QuicSentPacketManagerPeer::SetLossAlgorithm(
414 QuicConnectionPeer::GetSentPacketManager(this), loss_algorithm);
417 void SendPacket(EncryptionLevel level,
418 QuicPacketSequenceNumber sequence_number,
419 QuicPacket* packet,
420 QuicPacketEntropyHash entropy_hash,
421 HasRetransmittableData retransmittable) {
422 RetransmittableFrames* retransmittable_frames =
423 retransmittable == HAS_RETRANSMITTABLE_DATA
424 ? new RetransmittableFrames(ENCRYPTION_NONE)
425 : nullptr;
426 QuicEncryptedPacket* encrypted =
427 QuicConnectionPeer::GetFramer(this)
428 ->EncryptPacket(ENCRYPTION_NONE, sequence_number, *packet);
429 delete packet;
430 OnSerializedPacket(SerializedPacket(sequence_number,
431 PACKET_6BYTE_SEQUENCE_NUMBER, encrypted,
432 entropy_hash, retransmittable_frames));
435 QuicConsumedData SendStreamDataWithString(
436 QuicStreamId id,
437 StringPiece data,
438 QuicStreamOffset offset,
439 bool fin,
440 QuicAckNotifier::DelegateInterface* delegate) {
441 return SendStreamDataWithStringHelper(id, data, offset, fin,
442 MAY_FEC_PROTECT, delegate);
445 QuicConsumedData SendStreamDataWithStringWithFec(
446 QuicStreamId id,
447 StringPiece data,
448 QuicStreamOffset offset,
449 bool fin,
450 QuicAckNotifier::DelegateInterface* delegate) {
451 return SendStreamDataWithStringHelper(id, data, offset, fin,
452 MUST_FEC_PROTECT, delegate);
455 QuicConsumedData SendStreamDataWithStringHelper(
456 QuicStreamId id,
457 StringPiece data,
458 QuicStreamOffset offset,
459 bool fin,
460 FecProtection fec_protection,
461 QuicAckNotifier::DelegateInterface* delegate) {
462 IOVector data_iov;
463 if (!data.empty()) {
464 data_iov.Append(const_cast<char*>(data.data()), data.size());
466 return QuicConnection::SendStreamData(id, data_iov, offset, fin,
467 fec_protection, delegate);
470 QuicConsumedData SendStreamData3() {
471 return SendStreamDataWithString(kClientDataStreamId1, "food", 0, !kFin,
472 nullptr);
475 QuicConsumedData SendStreamData3WithFec() {
476 return SendStreamDataWithStringWithFec(kClientDataStreamId1, "food", 0,
477 !kFin, nullptr);
480 QuicConsumedData SendStreamData5() {
481 return SendStreamDataWithString(kClientDataStreamId2, "food2", 0, !kFin,
482 nullptr);
485 QuicConsumedData SendStreamData5WithFec() {
486 return SendStreamDataWithStringWithFec(kClientDataStreamId2, "food2", 0,
487 !kFin, nullptr);
489 // Ensures the connection can write stream data before writing.
490 QuicConsumedData EnsureWritableAndSendStreamData5() {
491 EXPECT_TRUE(CanWriteStreamData());
492 return SendStreamData5();
495 // The crypto stream has special semantics so that it is not blocked by a
496 // congestion window limitation, and also so that it gets put into a separate
497 // packet (so that it is easier to reason about a crypto frame not being
498 // split needlessly across packet boundaries). As a result, we have separate
499 // tests for some cases for this stream.
500 QuicConsumedData SendCryptoStreamData() {
501 return SendStreamDataWithString(kCryptoStreamId, "chlo", 0, !kFin, nullptr);
504 bool is_server() {
505 return QuicConnectionPeer::IsServer(this);
508 void set_version(QuicVersion version) {
509 QuicConnectionPeer::GetFramer(this)->set_version(version);
512 void SetSupportedVersions(const QuicVersionVector& versions) {
513 QuicConnectionPeer::GetFramer(this)->SetSupportedVersions(versions);
514 writer()->SetSupportedVersions(versions);
517 void set_is_server(bool is_server) {
518 writer()->set_is_server(is_server);
519 QuicConnectionPeer::SetIsServer(this, is_server);
522 TestConnectionHelper::TestAlarm* GetAckAlarm() {
523 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
524 QuicConnectionPeer::GetAckAlarm(this));
527 TestConnectionHelper::TestAlarm* GetPingAlarm() {
528 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
529 QuicConnectionPeer::GetPingAlarm(this));
532 TestConnectionHelper::TestAlarm* GetFecAlarm() {
533 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
534 QuicConnectionPeer::GetFecAlarm(this));
537 TestConnectionHelper::TestAlarm* GetResumeWritesAlarm() {
538 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
539 QuicConnectionPeer::GetResumeWritesAlarm(this));
542 TestConnectionHelper::TestAlarm* GetRetransmissionAlarm() {
543 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
544 QuicConnectionPeer::GetRetransmissionAlarm(this));
547 TestConnectionHelper::TestAlarm* GetSendAlarm() {
548 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
549 QuicConnectionPeer::GetSendAlarm(this));
552 TestConnectionHelper::TestAlarm* GetTimeoutAlarm() {
553 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
554 QuicConnectionPeer::GetTimeoutAlarm(this));
557 using QuicConnection::SelectMutualVersion;
559 private:
560 TestPacketWriter* writer() {
561 return static_cast<TestPacketWriter*>(QuicConnection::writer());
564 DISALLOW_COPY_AND_ASSIGN(TestConnection);
567 // Used for testing packets revived from FEC packets.
568 class FecQuicConnectionDebugVisitor
569 : public QuicConnectionDebugVisitor {
570 public:
571 void OnRevivedPacket(const QuicPacketHeader& header,
572 StringPiece data) override {
573 revived_header_ = header;
576 // Public accessor method.
577 QuicPacketHeader revived_header() const {
578 return revived_header_;
581 private:
582 QuicPacketHeader revived_header_;
585 class MockPacketWriterFactory : public QuicConnection::PacketWriterFactory {
586 public:
587 explicit MockPacketWriterFactory(QuicPacketWriter* writer) {
588 ON_CALL(*this, Create(_)).WillByDefault(Return(writer));
590 ~MockPacketWriterFactory() override {}
592 MOCK_CONST_METHOD1(Create, QuicPacketWriter*(QuicConnection* connection));
595 class QuicConnectionTest : public ::testing::TestWithParam<QuicVersion> {
596 protected:
597 QuicConnectionTest()
598 : connection_id_(42),
599 framer_(SupportedVersions(version()), QuicTime::Zero(), false),
600 peer_creator_(connection_id_, &framer_, &random_generator_),
601 send_algorithm_(new StrictMock<MockSendAlgorithm>),
602 loss_algorithm_(new MockLossAlgorithm()),
603 helper_(new TestConnectionHelper(&clock_, &random_generator_)),
604 writer_(new TestPacketWriter(version(), &clock_)),
605 factory_(writer_.get()),
606 connection_(connection_id_,
607 IPEndPoint(),
608 helper_.get(),
609 factory_,
610 false,
611 version()),
612 creator_(QuicConnectionPeer::GetPacketCreator(&connection_)),
613 generator_(QuicConnectionPeer::GetPacketGenerator(&connection_)),
614 manager_(QuicConnectionPeer::GetSentPacketManager(&connection_)),
615 frame1_(1, false, 0, MakeIOVector(data1)),
616 frame2_(1, false, 3, MakeIOVector(data2)),
617 sequence_number_length_(PACKET_6BYTE_SEQUENCE_NUMBER),
618 connection_id_length_(PACKET_8BYTE_CONNECTION_ID) {
619 connection_.set_visitor(&visitor_);
620 connection_.SetSendAlgorithm(send_algorithm_);
621 connection_.SetLossAlgorithm(loss_algorithm_);
622 framer_.set_received_entropy_calculator(&entropy_calculator_);
623 EXPECT_CALL(
624 *send_algorithm_, TimeUntilSend(_, _, _)).WillRepeatedly(Return(
625 QuicTime::Delta::Zero()));
626 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
627 .Times(AnyNumber());
628 EXPECT_CALL(*send_algorithm_, RetransmissionDelay()).WillRepeatedly(
629 Return(QuicTime::Delta::Zero()));
630 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
631 Return(kMaxPacketSize));
632 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
633 .WillByDefault(Return(true));
634 EXPECT_CALL(*send_algorithm_, HasReliableBandwidthEstimate())
635 .Times(AnyNumber());
636 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
637 .Times(AnyNumber())
638 .WillRepeatedly(Return(QuicBandwidth::Zero()));
639 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
640 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
641 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).Times(AnyNumber());
642 EXPECT_CALL(visitor_, HasPendingHandshake()).Times(AnyNumber());
643 EXPECT_CALL(visitor_, OnCanWrite()).Times(AnyNumber());
644 EXPECT_CALL(visitor_, HasOpenDataStreams()).WillRepeatedly(Return(false));
645 EXPECT_CALL(visitor_, OnCongestionWindowChange(_)).Times(AnyNumber());
647 EXPECT_CALL(*loss_algorithm_, GetLossTimeout())
648 .WillRepeatedly(Return(QuicTime::Zero()));
649 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
650 .WillRepeatedly(Return(SequenceNumberSet()));
653 QuicVersion version() {
654 return GetParam();
657 QuicAckFrame* outgoing_ack() {
658 QuicConnectionPeer::PopulateAckFrame(&connection_, &ack_);
659 return &ack_;
662 QuicStopWaitingFrame* stop_waiting() {
663 QuicConnectionPeer::PopulateStopWaitingFrame(&connection_, &stop_waiting_);
664 return &stop_waiting_;
667 QuicPacketSequenceNumber least_unacked() {
668 if (writer_->stop_waiting_frames().empty()) {
669 return 0;
671 return writer_->stop_waiting_frames()[0].least_unacked;
674 void use_tagging_decrypter() {
675 writer_->use_tagging_decrypter();
678 void ProcessPacket(QuicPacketSequenceNumber number) {
679 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
680 ProcessDataPacket(number, 0, !kEntropyFlag);
683 QuicPacketEntropyHash ProcessFramePacket(QuicFrame frame) {
684 QuicFrames frames;
685 frames.push_back(QuicFrame(frame));
686 QuicPacketCreatorPeer::SetSendVersionInPacket(&peer_creator_,
687 connection_.is_server());
688 SerializedPacket serialized_packet =
689 peer_creator_.SerializeAllFrames(frames);
690 scoped_ptr<QuicEncryptedPacket> encrypted(serialized_packet.packet);
691 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
692 return serialized_packet.entropy_hash;
695 size_t ProcessDataPacket(QuicPacketSequenceNumber number,
696 QuicFecGroupNumber fec_group,
697 bool entropy_flag) {
698 return ProcessDataPacketAtLevel(number, fec_group, entropy_flag,
699 ENCRYPTION_NONE);
702 size_t ProcessDataPacketAtLevel(QuicPacketSequenceNumber number,
703 QuicFecGroupNumber fec_group,
704 bool entropy_flag,
705 EncryptionLevel level) {
706 scoped_ptr<QuicPacket> packet(ConstructDataPacket(number, fec_group,
707 entropy_flag));
708 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPacket(
709 level, number, *packet));
710 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
711 return encrypted->length();
714 void ProcessClosePacket(QuicPacketSequenceNumber number,
715 QuicFecGroupNumber fec_group) {
716 scoped_ptr<QuicPacket> packet(ConstructClosePacket(number, fec_group));
717 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPacket(
718 ENCRYPTION_NONE, number, *packet));
719 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
722 size_t ProcessFecProtectedPacket(QuicPacketSequenceNumber number,
723 bool expect_revival, bool entropy_flag) {
724 if (expect_revival) {
725 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
727 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1).
728 RetiresOnSaturation();
729 return ProcessDataPacket(number, 1, entropy_flag);
732 // Processes an FEC packet that covers the packets that would have been
733 // received.
734 size_t ProcessFecPacket(QuicPacketSequenceNumber number,
735 QuicPacketSequenceNumber min_protected_packet,
736 bool expect_revival,
737 bool entropy_flag,
738 QuicPacket* packet) {
739 if (expect_revival) {
740 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
743 // Construct the decrypted data packet so we can compute the correct
744 // redundancy. If |packet| has been provided then use that, otherwise
745 // construct a default data packet.
746 scoped_ptr<QuicPacket> data_packet;
747 if (packet) {
748 data_packet.reset(packet);
749 } else {
750 data_packet.reset(ConstructDataPacket(number, 1, !kEntropyFlag));
753 header_.public_header.connection_id = connection_id_;
754 header_.public_header.reset_flag = false;
755 header_.public_header.version_flag = false;
756 header_.public_header.sequence_number_length = sequence_number_length_;
757 header_.public_header.connection_id_length = connection_id_length_;
758 header_.packet_sequence_number = number;
759 header_.entropy_flag = entropy_flag;
760 header_.fec_flag = true;
761 header_.is_in_fec_group = IN_FEC_GROUP;
762 header_.fec_group = min_protected_packet;
763 QuicFecData fec_data;
764 fec_data.fec_group = header_.fec_group;
766 // Since all data packets in this test have the same payload, the
767 // redundancy is either equal to that payload or the xor of that payload
768 // with itself, depending on the number of packets.
769 if (((number - min_protected_packet) % 2) == 0) {
770 for (size_t i = GetStartOfFecProtectedData(
771 header_.public_header.connection_id_length,
772 header_.public_header.version_flag,
773 header_.public_header.sequence_number_length);
774 i < data_packet->length(); ++i) {
775 data_packet->mutable_data()[i] ^= data_packet->data()[i];
778 fec_data.redundancy = data_packet->FecProtectedData();
780 scoped_ptr<QuicPacket> fec_packet(
781 framer_.BuildFecPacket(header_, fec_data));
782 scoped_ptr<QuicEncryptedPacket> encrypted(
783 framer_.EncryptPacket(ENCRYPTION_NONE, number, *fec_packet));
785 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
786 return encrypted->length();
789 QuicByteCount SendStreamDataToPeer(QuicStreamId id,
790 StringPiece data,
791 QuicStreamOffset offset,
792 bool fin,
793 QuicPacketSequenceNumber* last_packet) {
794 QuicByteCount packet_size;
795 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
796 .WillOnce(DoAll(SaveArg<3>(&packet_size), Return(true)));
797 connection_.SendStreamDataWithString(id, data, offset, fin, nullptr);
798 if (last_packet != nullptr) {
799 *last_packet = creator_->sequence_number();
801 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
802 .Times(AnyNumber());
803 return packet_size;
806 void SendAckPacketToPeer() {
807 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
808 connection_.SendAck();
809 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
810 .Times(AnyNumber());
813 QuicPacketEntropyHash ProcessAckPacket(QuicAckFrame* frame) {
814 return ProcessFramePacket(QuicFrame(frame));
817 QuicPacketEntropyHash ProcessStopWaitingPacket(QuicStopWaitingFrame* frame) {
818 return ProcessFramePacket(QuicFrame(frame));
821 QuicPacketEntropyHash ProcessGoAwayPacket(QuicGoAwayFrame* frame) {
822 return ProcessFramePacket(QuicFrame(frame));
825 bool IsMissing(QuicPacketSequenceNumber number) {
826 return IsAwaitingPacket(*outgoing_ack(), number);
829 QuicPacket* ConstructDataPacket(QuicPacketSequenceNumber number,
830 QuicFecGroupNumber fec_group,
831 bool entropy_flag) {
832 header_.public_header.connection_id = connection_id_;
833 header_.public_header.reset_flag = false;
834 header_.public_header.version_flag = false;
835 header_.public_header.sequence_number_length = sequence_number_length_;
836 header_.public_header.connection_id_length = connection_id_length_;
837 header_.entropy_flag = entropy_flag;
838 header_.fec_flag = false;
839 header_.packet_sequence_number = number;
840 header_.is_in_fec_group = fec_group == 0u ? NOT_IN_FEC_GROUP : IN_FEC_GROUP;
841 header_.fec_group = fec_group;
843 QuicFrames frames;
844 QuicFrame frame(&frame1_);
845 frames.push_back(frame);
846 QuicPacket* packet = BuildUnsizedDataPacket(&framer_, header_, frames);
847 EXPECT_TRUE(packet != nullptr);
848 return packet;
851 QuicPacket* ConstructPingPacket(QuicPacketSequenceNumber number) {
852 header_.public_header.connection_id = connection_id_;
853 header_.packet_sequence_number = number;
854 header_.public_header.reset_flag = false;
855 header_.public_header.version_flag = false;
856 header_.entropy_flag = false;
857 header_.fec_flag = false;
858 header_.is_in_fec_group = NOT_IN_FEC_GROUP;
859 header_.fec_group = 0;
861 QuicPingFrame ping;
863 QuicFrames frames;
864 QuicFrame frame(&ping);
865 frames.push_back(frame);
866 QuicPacket* packet = BuildUnsizedDataPacket(&framer_, header_, frames);
867 EXPECT_TRUE(packet != nullptr);
868 return packet;
871 QuicPacket* ConstructClosePacket(QuicPacketSequenceNumber number,
872 QuicFecGroupNumber fec_group) {
873 header_.public_header.connection_id = connection_id_;
874 header_.packet_sequence_number = number;
875 header_.public_header.reset_flag = false;
876 header_.public_header.version_flag = false;
877 header_.entropy_flag = false;
878 header_.fec_flag = false;
879 header_.is_in_fec_group = fec_group == 0u ? NOT_IN_FEC_GROUP : IN_FEC_GROUP;
880 header_.fec_group = fec_group;
882 QuicConnectionCloseFrame qccf;
883 qccf.error_code = QUIC_PEER_GOING_AWAY;
885 QuicFrames frames;
886 QuicFrame frame(&qccf);
887 frames.push_back(frame);
888 QuicPacket* packet = BuildUnsizedDataPacket(&framer_, header_, frames);
889 EXPECT_TRUE(packet != nullptr);
890 return packet;
893 QuicTime::Delta DefaultRetransmissionTime() {
894 return QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
897 QuicTime::Delta DefaultDelayedAckTime() {
898 return QuicTime::Delta::FromMilliseconds(kMaxDelayedAckTimeMs);
901 // Initialize a frame acknowledging all packets up to largest_observed.
902 const QuicAckFrame InitAckFrame(QuicPacketSequenceNumber largest_observed) {
903 QuicAckFrame frame(MakeAckFrame(largest_observed));
904 if (largest_observed > 0) {
905 frame.entropy_hash =
906 QuicConnectionPeer::GetSentEntropyHash(&connection_,
907 largest_observed);
909 return frame;
912 const QuicStopWaitingFrame InitStopWaitingFrame(
913 QuicPacketSequenceNumber least_unacked) {
914 QuicStopWaitingFrame frame;
915 frame.least_unacked = least_unacked;
916 return frame;
919 // Explicitly nack a packet.
920 void NackPacket(QuicPacketSequenceNumber missing, QuicAckFrame* frame) {
921 frame->missing_packets.insert(missing);
922 frame->entropy_hash ^=
923 QuicConnectionPeer::PacketEntropy(&connection_, missing);
926 // Undo nacking a packet within the frame.
927 void AckPacket(QuicPacketSequenceNumber arrived, QuicAckFrame* frame) {
928 EXPECT_THAT(frame->missing_packets, Contains(arrived));
929 frame->missing_packets.erase(arrived);
930 frame->entropy_hash ^=
931 QuicConnectionPeer::PacketEntropy(&connection_, arrived);
934 void TriggerConnectionClose() {
935 // Send an erroneous packet to close the connection.
936 EXPECT_CALL(visitor_,
937 OnConnectionClosed(QUIC_INVALID_PACKET_HEADER, false));
938 // Call ProcessDataPacket rather than ProcessPacket, as we should not get a
939 // packet call to the visitor.
940 ProcessDataPacket(6000, 0, !kEntropyFlag);
941 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
942 nullptr);
945 void BlockOnNextWrite() {
946 writer_->BlockOnNextWrite();
947 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
950 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
951 writer_->SetWritePauseTimeDelta(delta);
954 void CongestionBlockWrites() {
955 EXPECT_CALL(*send_algorithm_,
956 TimeUntilSend(_, _, _)).WillRepeatedly(
957 testing::Return(QuicTime::Delta::FromSeconds(1)));
960 void CongestionUnblockWrites() {
961 EXPECT_CALL(*send_algorithm_,
962 TimeUntilSend(_, _, _)).WillRepeatedly(
963 testing::Return(QuicTime::Delta::Zero()));
966 QuicConnectionId connection_id_;
967 QuicFramer framer_;
968 QuicPacketCreator peer_creator_;
969 MockEntropyCalculator entropy_calculator_;
971 MockSendAlgorithm* send_algorithm_;
972 MockLossAlgorithm* loss_algorithm_;
973 MockClock clock_;
974 MockRandom random_generator_;
975 scoped_ptr<TestConnectionHelper> helper_;
976 scoped_ptr<TestPacketWriter> writer_;
977 NiceMock<MockPacketWriterFactory> factory_;
978 TestConnection connection_;
979 QuicPacketCreator* creator_;
980 QuicPacketGenerator* generator_;
981 QuicSentPacketManager* manager_;
982 StrictMock<MockConnectionVisitor> visitor_;
984 QuicPacketHeader header_;
985 QuicStreamFrame frame1_;
986 QuicStreamFrame frame2_;
987 QuicAckFrame ack_;
988 QuicStopWaitingFrame stop_waiting_;
989 QuicSequenceNumberLength sequence_number_length_;
990 QuicConnectionIdLength connection_id_length_;
992 private:
993 DISALLOW_COPY_AND_ASSIGN(QuicConnectionTest);
996 // Run all end to end tests with all supported versions.
997 INSTANTIATE_TEST_CASE_P(SupportedVersion,
998 QuicConnectionTest,
999 ::testing::ValuesIn(QuicSupportedVersions()));
1001 TEST_P(QuicConnectionTest, MaxPacketSize) {
1002 EXPECT_FALSE(connection_.is_server());
1003 EXPECT_EQ(1350u, connection_.max_packet_length());
1006 TEST_P(QuicConnectionTest, SmallerServerMaxPacketSize) {
1007 ValueRestore<bool> old_flag(&FLAGS_quic_small_default_packet_size, true);
1008 QuicConnectionId connection_id = 42;
1009 bool kIsServer = true;
1010 TestConnection connection(connection_id, IPEndPoint(), helper_.get(),
1011 factory_, kIsServer, version());
1012 EXPECT_TRUE(connection.is_server());
1013 EXPECT_EQ(1000u, connection.max_packet_length());
1016 TEST_P(QuicConnectionTest, ServerMaxPacketSize) {
1017 ValueRestore<bool> old_flag(&FLAGS_quic_small_default_packet_size, false);
1018 QuicConnectionId connection_id = 42;
1019 bool kIsServer = true;
1020 TestConnection connection(connection_id, IPEndPoint(), helper_.get(),
1021 factory_, kIsServer, version());
1022 EXPECT_TRUE(connection.is_server());
1023 EXPECT_EQ(1350u, connection.max_packet_length());
1026 TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSize) {
1027 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1029 connection_.set_is_server(true);
1030 connection_.set_max_packet_length(1000);
1032 QuicPacketHeader header;
1033 header.public_header.connection_id = connection_id_;
1034 header.public_header.reset_flag = false;
1035 header.public_header.version_flag = true;
1036 header.entropy_flag = false;
1037 header.fec_flag = false;
1038 header.packet_sequence_number = 1;
1039 header.fec_group = 0;
1041 QuicFrames frames;
1042 QuicPaddingFrame padding;
1043 frames.push_back(QuicFrame(&frame1_));
1044 frames.push_back(QuicFrame(&padding));
1046 scoped_ptr<QuicPacket> packet(
1047 BuildUnsizedDataPacket(&framer_, header, frames));
1048 scoped_ptr<QuicEncryptedPacket> encrypted(
1049 framer_.EncryptPacket(ENCRYPTION_NONE, 12, *packet));
1050 EXPECT_EQ(kMaxPacketSize, encrypted->length());
1052 framer_.set_version(version());
1053 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
1054 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
1056 EXPECT_EQ(kMaxPacketSize, connection_.max_packet_length());
1059 TEST_P(QuicConnectionTest, PacketsInOrder) {
1060 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1062 ProcessPacket(1);
1063 EXPECT_EQ(1u, outgoing_ack()->largest_observed);
1064 EXPECT_EQ(0u, outgoing_ack()->missing_packets.size());
1066 ProcessPacket(2);
1067 EXPECT_EQ(2u, outgoing_ack()->largest_observed);
1068 EXPECT_EQ(0u, outgoing_ack()->missing_packets.size());
1070 ProcessPacket(3);
1071 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1072 EXPECT_EQ(0u, outgoing_ack()->missing_packets.size());
1075 TEST_P(QuicConnectionTest, PacketsOutOfOrder) {
1076 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1078 ProcessPacket(3);
1079 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1080 EXPECT_TRUE(IsMissing(2));
1081 EXPECT_TRUE(IsMissing(1));
1083 ProcessPacket(2);
1084 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1085 EXPECT_FALSE(IsMissing(2));
1086 EXPECT_TRUE(IsMissing(1));
1088 ProcessPacket(1);
1089 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1090 EXPECT_FALSE(IsMissing(2));
1091 EXPECT_FALSE(IsMissing(1));
1094 TEST_P(QuicConnectionTest, DuplicatePacket) {
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 // Send packet 3 again, but do not set the expectation that
1103 // the visitor OnStreamFrames() will be called.
1104 ProcessDataPacket(3, 0, !kEntropyFlag);
1105 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1106 EXPECT_TRUE(IsMissing(2));
1107 EXPECT_TRUE(IsMissing(1));
1110 TEST_P(QuicConnectionTest, PacketsOutOfOrderWithAdditionsAndLeastAwaiting) {
1111 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1113 ProcessPacket(3);
1114 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1115 EXPECT_TRUE(IsMissing(2));
1116 EXPECT_TRUE(IsMissing(1));
1118 ProcessPacket(2);
1119 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1120 EXPECT_TRUE(IsMissing(1));
1122 ProcessPacket(5);
1123 EXPECT_EQ(5u, outgoing_ack()->largest_observed);
1124 EXPECT_TRUE(IsMissing(1));
1125 EXPECT_TRUE(IsMissing(4));
1127 // Pretend at this point the client has gotten acks for 2 and 3 and 1 is a
1128 // packet the peer will not retransmit. It indicates this by sending 'least
1129 // awaiting' is 4. The connection should then realize 1 will not be
1130 // retransmitted, and will remove it from the missing list.
1131 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 5);
1132 QuicAckFrame frame = InitAckFrame(1);
1133 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _));
1134 ProcessAckPacket(&frame);
1136 // Force an ack to be sent.
1137 SendAckPacketToPeer();
1138 EXPECT_TRUE(IsMissing(4));
1141 TEST_P(QuicConnectionTest, RejectPacketTooFarOut) {
1142 EXPECT_CALL(visitor_,
1143 OnConnectionClosed(QUIC_INVALID_PACKET_HEADER, false));
1144 // Call ProcessDataPacket rather than ProcessPacket, as we should not get a
1145 // packet call to the visitor.
1146 ProcessDataPacket(6000, 0, !kEntropyFlag);
1147 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1148 nullptr);
1151 TEST_P(QuicConnectionTest, RejectUnencryptedStreamData) {
1152 // Process an unencrypted packet from the non-crypto stream.
1153 frame1_.stream_id = 3;
1154 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1155 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_UNENCRYPTED_STREAM_DATA,
1156 false));
1157 ProcessDataPacket(1, 0, !kEntropyFlag);
1158 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1159 nullptr);
1160 const vector<QuicConnectionCloseFrame>& connection_close_frames =
1161 writer_->connection_close_frames();
1162 EXPECT_EQ(1u, connection_close_frames.size());
1163 EXPECT_EQ(QUIC_UNENCRYPTED_STREAM_DATA,
1164 connection_close_frames[0].error_code);
1167 TEST_P(QuicConnectionTest, TruncatedAck) {
1168 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1169 QuicPacketSequenceNumber num_packets = 256 * 2 + 1;
1170 for (QuicPacketSequenceNumber i = 0; i < num_packets; ++i) {
1171 SendStreamDataToPeer(3, "foo", i * 3, !kFin, nullptr);
1174 QuicAckFrame frame = InitAckFrame(num_packets);
1175 SequenceNumberSet lost_packets;
1176 // Create an ack with 256 nacks, none adjacent to one another.
1177 for (QuicPacketSequenceNumber i = 1; i <= 256; ++i) {
1178 NackPacket(i * 2, &frame);
1179 if (i < 256) { // Last packet is nacked, but not lost.
1180 lost_packets.insert(i * 2);
1183 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1184 .WillOnce(Return(lost_packets));
1185 EXPECT_CALL(entropy_calculator_, EntropyHash(511))
1186 .WillOnce(Return(static_cast<QuicPacketEntropyHash>(0)));
1187 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1188 ProcessAckPacket(&frame);
1190 // A truncated ack will not have the true largest observed.
1191 EXPECT_GT(num_packets, manager_->largest_observed());
1193 AckPacket(192, &frame);
1195 // Removing one missing packet allows us to ack 192 and one more range, but
1196 // 192 has already been declared lost, so it doesn't register as an ack.
1197 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1198 .WillOnce(Return(SequenceNumberSet()));
1199 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1200 ProcessAckPacket(&frame);
1201 EXPECT_EQ(num_packets, manager_->largest_observed());
1204 TEST_P(QuicConnectionTest, AckReceiptCausesAckSendBadEntropy) {
1205 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1207 ProcessPacket(1);
1208 // Delay sending, then queue up an ack.
1209 EXPECT_CALL(*send_algorithm_,
1210 TimeUntilSend(_, _, _)).WillOnce(
1211 testing::Return(QuicTime::Delta::FromMicroseconds(1)));
1212 QuicConnectionPeer::SendAck(&connection_);
1214 // Process an ack with a least unacked of the received ack.
1215 // This causes an ack to be sent when TimeUntilSend returns 0.
1216 EXPECT_CALL(*send_algorithm_,
1217 TimeUntilSend(_, _, _)).WillRepeatedly(
1218 testing::Return(QuicTime::Delta::Zero()));
1219 // Skip a packet and then record an ack.
1220 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 2);
1221 QuicAckFrame frame = InitAckFrame(0);
1222 ProcessAckPacket(&frame);
1225 TEST_P(QuicConnectionTest, OutOfOrderReceiptCausesAckSend) {
1226 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1228 ProcessPacket(3);
1229 // Should ack immediately since we have missing packets.
1230 EXPECT_EQ(1u, writer_->packets_write_attempts());
1232 ProcessPacket(2);
1233 // Should ack immediately since we have missing packets.
1234 EXPECT_EQ(2u, writer_->packets_write_attempts());
1236 ProcessPacket(1);
1237 // Should ack immediately, since this fills the last hole.
1238 EXPECT_EQ(3u, writer_->packets_write_attempts());
1240 ProcessPacket(4);
1241 // Should not cause an ack.
1242 EXPECT_EQ(3u, writer_->packets_write_attempts());
1245 TEST_P(QuicConnectionTest, AckReceiptCausesAckSend) {
1246 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1248 QuicPacketSequenceNumber original;
1249 QuicByteCount packet_size;
1250 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1251 .WillOnce(DoAll(SaveArg<2>(&original), SaveArg<3>(&packet_size),
1252 Return(true)));
1253 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
1254 QuicAckFrame frame = InitAckFrame(original);
1255 NackPacket(original, &frame);
1256 // First nack triggers early retransmit.
1257 SequenceNumberSet lost_packets;
1258 lost_packets.insert(1);
1259 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1260 .WillOnce(Return(lost_packets));
1261 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1262 QuicPacketSequenceNumber retransmission;
1263 EXPECT_CALL(*send_algorithm_,
1264 OnPacketSent(_, _, _, packet_size - kQuicVersionSize, _))
1265 .WillOnce(DoAll(SaveArg<2>(&retransmission), Return(true)));
1267 ProcessAckPacket(&frame);
1269 QuicAckFrame frame2 = InitAckFrame(retransmission);
1270 NackPacket(original, &frame2);
1271 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1272 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1273 .WillOnce(Return(SequenceNumberSet()));
1274 ProcessAckPacket(&frame2);
1276 // Now if the peer sends an ack which still reports the retransmitted packet
1277 // as missing, that will bundle an ack with data after two acks in a row
1278 // indicate the high water mark needs to be raised.
1279 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _,
1280 HAS_RETRANSMITTABLE_DATA));
1281 connection_.SendStreamDataWithString(3, "foo", 3, !kFin, nullptr);
1282 // No ack sent.
1283 EXPECT_EQ(1u, writer_->frame_count());
1284 EXPECT_EQ(1u, writer_->stream_frames().size());
1286 // No more packet loss for the rest of the test.
1287 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1288 .WillRepeatedly(Return(SequenceNumberSet()));
1289 ProcessAckPacket(&frame2);
1290 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _,
1291 HAS_RETRANSMITTABLE_DATA));
1292 connection_.SendStreamDataWithString(3, "foo", 3, !kFin, nullptr);
1293 // Ack bundled.
1294 EXPECT_EQ(3u, writer_->frame_count());
1295 EXPECT_EQ(1u, writer_->stream_frames().size());
1296 EXPECT_FALSE(writer_->ack_frames().empty());
1298 // But an ack with no missing packets will not send an ack.
1299 AckPacket(original, &frame2);
1300 ProcessAckPacket(&frame2);
1301 ProcessAckPacket(&frame2);
1304 TEST_P(QuicConnectionTest, 20AcksCausesAckSend) {
1305 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1307 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr);
1309 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
1310 // But an ack with no missing packets will not send an ack.
1311 QuicAckFrame frame = InitAckFrame(1);
1312 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1313 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1314 .WillRepeatedly(Return(SequenceNumberSet()));
1315 for (int i = 0; i < 20; ++i) {
1316 EXPECT_FALSE(ack_alarm->IsSet());
1317 ProcessAckPacket(&frame);
1319 EXPECT_TRUE(ack_alarm->IsSet());
1322 TEST_P(QuicConnectionTest, LeastUnackedLower) {
1323 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1325 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr);
1326 SendStreamDataToPeer(1, "bar", 3, !kFin, nullptr);
1327 SendStreamDataToPeer(1, "eep", 6, !kFin, nullptr);
1329 // Start out saying the least unacked is 2.
1330 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 5);
1331 QuicStopWaitingFrame frame = InitStopWaitingFrame(2);
1332 ProcessStopWaitingPacket(&frame);
1334 // Change it to 1, but lower the sequence number to fake out-of-order packets.
1335 // This should be fine.
1336 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 1);
1337 // The scheduler will not process out of order acks, but all packet processing
1338 // causes the connection to try to write.
1339 EXPECT_CALL(visitor_, OnCanWrite());
1340 QuicStopWaitingFrame frame2 = InitStopWaitingFrame(1);
1341 ProcessStopWaitingPacket(&frame2);
1343 // Now claim it's one, but set the ordering so it was sent "after" the first
1344 // one. This should cause a connection error.
1345 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
1346 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 7);
1347 EXPECT_CALL(visitor_,
1348 OnConnectionClosed(QUIC_INVALID_STOP_WAITING_DATA, false));
1349 QuicStopWaitingFrame frame3 = InitStopWaitingFrame(1);
1350 ProcessStopWaitingPacket(&frame3);
1353 TEST_P(QuicConnectionTest, TooManySentPackets) {
1354 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1355 const QuicPacketCount num_sent_packets = kMaxTrackedPackets + 100;
1356 for (QuicPacketCount i = 0; i < num_sent_packets; ++i) {
1357 SendStreamDataToPeer(1, "foo", 3 * i, !kFin, nullptr);
1360 // Ack packet 1, which leaves more than the limit outstanding.
1361 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1362 EXPECT_CALL(visitor_, OnConnectionClosed(
1363 QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS, false));
1364 // We're receive buffer limited, so the connection won't try to write more.
1365 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
1367 // Nack every packet except the last one, leaving a huge gap.
1368 QuicAckFrame frame1 = InitAckFrame(num_sent_packets);
1369 for (QuicPacketSequenceNumber i = 1; i < num_sent_packets; ++i) {
1370 NackPacket(i, &frame1);
1372 ProcessAckPacket(&frame1);
1375 TEST_P(QuicConnectionTest, TooManyReceivedPackets) {
1376 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1377 EXPECT_CALL(visitor_, OnConnectionClosed(
1378 QUIC_TOO_MANY_OUTSTANDING_RECEIVED_PACKETS, false));
1380 // Miss every other packet for 5000 packets.
1381 for (QuicPacketSequenceNumber i = 1; i < kMaxTrackedPackets; ++i) {
1382 ProcessPacket(i * 2);
1383 if (!connection_.connected()) {
1384 break;
1389 TEST_P(QuicConnectionTest, LargestObservedLower) {
1390 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1392 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr);
1393 SendStreamDataToPeer(1, "bar", 3, !kFin, nullptr);
1394 SendStreamDataToPeer(1, "eep", 6, !kFin, nullptr);
1395 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1397 // Start out saying the largest observed is 2.
1398 QuicAckFrame frame1 = InitAckFrame(1);
1399 QuicAckFrame frame2 = InitAckFrame(2);
1400 ProcessAckPacket(&frame2);
1402 // Now change it to 1, and it should cause a connection error.
1403 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, false));
1404 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
1405 ProcessAckPacket(&frame1);
1408 TEST_P(QuicConnectionTest, AckUnsentData) {
1409 // Ack a packet which has not been sent.
1410 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, false));
1411 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1412 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
1413 QuicAckFrame frame(MakeAckFrame(1));
1414 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
1415 ProcessAckPacket(&frame);
1418 TEST_P(QuicConnectionTest, AckAll) {
1419 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1420 ProcessPacket(1);
1422 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 1);
1423 QuicAckFrame frame1 = InitAckFrame(0);
1424 ProcessAckPacket(&frame1);
1427 TEST_P(QuicConnectionTest, SendingDifferentSequenceNumberLengthsBandwidth) {
1428 QuicPacketSequenceNumber last_packet;
1429 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet);
1430 EXPECT_EQ(1u, last_packet);
1431 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1432 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1433 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1434 writer_->header().public_header.sequence_number_length);
1436 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
1437 Return(kMaxPacketSize * 256));
1439 SendStreamDataToPeer(1, "bar", 3, !kFin, &last_packet);
1440 EXPECT_EQ(2u, last_packet);
1441 EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER,
1442 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1443 // The 1 packet lag is due to the sequence number length being recalculated in
1444 // QuicConnection after a packet is sent.
1445 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1446 writer_->header().public_header.sequence_number_length);
1448 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
1449 Return(kMaxPacketSize * 256 * 256));
1451 SendStreamDataToPeer(1, "foo", 6, !kFin, &last_packet);
1452 EXPECT_EQ(3u, last_packet);
1453 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1454 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1455 EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER,
1456 writer_->header().public_header.sequence_number_length);
1458 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
1459 Return(kMaxPacketSize * 256 * 256 * 256));
1461 SendStreamDataToPeer(1, "bar", 9, !kFin, &last_packet);
1462 EXPECT_EQ(4u, last_packet);
1463 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1464 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1465 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1466 writer_->header().public_header.sequence_number_length);
1468 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
1469 Return(kMaxPacketSize * 256 * 256 * 256 * 256));
1471 SendStreamDataToPeer(1, "foo", 12, !kFin, &last_packet);
1472 EXPECT_EQ(5u, last_packet);
1473 EXPECT_EQ(PACKET_6BYTE_SEQUENCE_NUMBER,
1474 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1475 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1476 writer_->header().public_header.sequence_number_length);
1479 // TODO(ianswett): Re-enable this test by finding a good way to test different
1480 // sequence number lengths without sending packets with giant gaps.
1481 TEST_P(QuicConnectionTest,
1482 DISABLED_SendingDifferentSequenceNumberLengthsUnackedDelta) {
1483 QuicPacketSequenceNumber last_packet;
1484 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet);
1485 EXPECT_EQ(1u, last_packet);
1486 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1487 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1488 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1489 writer_->header().public_header.sequence_number_length);
1491 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 100);
1493 SendStreamDataToPeer(1, "bar", 3, !kFin, &last_packet);
1494 EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER,
1495 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1496 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1497 writer_->header().public_header.sequence_number_length);
1499 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 100 * 256);
1501 SendStreamDataToPeer(1, "foo", 6, !kFin, &last_packet);
1502 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1503 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1504 EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER,
1505 writer_->header().public_header.sequence_number_length);
1507 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 100 * 256 * 256);
1509 SendStreamDataToPeer(1, "bar", 9, !kFin, &last_packet);
1510 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1511 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1512 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1513 writer_->header().public_header.sequence_number_length);
1515 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_,
1516 100 * 256 * 256 * 256);
1518 SendStreamDataToPeer(1, "foo", 12, !kFin, &last_packet);
1519 EXPECT_EQ(PACKET_6BYTE_SEQUENCE_NUMBER,
1520 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1521 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1522 writer_->header().public_header.sequence_number_length);
1525 TEST_P(QuicConnectionTest, BasicSending) {
1526 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1527 QuicPacketSequenceNumber last_packet;
1528 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet); // Packet 1
1529 EXPECT_EQ(1u, last_packet);
1530 SendAckPacketToPeer(); // Packet 2
1532 EXPECT_EQ(1u, least_unacked());
1534 SendAckPacketToPeer(); // Packet 3
1535 EXPECT_EQ(1u, least_unacked());
1537 SendStreamDataToPeer(1, "bar", 3, !kFin, &last_packet); // Packet 4
1538 EXPECT_EQ(4u, last_packet);
1539 SendAckPacketToPeer(); // Packet 5
1540 EXPECT_EQ(1u, least_unacked());
1542 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1544 // Peer acks up to packet 3.
1545 QuicAckFrame frame = InitAckFrame(3);
1546 ProcessAckPacket(&frame);
1547 SendAckPacketToPeer(); // Packet 6
1549 // As soon as we've acked one, we skip ack packets 2 and 3 and note lack of
1550 // ack for 4.
1551 EXPECT_EQ(4u, least_unacked());
1553 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1555 // Peer acks up to packet 4, the last packet.
1556 QuicAckFrame frame2 = InitAckFrame(6);
1557 ProcessAckPacket(&frame2); // Acks don't instigate acks.
1559 // Verify that we did not send an ack.
1560 EXPECT_EQ(6u, writer_->header().packet_sequence_number);
1562 // So the last ack has not changed.
1563 EXPECT_EQ(4u, least_unacked());
1565 // If we force an ack, we shouldn't change our retransmit state.
1566 SendAckPacketToPeer(); // Packet 7
1567 EXPECT_EQ(7u, least_unacked());
1569 // But if we send more data it should.
1570 SendStreamDataToPeer(1, "eep", 6, !kFin, &last_packet); // Packet 8
1571 EXPECT_EQ(8u, last_packet);
1572 SendAckPacketToPeer(); // Packet 9
1573 EXPECT_EQ(7u, least_unacked());
1576 // QuicConnection should record the the packet sent-time prior to sending the
1577 // packet.
1578 TEST_P(QuicConnectionTest, RecordSentTimeBeforePacketSent) {
1579 // We're using a MockClock for the tests, so we have complete control over the
1580 // time.
1581 // Our recorded timestamp for the last packet sent time will be passed in to
1582 // the send_algorithm. Make sure that it is set to the correct value.
1583 QuicTime actual_recorded_send_time = QuicTime::Zero();
1584 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1585 .WillOnce(DoAll(SaveArg<0>(&actual_recorded_send_time), Return(true)));
1587 // First send without any pause and check the result.
1588 QuicTime expected_recorded_send_time = clock_.Now();
1589 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
1590 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
1591 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
1592 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
1594 // Now pause during the write, and check the results.
1595 actual_recorded_send_time = QuicTime::Zero();
1596 const QuicTime::Delta kWritePauseTimeDelta =
1597 QuicTime::Delta::FromMilliseconds(5000);
1598 SetWritePauseTimeDelta(kWritePauseTimeDelta);
1599 expected_recorded_send_time = clock_.Now();
1601 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1602 .WillOnce(DoAll(SaveArg<0>(&actual_recorded_send_time), Return(true)));
1603 connection_.SendStreamDataWithString(2, "baz", 0, !kFin, nullptr);
1604 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
1605 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
1606 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
1609 TEST_P(QuicConnectionTest, FECSending) {
1610 // All packets carry version info till version is negotiated.
1611 size_t payload_length;
1612 // GetPacketLengthForOneStream() assumes a stream offset of 0 in determining
1613 // packet length. The size of the offset field in a stream frame is 0 for
1614 // offset 0, and 2 for non-zero offsets up through 64K. Increase
1615 // max_packet_length by 2 so that subsequent packets containing subsequent
1616 // stream frames with non-zero offets will fit within the packet length.
1617 size_t length = 2 + GetPacketLengthForOneStream(
1618 connection_.version(), kIncludeVersion,
1619 PACKET_8BYTE_CONNECTION_ID, PACKET_1BYTE_SEQUENCE_NUMBER,
1620 IN_FEC_GROUP, &payload_length);
1621 creator_->set_max_packet_length(length);
1623 // Send 4 protected data packets, which should also trigger 1 FEC packet.
1624 EXPECT_CALL(*send_algorithm_,
1625 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(5);
1626 // The first stream frame will have 2 fewer overhead bytes than the other 3.
1627 const string payload(payload_length * 4 + 2, 'a');
1628 connection_.SendStreamDataWithStringWithFec(1, payload, 0, !kFin, nullptr);
1629 // Expect the FEC group to be closed after SendStreamDataWithString.
1630 EXPECT_FALSE(creator_->IsFecGroupOpen());
1631 EXPECT_FALSE(creator_->IsFecProtected());
1634 TEST_P(QuicConnectionTest, FECQueueing) {
1635 // All packets carry version info till version is negotiated.
1636 size_t payload_length;
1637 size_t length = GetPacketLengthForOneStream(
1638 connection_.version(), kIncludeVersion,
1639 PACKET_8BYTE_CONNECTION_ID, PACKET_1BYTE_SEQUENCE_NUMBER,
1640 IN_FEC_GROUP, &payload_length);
1641 creator_->set_max_packet_length(length);
1642 EXPECT_TRUE(creator_->IsFecEnabled());
1644 EXPECT_EQ(0u, connection_.NumQueuedPackets());
1645 BlockOnNextWrite();
1646 const string payload(payload_length, 'a');
1647 connection_.SendStreamDataWithStringWithFec(1, payload, 0, !kFin, nullptr);
1648 EXPECT_FALSE(creator_->IsFecGroupOpen());
1649 EXPECT_FALSE(creator_->IsFecProtected());
1650 // Expect the first data packet and the fec packet to be queued.
1651 EXPECT_EQ(2u, connection_.NumQueuedPackets());
1654 TEST_P(QuicConnectionTest, FECAlarmStoppedWhenFECPacketSent) {
1655 EXPECT_TRUE(creator_->IsFecEnabled());
1656 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1657 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1659 creator_->set_max_packets_per_fec_group(2);
1661 // 1 Data packet. FEC alarm should be set.
1662 EXPECT_CALL(*send_algorithm_,
1663 OnPacketSent(_, _, 1u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1664 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, true, nullptr);
1665 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1667 // Second data packet triggers FEC packet out. FEC alarm should not be set.
1668 EXPECT_CALL(*send_algorithm_,
1669 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(2);
1670 connection_.SendStreamDataWithStringWithFec(5, "foo", 0, true, nullptr);
1671 EXPECT_TRUE(writer_->header().fec_flag);
1672 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1675 TEST_P(QuicConnectionTest, FECAlarmStoppedOnConnectionClose) {
1676 EXPECT_TRUE(creator_->IsFecEnabled());
1677 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1678 creator_->set_max_packets_per_fec_group(100);
1680 // 1 Data packet. FEC alarm should be set.
1681 EXPECT_CALL(*send_algorithm_,
1682 OnPacketSent(_, _, 1u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1683 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, kFin, nullptr);
1684 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1686 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NO_ERROR, false));
1687 // Closing connection should stop the FEC alarm.
1688 connection_.CloseConnection(QUIC_NO_ERROR, /*from_peer=*/false);
1689 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1692 TEST_P(QuicConnectionTest, RemoveFECFromInflightOnRetransmissionTimeout) {
1693 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1694 EXPECT_TRUE(creator_->IsFecEnabled());
1695 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1696 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1698 // 1 Data packet. FEC alarm should be set.
1699 EXPECT_CALL(*send_algorithm_,
1700 OnPacketSent(_, _, 1u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1701 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, !kFin, nullptr);
1702 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1703 size_t protected_packet =
1704 QuicSentPacketManagerPeer::GetBytesInFlight(manager_);
1706 // Force FEC timeout to send FEC packet out.
1707 EXPECT_CALL(*send_algorithm_,
1708 OnPacketSent(_, _, 2u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1709 connection_.GetFecAlarm()->Fire();
1710 EXPECT_TRUE(writer_->header().fec_flag);
1712 size_t fec_packet = protected_packet;
1713 EXPECT_EQ(protected_packet + fec_packet,
1714 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1715 clock_.AdvanceTime(DefaultRetransmissionTime());
1717 // On RTO, both data and FEC packets are removed from inflight, only the data
1718 // packet is retransmitted, and this retransmission (but not FEC) gets added
1719 // back into the inflight.
1720 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
1721 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1722 connection_.GetRetransmissionAlarm()->Fire();
1724 // The retransmission of packet 1 will be 3 bytes smaller than packet 1, since
1725 // the first transmission will have 1 byte for FEC group number and 2 bytes of
1726 // stream frame size, which are absent in the retransmission.
1727 size_t retransmitted_packet = protected_packet - 3;
1728 EXPECT_EQ(protected_packet + retransmitted_packet,
1729 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1730 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1732 // Receive ack for the retransmission. No data should be outstanding.
1733 QuicAckFrame ack = InitAckFrame(3);
1734 NackPacket(1, &ack);
1735 NackPacket(2, &ack);
1736 SequenceNumberSet lost_packets;
1737 lost_packets.insert(1);
1738 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1739 .WillOnce(Return(lost_packets));
1740 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1741 ProcessAckPacket(&ack);
1743 // Ensure the alarm is not set since all packets have been acked or abandoned.
1744 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
1745 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1748 TEST_P(QuicConnectionTest, RemoveFECFromInflightOnLossRetransmission) {
1749 EXPECT_TRUE(creator_->IsFecEnabled());
1750 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1752 // 1 FEC-protected data packet. FEC alarm should be set.
1753 EXPECT_CALL(*send_algorithm_,
1754 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1755 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, kFin, nullptr);
1756 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1757 size_t protected_packet =
1758 QuicSentPacketManagerPeer::GetBytesInFlight(manager_);
1760 // Force FEC timeout to send FEC packet out.
1761 EXPECT_CALL(*send_algorithm_,
1762 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1763 connection_.GetFecAlarm()->Fire();
1764 EXPECT_TRUE(writer_->header().fec_flag);
1765 size_t fec_packet = protected_packet;
1766 EXPECT_EQ(protected_packet + fec_packet,
1767 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1769 // Send more data to trigger NACKs. Note that all data starts at stream offset
1770 // 0 to ensure the same packet size, for ease of testing.
1771 EXPECT_CALL(*send_algorithm_,
1772 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(4);
1773 connection_.SendStreamDataWithString(5, "foo", 0, kFin, nullptr);
1774 connection_.SendStreamDataWithString(7, "foo", 0, kFin, nullptr);
1775 connection_.SendStreamDataWithString(9, "foo", 0, kFin, nullptr);
1776 connection_.SendStreamDataWithString(11, "foo", 0, kFin, nullptr);
1778 // An unprotected packet will be 3 bytes smaller than an FEC-protected packet,
1779 // since the protected packet will have 1 byte for FEC group number and
1780 // 2 bytes of stream frame size, which are absent in the unprotected packet.
1781 size_t unprotected_packet = protected_packet - 3;
1782 EXPECT_EQ(protected_packet + fec_packet + 4 * unprotected_packet,
1783 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1784 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1786 // Ack data packets, and NACK FEC packet and one data packet. Triggers
1787 // NACK-based loss detection of both packets, but only data packet is
1788 // retransmitted and considered oustanding.
1789 QuicAckFrame ack = InitAckFrame(6);
1790 NackPacket(2, &ack);
1791 NackPacket(3, &ack);
1792 SequenceNumberSet lost_packets;
1793 lost_packets.insert(2);
1794 lost_packets.insert(3);
1795 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1796 .WillOnce(Return(lost_packets));
1797 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1798 EXPECT_CALL(*send_algorithm_,
1799 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1800 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1801 ProcessAckPacket(&ack);
1802 // On receiving this ack from the server, the client will no longer send
1803 // version number in subsequent packets, including in this retransmission.
1804 size_t unprotected_packet_no_version = unprotected_packet - 4;
1805 EXPECT_EQ(unprotected_packet_no_version,
1806 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1808 // Receive ack for the retransmission. No data should be outstanding.
1809 QuicAckFrame ack2 = InitAckFrame(7);
1810 NackPacket(2, &ack2);
1811 NackPacket(3, &ack2);
1812 SequenceNumberSet lost_packets2;
1813 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1814 .WillOnce(Return(lost_packets2));
1815 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1816 ProcessAckPacket(&ack2);
1817 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1820 TEST_P(QuicConnectionTest, FECRemainsInflightOnTLPOfEarlierData) {
1821 // This test checks if TLP is sent correctly when a data and an FEC packet
1822 // are outstanding. TLP should be sent for the data packet when the
1823 // retransmission alarm fires.
1824 // Turn on TLP for this test.
1825 QuicSentPacketManagerPeer::SetMaxTailLossProbes(manager_, 1);
1826 EXPECT_TRUE(creator_->IsFecEnabled());
1827 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1828 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1830 // 1 Data packet. FEC alarm should be set.
1831 EXPECT_CALL(*send_algorithm_,
1832 OnPacketSent(_, _, 1u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1833 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, kFin, nullptr);
1834 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1835 size_t protected_packet =
1836 QuicSentPacketManagerPeer::GetBytesInFlight(manager_);
1837 EXPECT_LT(0u, protected_packet);
1839 // Force FEC timeout to send FEC packet out.
1840 EXPECT_CALL(*send_algorithm_,
1841 OnPacketSent(_, _, 2u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1842 connection_.GetFecAlarm()->Fire();
1843 EXPECT_TRUE(writer_->header().fec_flag);
1844 size_t fec_packet = protected_packet;
1845 EXPECT_EQ(protected_packet + fec_packet,
1846 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1848 // TLP alarm should be set.
1849 QuicTime retransmission_time =
1850 connection_.GetRetransmissionAlarm()->deadline();
1851 EXPECT_NE(QuicTime::Zero(), retransmission_time);
1852 // Simulate the retransmission alarm firing and sending a TLP, so send
1853 // algorithm's OnRetransmissionTimeout is not called.
1854 clock_.AdvanceTime(retransmission_time.Subtract(clock_.Now()));
1855 EXPECT_CALL(*send_algorithm_,
1856 OnPacketSent(_, _, 3u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1857 connection_.GetRetransmissionAlarm()->Fire();
1858 // The TLP retransmission of packet 1 will be 3 bytes smaller than packet 1,
1859 // since packet 1 will have 1 byte for FEC group number and 2 bytes of stream
1860 // frame size, which are absent in the the TLP retransmission.
1861 size_t tlp_packet = protected_packet - 3;
1862 EXPECT_EQ(protected_packet + fec_packet + tlp_packet,
1863 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1866 TEST_P(QuicConnectionTest, FECRemainsInflightOnTLPOfLaterData) {
1867 // Tests if TLP is sent correctly when data packet 1 and an FEC packet are
1868 // sent followed by data packet 2, and data packet 1 is acked. TLP should be
1869 // sent for data packet 2 when the retransmission alarm fires. Turn on TLP for
1870 // this test.
1871 QuicSentPacketManagerPeer::SetMaxTailLossProbes(manager_, 1);
1872 EXPECT_TRUE(creator_->IsFecEnabled());
1873 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1874 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1876 // 1 Data packet. FEC alarm should be set.
1877 EXPECT_CALL(*send_algorithm_,
1878 OnPacketSent(_, _, 1u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1879 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, kFin, nullptr);
1880 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1881 size_t protected_packet =
1882 QuicSentPacketManagerPeer::GetBytesInFlight(manager_);
1883 EXPECT_LT(0u, protected_packet);
1885 // Force FEC timeout to send FEC packet out.
1886 EXPECT_CALL(*send_algorithm_,
1887 OnPacketSent(_, _, 2u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1888 connection_.GetFecAlarm()->Fire();
1889 EXPECT_TRUE(writer_->header().fec_flag);
1890 // Protected data packet and FEC packet oustanding.
1891 size_t fec_packet = protected_packet;
1892 EXPECT_EQ(protected_packet + fec_packet,
1893 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1895 // Send 1 unprotected data packet. No FEC alarm should be set.
1896 EXPECT_CALL(*send_algorithm_,
1897 OnPacketSent(_, _, 3u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1898 connection_.SendStreamDataWithString(5, "foo", 0, kFin, nullptr);
1899 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1900 // Protected data packet, FEC packet, and unprotected data packet oustanding.
1901 // An unprotected packet will be 3 bytes smaller than an FEC-protected packet,
1902 // since the protected packet will have 1 byte for FEC group number and
1903 // 2 bytes of stream frame size, which are absent in the unprotected packet.
1904 size_t unprotected_packet = protected_packet - 3;
1905 EXPECT_EQ(protected_packet + fec_packet + unprotected_packet,
1906 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1908 // Receive ack for first data packet. FEC and second data packet are still
1909 // outstanding.
1910 QuicAckFrame ack = InitAckFrame(1);
1911 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1912 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1913 ProcessAckPacket(&ack);
1914 // FEC packet and unprotected data packet oustanding.
1915 EXPECT_EQ(fec_packet + unprotected_packet,
1916 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1918 // TLP alarm should be set.
1919 QuicTime retransmission_time =
1920 connection_.GetRetransmissionAlarm()->deadline();
1921 EXPECT_NE(QuicTime::Zero(), retransmission_time);
1922 // Simulate the retransmission alarm firing and sending a TLP, so send
1923 // algorithm's OnRetransmissionTimeout is not called.
1924 clock_.AdvanceTime(retransmission_time.Subtract(clock_.Now()));
1925 EXPECT_CALL(*send_algorithm_,
1926 OnPacketSent(_, _, 4u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1927 connection_.GetRetransmissionAlarm()->Fire();
1929 // Having received an ack from the server, the client will no longer send
1930 // version number in subsequent packets, including in this retransmission.
1931 size_t tlp_packet_no_version = unprotected_packet - 4;
1932 EXPECT_EQ(fec_packet + unprotected_packet + tlp_packet_no_version,
1933 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1936 TEST_P(QuicConnectionTest, NoTLPForFECPacket) {
1937 // Turn on TLP for this test.
1938 QuicSentPacketManagerPeer::SetMaxTailLossProbes(manager_, 1);
1939 EXPECT_TRUE(creator_->IsFecEnabled());
1940 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1942 // Send 1 FEC-protected data packet. FEC alarm should be set.
1943 EXPECT_CALL(*send_algorithm_,
1944 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1945 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, !kFin, nullptr);
1946 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1947 // Force FEC timeout to send FEC packet out.
1948 EXPECT_CALL(*send_algorithm_,
1949 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1950 connection_.GetFecAlarm()->Fire();
1951 EXPECT_TRUE(writer_->header().fec_flag);
1953 // Ack data packet, but not FEC packet.
1954 QuicAckFrame ack = InitAckFrame(1);
1955 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1956 ProcessAckPacket(&ack);
1958 // No TLP alarm for FEC, but retransmission alarm should be set for an RTO.
1959 EXPECT_LT(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1960 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
1961 QuicTime rto_time = connection_.GetRetransmissionAlarm()->deadline();
1962 EXPECT_NE(QuicTime::Zero(), rto_time);
1964 // Simulate the retransmission alarm firing. FEC packet is no longer
1965 // outstanding.
1966 clock_.AdvanceTime(rto_time.Subtract(clock_.Now()));
1967 connection_.GetRetransmissionAlarm()->Fire();
1969 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
1970 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1973 TEST_P(QuicConnectionTest, FramePacking) {
1974 CongestionBlockWrites();
1976 // Send an ack and two stream frames in 1 packet by queueing them.
1977 connection_.SendAck();
1978 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
1979 IgnoreResult(InvokeWithoutArgs(&connection_,
1980 &TestConnection::SendStreamData3)),
1981 IgnoreResult(InvokeWithoutArgs(&connection_,
1982 &TestConnection::SendStreamData5))));
1984 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1985 CongestionUnblockWrites();
1986 connection_.GetSendAlarm()->Fire();
1987 EXPECT_EQ(0u, connection_.NumQueuedPackets());
1988 EXPECT_FALSE(connection_.HasQueuedData());
1990 // Parse the last packet and ensure it's an ack and two stream frames from
1991 // two different streams.
1992 EXPECT_EQ(4u, writer_->frame_count());
1993 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
1994 EXPECT_FALSE(writer_->ack_frames().empty());
1995 ASSERT_EQ(2u, writer_->stream_frames().size());
1996 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id);
1997 EXPECT_EQ(kClientDataStreamId2, writer_->stream_frames()[1].stream_id);
2000 TEST_P(QuicConnectionTest, FramePackingNonCryptoThenCrypto) {
2001 CongestionBlockWrites();
2003 // Send an ack and two stream frames (one non-crypto, then one crypto) in 2
2004 // packets by queueing them.
2005 connection_.SendAck();
2006 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
2007 IgnoreResult(InvokeWithoutArgs(&connection_,
2008 &TestConnection::SendStreamData3)),
2009 IgnoreResult(InvokeWithoutArgs(&connection_,
2010 &TestConnection::SendCryptoStreamData))));
2012 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
2013 CongestionUnblockWrites();
2014 connection_.GetSendAlarm()->Fire();
2015 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2016 EXPECT_FALSE(connection_.HasQueuedData());
2018 // Parse the last packet and ensure it's the crypto stream frame.
2019 EXPECT_EQ(1u, writer_->frame_count());
2020 ASSERT_EQ(1u, writer_->stream_frames().size());
2021 EXPECT_EQ(kCryptoStreamId, writer_->stream_frames()[0].stream_id);
2024 TEST_P(QuicConnectionTest, FramePackingCryptoThenNonCrypto) {
2025 CongestionBlockWrites();
2027 // Send an ack and two stream frames (one crypto, then one non-crypto) in 2
2028 // packets by queueing them.
2029 connection_.SendAck();
2030 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
2031 IgnoreResult(InvokeWithoutArgs(&connection_,
2032 &TestConnection::SendCryptoStreamData)),
2033 IgnoreResult(InvokeWithoutArgs(&connection_,
2034 &TestConnection::SendStreamData3))));
2036 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
2037 CongestionUnblockWrites();
2038 connection_.GetSendAlarm()->Fire();
2039 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2040 EXPECT_FALSE(connection_.HasQueuedData());
2042 // Parse the last packet and ensure it's the stream frame from stream 3.
2043 EXPECT_EQ(1u, writer_->frame_count());
2044 ASSERT_EQ(1u, writer_->stream_frames().size());
2045 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id);
2048 TEST_P(QuicConnectionTest, FramePackingFEC) {
2049 EXPECT_TRUE(creator_->IsFecEnabled());
2051 CongestionBlockWrites();
2053 // Queue an ack and two stream frames. Ack gets flushed when FEC is turned on
2054 // for sending protected data; two stream frames are packed in 1 packet.
2055 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
2056 IgnoreResult(InvokeWithoutArgs(
2057 &connection_, &TestConnection::SendStreamData3WithFec)),
2058 IgnoreResult(InvokeWithoutArgs(
2059 &connection_, &TestConnection::SendStreamData5WithFec))));
2060 connection_.SendAck();
2062 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
2063 CongestionUnblockWrites();
2064 connection_.GetSendAlarm()->Fire();
2065 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2066 EXPECT_FALSE(connection_.HasQueuedData());
2068 // Parse the last packet and ensure it's in an fec group.
2069 EXPECT_EQ(2u, writer_->header().fec_group);
2070 EXPECT_EQ(2u, writer_->frame_count());
2072 // FEC alarm should be set.
2073 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
2076 TEST_P(QuicConnectionTest, FramePackingAckResponse) {
2077 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2078 // Process a data packet to queue up a pending ack.
2079 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
2080 ProcessDataPacket(1, 1, kEntropyFlag);
2082 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
2083 IgnoreResult(InvokeWithoutArgs(&connection_,
2084 &TestConnection::SendStreamData3)),
2085 IgnoreResult(InvokeWithoutArgs(&connection_,
2086 &TestConnection::SendStreamData5))));
2088 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2090 // Process an ack to cause the visitor's OnCanWrite to be invoked.
2091 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 2);
2092 QuicAckFrame ack_one = InitAckFrame(0);
2093 ProcessAckPacket(&ack_one);
2095 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2096 EXPECT_FALSE(connection_.HasQueuedData());
2098 // Parse the last packet and ensure it's an ack and two stream frames from
2099 // two different streams.
2100 EXPECT_EQ(4u, writer_->frame_count());
2101 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
2102 EXPECT_FALSE(writer_->ack_frames().empty());
2103 ASSERT_EQ(2u, writer_->stream_frames().size());
2104 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id);
2105 EXPECT_EQ(kClientDataStreamId2, writer_->stream_frames()[1].stream_id);
2108 TEST_P(QuicConnectionTest, FramePackingSendv) {
2109 // Send data in 1 packet by writing multiple blocks in a single iovector
2110 // using writev.
2111 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2113 char data[] = "ABCD";
2114 IOVector data_iov;
2115 data_iov.AppendNoCoalesce(data, 2);
2116 data_iov.AppendNoCoalesce(data + 2, 2);
2117 connection_.SendStreamData(1, data_iov, 0, !kFin, MAY_FEC_PROTECT, nullptr);
2119 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2120 EXPECT_FALSE(connection_.HasQueuedData());
2122 // Parse the last packet and ensure multiple iovector blocks have
2123 // been packed into a single stream frame from one stream.
2124 EXPECT_EQ(1u, writer_->frame_count());
2125 EXPECT_EQ(1u, writer_->stream_frames().size());
2126 QuicStreamFrame frame = writer_->stream_frames()[0];
2127 EXPECT_EQ(1u, frame.stream_id);
2128 EXPECT_EQ("ABCD", string(static_cast<char*>
2129 (frame.data.iovec()[0].iov_base),
2130 (frame.data.iovec()[0].iov_len)));
2133 TEST_P(QuicConnectionTest, FramePackingSendvQueued) {
2134 // Try to send two stream frames in 1 packet by using writev.
2135 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2137 BlockOnNextWrite();
2138 char data[] = "ABCD";
2139 IOVector data_iov;
2140 data_iov.AppendNoCoalesce(data, 2);
2141 data_iov.AppendNoCoalesce(data + 2, 2);
2142 connection_.SendStreamData(1, data_iov, 0, !kFin, MAY_FEC_PROTECT, nullptr);
2144 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2145 EXPECT_TRUE(connection_.HasQueuedData());
2147 // Unblock the writes and actually send.
2148 writer_->SetWritable();
2149 connection_.OnCanWrite();
2150 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2152 // Parse the last packet and ensure it's one stream frame from one stream.
2153 EXPECT_EQ(1u, writer_->frame_count());
2154 EXPECT_EQ(1u, writer_->stream_frames().size());
2155 EXPECT_EQ(1u, writer_->stream_frames()[0].stream_id);
2158 TEST_P(QuicConnectionTest, SendingZeroBytes) {
2159 // Send a zero byte write with a fin using writev.
2160 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2161 IOVector empty_iov;
2162 connection_.SendStreamData(1, empty_iov, 0, kFin, MAY_FEC_PROTECT, nullptr);
2164 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2165 EXPECT_FALSE(connection_.HasQueuedData());
2167 // Parse the last packet and ensure it's one stream frame from one stream.
2168 EXPECT_EQ(1u, writer_->frame_count());
2169 EXPECT_EQ(1u, writer_->stream_frames().size());
2170 EXPECT_EQ(1u, writer_->stream_frames()[0].stream_id);
2171 EXPECT_TRUE(writer_->stream_frames()[0].fin);
2174 TEST_P(QuicConnectionTest, OnCanWrite) {
2175 // Visitor's OnCanWrite will send data, but will have more pending writes.
2176 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
2177 IgnoreResult(InvokeWithoutArgs(&connection_,
2178 &TestConnection::SendStreamData3)),
2179 IgnoreResult(InvokeWithoutArgs(&connection_,
2180 &TestConnection::SendStreamData5))));
2181 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillOnce(Return(true));
2182 EXPECT_CALL(*send_algorithm_,
2183 TimeUntilSend(_, _, _)).WillRepeatedly(
2184 testing::Return(QuicTime::Delta::Zero()));
2186 connection_.OnCanWrite();
2188 // Parse the last packet and ensure it's the two stream frames from
2189 // two different streams.
2190 EXPECT_EQ(2u, writer_->frame_count());
2191 EXPECT_EQ(2u, writer_->stream_frames().size());
2192 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id);
2193 EXPECT_EQ(kClientDataStreamId2, writer_->stream_frames()[1].stream_id);
2196 TEST_P(QuicConnectionTest, RetransmitOnNack) {
2197 QuicPacketSequenceNumber last_packet;
2198 QuicByteCount second_packet_size;
2199 SendStreamDataToPeer(3, "foo", 0, !kFin, &last_packet); // Packet 1
2200 second_packet_size =
2201 SendStreamDataToPeer(3, "foos", 3, !kFin, &last_packet); // Packet 2
2202 SendStreamDataToPeer(3, "fooos", 7, !kFin, &last_packet); // Packet 3
2204 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2206 // Don't lose a packet on an ack, and nothing is retransmitted.
2207 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2208 QuicAckFrame ack_one = InitAckFrame(1);
2209 ProcessAckPacket(&ack_one);
2211 // Lose a packet and ensure it triggers retransmission.
2212 QuicAckFrame nack_two = InitAckFrame(3);
2213 NackPacket(2, &nack_two);
2214 SequenceNumberSet lost_packets;
2215 lost_packets.insert(2);
2216 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2217 .WillOnce(Return(lost_packets));
2218 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2219 EXPECT_CALL(*send_algorithm_,
2220 OnPacketSent(_, _, _, second_packet_size - kQuicVersionSize, _)).
2221 Times(1);
2222 ProcessAckPacket(&nack_two);
2225 TEST_P(QuicConnectionTest, DiscardRetransmit) {
2226 QuicPacketSequenceNumber last_packet;
2227 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet); // Packet 1
2228 SendStreamDataToPeer(1, "foos", 3, !kFin, &last_packet); // Packet 2
2229 SendStreamDataToPeer(1, "fooos", 7, !kFin, &last_packet); // Packet 3
2231 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2233 // Instigate a loss with an ack.
2234 QuicAckFrame nack_two = InitAckFrame(3);
2235 NackPacket(2, &nack_two);
2236 // The first nack should trigger a fast retransmission, but we'll be
2237 // write blocked, so the packet will be queued.
2238 BlockOnNextWrite();
2239 SequenceNumberSet lost_packets;
2240 lost_packets.insert(2);
2241 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2242 .WillOnce(Return(lost_packets));
2243 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2244 ProcessAckPacket(&nack_two);
2245 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2247 // Now, ack the previous transmission.
2248 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2249 .WillOnce(Return(SequenceNumberSet()));
2250 QuicAckFrame ack_all = InitAckFrame(3);
2251 ProcessAckPacket(&ack_all);
2253 // Unblock the socket and attempt to send the queued packets. However,
2254 // since the previous transmission has been acked, we will not
2255 // send the retransmission.
2256 EXPECT_CALL(*send_algorithm_,
2257 OnPacketSent(_, _, _, _, _)).Times(0);
2259 writer_->SetWritable();
2260 connection_.OnCanWrite();
2262 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2265 TEST_P(QuicConnectionTest, RetransmitNackedLargestObserved) {
2266 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2267 QuicPacketSequenceNumber largest_observed;
2268 QuicByteCount packet_size;
2269 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2270 .WillOnce(DoAll(SaveArg<2>(&largest_observed), SaveArg<3>(&packet_size),
2271 Return(true)));
2272 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
2274 QuicAckFrame frame = InitAckFrame(1);
2275 NackPacket(largest_observed, &frame);
2276 // The first nack should retransmit the largest observed packet.
2277 SequenceNumberSet lost_packets;
2278 lost_packets.insert(1);
2279 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2280 .WillOnce(Return(lost_packets));
2281 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2282 EXPECT_CALL(*send_algorithm_,
2283 OnPacketSent(_, _, _, packet_size - kQuicVersionSize, _));
2284 ProcessAckPacket(&frame);
2287 TEST_P(QuicConnectionTest, QueueAfterTwoRTOs) {
2288 for (int i = 0; i < 10; ++i) {
2289 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2290 connection_.SendStreamDataWithString(3, "foo", i * 3, !kFin, nullptr);
2293 // Block the writer and ensure they're queued.
2294 BlockOnNextWrite();
2295 clock_.AdvanceTime(DefaultRetransmissionTime());
2296 // Only one packet should be retransmitted.
2297 connection_.GetRetransmissionAlarm()->Fire();
2298 EXPECT_TRUE(connection_.HasQueuedData());
2300 // Unblock the writer.
2301 writer_->SetWritable();
2302 clock_.AdvanceTime(QuicTime::Delta::FromMicroseconds(
2303 2 * DefaultRetransmissionTime().ToMicroseconds()));
2304 // Retransmit already retransmitted packets event though the sequence number
2305 // greater than the largest observed.
2306 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
2307 connection_.GetRetransmissionAlarm()->Fire();
2308 connection_.OnCanWrite();
2311 TEST_P(QuicConnectionTest, WriteBlockedThenSent) {
2312 BlockOnNextWrite();
2313 writer_->set_is_write_blocked_data_buffered(true);
2314 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2315 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
2316 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2318 writer_->SetWritable();
2319 connection_.OnCanWrite();
2320 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2323 TEST_P(QuicConnectionTest, RetransmitWriteBlockedAckedOriginalThenSent) {
2324 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2325 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
2326 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2328 BlockOnNextWrite();
2329 writer_->set_is_write_blocked_data_buffered(true);
2330 // Simulate the retransmission alarm firing.
2331 clock_.AdvanceTime(DefaultRetransmissionTime());
2332 connection_.GetRetransmissionAlarm()->Fire();
2334 // Ack the sent packet before the callback returns, which happens in
2335 // rare circumstances with write blocked sockets.
2336 QuicAckFrame ack = InitAckFrame(1);
2337 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2338 ProcessAckPacket(&ack);
2340 writer_->SetWritable();
2341 connection_.OnCanWrite();
2342 // There is now a pending packet, but with no retransmittable frames.
2343 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2344 EXPECT_FALSE(connection_.sent_packet_manager().HasRetransmittableFrames(2));
2347 TEST_P(QuicConnectionTest, AlarmsWhenWriteBlocked) {
2348 // Block the connection.
2349 BlockOnNextWrite();
2350 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
2351 EXPECT_EQ(1u, writer_->packets_write_attempts());
2352 EXPECT_TRUE(writer_->IsWriteBlocked());
2354 // Set the send and resumption alarms. Fire the alarms and ensure they don't
2355 // attempt to write.
2356 connection_.GetResumeWritesAlarm()->Set(clock_.ApproximateNow());
2357 connection_.GetSendAlarm()->Set(clock_.ApproximateNow());
2358 connection_.GetResumeWritesAlarm()->Fire();
2359 connection_.GetSendAlarm()->Fire();
2360 EXPECT_TRUE(writer_->IsWriteBlocked());
2361 EXPECT_EQ(1u, writer_->packets_write_attempts());
2364 TEST_P(QuicConnectionTest, NoLimitPacketsPerNack) {
2365 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2366 int offset = 0;
2367 // Send packets 1 to 15.
2368 for (int i = 0; i < 15; ++i) {
2369 SendStreamDataToPeer(1, "foo", offset, !kFin, nullptr);
2370 offset += 3;
2373 // Ack 15, nack 1-14.
2374 SequenceNumberSet lost_packets;
2375 QuicAckFrame nack = InitAckFrame(15);
2376 for (int i = 1; i < 15; ++i) {
2377 NackPacket(i, &nack);
2378 lost_packets.insert(i);
2381 // 14 packets have been NACK'd and lost. In TCP cubic, PRR limits
2382 // the retransmission rate in the case of burst losses.
2383 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2384 .WillOnce(Return(lost_packets));
2385 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2386 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(14);
2387 ProcessAckPacket(&nack);
2390 // Test sending multiple acks from the connection to the session.
2391 TEST_P(QuicConnectionTest, MultipleAcks) {
2392 QuicPacketSequenceNumber last_packet;
2393 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet); // Packet 1
2394 EXPECT_EQ(1u, last_packet);
2395 SendStreamDataToPeer(3, "foo", 0, !kFin, &last_packet); // Packet 2
2396 EXPECT_EQ(2u, last_packet);
2397 SendAckPacketToPeer(); // Packet 3
2398 SendStreamDataToPeer(5, "foo", 0, !kFin, &last_packet); // Packet 4
2399 EXPECT_EQ(4u, last_packet);
2400 SendStreamDataToPeer(1, "foo", 3, !kFin, &last_packet); // Packet 5
2401 EXPECT_EQ(5u, last_packet);
2402 SendStreamDataToPeer(3, "foo", 3, !kFin, &last_packet); // Packet 6
2403 EXPECT_EQ(6u, last_packet);
2405 // Client will ack packets 1, 2, [!3], 4, 5.
2406 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2407 QuicAckFrame frame1 = InitAckFrame(5);
2408 NackPacket(3, &frame1);
2409 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2410 ProcessAckPacket(&frame1);
2412 // Now the client implicitly acks 3, and explicitly acks 6.
2413 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2414 QuicAckFrame frame2 = InitAckFrame(6);
2415 ProcessAckPacket(&frame2);
2418 TEST_P(QuicConnectionTest, DontLatchUnackedPacket) {
2419 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr); // Packet 1;
2420 // From now on, we send acks, so the send algorithm won't mark them pending.
2421 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2422 .WillByDefault(Return(false));
2423 SendAckPacketToPeer(); // Packet 2
2425 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2426 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2427 QuicAckFrame frame = InitAckFrame(1);
2428 ProcessAckPacket(&frame);
2430 // Verify that our internal state has least-unacked as 2, because we're still
2431 // waiting for a potential ack for 2.
2433 EXPECT_EQ(2u, stop_waiting()->least_unacked);
2435 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2436 frame = InitAckFrame(2);
2437 ProcessAckPacket(&frame);
2438 EXPECT_EQ(3u, stop_waiting()->least_unacked);
2440 // When we send an ack, we make sure our least-unacked makes sense. In this
2441 // case since we're not waiting on an ack for 2 and all packets are acked, we
2442 // set it to 3.
2443 SendAckPacketToPeer(); // Packet 3
2444 // Least_unacked remains at 3 until another ack is received.
2445 EXPECT_EQ(3u, stop_waiting()->least_unacked);
2446 // Check that the outgoing ack had its sequence number as least_unacked.
2447 EXPECT_EQ(3u, least_unacked());
2449 // Ack the ack, which updates the rtt and raises the least unacked.
2450 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2451 frame = InitAckFrame(3);
2452 ProcessAckPacket(&frame);
2454 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2455 .WillByDefault(Return(true));
2456 SendStreamDataToPeer(1, "bar", 3, false, nullptr); // Packet 4
2457 EXPECT_EQ(4u, stop_waiting()->least_unacked);
2458 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2459 .WillByDefault(Return(false));
2460 SendAckPacketToPeer(); // Packet 5
2461 EXPECT_EQ(4u, least_unacked());
2463 // Send two data packets at the end, and ensure if the last one is acked,
2464 // the least unacked is raised above the ack packets.
2465 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2466 .WillByDefault(Return(true));
2467 SendStreamDataToPeer(1, "bar", 6, false, nullptr); // Packet 6
2468 SendStreamDataToPeer(1, "bar", 9, false, nullptr); // Packet 7
2470 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2471 frame = InitAckFrame(7);
2472 NackPacket(5, &frame);
2473 NackPacket(6, &frame);
2474 ProcessAckPacket(&frame);
2476 EXPECT_EQ(6u, stop_waiting()->least_unacked);
2479 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterFecPacket) {
2480 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2482 // Don't send missing packet 1.
2483 ProcessFecPacket(2, 1, true, !kEntropyFlag, nullptr);
2484 // Entropy flag should be false, so entropy should be 0.
2485 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2488 TEST_P(QuicConnectionTest, ReviveMissingPacketWithVaryingSeqNumLengths) {
2489 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2491 // Set up a debug visitor to the connection.
2492 scoped_ptr<FecQuicConnectionDebugVisitor> fec_visitor(
2493 new FecQuicConnectionDebugVisitor());
2494 connection_.set_debug_visitor(fec_visitor.get());
2496 QuicPacketSequenceNumber fec_packet = 0;
2497 QuicSequenceNumberLength lengths[] = {PACKET_6BYTE_SEQUENCE_NUMBER,
2498 PACKET_4BYTE_SEQUENCE_NUMBER,
2499 PACKET_2BYTE_SEQUENCE_NUMBER,
2500 PACKET_1BYTE_SEQUENCE_NUMBER};
2501 // For each sequence number length size, revive a packet and check sequence
2502 // number length in the revived packet.
2503 for (size_t i = 0; i < arraysize(lengths); ++i) {
2504 // Set sequence_number_length_ (for data and FEC packets).
2505 sequence_number_length_ = lengths[i];
2506 fec_packet += 2;
2507 // Don't send missing packet, but send fec packet right after it.
2508 ProcessFecPacket(fec_packet, fec_packet - 1, true, !kEntropyFlag, nullptr);
2509 // Sequence number length in the revived header should be the same as
2510 // in the original data/fec packet headers.
2511 EXPECT_EQ(sequence_number_length_, fec_visitor->revived_header().
2512 public_header.sequence_number_length);
2516 TEST_P(QuicConnectionTest, ReviveMissingPacketWithVaryingConnectionIdLengths) {
2517 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2519 // Set up a debug visitor to the connection.
2520 scoped_ptr<FecQuicConnectionDebugVisitor> fec_visitor(
2521 new FecQuicConnectionDebugVisitor());
2522 connection_.set_debug_visitor(fec_visitor.get());
2524 QuicPacketSequenceNumber fec_packet = 0;
2525 QuicConnectionIdLength lengths[] = {PACKET_8BYTE_CONNECTION_ID,
2526 PACKET_4BYTE_CONNECTION_ID,
2527 PACKET_1BYTE_CONNECTION_ID,
2528 PACKET_0BYTE_CONNECTION_ID};
2529 // For each connection id length size, revive a packet and check connection
2530 // id length in the revived packet.
2531 for (size_t i = 0; i < arraysize(lengths); ++i) {
2532 // Set connection id length (for data and FEC packets).
2533 connection_id_length_ = lengths[i];
2534 fec_packet += 2;
2535 // Don't send missing packet, but send fec packet right after it.
2536 ProcessFecPacket(fec_packet, fec_packet - 1, true, !kEntropyFlag, nullptr);
2537 // Connection id length in the revived header should be the same as
2538 // in the original data/fec packet headers.
2539 EXPECT_EQ(connection_id_length_,
2540 fec_visitor->revived_header().public_header.connection_id_length);
2544 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPacketThenFecPacket) {
2545 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2547 ProcessFecProtectedPacket(1, false, kEntropyFlag);
2548 // Don't send missing packet 2.
2549 ProcessFecPacket(3, 1, true, !kEntropyFlag, nullptr);
2550 // Entropy flag should be true, so entropy should not be 0.
2551 EXPECT_NE(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2554 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPacketsThenFecPacket) {
2555 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2557 ProcessFecProtectedPacket(1, false, !kEntropyFlag);
2558 // Don't send missing packet 2.
2559 ProcessFecProtectedPacket(3, false, !kEntropyFlag);
2560 ProcessFecPacket(4, 1, true, kEntropyFlag, nullptr);
2561 // Ensure QUIC no longer revives entropy for lost packets.
2562 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2563 EXPECT_NE(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 4));
2566 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPacket) {
2567 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2569 // Don't send missing packet 1.
2570 ProcessFecPacket(3, 1, false, !kEntropyFlag, nullptr);
2571 // Out of order.
2572 ProcessFecProtectedPacket(2, true, !kEntropyFlag);
2573 // Entropy flag should be false, so entropy should be 0.
2574 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2577 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPackets) {
2578 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2580 ProcessFecProtectedPacket(1, false, !kEntropyFlag);
2581 // Don't send missing packet 2.
2582 ProcessFecPacket(6, 1, false, kEntropyFlag, nullptr);
2583 ProcessFecProtectedPacket(3, false, kEntropyFlag);
2584 ProcessFecProtectedPacket(4, false, kEntropyFlag);
2585 ProcessFecProtectedPacket(5, true, !kEntropyFlag);
2586 // Ensure entropy is not revived for the missing packet.
2587 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2588 EXPECT_NE(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 3));
2591 TEST_P(QuicConnectionTest, TLP) {
2592 QuicSentPacketManagerPeer::SetMaxTailLossProbes(manager_, 1);
2594 SendStreamDataToPeer(3, "foo", 0, !kFin, nullptr);
2595 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2596 QuicTime retransmission_time =
2597 connection_.GetRetransmissionAlarm()->deadline();
2598 EXPECT_NE(QuicTime::Zero(), retransmission_time);
2600 EXPECT_EQ(1u, writer_->header().packet_sequence_number);
2601 // Simulate the retransmission alarm firing and sending a tlp,
2602 // so send algorithm's OnRetransmissionTimeout is not called.
2603 clock_.AdvanceTime(retransmission_time.Subtract(clock_.Now()));
2604 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 2u, _, _));
2605 connection_.GetRetransmissionAlarm()->Fire();
2606 EXPECT_EQ(2u, writer_->header().packet_sequence_number);
2607 // We do not raise the high water mark yet.
2608 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2611 TEST_P(QuicConnectionTest, RTO) {
2612 QuicTime default_retransmission_time = clock_.ApproximateNow().Add(
2613 DefaultRetransmissionTime());
2614 SendStreamDataToPeer(3, "foo", 0, !kFin, nullptr);
2615 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2617 EXPECT_EQ(1u, writer_->header().packet_sequence_number);
2618 EXPECT_EQ(default_retransmission_time,
2619 connection_.GetRetransmissionAlarm()->deadline());
2620 // Simulate the retransmission alarm firing.
2621 clock_.AdvanceTime(DefaultRetransmissionTime());
2622 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 2u, _, _));
2623 connection_.GetRetransmissionAlarm()->Fire();
2624 EXPECT_EQ(2u, writer_->header().packet_sequence_number);
2625 // We do not raise the high water mark yet.
2626 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2629 TEST_P(QuicConnectionTest, RTOWithSameEncryptionLevel) {
2630 QuicTime default_retransmission_time = clock_.ApproximateNow().Add(
2631 DefaultRetransmissionTime());
2632 use_tagging_decrypter();
2634 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
2635 // the end of the packet. We can test this to check which encrypter was used.
2636 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2637 SendStreamDataToPeer(3, "foo", 0, !kFin, nullptr);
2638 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
2640 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2641 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2642 SendStreamDataToPeer(3, "foo", 0, !kFin, nullptr);
2643 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2645 EXPECT_EQ(default_retransmission_time,
2646 connection_.GetRetransmissionAlarm()->deadline());
2648 InSequence s;
2649 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 3, _, _));
2650 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 4, _, _));
2653 // Simulate the retransmission alarm firing.
2654 clock_.AdvanceTime(DefaultRetransmissionTime());
2655 connection_.GetRetransmissionAlarm()->Fire();
2657 // Packet should have been sent with ENCRYPTION_NONE.
2658 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_previous_packet());
2660 // Packet should have been sent with ENCRYPTION_INITIAL.
2661 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2664 TEST_P(QuicConnectionTest, SendHandshakeMessages) {
2665 use_tagging_decrypter();
2666 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
2667 // the end of the packet. We can test this to check which encrypter was used.
2668 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2670 // Attempt to send a handshake message and have the socket block.
2671 EXPECT_CALL(*send_algorithm_,
2672 TimeUntilSend(_, _, _)).WillRepeatedly(
2673 testing::Return(QuicTime::Delta::Zero()));
2674 BlockOnNextWrite();
2675 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
2676 // The packet should be serialized, but not queued.
2677 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2679 // Switch to the new encrypter.
2680 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2681 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2683 // Now become writeable and flush the packets.
2684 writer_->SetWritable();
2685 EXPECT_CALL(visitor_, OnCanWrite());
2686 connection_.OnCanWrite();
2687 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2689 // Verify that the handshake packet went out at the null encryption.
2690 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
2693 TEST_P(QuicConnectionTest,
2694 DropRetransmitsForNullEncryptedPacketAfterForwardSecure) {
2695 use_tagging_decrypter();
2696 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2697 QuicPacketSequenceNumber sequence_number;
2698 SendStreamDataToPeer(3, "foo", 0, !kFin, &sequence_number);
2700 // Simulate the retransmission alarm firing and the socket blocking.
2701 BlockOnNextWrite();
2702 clock_.AdvanceTime(DefaultRetransmissionTime());
2703 connection_.GetRetransmissionAlarm()->Fire();
2705 // Go forward secure.
2706 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
2707 new TaggingEncrypter(0x02));
2708 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2709 connection_.NeuterUnencryptedPackets();
2711 EXPECT_EQ(QuicTime::Zero(),
2712 connection_.GetRetransmissionAlarm()->deadline());
2713 // Unblock the socket and ensure that no packets are sent.
2714 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
2715 writer_->SetWritable();
2716 connection_.OnCanWrite();
2719 TEST_P(QuicConnectionTest, RetransmitPacketsWithInitialEncryption) {
2720 use_tagging_decrypter();
2721 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2722 connection_.SetDefaultEncryptionLevel(ENCRYPTION_NONE);
2724 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr);
2726 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2727 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2729 SendStreamDataToPeer(2, "bar", 0, !kFin, nullptr);
2730 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2732 connection_.RetransmitUnackedPackets(ALL_INITIAL_RETRANSMISSION);
2735 TEST_P(QuicConnectionTest, DelayForwardSecureEncryptionUntilClientIsReady) {
2736 // A TaggingEncrypter puts kTagSize copies of the given byte (0x02 here) at
2737 // the end of the packet. We can test this to check which encrypter was used.
2738 use_tagging_decrypter();
2739 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2740 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2741 SendAckPacketToPeer();
2742 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2744 // Set a forward-secure encrypter but do not make it the default, and verify
2745 // that it is not yet used.
2746 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
2747 new TaggingEncrypter(0x03));
2748 SendAckPacketToPeer();
2749 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2751 // Now simulate receipt of a forward-secure packet and verify that the
2752 // forward-secure encrypter is now used.
2753 connection_.OnDecryptedPacket(ENCRYPTION_FORWARD_SECURE);
2754 SendAckPacketToPeer();
2755 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
2758 TEST_P(QuicConnectionTest, DelayForwardSecureEncryptionUntilManyPacketSent) {
2759 // Set a congestion window of 10 packets.
2760 QuicPacketCount congestion_window = 10;
2761 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
2762 Return(congestion_window * kDefaultMaxPacketSize));
2764 // A TaggingEncrypter puts kTagSize copies of the given byte (0x02 here) at
2765 // the end of the packet. We can test this to check which encrypter was used.
2766 use_tagging_decrypter();
2767 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2768 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2769 SendAckPacketToPeer();
2770 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2772 // Set a forward-secure encrypter but do not make it the default, and
2773 // verify that it is not yet used.
2774 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
2775 new TaggingEncrypter(0x03));
2776 SendAckPacketToPeer();
2777 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2779 // Now send a packet "Far enough" after the encrypter was set and verify that
2780 // the forward-secure encrypter is now used.
2781 for (uint64 i = 0; i < 3 * congestion_window - 1; ++i) {
2782 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2783 SendAckPacketToPeer();
2785 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
2788 TEST_P(QuicConnectionTest, BufferNonDecryptablePackets) {
2789 // SetFromConfig is always called after construction from InitializeSession.
2790 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _, _));
2791 QuicConfig config;
2792 connection_.SetFromConfig(config);
2793 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2794 use_tagging_decrypter();
2796 const uint8 tag = 0x07;
2797 framer_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
2799 // Process an encrypted packet which can not yet be decrypted which should
2800 // result in the packet being buffered.
2801 ProcessDataPacketAtLevel(1, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2803 // Transition to the new encryption state and process another encrypted packet
2804 // which should result in the original packet being processed.
2805 connection_.SetDecrypter(new StrictTaggingDecrypter(tag),
2806 ENCRYPTION_INITIAL);
2807 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2808 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
2809 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(2);
2810 ProcessDataPacketAtLevel(2, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2812 // Finally, process a third packet and note that we do not reprocess the
2813 // buffered packet.
2814 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
2815 ProcessDataPacketAtLevel(3, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2818 TEST_P(QuicConnectionTest, Buffer100NonDecryptablePackets) {
2819 // SetFromConfig is always called after construction from InitializeSession.
2820 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _, _));
2821 QuicConfig config;
2822 config.set_max_undecryptable_packets(100);
2823 connection_.SetFromConfig(config);
2824 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2825 use_tagging_decrypter();
2827 const uint8 tag = 0x07;
2828 framer_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
2830 // Process an encrypted packet which can not yet be decrypted which should
2831 // result in the packet being buffered.
2832 for (QuicPacketSequenceNumber i = 1; i <= 100; ++i) {
2833 ProcessDataPacketAtLevel(i, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2836 // Transition to the new encryption state and process another encrypted packet
2837 // which should result in the original packets being processed.
2838 connection_.SetDecrypter(new StrictTaggingDecrypter(tag), ENCRYPTION_INITIAL);
2839 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2840 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
2841 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(101);
2842 ProcessDataPacketAtLevel(101, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2844 // Finally, process a third packet and note that we do not reprocess the
2845 // buffered packet.
2846 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
2847 ProcessDataPacketAtLevel(102, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2850 TEST_P(QuicConnectionTest, TestRetransmitOrder) {
2851 QuicByteCount first_packet_size;
2852 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).WillOnce(
2853 DoAll(SaveArg<3>(&first_packet_size), Return(true)));
2855 connection_.SendStreamDataWithString(3, "first_packet", 0, !kFin, nullptr);
2856 QuicByteCount second_packet_size;
2857 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).WillOnce(
2858 DoAll(SaveArg<3>(&second_packet_size), Return(true)));
2859 connection_.SendStreamDataWithString(3, "second_packet", 12, !kFin, nullptr);
2860 EXPECT_NE(first_packet_size, second_packet_size);
2861 // Advance the clock by huge time to make sure packets will be retransmitted.
2862 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
2864 InSequence s;
2865 EXPECT_CALL(*send_algorithm_,
2866 OnPacketSent(_, _, _, first_packet_size, _));
2867 EXPECT_CALL(*send_algorithm_,
2868 OnPacketSent(_, _, _, second_packet_size, _));
2870 connection_.GetRetransmissionAlarm()->Fire();
2872 // Advance again and expect the packets to be sent again in the same order.
2873 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(20));
2875 InSequence s;
2876 EXPECT_CALL(*send_algorithm_,
2877 OnPacketSent(_, _, _, first_packet_size, _));
2878 EXPECT_CALL(*send_algorithm_,
2879 OnPacketSent(_, _, _, second_packet_size, _));
2881 connection_.GetRetransmissionAlarm()->Fire();
2884 TEST_P(QuicConnectionTest, SetRTOAfterWritingToSocket) {
2885 BlockOnNextWrite();
2886 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
2887 // Make sure that RTO is not started when the packet is queued.
2888 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
2890 // Test that RTO is started once we write to the socket.
2891 writer_->SetWritable();
2892 connection_.OnCanWrite();
2893 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2896 TEST_P(QuicConnectionTest, DelayRTOWithAckReceipt) {
2897 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2898 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2899 .Times(2);
2900 connection_.SendStreamDataWithString(2, "foo", 0, !kFin, nullptr);
2901 connection_.SendStreamDataWithString(3, "bar", 0, !kFin, nullptr);
2902 QuicAlarm* retransmission_alarm = connection_.GetRetransmissionAlarm();
2903 EXPECT_TRUE(retransmission_alarm->IsSet());
2904 EXPECT_EQ(clock_.Now().Add(DefaultRetransmissionTime()),
2905 retransmission_alarm->deadline());
2907 // Advance the time right before the RTO, then receive an ack for the first
2908 // packet to delay the RTO.
2909 clock_.AdvanceTime(DefaultRetransmissionTime());
2910 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2911 QuicAckFrame ack = InitAckFrame(1);
2912 ProcessAckPacket(&ack);
2913 EXPECT_TRUE(retransmission_alarm->IsSet());
2914 EXPECT_GT(retransmission_alarm->deadline(), clock_.Now());
2916 // Move forward past the original RTO and ensure the RTO is still pending.
2917 clock_.AdvanceTime(DefaultRetransmissionTime().Multiply(2));
2919 // Ensure the second packet gets retransmitted when it finally fires.
2920 EXPECT_TRUE(retransmission_alarm->IsSet());
2921 EXPECT_LT(retransmission_alarm->deadline(), clock_.ApproximateNow());
2922 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2923 // Manually cancel the alarm to simulate a real test.
2924 connection_.GetRetransmissionAlarm()->Fire();
2926 // The new retransmitted sequence number should set the RTO to a larger value
2927 // than previously.
2928 EXPECT_TRUE(retransmission_alarm->IsSet());
2929 QuicTime next_rto_time = retransmission_alarm->deadline();
2930 QuicTime expected_rto_time =
2931 connection_.sent_packet_manager().GetRetransmissionTime();
2932 EXPECT_EQ(next_rto_time, expected_rto_time);
2935 TEST_P(QuicConnectionTest, TestQueued) {
2936 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2937 BlockOnNextWrite();
2938 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
2939 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2941 // Unblock the writes and actually send.
2942 writer_->SetWritable();
2943 connection_.OnCanWrite();
2944 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2947 TEST_P(QuicConnectionTest, CloseFecGroup) {
2948 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2949 // Don't send missing packet 1.
2950 // Don't send missing packet 2.
2951 ProcessFecProtectedPacket(3, false, !kEntropyFlag);
2952 // Don't send missing FEC packet 3.
2953 ASSERT_EQ(1u, connection_.NumFecGroups());
2955 // Now send non-fec protected ack packet and close the group.
2956 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 4);
2957 QuicStopWaitingFrame frame = InitStopWaitingFrame(5);
2958 ProcessStopWaitingPacket(&frame);
2959 ASSERT_EQ(0u, connection_.NumFecGroups());
2962 TEST_P(QuicConnectionTest, InitialTimeout) {
2963 EXPECT_TRUE(connection_.connected());
2964 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
2965 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
2967 // SetFromConfig sets the initial timeouts before negotiation.
2968 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _, _));
2969 QuicConfig config;
2970 connection_.SetFromConfig(config);
2971 // Subtract a second from the idle timeout on the client side.
2972 QuicTime default_timeout = clock_.ApproximateNow().Add(
2973 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1));
2974 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
2976 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_CONNECTION_TIMED_OUT, false));
2977 // Simulate the timeout alarm firing.
2978 clock_.AdvanceTime(
2979 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1));
2980 connection_.GetTimeoutAlarm()->Fire();
2982 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
2983 EXPECT_FALSE(connection_.connected());
2985 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
2986 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
2987 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
2988 EXPECT_FALSE(connection_.GetResumeWritesAlarm()->IsSet());
2989 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
2990 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
2993 TEST_P(QuicConnectionTest, OverallTimeout) {
2994 // Use a shorter overall connection timeout than idle timeout for this test.
2995 const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(5);
2996 connection_.SetNetworkTimeouts(timeout, timeout);
2997 EXPECT_TRUE(connection_.connected());
2998 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
3000 QuicTime overall_timeout = clock_.ApproximateNow().Add(timeout).Subtract(
3001 QuicTime::Delta::FromSeconds(1));
3002 EXPECT_EQ(overall_timeout, connection_.GetTimeoutAlarm()->deadline());
3003 EXPECT_TRUE(connection_.connected());
3005 // Send and ack new data 3 seconds later to lengthen the idle timeout.
3006 SendStreamDataToPeer(1, "GET /", 0, kFin, nullptr);
3007 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(3));
3008 QuicAckFrame frame = InitAckFrame(1);
3009 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3010 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3011 ProcessAckPacket(&frame);
3013 // Fire early to verify it wouldn't timeout yet.
3014 connection_.GetTimeoutAlarm()->Fire();
3015 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
3016 EXPECT_TRUE(connection_.connected());
3018 clock_.AdvanceTime(timeout.Subtract(QuicTime::Delta::FromSeconds(2)));
3020 EXPECT_CALL(visitor_,
3021 OnConnectionClosed(QUIC_CONNECTION_OVERALL_TIMED_OUT, false));
3022 // Simulate the timeout alarm firing.
3023 connection_.GetTimeoutAlarm()->Fire();
3025 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3026 EXPECT_FALSE(connection_.connected());
3028 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3029 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
3030 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
3031 EXPECT_FALSE(connection_.GetResumeWritesAlarm()->IsSet());
3032 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3033 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
3036 TEST_P(QuicConnectionTest, PingAfterSend) {
3037 EXPECT_TRUE(connection_.connected());
3038 EXPECT_CALL(visitor_, HasOpenDataStreams()).WillRepeatedly(Return(true));
3039 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
3041 // Advance to 5ms, and send a packet to the peer, which will set
3042 // the ping alarm.
3043 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
3044 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3045 SendStreamDataToPeer(1, "GET /", 0, kFin, nullptr);
3046 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
3047 EXPECT_EQ(clock_.ApproximateNow().Add(QuicTime::Delta::FromSeconds(15)),
3048 connection_.GetPingAlarm()->deadline());
3050 // Now recevie and ACK of the previous packet, which will move the
3051 // ping alarm forward.
3052 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
3053 QuicAckFrame frame = InitAckFrame(1);
3054 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3055 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3056 ProcessAckPacket(&frame);
3057 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
3058 // The ping timer is set slightly less than 15 seconds in the future, because
3059 // of the 1s ping timer alarm granularity.
3060 EXPECT_EQ(clock_.ApproximateNow().Add(QuicTime::Delta::FromSeconds(15))
3061 .Subtract(QuicTime::Delta::FromMilliseconds(5)),
3062 connection_.GetPingAlarm()->deadline());
3064 writer_->Reset();
3065 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15));
3066 connection_.GetPingAlarm()->Fire();
3067 EXPECT_EQ(1u, writer_->frame_count());
3068 ASSERT_EQ(1u, writer_->ping_frames().size());
3069 writer_->Reset();
3071 EXPECT_CALL(visitor_, HasOpenDataStreams()).WillRepeatedly(Return(false));
3072 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
3073 SendAckPacketToPeer();
3075 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
3078 TEST_P(QuicConnectionTest, TimeoutAfterSend) {
3079 EXPECT_TRUE(connection_.connected());
3080 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _, _));
3081 QuicConfig config;
3082 connection_.SetFromConfig(config);
3083 EXPECT_FALSE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
3085 const QuicTime::Delta initial_idle_timeout =
3086 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
3087 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
3088 QuicTime default_timeout = clock_.ApproximateNow().Add(initial_idle_timeout);
3090 // When we send a packet, the timeout will change to 5ms +
3091 // kInitialIdleTimeoutSecs.
3092 clock_.AdvanceTime(five_ms);
3094 // Send an ack so we don't set the retransmission alarm.
3095 SendAckPacketToPeer();
3096 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
3098 // The original alarm will fire. We should not time out because we had a
3099 // network event at t=5ms. The alarm will reregister.
3100 clock_.AdvanceTime(initial_idle_timeout.Subtract(five_ms));
3101 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
3102 connection_.GetTimeoutAlarm()->Fire();
3103 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
3104 EXPECT_TRUE(connection_.connected());
3105 EXPECT_EQ(default_timeout.Add(five_ms),
3106 connection_.GetTimeoutAlarm()->deadline());
3108 // This time, we should time out.
3109 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_CONNECTION_TIMED_OUT, false));
3110 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3111 clock_.AdvanceTime(five_ms);
3112 EXPECT_EQ(default_timeout.Add(five_ms), clock_.ApproximateNow());
3113 connection_.GetTimeoutAlarm()->Fire();
3114 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3115 EXPECT_FALSE(connection_.connected());
3118 TEST_P(QuicConnectionTest, TimeoutAfterSendSilentClose) {
3119 // Same test as above, but complete a handshake which enables silent close,
3120 // causing no connection close packet to be sent.
3121 EXPECT_TRUE(connection_.connected());
3122 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _, _));
3123 QuicConfig config;
3125 // Create a handshake message that also enables silent close.
3126 CryptoHandshakeMessage msg;
3127 string error_details;
3128 QuicConfig client_config;
3129 client_config.SetInitialStreamFlowControlWindowToSend(
3130 kInitialStreamFlowControlWindowForTest);
3131 client_config.SetInitialSessionFlowControlWindowToSend(
3132 kInitialSessionFlowControlWindowForTest);
3133 client_config.SetIdleConnectionStateLifetime(
3134 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs),
3135 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs));
3136 client_config.ToHandshakeMessage(&msg);
3137 const QuicErrorCode error =
3138 config.ProcessPeerHello(msg, CLIENT, &error_details);
3139 EXPECT_EQ(QUIC_NO_ERROR, error);
3141 connection_.SetFromConfig(config);
3142 EXPECT_TRUE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
3144 const QuicTime::Delta default_idle_timeout =
3145 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs - 1);
3146 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
3147 QuicTime default_timeout = clock_.ApproximateNow().Add(default_idle_timeout);
3149 // When we send a packet, the timeout will change to 5ms +
3150 // kInitialIdleTimeoutSecs.
3151 clock_.AdvanceTime(five_ms);
3153 // Send an ack so we don't set the retransmission alarm.
3154 SendAckPacketToPeer();
3155 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
3157 // The original alarm will fire. We should not time out because we had a
3158 // network event at t=5ms. The alarm will reregister.
3159 clock_.AdvanceTime(default_idle_timeout.Subtract(five_ms));
3160 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
3161 connection_.GetTimeoutAlarm()->Fire();
3162 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
3163 EXPECT_TRUE(connection_.connected());
3164 EXPECT_EQ(default_timeout.Add(five_ms),
3165 connection_.GetTimeoutAlarm()->deadline());
3167 // This time, we should time out.
3168 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_CONNECTION_TIMED_OUT, false));
3169 clock_.AdvanceTime(five_ms);
3170 EXPECT_EQ(default_timeout.Add(five_ms), clock_.ApproximateNow());
3171 connection_.GetTimeoutAlarm()->Fire();
3172 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3173 EXPECT_FALSE(connection_.connected());
3176 TEST_P(QuicConnectionTest, SendScheduler) {
3177 // Test that if we send a packet without delay, it is not queued.
3178 QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
3179 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3180 connection_.SendPacket(
3181 ENCRYPTION_NONE, 1, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA);
3182 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3185 TEST_P(QuicConnectionTest, SendSchedulerEAGAIN) {
3186 QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
3187 BlockOnNextWrite();
3188 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 1, _, _)).Times(0);
3189 connection_.SendPacket(
3190 ENCRYPTION_NONE, 1, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA);
3191 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3194 TEST_P(QuicConnectionTest, TestQueueLimitsOnSendStreamData) {
3195 // All packets carry version info till version is negotiated.
3196 size_t payload_length;
3197 size_t length = GetPacketLengthForOneStream(
3198 connection_.version(), kIncludeVersion,
3199 PACKET_8BYTE_CONNECTION_ID, PACKET_1BYTE_SEQUENCE_NUMBER,
3200 NOT_IN_FEC_GROUP, &payload_length);
3201 creator_->set_max_packet_length(length);
3203 // Queue the first packet.
3204 EXPECT_CALL(*send_algorithm_,
3205 TimeUntilSend(_, _, _)).WillOnce(
3206 testing::Return(QuicTime::Delta::FromMicroseconds(10)));
3207 const string payload(payload_length, 'a');
3208 EXPECT_EQ(0u, connection_.SendStreamDataWithString(3, payload, 0, !kFin,
3209 nullptr).bytes_consumed);
3210 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3213 TEST_P(QuicConnectionTest, LoopThroughSendingPackets) {
3214 // All packets carry version info till version is negotiated.
3215 size_t payload_length;
3216 // GetPacketLengthForOneStream() assumes a stream offset of 0 in determining
3217 // packet length. The size of the offset field in a stream frame is 0 for
3218 // offset 0, and 2 for non-zero offsets up through 16K. Increase
3219 // max_packet_length by 2 so that subsequent packets containing subsequent
3220 // stream frames with non-zero offets will fit within the packet length.
3221 size_t length = 2 + GetPacketLengthForOneStream(
3222 connection_.version(), kIncludeVersion,
3223 PACKET_8BYTE_CONNECTION_ID, PACKET_1BYTE_SEQUENCE_NUMBER,
3224 NOT_IN_FEC_GROUP, &payload_length);
3225 creator_->set_max_packet_length(length);
3227 // Queue the first packet.
3228 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(7);
3229 // The first stream frame will have 2 fewer overhead bytes than the other six.
3230 const string payload(payload_length * 7 + 2, 'a');
3231 EXPECT_EQ(payload.size(),
3232 connection_.SendStreamDataWithString(1, payload, 0, !kFin, nullptr)
3233 .bytes_consumed);
3236 TEST_P(QuicConnectionTest, LoopThroughSendingPacketsWithTruncation) {
3237 // Set up a larger payload than will fit in one packet.
3238 const string payload(connection_.max_packet_length(), 'a');
3239 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _, _)).Times(AnyNumber());
3241 // Now send some packets with no truncation.
3242 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3243 EXPECT_EQ(payload.size(),
3244 connection_.SendStreamDataWithString(
3245 3, payload, 0, !kFin, nullptr).bytes_consumed);
3246 // Track the size of the second packet here. The overhead will be the largest
3247 // we see in this test, due to the non-truncated CID.
3248 size_t non_truncated_packet_size = writer_->last_packet_size();
3250 // Change to a 4 byte CID.
3251 QuicConfig config;
3252 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 4);
3253 connection_.SetFromConfig(config);
3254 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3255 EXPECT_EQ(payload.size(),
3256 connection_.SendStreamDataWithString(
3257 3, payload, 0, !kFin, nullptr).bytes_consumed);
3258 // Verify that we have 8 fewer bytes than in the non-truncated case. The
3259 // first packet got 4 bytes of extra payload due to the truncation, and the
3260 // headers here are also 4 byte smaller.
3261 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() + 8);
3264 // Change to a 1 byte CID.
3265 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 1);
3266 connection_.SetFromConfig(config);
3267 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3268 EXPECT_EQ(payload.size(),
3269 connection_.SendStreamDataWithString(
3270 3, payload, 0, !kFin, nullptr).bytes_consumed);
3271 // Just like above, we save 7 bytes on payload, and 7 on truncation.
3272 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() + 7 * 2);
3274 // Change to a 0 byte CID.
3275 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
3276 connection_.SetFromConfig(config);
3277 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3278 EXPECT_EQ(payload.size(),
3279 connection_.SendStreamDataWithString(
3280 3, payload, 0, !kFin, nullptr).bytes_consumed);
3281 // Just like above, we save 8 bytes on payload, and 8 on truncation.
3282 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() + 8 * 2);
3285 TEST_P(QuicConnectionTest, SendDelayedAck) {
3286 QuicTime ack_time = clock_.ApproximateNow().Add(DefaultDelayedAckTime());
3287 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3288 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3289 const uint8 tag = 0x07;
3290 connection_.SetDecrypter(new StrictTaggingDecrypter(tag),
3291 ENCRYPTION_INITIAL);
3292 framer_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
3293 // Process a packet from the non-crypto stream.
3294 frame1_.stream_id = 3;
3296 // The same as ProcessPacket(1) except that ENCRYPTION_INITIAL is used
3297 // instead of ENCRYPTION_NONE.
3298 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
3299 ProcessDataPacketAtLevel(1, 0, !kEntropyFlag, ENCRYPTION_INITIAL);
3301 // Check if delayed ack timer is running for the expected interval.
3302 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3303 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
3304 // Simulate delayed ack alarm firing.
3305 connection_.GetAckAlarm()->Fire();
3306 // Check that ack is sent and that delayed ack alarm is reset.
3307 EXPECT_EQ(2u, writer_->frame_count());
3308 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3309 EXPECT_FALSE(writer_->ack_frames().empty());
3310 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3313 TEST_P(QuicConnectionTest, SendDelayedAckOnHandshakeConfirmed) {
3314 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3315 ProcessPacket(1);
3316 // Check that ack is sent and that delayed ack alarm is set.
3317 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3318 QuicTime ack_time = clock_.ApproximateNow().Add(DefaultDelayedAckTime());
3319 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
3321 // Completing the handshake as the server does nothing.
3322 QuicConnectionPeer::SetIsServer(&connection_, true);
3323 connection_.OnHandshakeComplete();
3324 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3325 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
3327 // Complete the handshake as the client decreases the delayed ack time to 0ms.
3328 QuicConnectionPeer::SetIsServer(&connection_, false);
3329 connection_.OnHandshakeComplete();
3330 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3331 EXPECT_EQ(clock_.ApproximateNow(), connection_.GetAckAlarm()->deadline());
3334 TEST_P(QuicConnectionTest, SendDelayedAckOnSecondPacket) {
3335 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3336 ProcessPacket(1);
3337 ProcessPacket(2);
3338 // Check that ack is sent and that delayed ack alarm is reset.
3339 EXPECT_EQ(2u, writer_->frame_count());
3340 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3341 EXPECT_FALSE(writer_->ack_frames().empty());
3342 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3345 TEST_P(QuicConnectionTest, NoAckOnOldNacks) {
3346 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3347 // Drop one packet, triggering a sequence of acks.
3348 ProcessPacket(2);
3349 size_t frames_per_ack = 2;
3350 EXPECT_EQ(frames_per_ack, writer_->frame_count());
3351 EXPECT_FALSE(writer_->ack_frames().empty());
3352 writer_->Reset();
3353 ProcessPacket(3);
3354 EXPECT_EQ(frames_per_ack, writer_->frame_count());
3355 EXPECT_FALSE(writer_->ack_frames().empty());
3356 writer_->Reset();
3357 ProcessPacket(4);
3358 EXPECT_EQ(frames_per_ack, writer_->frame_count());
3359 EXPECT_FALSE(writer_->ack_frames().empty());
3360 writer_->Reset();
3361 ProcessPacket(5);
3362 EXPECT_EQ(frames_per_ack, writer_->frame_count());
3363 EXPECT_FALSE(writer_->ack_frames().empty());
3364 writer_->Reset();
3365 // Now only set the timer on the 6th packet, instead of sending another ack.
3366 ProcessPacket(6);
3367 EXPECT_EQ(0u, writer_->frame_count());
3368 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3371 TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingPacket) {
3372 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3373 ProcessPacket(1);
3374 connection_.SendStreamDataWithString(kClientDataStreamId1, "foo", 0, !kFin,
3375 nullptr);
3376 // Check that ack is bundled with outgoing data and that delayed ack
3377 // alarm is reset.
3378 EXPECT_EQ(3u, writer_->frame_count());
3379 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3380 EXPECT_FALSE(writer_->ack_frames().empty());
3381 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3384 TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingCryptoPacket) {
3385 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3386 ProcessPacket(1);
3387 connection_.SendStreamDataWithString(kCryptoStreamId, "foo", 0, !kFin,
3388 nullptr);
3389 // Check that ack is bundled with outgoing crypto data.
3390 EXPECT_EQ(3u, writer_->frame_count());
3391 EXPECT_FALSE(writer_->ack_frames().empty());
3392 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3395 TEST_P(QuicConnectionTest, BlockAndBufferOnFirstCHLOPacketOfTwo) {
3396 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3397 ProcessPacket(1);
3398 BlockOnNextWrite();
3399 writer_->set_is_write_blocked_data_buffered(true);
3400 connection_.SendStreamDataWithString(kCryptoStreamId, "foo", 0, !kFin,
3401 nullptr);
3402 EXPECT_TRUE(writer_->IsWriteBlocked());
3403 EXPECT_FALSE(connection_.HasQueuedData());
3404 connection_.SendStreamDataWithString(kCryptoStreamId, "bar", 3, !kFin,
3405 nullptr);
3406 EXPECT_TRUE(writer_->IsWriteBlocked());
3407 EXPECT_TRUE(connection_.HasQueuedData());
3410 TEST_P(QuicConnectionTest, BundleAckForSecondCHLO) {
3411 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3412 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3413 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(
3414 IgnoreResult(InvokeWithoutArgs(&connection_,
3415 &TestConnection::SendCryptoStreamData)));
3416 // Process a packet from the crypto stream, which is frame1_'s default.
3417 // Receiving the CHLO as packet 2 first will cause the connection to
3418 // immediately send an ack, due to the packet gap.
3419 ProcessPacket(2);
3420 // Check that ack is sent and that delayed ack alarm is reset.
3421 EXPECT_EQ(3u, writer_->frame_count());
3422 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3423 EXPECT_EQ(1u, writer_->stream_frames().size());
3424 EXPECT_FALSE(writer_->ack_frames().empty());
3425 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3428 TEST_P(QuicConnectionTest, BundleAckWithDataOnIncomingAck) {
3429 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3430 connection_.SendStreamDataWithString(kClientDataStreamId1, "foo", 0, !kFin,
3431 nullptr);
3432 connection_.SendStreamDataWithString(kClientDataStreamId1, "foo", 3, !kFin,
3433 nullptr);
3434 // Ack the second packet, which will retransmit the first packet.
3435 QuicAckFrame ack = InitAckFrame(2);
3436 NackPacket(1, &ack);
3437 SequenceNumberSet lost_packets;
3438 lost_packets.insert(1);
3439 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3440 .WillOnce(Return(lost_packets));
3441 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3442 ProcessAckPacket(&ack);
3443 EXPECT_EQ(1u, writer_->frame_count());
3444 EXPECT_EQ(1u, writer_->stream_frames().size());
3445 writer_->Reset();
3447 // Now ack the retransmission, which will both raise the high water mark
3448 // and see if there is more data to send.
3449 ack = InitAckFrame(3);
3450 NackPacket(1, &ack);
3451 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3452 .WillOnce(Return(SequenceNumberSet()));
3453 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3454 ProcessAckPacket(&ack);
3456 // Check that no packet is sent and the ack alarm isn't set.
3457 EXPECT_EQ(0u, writer_->frame_count());
3458 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3459 writer_->Reset();
3461 // Send the same ack, but send both data and an ack together.
3462 ack = InitAckFrame(3);
3463 NackPacket(1, &ack);
3464 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3465 .WillOnce(Return(SequenceNumberSet()));
3466 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(
3467 IgnoreResult(InvokeWithoutArgs(
3468 &connection_,
3469 &TestConnection::EnsureWritableAndSendStreamData5)));
3470 ProcessAckPacket(&ack);
3472 // Check that ack is bundled with outgoing data and the delayed ack
3473 // alarm is reset.
3474 EXPECT_EQ(3u, writer_->frame_count());
3475 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3476 EXPECT_FALSE(writer_->ack_frames().empty());
3477 EXPECT_EQ(1u, writer_->stream_frames().size());
3478 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3481 TEST_P(QuicConnectionTest, NoAckSentForClose) {
3482 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3483 ProcessPacket(1);
3484 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, true));
3485 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3486 ProcessClosePacket(2, 0);
3489 TEST_P(QuicConnectionTest, SendWhenDisconnected) {
3490 EXPECT_TRUE(connection_.connected());
3491 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, false));
3492 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, false);
3493 EXPECT_FALSE(connection_.connected());
3494 EXPECT_FALSE(connection_.CanWriteStreamData());
3495 QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
3496 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 1, _, _)).Times(0);
3497 connection_.SendPacket(
3498 ENCRYPTION_NONE, 1, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA);
3501 TEST_P(QuicConnectionTest, PublicReset) {
3502 QuicPublicResetPacket header;
3503 header.public_header.connection_id = connection_id_;
3504 header.public_header.reset_flag = true;
3505 header.public_header.version_flag = false;
3506 header.rejected_sequence_number = 10101;
3507 scoped_ptr<QuicEncryptedPacket> packet(
3508 framer_.BuildPublicResetPacket(header));
3509 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PUBLIC_RESET, true));
3510 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *packet);
3513 TEST_P(QuicConnectionTest, GoAway) {
3514 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3516 QuicGoAwayFrame goaway;
3517 goaway.last_good_stream_id = 1;
3518 goaway.error_code = QUIC_PEER_GOING_AWAY;
3519 goaway.reason_phrase = "Going away.";
3520 EXPECT_CALL(visitor_, OnGoAway(_));
3521 ProcessGoAwayPacket(&goaway);
3524 TEST_P(QuicConnectionTest, WindowUpdate) {
3525 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3527 QuicWindowUpdateFrame window_update;
3528 window_update.stream_id = 3;
3529 window_update.byte_offset = 1234;
3530 EXPECT_CALL(visitor_, OnWindowUpdateFrames(_));
3531 ProcessFramePacket(QuicFrame(&window_update));
3534 TEST_P(QuicConnectionTest, Blocked) {
3535 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3537 QuicBlockedFrame blocked;
3538 blocked.stream_id = 3;
3539 EXPECT_CALL(visitor_, OnBlockedFrames(_));
3540 ProcessFramePacket(QuicFrame(&blocked));
3543 TEST_P(QuicConnectionTest, ZeroBytePacket) {
3544 // Don't close the connection for zero byte packets.
3545 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
3546 QuicEncryptedPacket encrypted(nullptr, 0);
3547 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), encrypted);
3550 TEST_P(QuicConnectionTest, MissingPacketsBeforeLeastUnacked) {
3551 // Set the sequence number of the ack packet to be least unacked (4).
3552 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 3);
3553 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3554 QuicStopWaitingFrame frame = InitStopWaitingFrame(4);
3555 ProcessStopWaitingPacket(&frame);
3556 EXPECT_TRUE(outgoing_ack()->missing_packets.empty());
3559 TEST_P(QuicConnectionTest, ReceivedEntropyHashCalculation) {
3560 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(AtLeast(1));
3561 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3562 ProcessDataPacket(1, 1, kEntropyFlag);
3563 ProcessDataPacket(4, 1, kEntropyFlag);
3564 ProcessDataPacket(3, 1, !kEntropyFlag);
3565 ProcessDataPacket(7, 1, kEntropyFlag);
3566 EXPECT_EQ(146u, outgoing_ack()->entropy_hash);
3569 TEST_P(QuicConnectionTest, ReceivedEntropyHashCalculationHalfFEC) {
3570 // FEC packets should not change the entropy hash calculation.
3571 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(AtLeast(1));
3572 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3573 ProcessDataPacket(1, 1, kEntropyFlag);
3574 ProcessFecPacket(4, 1, false, kEntropyFlag, nullptr);
3575 ProcessDataPacket(3, 3, !kEntropyFlag);
3576 ProcessFecPacket(7, 3, false, kEntropyFlag, nullptr);
3577 EXPECT_EQ(146u, outgoing_ack()->entropy_hash);
3580 TEST_P(QuicConnectionTest, UpdateEntropyForReceivedPackets) {
3581 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(AtLeast(1));
3582 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3583 ProcessDataPacket(1, 1, kEntropyFlag);
3584 ProcessDataPacket(5, 1, kEntropyFlag);
3585 ProcessDataPacket(4, 1, !kEntropyFlag);
3586 EXPECT_EQ(34u, outgoing_ack()->entropy_hash);
3587 // Make 4th packet my least unacked, and update entropy for 2, 3 packets.
3588 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 5);
3589 QuicPacketEntropyHash six_packet_entropy_hash = 0;
3590 QuicPacketEntropyHash kRandomEntropyHash = 129u;
3591 QuicStopWaitingFrame frame = InitStopWaitingFrame(4);
3592 frame.entropy_hash = kRandomEntropyHash;
3593 if (ProcessStopWaitingPacket(&frame)) {
3594 six_packet_entropy_hash = 1 << 6;
3597 EXPECT_EQ((kRandomEntropyHash + (1 << 5) + six_packet_entropy_hash),
3598 outgoing_ack()->entropy_hash);
3601 TEST_P(QuicConnectionTest, UpdateEntropyHashUptoCurrentPacket) {
3602 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(AtLeast(1));
3603 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3604 ProcessDataPacket(1, 1, kEntropyFlag);
3605 ProcessDataPacket(5, 1, !kEntropyFlag);
3606 ProcessDataPacket(22, 1, kEntropyFlag);
3607 EXPECT_EQ(66u, outgoing_ack()->entropy_hash);
3608 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 22);
3609 QuicPacketEntropyHash kRandomEntropyHash = 85u;
3610 // Current packet is the least unacked packet.
3611 QuicPacketEntropyHash ack_entropy_hash;
3612 QuicStopWaitingFrame frame = InitStopWaitingFrame(23);
3613 frame.entropy_hash = kRandomEntropyHash;
3614 ack_entropy_hash = ProcessStopWaitingPacket(&frame);
3615 EXPECT_EQ((kRandomEntropyHash + ack_entropy_hash),
3616 outgoing_ack()->entropy_hash);
3617 ProcessDataPacket(25, 1, kEntropyFlag);
3618 EXPECT_EQ((kRandomEntropyHash + ack_entropy_hash + (1 << (25 % 8))),
3619 outgoing_ack()->entropy_hash);
3622 TEST_P(QuicConnectionTest, EntropyCalculationForTruncatedAck) {
3623 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(AtLeast(1));
3624 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3625 QuicPacketEntropyHash entropy[51];
3626 entropy[0] = 0;
3627 for (int i = 1; i < 51; ++i) {
3628 bool should_send = i % 10 != 1;
3629 bool entropy_flag = (i & (i - 1)) != 0;
3630 if (!should_send) {
3631 entropy[i] = entropy[i - 1];
3632 continue;
3634 if (entropy_flag) {
3635 entropy[i] = entropy[i - 1] ^ (1 << (i % 8));
3636 } else {
3637 entropy[i] = entropy[i - 1];
3639 ProcessDataPacket(i, 1, entropy_flag);
3641 for (int i = 1; i < 50; ++i) {
3642 EXPECT_EQ(entropy[i], QuicConnectionPeer::ReceivedEntropyHash(
3643 &connection_, i));
3647 TEST_P(QuicConnectionTest, ServerSendsVersionNegotiationPacket) {
3648 connection_.SetSupportedVersions(QuicSupportedVersions());
3649 framer_.set_version_for_tests(QUIC_VERSION_UNSUPPORTED);
3651 QuicPacketHeader header;
3652 header.public_header.connection_id = connection_id_;
3653 header.public_header.reset_flag = false;
3654 header.public_header.version_flag = true;
3655 header.entropy_flag = false;
3656 header.fec_flag = false;
3657 header.packet_sequence_number = 12;
3658 header.fec_group = 0;
3660 QuicFrames frames;
3661 QuicFrame frame(&frame1_);
3662 frames.push_back(frame);
3663 scoped_ptr<QuicPacket> packet(
3664 BuildUnsizedDataPacket(&framer_, header, frames));
3665 scoped_ptr<QuicEncryptedPacket> encrypted(
3666 framer_.EncryptPacket(ENCRYPTION_NONE, 12, *packet));
3668 framer_.set_version(version());
3669 connection_.set_is_server(true);
3670 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3671 EXPECT_TRUE(writer_->version_negotiation_packet() != nullptr);
3673 size_t num_versions = arraysize(kSupportedQuicVersions);
3674 ASSERT_EQ(num_versions,
3675 writer_->version_negotiation_packet()->versions.size());
3677 // We expect all versions in kSupportedQuicVersions to be
3678 // included in the packet.
3679 for (size_t i = 0; i < num_versions; ++i) {
3680 EXPECT_EQ(kSupportedQuicVersions[i],
3681 writer_->version_negotiation_packet()->versions[i]);
3685 TEST_P(QuicConnectionTest, ServerSendsVersionNegotiationPacketSocketBlocked) {
3686 connection_.SetSupportedVersions(QuicSupportedVersions());
3687 framer_.set_version_for_tests(QUIC_VERSION_UNSUPPORTED);
3689 QuicPacketHeader header;
3690 header.public_header.connection_id = connection_id_;
3691 header.public_header.reset_flag = false;
3692 header.public_header.version_flag = true;
3693 header.entropy_flag = false;
3694 header.fec_flag = false;
3695 header.packet_sequence_number = 12;
3696 header.fec_group = 0;
3698 QuicFrames frames;
3699 QuicFrame frame(&frame1_);
3700 frames.push_back(frame);
3701 scoped_ptr<QuicPacket> packet(
3702 BuildUnsizedDataPacket(&framer_, header, frames));
3703 scoped_ptr<QuicEncryptedPacket> encrypted(
3704 framer_.EncryptPacket(ENCRYPTION_NONE, 12, *packet));
3706 framer_.set_version(version());
3707 connection_.set_is_server(true);
3708 BlockOnNextWrite();
3709 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3710 EXPECT_EQ(0u, writer_->last_packet_size());
3711 EXPECT_TRUE(connection_.HasQueuedData());
3713 writer_->SetWritable();
3714 connection_.OnCanWrite();
3715 EXPECT_TRUE(writer_->version_negotiation_packet() != nullptr);
3717 size_t num_versions = arraysize(kSupportedQuicVersions);
3718 ASSERT_EQ(num_versions,
3719 writer_->version_negotiation_packet()->versions.size());
3721 // We expect all versions in kSupportedQuicVersions to be
3722 // included in the packet.
3723 for (size_t i = 0; i < num_versions; ++i) {
3724 EXPECT_EQ(kSupportedQuicVersions[i],
3725 writer_->version_negotiation_packet()->versions[i]);
3729 TEST_P(QuicConnectionTest,
3730 ServerSendsVersionNegotiationPacketSocketBlockedDataBuffered) {
3731 connection_.SetSupportedVersions(QuicSupportedVersions());
3732 framer_.set_version_for_tests(QUIC_VERSION_UNSUPPORTED);
3734 QuicPacketHeader header;
3735 header.public_header.connection_id = connection_id_;
3736 header.public_header.reset_flag = false;
3737 header.public_header.version_flag = true;
3738 header.entropy_flag = false;
3739 header.fec_flag = false;
3740 header.packet_sequence_number = 12;
3741 header.fec_group = 0;
3743 QuicFrames frames;
3744 QuicFrame frame(&frame1_);
3745 frames.push_back(frame);
3746 scoped_ptr<QuicPacket> packet(
3747 BuildUnsizedDataPacket(&framer_, header, frames));
3748 scoped_ptr<QuicEncryptedPacket> encrypted(
3749 framer_.EncryptPacket(ENCRYPTION_NONE, 12, *packet));
3751 framer_.set_version(version());
3752 connection_.set_is_server(true);
3753 BlockOnNextWrite();
3754 writer_->set_is_write_blocked_data_buffered(true);
3755 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3756 EXPECT_EQ(0u, writer_->last_packet_size());
3757 EXPECT_FALSE(connection_.HasQueuedData());
3760 TEST_P(QuicConnectionTest, ClientHandlesVersionNegotiation) {
3761 // Start out with some unsupported version.
3762 QuicConnectionPeer::GetFramer(&connection_)->set_version_for_tests(
3763 QUIC_VERSION_UNSUPPORTED);
3765 QuicPacketHeader header;
3766 header.public_header.connection_id = connection_id_;
3767 header.public_header.reset_flag = false;
3768 header.public_header.version_flag = true;
3769 header.entropy_flag = false;
3770 header.fec_flag = false;
3771 header.packet_sequence_number = 12;
3772 header.fec_group = 0;
3774 QuicVersionVector supported_versions;
3775 for (size_t i = 0; i < arraysize(kSupportedQuicVersions); ++i) {
3776 supported_versions.push_back(kSupportedQuicVersions[i]);
3779 // Send a version negotiation packet.
3780 scoped_ptr<QuicEncryptedPacket> encrypted(
3781 framer_.BuildVersionNegotiationPacket(
3782 header.public_header, supported_versions));
3783 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3785 // Now force another packet. The connection should transition into
3786 // NEGOTIATED_VERSION state and tell the packet creator to StopSendingVersion.
3787 header.public_header.version_flag = false;
3788 QuicFrames frames;
3789 QuicFrame frame(&frame1_);
3790 frames.push_back(frame);
3791 scoped_ptr<QuicPacket> packet(
3792 BuildUnsizedDataPacket(&framer_, header, frames));
3793 encrypted.reset(framer_.EncryptPacket(ENCRYPTION_NONE, 12, *packet));
3794 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
3795 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3796 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3798 ASSERT_FALSE(QuicPacketCreatorPeer::SendVersionInPacket(creator_));
3801 TEST_P(QuicConnectionTest, BadVersionNegotiation) {
3802 QuicPacketHeader header;
3803 header.public_header.connection_id = connection_id_;
3804 header.public_header.reset_flag = false;
3805 header.public_header.version_flag = true;
3806 header.entropy_flag = false;
3807 header.fec_flag = false;
3808 header.packet_sequence_number = 12;
3809 header.fec_group = 0;
3811 QuicVersionVector supported_versions;
3812 for (size_t i = 0; i < arraysize(kSupportedQuicVersions); ++i) {
3813 supported_versions.push_back(kSupportedQuicVersions[i]);
3816 // Send a version negotiation packet with the version the client started with.
3817 // It should be rejected.
3818 EXPECT_CALL(visitor_,
3819 OnConnectionClosed(QUIC_INVALID_VERSION_NEGOTIATION_PACKET,
3820 false));
3821 scoped_ptr<QuicEncryptedPacket> encrypted(
3822 framer_.BuildVersionNegotiationPacket(
3823 header.public_header, supported_versions));
3824 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3827 TEST_P(QuicConnectionTest, CheckSendStats) {
3828 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3829 connection_.SendStreamDataWithString(3, "first", 0, !kFin, nullptr);
3830 size_t first_packet_size = writer_->last_packet_size();
3832 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3833 connection_.SendStreamDataWithString(5, "second", 0, !kFin, nullptr);
3834 size_t second_packet_size = writer_->last_packet_size();
3836 // 2 retransmissions due to rto, 1 due to explicit nack.
3837 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
3838 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
3840 // Retransmit due to RTO.
3841 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
3842 connection_.GetRetransmissionAlarm()->Fire();
3844 // Retransmit due to explicit nacks.
3845 QuicAckFrame nack_three = InitAckFrame(4);
3846 NackPacket(3, &nack_three);
3847 NackPacket(1, &nack_three);
3848 SequenceNumberSet lost_packets;
3849 lost_packets.insert(1);
3850 lost_packets.insert(3);
3851 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3852 .WillOnce(Return(lost_packets));
3853 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3854 EXPECT_CALL(visitor_, OnCanWrite()).Times(2);
3855 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3856 ProcessAckPacket(&nack_three);
3858 EXPECT_CALL(*send_algorithm_, BandwidthEstimate()).WillOnce(
3859 Return(QuicBandwidth::Zero()));
3861 const QuicConnectionStats& stats = connection_.GetStats();
3862 EXPECT_EQ(3 * first_packet_size + 2 * second_packet_size - kQuicVersionSize,
3863 stats.bytes_sent);
3864 EXPECT_EQ(5u, stats.packets_sent);
3865 EXPECT_EQ(2 * first_packet_size + second_packet_size - kQuicVersionSize,
3866 stats.bytes_retransmitted);
3867 EXPECT_EQ(3u, stats.packets_retransmitted);
3868 EXPECT_EQ(1u, stats.rto_count);
3869 EXPECT_EQ(kDefaultMaxPacketSize, stats.max_packet_size);
3872 TEST_P(QuicConnectionTest, CheckReceiveStats) {
3873 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3875 size_t received_bytes = 0;
3876 received_bytes += ProcessFecProtectedPacket(1, false, !kEntropyFlag);
3877 received_bytes += ProcessFecProtectedPacket(3, false, !kEntropyFlag);
3878 // Should be counted against dropped packets.
3879 received_bytes += ProcessDataPacket(3, 1, !kEntropyFlag);
3880 received_bytes += ProcessFecPacket(4, 1, true, !kEntropyFlag, nullptr);
3882 EXPECT_CALL(*send_algorithm_, BandwidthEstimate()).WillOnce(
3883 Return(QuicBandwidth::Zero()));
3885 const QuicConnectionStats& stats = connection_.GetStats();
3886 EXPECT_EQ(received_bytes, stats.bytes_received);
3887 EXPECT_EQ(4u, stats.packets_received);
3889 EXPECT_EQ(1u, stats.packets_revived);
3890 EXPECT_EQ(1u, stats.packets_dropped);
3893 TEST_P(QuicConnectionTest, TestFecGroupLimits) {
3894 // Create and return a group for 1.
3895 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 1) != nullptr);
3897 // Create and return a group for 2.
3898 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 2) != nullptr);
3900 // Create and return a group for 4. This should remove 1 but not 2.
3901 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 4) != nullptr);
3902 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 1) == nullptr);
3903 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 2) != nullptr);
3905 // Create and return a group for 3. This will kill off 2.
3906 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 3) != nullptr);
3907 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 2) == nullptr);
3909 // Verify that adding 5 kills off 3, despite 4 being created before 3.
3910 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 5) != nullptr);
3911 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 4) != nullptr);
3912 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 3) == nullptr);
3915 TEST_P(QuicConnectionTest, ProcessFramesIfPacketClosedConnection) {
3916 // Construct a packet with stream frame and connection close frame.
3917 header_.public_header.connection_id = connection_id_;
3918 header_.packet_sequence_number = 1;
3919 header_.public_header.reset_flag = false;
3920 header_.public_header.version_flag = false;
3921 header_.entropy_flag = false;
3922 header_.fec_flag = false;
3923 header_.fec_group = 0;
3925 QuicConnectionCloseFrame qccf;
3926 qccf.error_code = QUIC_PEER_GOING_AWAY;
3927 QuicFrame close_frame(&qccf);
3928 QuicFrame stream_frame(&frame1_);
3930 QuicFrames frames;
3931 frames.push_back(stream_frame);
3932 frames.push_back(close_frame);
3933 scoped_ptr<QuicPacket> packet(
3934 BuildUnsizedDataPacket(&framer_, header_, frames));
3935 EXPECT_TRUE(nullptr != packet.get());
3936 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPacket(
3937 ENCRYPTION_NONE, 1, *packet));
3939 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, true));
3940 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
3941 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3943 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3946 TEST_P(QuicConnectionTest, SelectMutualVersion) {
3947 connection_.SetSupportedVersions(QuicSupportedVersions());
3948 // Set the connection to speak the lowest quic version.
3949 connection_.set_version(QuicVersionMin());
3950 EXPECT_EQ(QuicVersionMin(), connection_.version());
3952 // Pass in available versions which includes a higher mutually supported
3953 // version. The higher mutually supported version should be selected.
3954 QuicVersionVector supported_versions;
3955 for (size_t i = 0; i < arraysize(kSupportedQuicVersions); ++i) {
3956 supported_versions.push_back(kSupportedQuicVersions[i]);
3958 EXPECT_TRUE(connection_.SelectMutualVersion(supported_versions));
3959 EXPECT_EQ(QuicVersionMax(), connection_.version());
3961 // Expect that the lowest version is selected.
3962 // Ensure the lowest supported version is less than the max, unless they're
3963 // the same.
3964 EXPECT_LE(QuicVersionMin(), QuicVersionMax());
3965 QuicVersionVector lowest_version_vector;
3966 lowest_version_vector.push_back(QuicVersionMin());
3967 EXPECT_TRUE(connection_.SelectMutualVersion(lowest_version_vector));
3968 EXPECT_EQ(QuicVersionMin(), connection_.version());
3970 // Shouldn't be able to find a mutually supported version.
3971 QuicVersionVector unsupported_version;
3972 unsupported_version.push_back(QUIC_VERSION_UNSUPPORTED);
3973 EXPECT_FALSE(connection_.SelectMutualVersion(unsupported_version));
3976 TEST_P(QuicConnectionTest, ConnectionCloseWhenWritable) {
3977 EXPECT_FALSE(writer_->IsWriteBlocked());
3979 // Send a packet.
3980 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
3981 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3982 EXPECT_EQ(1u, writer_->packets_write_attempts());
3984 TriggerConnectionClose();
3985 EXPECT_EQ(2u, writer_->packets_write_attempts());
3988 TEST_P(QuicConnectionTest, ConnectionCloseGettingWriteBlocked) {
3989 BlockOnNextWrite();
3990 TriggerConnectionClose();
3991 EXPECT_EQ(1u, writer_->packets_write_attempts());
3992 EXPECT_TRUE(writer_->IsWriteBlocked());
3995 TEST_P(QuicConnectionTest, ConnectionCloseWhenWriteBlocked) {
3996 BlockOnNextWrite();
3997 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
3998 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3999 EXPECT_EQ(1u, writer_->packets_write_attempts());
4000 EXPECT_TRUE(writer_->IsWriteBlocked());
4001 TriggerConnectionClose();
4002 EXPECT_EQ(1u, writer_->packets_write_attempts());
4005 TEST_P(QuicConnectionTest, AckNotifierTriggerCallback) {
4006 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4008 // Create a delegate which we expect to be called.
4009 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4010 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(1);
4012 // Send some data, which will register the delegate to be notified.
4013 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
4015 // Process an ACK from the server which should trigger the callback.
4016 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4017 QuicAckFrame frame = InitAckFrame(1);
4018 ProcessAckPacket(&frame);
4021 TEST_P(QuicConnectionTest, AckNotifierFailToTriggerCallback) {
4022 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4024 // Create a delegate which we don't expect to be called.
4025 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4026 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(0);
4028 // Send some data, which will register the delegate to be notified. This will
4029 // not be ACKed and so the delegate should never be called.
4030 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
4032 // Send some other data which we will ACK.
4033 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
4034 connection_.SendStreamDataWithString(1, "bar", 0, !kFin, nullptr);
4036 // Now we receive ACK for packets 2 and 3, but importantly missing packet 1
4037 // which we registered to be notified about.
4038 QuicAckFrame frame = InitAckFrame(3);
4039 NackPacket(1, &frame);
4040 SequenceNumberSet lost_packets;
4041 lost_packets.insert(1);
4042 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4043 .WillOnce(Return(lost_packets));
4044 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4045 ProcessAckPacket(&frame);
4048 TEST_P(QuicConnectionTest, AckNotifierCallbackAfterRetransmission) {
4049 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4051 // Create a delegate which we expect to be called.
4052 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4053 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(1);
4055 // Send four packets, and register to be notified on ACK of packet 2.
4056 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
4057 connection_.SendStreamDataWithString(3, "bar", 0, !kFin, delegate.get());
4058 connection_.SendStreamDataWithString(3, "baz", 0, !kFin, nullptr);
4059 connection_.SendStreamDataWithString(3, "qux", 0, !kFin, nullptr);
4061 // Now we receive ACK for packets 1, 3, and 4 and lose 2.
4062 QuicAckFrame frame = InitAckFrame(4);
4063 NackPacket(2, &frame);
4064 SequenceNumberSet lost_packets;
4065 lost_packets.insert(2);
4066 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4067 .WillOnce(Return(lost_packets));
4068 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4069 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4070 ProcessAckPacket(&frame);
4072 // Now we get an ACK for packet 5 (retransmitted packet 2), which should
4073 // trigger the callback.
4074 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4075 .WillRepeatedly(Return(SequenceNumberSet()));
4076 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4077 QuicAckFrame second_ack_frame = InitAckFrame(5);
4078 ProcessAckPacket(&second_ack_frame);
4081 // AckNotifierCallback is triggered by the ack of a packet that timed
4082 // out and was retransmitted, even though the retransmission has a
4083 // different sequence number.
4084 TEST_P(QuicConnectionTest, AckNotifierCallbackForAckAfterRTO) {
4085 InSequence s;
4087 // Create a delegate which we expect to be called.
4088 scoped_refptr<MockAckNotifierDelegate> delegate(
4089 new StrictMock<MockAckNotifierDelegate>);
4091 QuicTime default_retransmission_time = clock_.ApproximateNow().Add(
4092 DefaultRetransmissionTime());
4093 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, delegate.get());
4094 EXPECT_EQ(1u, stop_waiting()->least_unacked);
4096 EXPECT_EQ(1u, writer_->header().packet_sequence_number);
4097 EXPECT_EQ(default_retransmission_time,
4098 connection_.GetRetransmissionAlarm()->deadline());
4099 // Simulate the retransmission alarm firing.
4100 clock_.AdvanceTime(DefaultRetransmissionTime());
4101 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 2u, _, _));
4102 connection_.GetRetransmissionAlarm()->Fire();
4103 EXPECT_EQ(2u, writer_->header().packet_sequence_number);
4104 // We do not raise the high water mark yet.
4105 EXPECT_EQ(1u, stop_waiting()->least_unacked);
4107 // Ack the original packet, which will revert the RTO.
4108 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4109 EXPECT_CALL(*delegate, OnAckNotification(1, _, _));
4110 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4111 QuicAckFrame ack_frame = InitAckFrame(1);
4112 ProcessAckPacket(&ack_frame);
4114 // Delegate is not notified again when the retransmit is acked.
4115 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4116 QuicAckFrame second_ack_frame = InitAckFrame(2);
4117 ProcessAckPacket(&second_ack_frame);
4120 // AckNotifierCallback is triggered by the ack of a packet that was
4121 // previously nacked, even though the retransmission has a different
4122 // sequence number.
4123 TEST_P(QuicConnectionTest, AckNotifierCallbackForAckOfNackedPacket) {
4124 InSequence s;
4126 // Create a delegate which we expect to be called.
4127 scoped_refptr<MockAckNotifierDelegate> delegate(
4128 new StrictMock<MockAckNotifierDelegate>);
4130 // Send four packets, and register to be notified on ACK of packet 2.
4131 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
4132 connection_.SendStreamDataWithString(3, "bar", 0, !kFin, delegate.get());
4133 connection_.SendStreamDataWithString(3, "baz", 0, !kFin, nullptr);
4134 connection_.SendStreamDataWithString(3, "qux", 0, !kFin, nullptr);
4136 // Now we receive ACK for packets 1, 3, and 4 and lose 2.
4137 QuicAckFrame frame = InitAckFrame(4);
4138 NackPacket(2, &frame);
4139 SequenceNumberSet lost_packets;
4140 lost_packets.insert(2);
4141 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4142 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4143 .WillOnce(Return(lost_packets));
4144 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4145 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4146 ProcessAckPacket(&frame);
4148 // Now we get an ACK for packet 2, which was previously nacked.
4149 SequenceNumberSet no_lost_packets;
4150 EXPECT_CALL(*delegate.get(), OnAckNotification(1, _, _));
4151 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4152 .WillOnce(Return(no_lost_packets));
4153 QuicAckFrame second_ack_frame = InitAckFrame(4);
4154 ProcessAckPacket(&second_ack_frame);
4156 // Verify that the delegate is not notified again when the
4157 // retransmit is acked.
4158 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4159 .WillOnce(Return(no_lost_packets));
4160 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4161 QuicAckFrame third_ack_frame = InitAckFrame(5);
4162 ProcessAckPacket(&third_ack_frame);
4165 TEST_P(QuicConnectionTest, AckNotifierFECTriggerCallback) {
4166 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4168 // Create a delegate which we expect to be called.
4169 scoped_refptr<MockAckNotifierDelegate> delegate(
4170 new MockAckNotifierDelegate);
4171 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(1);
4173 // Send some data, which will register the delegate to be notified.
4174 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
4175 connection_.SendStreamDataWithString(2, "bar", 0, !kFin, nullptr);
4177 // Process an ACK from the server with a revived packet, which should trigger
4178 // the callback.
4179 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4180 QuicAckFrame frame = InitAckFrame(2);
4181 NackPacket(1, &frame);
4182 frame.revived_packets.insert(1);
4183 ProcessAckPacket(&frame);
4184 // If the ack is processed again, the notifier should not be called again.
4185 ProcessAckPacket(&frame);
4188 TEST_P(QuicConnectionTest, AckNotifierCallbackAfterFECRecovery) {
4189 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4190 EXPECT_CALL(visitor_, OnCanWrite());
4192 // Create a delegate which we expect to be called.
4193 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4194 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(1);
4196 // Expect ACKs for 1 packet.
4197 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4199 // Send one packet, and register to be notified on ACK.
4200 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
4202 // Ack packet gets dropped, but we receive an FEC packet that covers it.
4203 // Should recover the Ack packet and trigger the notification callback.
4204 QuicFrames frames;
4206 QuicAckFrame ack_frame = InitAckFrame(1);
4207 frames.push_back(QuicFrame(&ack_frame));
4209 // Dummy stream frame to satisfy expectations set elsewhere.
4210 frames.push_back(QuicFrame(&frame1_));
4212 QuicPacketHeader ack_header;
4213 ack_header.public_header.connection_id = connection_id_;
4214 ack_header.public_header.reset_flag = false;
4215 ack_header.public_header.version_flag = false;
4216 ack_header.entropy_flag = !kEntropyFlag;
4217 ack_header.fec_flag = true;
4218 ack_header.packet_sequence_number = 1;
4219 ack_header.is_in_fec_group = IN_FEC_GROUP;
4220 ack_header.fec_group = 1;
4222 QuicPacket* packet = BuildUnsizedDataPacket(&framer_, ack_header, frames);
4224 // Take the packet which contains the ACK frame, and construct and deliver an
4225 // FEC packet which allows the ACK packet to be recovered.
4226 ProcessFecPacket(2, 1, true, !kEntropyFlag, packet);
4229 TEST_P(QuicConnectionTest, NetworkChangeVisitorCwndCallbackChangesFecState) {
4230 size_t max_packets_per_fec_group = creator_->max_packets_per_fec_group();
4232 QuicSentPacketManager::NetworkChangeVisitor* visitor =
4233 QuicSentPacketManagerPeer::GetNetworkChangeVisitor(manager_);
4234 EXPECT_TRUE(visitor);
4236 // Increase FEC group size by increasing congestion window to a large number.
4237 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
4238 Return(1000 * kDefaultTCPMSS));
4239 visitor->OnCongestionWindowChange();
4240 EXPECT_LT(max_packets_per_fec_group, creator_->max_packets_per_fec_group());
4243 TEST_P(QuicConnectionTest, NetworkChangeVisitorConfigCallbackChangesFecState) {
4244 QuicSentPacketManager::NetworkChangeVisitor* visitor =
4245 QuicSentPacketManagerPeer::GetNetworkChangeVisitor(manager_);
4246 EXPECT_TRUE(visitor);
4247 EXPECT_EQ(QuicTime::Delta::Zero(),
4248 QuicPacketGeneratorPeer::GetFecTimeout(generator_));
4250 // Verify that sending a config with a new initial rtt changes fec timeout.
4251 // Create and process a config with a non-zero initial RTT.
4252 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _, _));
4253 QuicConfig config;
4254 config.SetInitialRoundTripTimeUsToSend(300000);
4255 connection_.SetFromConfig(config);
4256 EXPECT_LT(QuicTime::Delta::Zero(),
4257 QuicPacketGeneratorPeer::GetFecTimeout(generator_));
4260 TEST_P(QuicConnectionTest, NetworkChangeVisitorRttCallbackChangesFecState) {
4261 // Verify that sending a config with a new initial rtt changes fec timeout.
4262 QuicSentPacketManager::NetworkChangeVisitor* visitor =
4263 QuicSentPacketManagerPeer::GetNetworkChangeVisitor(manager_);
4264 EXPECT_TRUE(visitor);
4265 EXPECT_EQ(QuicTime::Delta::Zero(),
4266 QuicPacketGeneratorPeer::GetFecTimeout(generator_));
4268 // Increase FEC timeout by increasing RTT.
4269 RttStats* rtt_stats = QuicSentPacketManagerPeer::GetRttStats(manager_);
4270 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(300),
4271 QuicTime::Delta::Zero(), QuicTime::Zero());
4272 visitor->OnRttChange();
4273 EXPECT_LT(QuicTime::Delta::Zero(),
4274 QuicPacketGeneratorPeer::GetFecTimeout(generator_));
4277 class MockQuicConnectionDebugVisitor
4278 : public QuicConnectionDebugVisitor {
4279 public:
4280 MOCK_METHOD1(OnFrameAddedToPacket,
4281 void(const QuicFrame&));
4283 MOCK_METHOD6(OnPacketSent,
4284 void(const SerializedPacket&,
4285 QuicPacketSequenceNumber,
4286 EncryptionLevel,
4287 TransmissionType,
4288 const QuicEncryptedPacket&,
4289 QuicTime));
4291 MOCK_METHOD3(OnPacketReceived,
4292 void(const IPEndPoint&,
4293 const IPEndPoint&,
4294 const QuicEncryptedPacket&));
4296 MOCK_METHOD1(OnProtocolVersionMismatch,
4297 void(QuicVersion));
4299 MOCK_METHOD1(OnPacketHeader,
4300 void(const QuicPacketHeader& header));
4302 MOCK_METHOD1(OnStreamFrame,
4303 void(const QuicStreamFrame&));
4305 MOCK_METHOD1(OnAckFrame,
4306 void(const QuicAckFrame& frame));
4308 MOCK_METHOD1(OnStopWaitingFrame,
4309 void(const QuicStopWaitingFrame&));
4311 MOCK_METHOD1(OnRstStreamFrame,
4312 void(const QuicRstStreamFrame&));
4314 MOCK_METHOD1(OnConnectionCloseFrame,
4315 void(const QuicConnectionCloseFrame&));
4317 MOCK_METHOD1(OnPublicResetPacket,
4318 void(const QuicPublicResetPacket&));
4320 MOCK_METHOD1(OnVersionNegotiationPacket,
4321 void(const QuicVersionNegotiationPacket&));
4323 MOCK_METHOD2(OnRevivedPacket,
4324 void(const QuicPacketHeader&, StringPiece payload));
4327 TEST_P(QuicConnectionTest, OnPacketHeaderDebugVisitor) {
4328 QuicPacketHeader header;
4330 scoped_ptr<MockQuicConnectionDebugVisitor> debug_visitor(
4331 new MockQuicConnectionDebugVisitor());
4332 connection_.set_debug_visitor(debug_visitor.get());
4333 EXPECT_CALL(*debug_visitor, OnPacketHeader(Ref(header))).Times(1);
4334 connection_.OnPacketHeader(header);
4337 TEST_P(QuicConnectionTest, Pacing) {
4338 TestConnection server(connection_id_, IPEndPoint(), helper_.get(),
4339 factory_, /* is_server= */ true, version());
4340 TestConnection client(connection_id_, IPEndPoint(), helper_.get(),
4341 factory_, /* is_server= */ false, version());
4342 EXPECT_FALSE(client.sent_packet_manager().using_pacing());
4343 EXPECT_FALSE(server.sent_packet_manager().using_pacing());
4346 TEST_P(QuicConnectionTest, ControlFramesInstigateAcks) {
4347 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4349 // Send a WINDOW_UPDATE frame.
4350 QuicWindowUpdateFrame window_update;
4351 window_update.stream_id = 3;
4352 window_update.byte_offset = 1234;
4353 EXPECT_CALL(visitor_, OnWindowUpdateFrames(_));
4354 ProcessFramePacket(QuicFrame(&window_update));
4356 // Ensure that this has caused the ACK alarm to be set.
4357 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
4358 EXPECT_TRUE(ack_alarm->IsSet());
4360 // Cancel alarm, and try again with BLOCKED frame.
4361 ack_alarm->Cancel();
4362 QuicBlockedFrame blocked;
4363 blocked.stream_id = 3;
4364 EXPECT_CALL(visitor_, OnBlockedFrames(_));
4365 ProcessFramePacket(QuicFrame(&blocked));
4366 EXPECT_TRUE(ack_alarm->IsSet());
4369 TEST_P(QuicConnectionTest, NoDataNoFin) {
4370 // Make sure that a call to SendStreamWithData, with no data and no FIN, does
4371 // not result in a QuicAckNotifier being used-after-free (fail under ASAN).
4372 // Regression test for b/18594622
4373 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4374 EXPECT_DFATAL(
4375 connection_.SendStreamDataWithString(3, "", 0, !kFin, delegate.get()),
4376 "Attempt to send empty stream frame");
4379 } // namespace
4380 } // namespace test
4381 } // namespace net