Explicitly add python-numpy dependency to install-build-deps.
[chromium-blink-merge.git] / net / quic / quic_connection_test.cc
blobede61c8a98dc8aaec975c0470b680bef2bad7826
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/quic/quic_connection.h"
7 #include "base/basictypes.h"
8 #include "base/bind.h"
9 #include "base/stl_util.h"
10 #include "net/base/net_errors.h"
11 #include "net/quic/congestion_control/loss_detection_interface.h"
12 #include "net/quic/congestion_control/receive_algorithm_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_flags.h"
18 #include "net/quic/quic_protocol.h"
19 #include "net/quic/quic_utils.h"
20 #include "net/quic/test_tools/mock_clock.h"
21 #include "net/quic/test_tools/mock_random.h"
22 #include "net/quic/test_tools/quic_config_peer.h"
23 #include "net/quic/test_tools/quic_connection_peer.h"
24 #include "net/quic/test_tools/quic_framer_peer.h"
25 #include "net/quic/test_tools/quic_packet_creator_peer.h"
26 #include "net/quic/test_tools/quic_sent_packet_manager_peer.h"
27 #include "net/quic/test_tools/quic_test_utils.h"
28 #include "net/quic/test_tools/simple_quic_framer.h"
29 #include "testing/gmock/include/gmock/gmock.h"
30 #include "testing/gtest/include/gtest/gtest.h"
32 using base::StringPiece;
33 using std::map;
34 using std::vector;
35 using testing::AnyNumber;
36 using testing::AtLeast;
37 using testing::ContainerEq;
38 using testing::Contains;
39 using testing::DoAll;
40 using testing::InSequence;
41 using testing::InvokeWithoutArgs;
42 using testing::NiceMock;
43 using testing::Ref;
44 using testing::Return;
45 using testing::SaveArg;
46 using testing::StrictMock;
47 using testing::_;
49 namespace net {
50 namespace test {
51 namespace {
53 const char data1[] = "foo";
54 const char data2[] = "bar";
56 const bool kFin = true;
57 const bool kEntropyFlag = true;
59 const QuicPacketEntropyHash kTestEntropyHash = 76;
61 const int kDefaultRetransmissionTimeMs = 500;
63 class TestReceiveAlgorithm : public ReceiveAlgorithmInterface {
64 public:
65 explicit TestReceiveAlgorithm(QuicCongestionFeedbackFrame* feedback)
66 : feedback_(feedback) {
69 bool GenerateCongestionFeedback(
70 QuicCongestionFeedbackFrame* congestion_feedback) override {
71 if (feedback_ == nullptr) {
72 return false;
74 *congestion_feedback = *feedback_;
75 return true;
78 MOCK_METHOD3(RecordIncomingPacket,
79 void(QuicByteCount, QuicPacketSequenceNumber, QuicTime));
81 private:
82 QuicCongestionFeedbackFrame* feedback_;
84 DISALLOW_COPY_AND_ASSIGN(TestReceiveAlgorithm);
87 // TaggingEncrypter appends kTagSize bytes of |tag| to the end of each message.
88 class TaggingEncrypter : public QuicEncrypter {
89 public:
90 explicit TaggingEncrypter(uint8 tag)
91 : tag_(tag) {
94 ~TaggingEncrypter() override {}
96 // QuicEncrypter interface.
97 bool SetKey(StringPiece key) override { return true; }
99 bool SetNoncePrefix(StringPiece nonce_prefix) override { return true; }
101 bool Encrypt(StringPiece nonce,
102 StringPiece associated_data,
103 StringPiece plaintext,
104 unsigned char* output) override {
105 memcpy(output, plaintext.data(), plaintext.size());
106 output += plaintext.size();
107 memset(output, tag_, kTagSize);
108 return true;
111 QuicData* EncryptPacket(QuicPacketSequenceNumber sequence_number,
112 StringPiece associated_data,
113 StringPiece plaintext) override {
114 const size_t len = plaintext.size() + kTagSize;
115 uint8* buffer = new uint8[len];
116 Encrypt(StringPiece(), associated_data, plaintext, buffer);
117 return new QuicData(reinterpret_cast<char*>(buffer), len, true);
120 size_t GetKeySize() const override { return 0; }
121 size_t GetNoncePrefixSize() const override { return 0; }
123 size_t GetMaxPlaintextSize(size_t ciphertext_size) const override {
124 return ciphertext_size - kTagSize;
127 size_t GetCiphertextSize(size_t plaintext_size) const override {
128 return plaintext_size + kTagSize;
131 StringPiece GetKey() const override { return StringPiece(); }
133 StringPiece GetNoncePrefix() const override { return StringPiece(); }
135 private:
136 enum {
137 kTagSize = 12,
140 const uint8 tag_;
142 DISALLOW_COPY_AND_ASSIGN(TaggingEncrypter);
145 // TaggingDecrypter ensures that the final kTagSize bytes of the message all
146 // have the same value and then removes them.
147 class TaggingDecrypter : public QuicDecrypter {
148 public:
149 ~TaggingDecrypter() override {}
151 // QuicDecrypter interface
152 bool SetKey(StringPiece key) override { return true; }
154 bool SetNoncePrefix(StringPiece nonce_prefix) override { return true; }
156 bool Decrypt(StringPiece nonce,
157 StringPiece associated_data,
158 StringPiece ciphertext,
159 unsigned char* output,
160 size_t* output_length) override {
161 if (ciphertext.size() < kTagSize) {
162 return false;
164 if (!CheckTag(ciphertext, GetTag(ciphertext))) {
165 return false;
167 *output_length = ciphertext.size() - kTagSize;
168 memcpy(output, ciphertext.data(), *output_length);
169 return true;
172 QuicData* DecryptPacket(QuicPacketSequenceNumber sequence_number,
173 StringPiece associated_data,
174 StringPiece ciphertext) override {
175 if (ciphertext.size() < kTagSize) {
176 return nullptr;
178 if (!CheckTag(ciphertext, GetTag(ciphertext))) {
179 return nullptr;
181 const size_t len = ciphertext.size() - kTagSize;
182 uint8* buf = new uint8[len];
183 memcpy(buf, ciphertext.data(), len);
184 return new QuicData(reinterpret_cast<char*>(buf), len,
185 true /* owns buffer */);
188 StringPiece GetKey() const override { return StringPiece(); }
189 StringPiece GetNoncePrefix() const override { return StringPiece(); }
191 protected:
192 virtual uint8 GetTag(StringPiece ciphertext) {
193 return ciphertext.data()[ciphertext.size()-1];
196 private:
197 enum {
198 kTagSize = 12,
201 bool CheckTag(StringPiece ciphertext, uint8 tag) {
202 for (size_t i = ciphertext.size() - kTagSize; i < ciphertext.size(); i++) {
203 if (ciphertext.data()[i] != tag) {
204 return false;
208 return true;
212 // StringTaggingDecrypter ensures that the final kTagSize bytes of the message
213 // match the expected value.
214 class StrictTaggingDecrypter : public TaggingDecrypter {
215 public:
216 explicit StrictTaggingDecrypter(uint8 tag) : tag_(tag) {}
217 ~StrictTaggingDecrypter() override {}
219 // TaggingQuicDecrypter
220 uint8 GetTag(StringPiece ciphertext) override { return tag_; }
222 private:
223 const uint8 tag_;
226 class TestConnectionHelper : public QuicConnectionHelperInterface {
227 public:
228 class TestAlarm : public QuicAlarm {
229 public:
230 explicit TestAlarm(QuicAlarm::Delegate* delegate)
231 : QuicAlarm(delegate) {
234 void SetImpl() override {}
235 void CancelImpl() override {}
236 using QuicAlarm::Fire;
239 TestConnectionHelper(MockClock* clock, MockRandom* random_generator)
240 : clock_(clock),
241 random_generator_(random_generator) {
242 clock_->AdvanceTime(QuicTime::Delta::FromSeconds(1));
245 // QuicConnectionHelperInterface
246 const QuicClock* GetClock() const override { return clock_; }
248 QuicRandom* GetRandomGenerator() override { return random_generator_; }
250 QuicAlarm* CreateAlarm(QuicAlarm::Delegate* delegate) override {
251 return new TestAlarm(delegate);
254 private:
255 MockClock* clock_;
256 MockRandom* random_generator_;
258 DISALLOW_COPY_AND_ASSIGN(TestConnectionHelper);
261 class TestPacketWriter : public QuicPacketWriter {
262 public:
263 TestPacketWriter(QuicVersion version, MockClock *clock)
264 : version_(version),
265 framer_(SupportedVersions(version_)),
266 last_packet_size_(0),
267 write_blocked_(false),
268 block_on_next_write_(false),
269 is_write_blocked_data_buffered_(false),
270 final_bytes_of_last_packet_(0),
271 final_bytes_of_previous_packet_(0),
272 use_tagging_decrypter_(false),
273 packets_write_attempts_(0),
274 clock_(clock),
275 write_pause_time_delta_(QuicTime::Delta::Zero()) {
278 // QuicPacketWriter interface
279 WriteResult WritePacket(const char* buffer,
280 size_t buf_len,
281 const IPAddressNumber& self_address,
282 const IPEndPoint& peer_address) override {
283 QuicEncryptedPacket packet(buffer, buf_len);
284 ++packets_write_attempts_;
286 if (packet.length() >= sizeof(final_bytes_of_last_packet_)) {
287 final_bytes_of_previous_packet_ = final_bytes_of_last_packet_;
288 memcpy(&final_bytes_of_last_packet_, packet.data() + packet.length() - 4,
289 sizeof(final_bytes_of_last_packet_));
292 if (use_tagging_decrypter_) {
293 framer_.framer()->SetDecrypter(new TaggingDecrypter, ENCRYPTION_NONE);
295 EXPECT_TRUE(framer_.ProcessPacket(packet));
296 if (block_on_next_write_) {
297 write_blocked_ = true;
298 block_on_next_write_ = false;
300 if (IsWriteBlocked()) {
301 return WriteResult(WRITE_STATUS_BLOCKED, -1);
303 last_packet_size_ = packet.length();
305 if (!write_pause_time_delta_.IsZero()) {
306 clock_->AdvanceTime(write_pause_time_delta_);
308 return WriteResult(WRITE_STATUS_OK, last_packet_size_);
311 bool IsWriteBlockedDataBuffered() const override {
312 return is_write_blocked_data_buffered_;
315 bool IsWriteBlocked() const override { return write_blocked_; }
317 void SetWritable() override { write_blocked_ = false; }
319 void BlockOnNextWrite() { block_on_next_write_ = true; }
321 // Sets the amount of time that the writer should before the actual write.
322 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
323 write_pause_time_delta_ = delta;
326 const QuicPacketHeader& header() { return framer_.header(); }
328 size_t frame_count() const { return framer_.num_frames(); }
330 const vector<QuicAckFrame>& ack_frames() const {
331 return framer_.ack_frames();
334 const vector<QuicCongestionFeedbackFrame>& feedback_frames() const {
335 return framer_.feedback_frames();
338 const vector<QuicStopWaitingFrame>& stop_waiting_frames() const {
339 return framer_.stop_waiting_frames();
342 const vector<QuicConnectionCloseFrame>& connection_close_frames() const {
343 return framer_.connection_close_frames();
346 const vector<QuicStreamFrame>& stream_frames() const {
347 return framer_.stream_frames();
350 const vector<QuicPingFrame>& ping_frames() const {
351 return framer_.ping_frames();
354 size_t last_packet_size() {
355 return last_packet_size_;
358 const QuicVersionNegotiationPacket* version_negotiation_packet() {
359 return framer_.version_negotiation_packet();
362 void set_is_write_blocked_data_buffered(bool buffered) {
363 is_write_blocked_data_buffered_ = buffered;
366 void set_is_server(bool is_server) {
367 // We invert is_server here, because the framer needs to parse packets
368 // we send.
369 QuicFramerPeer::SetIsServer(framer_.framer(), !is_server);
372 // final_bytes_of_last_packet_ returns the last four bytes of the previous
373 // packet as a little-endian, uint32. This is intended to be used with a
374 // TaggingEncrypter so that tests can determine which encrypter was used for
375 // a given packet.
376 uint32 final_bytes_of_last_packet() { return final_bytes_of_last_packet_; }
378 // Returns the final bytes of the second to last packet.
379 uint32 final_bytes_of_previous_packet() {
380 return final_bytes_of_previous_packet_;
383 void use_tagging_decrypter() {
384 use_tagging_decrypter_ = true;
387 uint32 packets_write_attempts() { return packets_write_attempts_; }
389 void Reset() { framer_.Reset(); }
391 void SetSupportedVersions(const QuicVersionVector& versions) {
392 framer_.SetSupportedVersions(versions);
395 private:
396 QuicVersion version_;
397 SimpleQuicFramer framer_;
398 size_t last_packet_size_;
399 bool write_blocked_;
400 bool block_on_next_write_;
401 bool is_write_blocked_data_buffered_;
402 uint32 final_bytes_of_last_packet_;
403 uint32 final_bytes_of_previous_packet_;
404 bool use_tagging_decrypter_;
405 uint32 packets_write_attempts_;
406 MockClock *clock_;
407 // If non-zero, the clock will pause during WritePacket for this amount of
408 // time.
409 QuicTime::Delta write_pause_time_delta_;
411 DISALLOW_COPY_AND_ASSIGN(TestPacketWriter);
414 class TestConnection : public QuicConnection {
415 public:
416 TestConnection(QuicConnectionId connection_id,
417 IPEndPoint address,
418 TestConnectionHelper* helper,
419 const PacketWriterFactory& factory,
420 bool is_server,
421 QuicVersion version)
422 : QuicConnection(connection_id,
423 address,
424 helper,
425 factory,
426 /* owns_writer= */ false,
427 is_server,
428 /* is_secure= */ false,
429 SupportedVersions(version)) {
430 // Disable tail loss probes for most tests.
431 QuicSentPacketManagerPeer::SetMaxTailLossProbes(
432 QuicConnectionPeer::GetSentPacketManager(this), 0);
433 writer()->set_is_server(is_server);
436 void SendAck() {
437 QuicConnectionPeer::SendAck(this);
440 void SetReceiveAlgorithm(TestReceiveAlgorithm* receive_algorithm) {
441 QuicConnectionPeer::SetReceiveAlgorithm(this, receive_algorithm);
444 void SetSendAlgorithm(SendAlgorithmInterface* send_algorithm) {
445 QuicConnectionPeer::SetSendAlgorithm(this, send_algorithm);
448 void SetLossAlgorithm(LossDetectionInterface* loss_algorithm) {
449 QuicSentPacketManagerPeer::SetLossAlgorithm(
450 QuicConnectionPeer::GetSentPacketManager(this), loss_algorithm);
453 void SendPacket(EncryptionLevel level,
454 QuicPacketSequenceNumber sequence_number,
455 QuicPacket* packet,
456 QuicPacketEntropyHash entropy_hash,
457 HasRetransmittableData retransmittable) {
458 RetransmittableFrames* retransmittable_frames =
459 retransmittable == HAS_RETRANSMITTABLE_DATA
460 ? new RetransmittableFrames()
461 : nullptr;
462 OnSerializedPacket(
463 SerializedPacket(sequence_number, PACKET_6BYTE_SEQUENCE_NUMBER,
464 packet, entropy_hash, retransmittable_frames));
467 QuicConsumedData SendStreamDataWithString(
468 QuicStreamId id,
469 StringPiece data,
470 QuicStreamOffset offset,
471 bool fin,
472 QuicAckNotifier::DelegateInterface* delegate) {
473 return SendStreamDataWithStringHelper(id, data, offset, fin,
474 MAY_FEC_PROTECT, delegate);
477 QuicConsumedData SendStreamDataWithStringWithFec(
478 QuicStreamId id,
479 StringPiece data,
480 QuicStreamOffset offset,
481 bool fin,
482 QuicAckNotifier::DelegateInterface* delegate) {
483 return SendStreamDataWithStringHelper(id, data, offset, fin,
484 MUST_FEC_PROTECT, delegate);
487 QuicConsumedData SendStreamDataWithStringHelper(
488 QuicStreamId id,
489 StringPiece data,
490 QuicStreamOffset offset,
491 bool fin,
492 FecProtection fec_protection,
493 QuicAckNotifier::DelegateInterface* delegate) {
494 IOVector data_iov;
495 if (!data.empty()) {
496 data_iov.Append(const_cast<char*>(data.data()), data.size());
498 return QuicConnection::SendStreamData(id, data_iov, offset, fin,
499 fec_protection, delegate);
502 QuicConsumedData SendStreamData3() {
503 return SendStreamDataWithString(kClientDataStreamId1, "food", 0, !kFin,
504 nullptr);
507 QuicConsumedData SendStreamData3WithFec() {
508 return SendStreamDataWithStringWithFec(kClientDataStreamId1, "food", 0,
509 !kFin, nullptr);
512 QuicConsumedData SendStreamData5() {
513 return SendStreamDataWithString(kClientDataStreamId2, "food2", 0, !kFin,
514 nullptr);
517 QuicConsumedData SendStreamData5WithFec() {
518 return SendStreamDataWithStringWithFec(kClientDataStreamId2, "food2", 0,
519 !kFin, nullptr);
521 // Ensures the connection can write stream data before writing.
522 QuicConsumedData EnsureWritableAndSendStreamData5() {
523 EXPECT_TRUE(CanWriteStreamData());
524 return SendStreamData5();
527 // The crypto stream has special semantics so that it is not blocked by a
528 // congestion window limitation, and also so that it gets put into a separate
529 // packet (so that it is easier to reason about a crypto frame not being
530 // split needlessly across packet boundaries). As a result, we have separate
531 // tests for some cases for this stream.
532 QuicConsumedData SendCryptoStreamData() {
533 return SendStreamDataWithString(kCryptoStreamId, "chlo", 0, !kFin, nullptr);
536 bool is_server() {
537 return QuicConnectionPeer::IsServer(this);
540 void set_version(QuicVersion version) {
541 QuicConnectionPeer::GetFramer(this)->set_version(version);
544 void SetSupportedVersions(const QuicVersionVector& versions) {
545 QuicConnectionPeer::GetFramer(this)->SetSupportedVersions(versions);
546 writer()->SetSupportedVersions(versions);
549 void set_is_server(bool is_server) {
550 writer()->set_is_server(is_server);
551 QuicConnectionPeer::SetIsServer(this, is_server);
554 TestConnectionHelper::TestAlarm* GetAckAlarm() {
555 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
556 QuicConnectionPeer::GetAckAlarm(this));
559 TestConnectionHelper::TestAlarm* GetPingAlarm() {
560 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
561 QuicConnectionPeer::GetPingAlarm(this));
564 TestConnectionHelper::TestAlarm* GetResumeWritesAlarm() {
565 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
566 QuicConnectionPeer::GetResumeWritesAlarm(this));
569 TestConnectionHelper::TestAlarm* GetRetransmissionAlarm() {
570 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
571 QuicConnectionPeer::GetRetransmissionAlarm(this));
574 TestConnectionHelper::TestAlarm* GetSendAlarm() {
575 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
576 QuicConnectionPeer::GetSendAlarm(this));
579 TestConnectionHelper::TestAlarm* GetTimeoutAlarm() {
580 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
581 QuicConnectionPeer::GetTimeoutAlarm(this));
584 using QuicConnection::SelectMutualVersion;
586 private:
587 TestPacketWriter* writer() {
588 return static_cast<TestPacketWriter*>(QuicConnection::writer());
591 DISALLOW_COPY_AND_ASSIGN(TestConnection);
594 // Used for testing packets revived from FEC packets.
595 class FecQuicConnectionDebugVisitor
596 : public QuicConnectionDebugVisitor {
597 public:
598 void OnRevivedPacket(const QuicPacketHeader& header,
599 StringPiece data) override {
600 revived_header_ = header;
603 // Public accessor method.
604 QuicPacketHeader revived_header() const {
605 return revived_header_;
608 private:
609 QuicPacketHeader revived_header_;
612 class MockPacketWriterFactory : public QuicConnection::PacketWriterFactory {
613 public:
614 MockPacketWriterFactory(QuicPacketWriter* writer) {
615 ON_CALL(*this, Create(_)).WillByDefault(Return(writer));
617 ~MockPacketWriterFactory() override {}
619 MOCK_CONST_METHOD1(Create, QuicPacketWriter*(QuicConnection* connection));
622 class QuicConnectionTest : public ::testing::TestWithParam<QuicVersion> {
623 protected:
624 QuicConnectionTest()
625 : connection_id_(42),
626 framer_(SupportedVersions(version()), QuicTime::Zero(), false),
627 peer_creator_(connection_id_, &framer_, &random_generator_),
628 send_algorithm_(new StrictMock<MockSendAlgorithm>),
629 loss_algorithm_(new MockLossAlgorithm()),
630 helper_(new TestConnectionHelper(&clock_, &random_generator_)),
631 writer_(new TestPacketWriter(version(), &clock_)),
632 factory_(writer_.get()),
633 connection_(connection_id_, IPEndPoint(), helper_.get(),
634 factory_, false, version()),
635 frame1_(1, false, 0, MakeIOVector(data1)),
636 frame2_(1, false, 3, MakeIOVector(data2)),
637 sequence_number_length_(PACKET_6BYTE_SEQUENCE_NUMBER),
638 connection_id_length_(PACKET_8BYTE_CONNECTION_ID) {
639 connection_.set_visitor(&visitor_);
640 connection_.SetSendAlgorithm(send_algorithm_);
641 connection_.SetLossAlgorithm(loss_algorithm_);
642 framer_.set_received_entropy_calculator(&entropy_calculator_);
643 // Simplify tests by not sending feedback unless specifically configured.
644 SetFeedback(nullptr);
645 EXPECT_CALL(
646 *send_algorithm_, TimeUntilSend(_, _, _)).WillRepeatedly(Return(
647 QuicTime::Delta::Zero()));
648 EXPECT_CALL(*receive_algorithm_,
649 RecordIncomingPacket(_, _, _)).Times(AnyNumber());
650 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
651 .Times(AnyNumber());
652 EXPECT_CALL(*send_algorithm_, RetransmissionDelay()).WillRepeatedly(
653 Return(QuicTime::Delta::Zero()));
654 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
655 Return(kMaxPacketSize));
656 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
657 .WillByDefault(Return(true));
658 EXPECT_CALL(*send_algorithm_, HasReliableBandwidthEstimate())
659 .Times(AnyNumber());
660 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
661 .Times(AnyNumber())
662 .WillRepeatedly(Return(QuicBandwidth::Zero()));
663 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
664 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
665 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).Times(AnyNumber());
666 EXPECT_CALL(visitor_, HasPendingHandshake()).Times(AnyNumber());
667 EXPECT_CALL(visitor_, OnCanWrite()).Times(AnyNumber());
668 EXPECT_CALL(visitor_, HasOpenDataStreams()).WillRepeatedly(Return(false));
669 EXPECT_CALL(visitor_, OnCongestionWindowChange(_)).Times(AnyNumber());
671 EXPECT_CALL(*loss_algorithm_, GetLossTimeout())
672 .WillRepeatedly(Return(QuicTime::Zero()));
673 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
674 .WillRepeatedly(Return(SequenceNumberSet()));
677 QuicVersion version() {
678 return GetParam();
681 QuicAckFrame* outgoing_ack() {
682 outgoing_ack_.reset(QuicConnectionPeer::CreateAckFrame(&connection_));
683 return outgoing_ack_.get();
686 QuicStopWaitingFrame* stop_waiting() {
687 stop_waiting_.reset(
688 QuicConnectionPeer::CreateStopWaitingFrame(&connection_));
689 return stop_waiting_.get();
692 QuicPacketSequenceNumber least_unacked() {
693 if (writer_->stop_waiting_frames().empty()) {
694 return 0;
696 return writer_->stop_waiting_frames()[0].least_unacked;
699 void use_tagging_decrypter() {
700 writer_->use_tagging_decrypter();
703 void ProcessPacket(QuicPacketSequenceNumber number) {
704 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
705 ProcessDataPacket(number, 0, !kEntropyFlag);
708 QuicPacketEntropyHash ProcessFramePacket(QuicFrame frame) {
709 QuicFrames frames;
710 frames.push_back(QuicFrame(frame));
711 QuicPacketCreatorPeer::SetSendVersionInPacket(&peer_creator_,
712 connection_.is_server());
713 SerializedPacket serialized_packet =
714 peer_creator_.SerializeAllFrames(frames);
715 scoped_ptr<QuicPacket> packet(serialized_packet.packet);
716 scoped_ptr<QuicEncryptedPacket> encrypted(
717 framer_.EncryptPacket(ENCRYPTION_NONE,
718 serialized_packet.sequence_number, *packet));
719 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
720 return serialized_packet.entropy_hash;
723 size_t ProcessDataPacket(QuicPacketSequenceNumber number,
724 QuicFecGroupNumber fec_group,
725 bool entropy_flag) {
726 return ProcessDataPacketAtLevel(number, fec_group, entropy_flag,
727 ENCRYPTION_NONE);
730 size_t ProcessDataPacketAtLevel(QuicPacketSequenceNumber number,
731 QuicFecGroupNumber fec_group,
732 bool entropy_flag,
733 EncryptionLevel level) {
734 scoped_ptr<QuicPacket> packet(ConstructDataPacket(number, fec_group,
735 entropy_flag));
736 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPacket(
737 level, number, *packet));
738 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
739 return encrypted->length();
742 void ProcessPingPacket(QuicPacketSequenceNumber number) {
743 scoped_ptr<QuicPacket> packet(ConstructPingPacket(number));
744 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPacket(
745 ENCRYPTION_NONE, number, *packet));
746 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
749 void ProcessClosePacket(QuicPacketSequenceNumber number,
750 QuicFecGroupNumber fec_group) {
751 scoped_ptr<QuicPacket> packet(ConstructClosePacket(number, fec_group));
752 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPacket(
753 ENCRYPTION_NONE, number, *packet));
754 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
757 size_t ProcessFecProtectedPacket(QuicPacketSequenceNumber number,
758 bool expect_revival, bool entropy_flag) {
759 if (expect_revival) {
760 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
762 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1).
763 RetiresOnSaturation();
764 return ProcessDataPacket(number, 1, entropy_flag);
767 // Processes an FEC packet that covers the packets that would have been
768 // received.
769 size_t ProcessFecPacket(QuicPacketSequenceNumber number,
770 QuicPacketSequenceNumber min_protected_packet,
771 bool expect_revival,
772 bool entropy_flag,
773 QuicPacket* packet) {
774 if (expect_revival) {
775 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
778 // Construct the decrypted data packet so we can compute the correct
779 // redundancy. If |packet| has been provided then use that, otherwise
780 // construct a default data packet.
781 scoped_ptr<QuicPacket> data_packet;
782 if (packet) {
783 data_packet.reset(packet);
784 } else {
785 data_packet.reset(ConstructDataPacket(number, 1, !kEntropyFlag));
788 header_.public_header.connection_id = connection_id_;
789 header_.public_header.reset_flag = false;
790 header_.public_header.version_flag = false;
791 header_.public_header.sequence_number_length = sequence_number_length_;
792 header_.public_header.connection_id_length = connection_id_length_;
793 header_.packet_sequence_number = number;
794 header_.entropy_flag = entropy_flag;
795 header_.fec_flag = true;
796 header_.is_in_fec_group = IN_FEC_GROUP;
797 header_.fec_group = min_protected_packet;
798 QuicFecData fec_data;
799 fec_data.fec_group = header_.fec_group;
801 // Since all data packets in this test have the same payload, the
802 // redundancy is either equal to that payload or the xor of that payload
803 // with itself, depending on the number of packets.
804 if (((number - min_protected_packet) % 2) == 0) {
805 for (size_t i = GetStartOfFecProtectedData(
806 header_.public_header.connection_id_length,
807 header_.public_header.version_flag,
808 header_.public_header.sequence_number_length);
809 i < data_packet->length(); ++i) {
810 data_packet->mutable_data()[i] ^= data_packet->data()[i];
813 fec_data.redundancy = data_packet->FecProtectedData();
815 scoped_ptr<QuicPacket> fec_packet(
816 framer_.BuildFecPacket(header_, fec_data).packet);
817 scoped_ptr<QuicEncryptedPacket> encrypted(
818 framer_.EncryptPacket(ENCRYPTION_NONE, number, *fec_packet));
820 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
821 return encrypted->length();
824 QuicByteCount SendStreamDataToPeer(QuicStreamId id,
825 StringPiece data,
826 QuicStreamOffset offset,
827 bool fin,
828 QuicPacketSequenceNumber* last_packet) {
829 QuicByteCount packet_size;
830 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
831 .WillOnce(DoAll(SaveArg<3>(&packet_size), Return(true)));
832 connection_.SendStreamDataWithString(id, data, offset, fin, nullptr);
833 if (last_packet != nullptr) {
834 *last_packet =
835 QuicConnectionPeer::GetPacketCreator(&connection_)->sequence_number();
837 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
838 .Times(AnyNumber());
839 return packet_size;
842 void SendAckPacketToPeer() {
843 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
844 connection_.SendAck();
845 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
846 .Times(AnyNumber());
849 QuicPacketEntropyHash ProcessAckPacket(QuicAckFrame* frame) {
850 return ProcessFramePacket(QuicFrame(frame));
853 QuicPacketEntropyHash ProcessStopWaitingPacket(QuicStopWaitingFrame* frame) {
854 return ProcessFramePacket(QuicFrame(frame));
857 QuicPacketEntropyHash ProcessGoAwayPacket(QuicGoAwayFrame* frame) {
858 return ProcessFramePacket(QuicFrame(frame));
861 bool IsMissing(QuicPacketSequenceNumber number) {
862 return IsAwaitingPacket(*outgoing_ack(), number);
865 QuicPacket* ConstructDataPacket(QuicPacketSequenceNumber number,
866 QuicFecGroupNumber fec_group,
867 bool entropy_flag) {
868 header_.public_header.connection_id = connection_id_;
869 header_.public_header.reset_flag = false;
870 header_.public_header.version_flag = false;
871 header_.public_header.sequence_number_length = sequence_number_length_;
872 header_.public_header.connection_id_length = connection_id_length_;
873 header_.entropy_flag = entropy_flag;
874 header_.fec_flag = false;
875 header_.packet_sequence_number = number;
876 header_.is_in_fec_group = fec_group == 0u ? NOT_IN_FEC_GROUP : IN_FEC_GROUP;
877 header_.fec_group = fec_group;
879 QuicFrames frames;
880 QuicFrame frame(&frame1_);
881 frames.push_back(frame);
882 QuicPacket* packet =
883 BuildUnsizedDataPacket(&framer_, header_, frames).packet;
884 EXPECT_TRUE(packet != nullptr);
885 return packet;
888 QuicPacket* ConstructPingPacket(QuicPacketSequenceNumber number) {
889 header_.public_header.connection_id = connection_id_;
890 header_.packet_sequence_number = number;
891 header_.public_header.reset_flag = false;
892 header_.public_header.version_flag = false;
893 header_.entropy_flag = false;
894 header_.fec_flag = false;
895 header_.is_in_fec_group = NOT_IN_FEC_GROUP;
896 header_.fec_group = 0;
898 QuicPingFrame ping;
900 QuicFrames frames;
901 QuicFrame frame(&ping);
902 frames.push_back(frame);
903 QuicPacket* packet =
904 BuildUnsizedDataPacket(&framer_, header_, frames).packet;
905 EXPECT_TRUE(packet != nullptr);
906 return packet;
909 QuicPacket* ConstructClosePacket(QuicPacketSequenceNumber number,
910 QuicFecGroupNumber fec_group) {
911 header_.public_header.connection_id = connection_id_;
912 header_.packet_sequence_number = number;
913 header_.public_header.reset_flag = false;
914 header_.public_header.version_flag = false;
915 header_.entropy_flag = false;
916 header_.fec_flag = false;
917 header_.is_in_fec_group = fec_group == 0u ? NOT_IN_FEC_GROUP : IN_FEC_GROUP;
918 header_.fec_group = fec_group;
920 QuicConnectionCloseFrame qccf;
921 qccf.error_code = QUIC_PEER_GOING_AWAY;
923 QuicFrames frames;
924 QuicFrame frame(&qccf);
925 frames.push_back(frame);
926 QuicPacket* packet =
927 BuildUnsizedDataPacket(&framer_, header_, frames).packet;
928 EXPECT_TRUE(packet != nullptr);
929 return packet;
932 void SetFeedback(QuicCongestionFeedbackFrame* feedback) {
933 receive_algorithm_ = new TestReceiveAlgorithm(feedback);
934 connection_.SetReceiveAlgorithm(receive_algorithm_);
937 QuicTime::Delta DefaultRetransmissionTime() {
938 return QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
941 QuicTime::Delta DefaultDelayedAckTime() {
942 return QuicTime::Delta::FromMilliseconds(kMaxDelayedAckTimeMs);
945 // Initialize a frame acknowledging all packets up to largest_observed.
946 const QuicAckFrame InitAckFrame(QuicPacketSequenceNumber largest_observed) {
947 QuicAckFrame frame(MakeAckFrame(largest_observed));
948 if (largest_observed > 0) {
949 frame.entropy_hash =
950 QuicConnectionPeer::GetSentEntropyHash(&connection_,
951 largest_observed);
953 return frame;
956 const QuicStopWaitingFrame InitStopWaitingFrame(
957 QuicPacketSequenceNumber least_unacked) {
958 QuicStopWaitingFrame frame;
959 frame.least_unacked = least_unacked;
960 return frame;
963 // Explicitly nack a packet.
964 void NackPacket(QuicPacketSequenceNumber missing, QuicAckFrame* frame) {
965 frame->missing_packets.insert(missing);
966 frame->entropy_hash ^=
967 QuicConnectionPeer::PacketEntropy(&connection_, missing);
970 // Undo nacking a packet within the frame.
971 void AckPacket(QuicPacketSequenceNumber arrived, QuicAckFrame* frame) {
972 EXPECT_THAT(frame->missing_packets, Contains(arrived));
973 frame->missing_packets.erase(arrived);
974 frame->entropy_hash ^=
975 QuicConnectionPeer::PacketEntropy(&connection_, arrived);
978 void TriggerConnectionClose() {
979 // Send an erroneous packet to close the connection.
980 EXPECT_CALL(visitor_,
981 OnConnectionClosed(QUIC_INVALID_PACKET_HEADER, false));
982 // Call ProcessDataPacket rather than ProcessPacket, as we should not get a
983 // packet call to the visitor.
984 ProcessDataPacket(6000, 0, !kEntropyFlag);
985 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
986 nullptr);
989 void BlockOnNextWrite() {
990 writer_->BlockOnNextWrite();
991 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
994 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
995 writer_->SetWritePauseTimeDelta(delta);
998 void CongestionBlockWrites() {
999 EXPECT_CALL(*send_algorithm_,
1000 TimeUntilSend(_, _, _)).WillRepeatedly(
1001 testing::Return(QuicTime::Delta::FromSeconds(1)));
1004 void CongestionUnblockWrites() {
1005 EXPECT_CALL(*send_algorithm_,
1006 TimeUntilSend(_, _, _)).WillRepeatedly(
1007 testing::Return(QuicTime::Delta::Zero()));
1010 QuicConnectionId connection_id_;
1011 QuicFramer framer_;
1012 QuicPacketCreator peer_creator_;
1013 MockEntropyCalculator entropy_calculator_;
1015 MockSendAlgorithm* send_algorithm_;
1016 MockLossAlgorithm* loss_algorithm_;
1017 TestReceiveAlgorithm* receive_algorithm_;
1018 MockClock clock_;
1019 MockRandom random_generator_;
1020 scoped_ptr<TestConnectionHelper> helper_;
1021 scoped_ptr<TestPacketWriter> writer_;
1022 NiceMock<MockPacketWriterFactory> factory_;
1023 TestConnection connection_;
1024 StrictMock<MockConnectionVisitor> visitor_;
1026 QuicPacketHeader header_;
1027 QuicStreamFrame frame1_;
1028 QuicStreamFrame frame2_;
1029 scoped_ptr<QuicAckFrame> outgoing_ack_;
1030 scoped_ptr<QuicStopWaitingFrame> stop_waiting_;
1031 QuicSequenceNumberLength sequence_number_length_;
1032 QuicConnectionIdLength connection_id_length_;
1034 private:
1035 DISALLOW_COPY_AND_ASSIGN(QuicConnectionTest);
1038 // Run all end to end tests with all supported versions.
1039 INSTANTIATE_TEST_CASE_P(SupportedVersion,
1040 QuicConnectionTest,
1041 ::testing::ValuesIn(QuicSupportedVersions()));
1043 TEST_P(QuicConnectionTest, PacketsInOrder) {
1044 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1046 ProcessPacket(1);
1047 EXPECT_EQ(1u, outgoing_ack()->largest_observed);
1048 EXPECT_EQ(0u, outgoing_ack()->missing_packets.size());
1050 ProcessPacket(2);
1051 EXPECT_EQ(2u, outgoing_ack()->largest_observed);
1052 EXPECT_EQ(0u, outgoing_ack()->missing_packets.size());
1054 ProcessPacket(3);
1055 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1056 EXPECT_EQ(0u, outgoing_ack()->missing_packets.size());
1059 TEST_P(QuicConnectionTest, PacketsOutOfOrder) {
1060 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1062 ProcessPacket(3);
1063 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1064 EXPECT_TRUE(IsMissing(2));
1065 EXPECT_TRUE(IsMissing(1));
1067 ProcessPacket(2);
1068 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1069 EXPECT_FALSE(IsMissing(2));
1070 EXPECT_TRUE(IsMissing(1));
1072 ProcessPacket(1);
1073 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1074 EXPECT_FALSE(IsMissing(2));
1075 EXPECT_FALSE(IsMissing(1));
1078 TEST_P(QuicConnectionTest, DuplicatePacket) {
1079 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1081 ProcessPacket(3);
1082 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1083 EXPECT_TRUE(IsMissing(2));
1084 EXPECT_TRUE(IsMissing(1));
1086 // Send packet 3 again, but do not set the expectation that
1087 // the visitor OnStreamFrames() will be called.
1088 ProcessDataPacket(3, 0, !kEntropyFlag);
1089 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1090 EXPECT_TRUE(IsMissing(2));
1091 EXPECT_TRUE(IsMissing(1));
1094 TEST_P(QuicConnectionTest, PacketsOutOfOrderWithAdditionsAndLeastAwaiting) {
1095 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1097 ProcessPacket(3);
1098 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1099 EXPECT_TRUE(IsMissing(2));
1100 EXPECT_TRUE(IsMissing(1));
1102 ProcessPacket(2);
1103 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1104 EXPECT_TRUE(IsMissing(1));
1106 ProcessPacket(5);
1107 EXPECT_EQ(5u, outgoing_ack()->largest_observed);
1108 EXPECT_TRUE(IsMissing(1));
1109 EXPECT_TRUE(IsMissing(4));
1111 // Pretend at this point the client has gotten acks for 2 and 3 and 1 is a
1112 // packet the peer will not retransmit. It indicates this by sending 'least
1113 // awaiting' is 4. The connection should then realize 1 will not be
1114 // retransmitted, and will remove it from the missing list.
1115 peer_creator_.set_sequence_number(5);
1116 QuicAckFrame frame = InitAckFrame(1);
1117 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _));
1118 ProcessAckPacket(&frame);
1120 // Force an ack to be sent.
1121 SendAckPacketToPeer();
1122 EXPECT_TRUE(IsMissing(4));
1125 TEST_P(QuicConnectionTest, RejectPacketTooFarOut) {
1126 EXPECT_CALL(visitor_,
1127 OnConnectionClosed(QUIC_INVALID_PACKET_HEADER, false));
1128 // Call ProcessDataPacket rather than ProcessPacket, as we should not get a
1129 // packet call to the visitor.
1130 ProcessDataPacket(6000, 0, !kEntropyFlag);
1131 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1132 nullptr);
1135 TEST_P(QuicConnectionTest, RejectUnencryptedStreamData) {
1136 // Process an unencrypted packet from the non-crypto stream.
1137 frame1_.stream_id = 3;
1138 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1139 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_UNENCRYPTED_STREAM_DATA,
1140 false));
1141 ProcessDataPacket(1, 0, !kEntropyFlag);
1142 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1143 nullptr);
1144 const vector<QuicConnectionCloseFrame>& connection_close_frames =
1145 writer_->connection_close_frames();
1146 EXPECT_EQ(1u, connection_close_frames.size());
1147 EXPECT_EQ(QUIC_UNENCRYPTED_STREAM_DATA,
1148 connection_close_frames[0].error_code);
1151 TEST_P(QuicConnectionTest, TruncatedAck) {
1152 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1153 QuicPacketSequenceNumber num_packets = 256 * 2 + 1;
1154 for (QuicPacketSequenceNumber i = 0; i < num_packets; ++i) {
1155 SendStreamDataToPeer(3, "foo", i * 3, !kFin, nullptr);
1158 QuicAckFrame frame = InitAckFrame(num_packets);
1159 SequenceNumberSet lost_packets;
1160 // Create an ack with 256 nacks, none adjacent to one another.
1161 for (QuicPacketSequenceNumber i = 1; i <= 256; ++i) {
1162 NackPacket(i * 2, &frame);
1163 if (i < 256) { // Last packet is nacked, but not lost.
1164 lost_packets.insert(i * 2);
1167 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1168 .WillOnce(Return(lost_packets));
1169 EXPECT_CALL(entropy_calculator_,
1170 EntropyHash(511)).WillOnce(testing::Return(0));
1171 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1172 ProcessAckPacket(&frame);
1174 const QuicSentPacketManager& sent_packet_manager =
1175 connection_.sent_packet_manager();
1176 // A truncated ack will not have the true largest observed.
1177 EXPECT_GT(num_packets, sent_packet_manager.largest_observed());
1179 AckPacket(192, &frame);
1181 // Removing one missing packet allows us to ack 192 and one more range, but
1182 // 192 has already been declared lost, so it doesn't register as an ack.
1183 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1184 .WillOnce(Return(SequenceNumberSet()));
1185 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1186 ProcessAckPacket(&frame);
1187 EXPECT_EQ(num_packets, sent_packet_manager.largest_observed());
1190 TEST_P(QuicConnectionTest, AckReceiptCausesAckSendBadEntropy) {
1191 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1193 ProcessPacket(1);
1194 // Delay sending, then queue up an ack.
1195 EXPECT_CALL(*send_algorithm_,
1196 TimeUntilSend(_, _, _)).WillOnce(
1197 testing::Return(QuicTime::Delta::FromMicroseconds(1)));
1198 QuicConnectionPeer::SendAck(&connection_);
1200 // Process an ack with a least unacked of the received ack.
1201 // This causes an ack to be sent when TimeUntilSend returns 0.
1202 EXPECT_CALL(*send_algorithm_,
1203 TimeUntilSend(_, _, _)).WillRepeatedly(
1204 testing::Return(QuicTime::Delta::Zero()));
1205 // Skip a packet and then record an ack.
1206 peer_creator_.set_sequence_number(2);
1207 QuicAckFrame frame = InitAckFrame(0);
1208 ProcessAckPacket(&frame);
1211 TEST_P(QuicConnectionTest, OutOfOrderReceiptCausesAckSend) {
1212 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1214 ProcessPacket(3);
1215 // Should ack immediately since we have missing packets.
1216 EXPECT_EQ(1u, writer_->packets_write_attempts());
1218 ProcessPacket(2);
1219 // Should ack immediately since we have missing packets.
1220 EXPECT_EQ(2u, writer_->packets_write_attempts());
1222 ProcessPacket(1);
1223 // Should ack immediately, since this fills the last hole.
1224 EXPECT_EQ(3u, writer_->packets_write_attempts());
1226 ProcessPacket(4);
1227 // Should not cause an ack.
1228 EXPECT_EQ(3u, writer_->packets_write_attempts());
1231 TEST_P(QuicConnectionTest, AckReceiptCausesAckSend) {
1232 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1234 QuicPacketSequenceNumber original;
1235 QuicByteCount packet_size;
1236 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1237 .WillOnce(DoAll(SaveArg<2>(&original), SaveArg<3>(&packet_size),
1238 Return(true)));
1239 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
1240 QuicAckFrame frame = InitAckFrame(original);
1241 NackPacket(original, &frame);
1242 // First nack triggers early retransmit.
1243 SequenceNumberSet lost_packets;
1244 lost_packets.insert(1);
1245 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1246 .WillOnce(Return(lost_packets));
1247 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1248 QuicPacketSequenceNumber retransmission;
1249 EXPECT_CALL(*send_algorithm_,
1250 OnPacketSent(_, _, _, packet_size - kQuicVersionSize, _))
1251 .WillOnce(DoAll(SaveArg<2>(&retransmission), Return(true)));
1253 ProcessAckPacket(&frame);
1255 QuicAckFrame frame2 = InitAckFrame(retransmission);
1256 NackPacket(original, &frame2);
1257 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1258 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1259 .WillOnce(Return(SequenceNumberSet()));
1260 ProcessAckPacket(&frame2);
1262 // Now if the peer sends an ack which still reports the retransmitted packet
1263 // as missing, that will bundle an ack with data after two acks in a row
1264 // indicate the high water mark needs to be raised.
1265 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _,
1266 HAS_RETRANSMITTABLE_DATA));
1267 connection_.SendStreamDataWithString(3, "foo", 3, !kFin, nullptr);
1268 // No ack sent.
1269 EXPECT_EQ(1u, writer_->frame_count());
1270 EXPECT_EQ(1u, writer_->stream_frames().size());
1272 // No more packet loss for the rest of the test.
1273 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1274 .WillRepeatedly(Return(SequenceNumberSet()));
1275 ProcessAckPacket(&frame2);
1276 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _,
1277 HAS_RETRANSMITTABLE_DATA));
1278 connection_.SendStreamDataWithString(3, "foo", 3, !kFin, nullptr);
1279 // Ack bundled.
1280 EXPECT_EQ(3u, writer_->frame_count());
1281 EXPECT_EQ(1u, writer_->stream_frames().size());
1282 EXPECT_FALSE(writer_->ack_frames().empty());
1284 // But an ack with no missing packets will not send an ack.
1285 AckPacket(original, &frame2);
1286 ProcessAckPacket(&frame2);
1287 ProcessAckPacket(&frame2);
1290 TEST_P(QuicConnectionTest, 20AcksCausesAckSend) {
1291 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1293 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr);
1295 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
1296 // But an ack with no missing packets will not send an ack.
1297 QuicAckFrame frame = InitAckFrame(1);
1298 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1299 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1300 .WillRepeatedly(Return(SequenceNumberSet()));
1301 for (int i = 0; i < 20; ++i) {
1302 EXPECT_FALSE(ack_alarm->IsSet());
1303 ProcessAckPacket(&frame);
1305 EXPECT_TRUE(ack_alarm->IsSet());
1308 TEST_P(QuicConnectionTest, LeastUnackedLower) {
1309 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1311 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr);
1312 SendStreamDataToPeer(1, "bar", 3, !kFin, nullptr);
1313 SendStreamDataToPeer(1, "eep", 6, !kFin, nullptr);
1315 // Start out saying the least unacked is 2.
1316 peer_creator_.set_sequence_number(5);
1317 QuicStopWaitingFrame frame = InitStopWaitingFrame(2);
1318 ProcessStopWaitingPacket(&frame);
1320 // Change it to 1, but lower the sequence number to fake out-of-order packets.
1321 // This should be fine.
1322 peer_creator_.set_sequence_number(1);
1323 // The scheduler will not process out of order acks, but all packet processing
1324 // causes the connection to try to write.
1325 EXPECT_CALL(visitor_, OnCanWrite());
1326 QuicStopWaitingFrame frame2 = InitStopWaitingFrame(1);
1327 ProcessStopWaitingPacket(&frame2);
1329 // Now claim it's one, but set the ordering so it was sent "after" the first
1330 // one. This should cause a connection error.
1331 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
1332 peer_creator_.set_sequence_number(7);
1333 EXPECT_CALL(visitor_,
1334 OnConnectionClosed(QUIC_INVALID_STOP_WAITING_DATA, false));
1335 QuicStopWaitingFrame frame3 = InitStopWaitingFrame(1);
1336 ProcessStopWaitingPacket(&frame3);
1339 TEST_P(QuicConnectionTest, TooManySentPackets) {
1340 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1342 for (int i = 0; i < 1100; ++i) {
1343 SendStreamDataToPeer(1, "foo", 3 * i, !kFin, nullptr);
1346 // Ack packet 1, which leaves more than the limit outstanding.
1347 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1348 if (FLAGS_quic_too_many_outstanding_packets) {
1349 EXPECT_CALL(visitor_,
1350 OnConnectionClosed(QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS,
1351 false));
1353 // We're receive buffer limited, so the connection won't try to write more.
1354 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
1356 // Nack every packet except the last one, leaving a huge gap.
1357 QuicAckFrame frame1 = InitAckFrame(1100);
1358 for (QuicPacketSequenceNumber i = 1; i < 1100; ++i) {
1359 NackPacket(i, &frame1);
1361 ProcessAckPacket(&frame1);
1364 TEST_P(QuicConnectionTest, TooManyReceivedPackets) {
1365 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1367 if (FLAGS_quic_too_many_outstanding_packets) {
1368 EXPECT_CALL(visitor_,
1369 OnConnectionClosed(QUIC_TOO_MANY_OUTSTANDING_RECEIVED_PACKETS,
1370 false));
1373 // Miss every other packet for 1000 packets.
1374 for (QuicPacketSequenceNumber i = 1; i < 1000; ++i) {
1375 ProcessPacket(i * 2);
1376 if (!connection_.connected()) {
1377 break;
1382 TEST_P(QuicConnectionTest, LargestObservedLower) {
1383 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1385 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr);
1386 SendStreamDataToPeer(1, "bar", 3, !kFin, nullptr);
1387 SendStreamDataToPeer(1, "eep", 6, !kFin, nullptr);
1388 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1390 // Start out saying the largest observed is 2.
1391 QuicAckFrame frame1 = InitAckFrame(1);
1392 QuicAckFrame frame2 = InitAckFrame(2);
1393 ProcessAckPacket(&frame2);
1395 // Now change it to 1, and it should cause a connection error.
1396 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, false));
1397 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
1398 ProcessAckPacket(&frame1);
1401 TEST_P(QuicConnectionTest, AckUnsentData) {
1402 // Ack a packet which has not been sent.
1403 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, false));
1404 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1405 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
1406 QuicAckFrame frame(MakeAckFrame(1));
1407 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
1408 ProcessAckPacket(&frame);
1411 TEST_P(QuicConnectionTest, AckAll) {
1412 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1413 ProcessPacket(1);
1415 peer_creator_.set_sequence_number(1);
1416 QuicAckFrame frame1 = InitAckFrame(0);
1417 ProcessAckPacket(&frame1);
1420 TEST_P(QuicConnectionTest, SendingDifferentSequenceNumberLengthsBandwidth) {
1421 QuicPacketSequenceNumber last_packet;
1422 QuicPacketCreator* creator =
1423 QuicConnectionPeer::GetPacketCreator(&connection_);
1424 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet);
1425 EXPECT_EQ(1u, last_packet);
1426 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1427 creator->next_sequence_number_length());
1428 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1429 writer_->header().public_header.sequence_number_length);
1431 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
1432 Return(kMaxPacketSize * 256));
1434 SendStreamDataToPeer(1, "bar", 3, !kFin, &last_packet);
1435 EXPECT_EQ(2u, last_packet);
1436 EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER,
1437 creator->next_sequence_number_length());
1438 // The 1 packet lag is due to the sequence number length being recalculated in
1439 // QuicConnection after a packet is sent.
1440 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1441 writer_->header().public_header.sequence_number_length);
1443 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
1444 Return(kMaxPacketSize * 256 * 256));
1446 SendStreamDataToPeer(1, "foo", 6, !kFin, &last_packet);
1447 EXPECT_EQ(3u, last_packet);
1448 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1449 creator->next_sequence_number_length());
1450 EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER,
1451 writer_->header().public_header.sequence_number_length);
1453 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
1454 Return(kMaxPacketSize * 256 * 256 * 256));
1456 SendStreamDataToPeer(1, "bar", 9, !kFin, &last_packet);
1457 EXPECT_EQ(4u, last_packet);
1458 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1459 creator->next_sequence_number_length());
1460 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1461 writer_->header().public_header.sequence_number_length);
1463 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
1464 Return(kMaxPacketSize * 256 * 256 * 256 * 256));
1466 SendStreamDataToPeer(1, "foo", 12, !kFin, &last_packet);
1467 EXPECT_EQ(5u, last_packet);
1468 EXPECT_EQ(PACKET_6BYTE_SEQUENCE_NUMBER,
1469 creator->next_sequence_number_length());
1470 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1471 writer_->header().public_header.sequence_number_length);
1474 // TODO(ianswett): Re-enable this test by finding a good way to test different
1475 // sequence number lengths without sending packets with giant gaps.
1476 TEST_P(QuicConnectionTest,
1477 DISABLED_SendingDifferentSequenceNumberLengthsUnackedDelta) {
1478 QuicPacketSequenceNumber last_packet;
1479 QuicPacketCreator* creator =
1480 QuicConnectionPeer::GetPacketCreator(&connection_);
1481 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet);
1482 EXPECT_EQ(1u, last_packet);
1483 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1484 creator->next_sequence_number_length());
1485 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1486 writer_->header().public_header.sequence_number_length);
1488 creator->set_sequence_number(100);
1490 SendStreamDataToPeer(1, "bar", 3, !kFin, &last_packet);
1491 EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER,
1492 creator->next_sequence_number_length());
1493 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1494 writer_->header().public_header.sequence_number_length);
1496 creator->set_sequence_number(100 * 256);
1498 SendStreamDataToPeer(1, "foo", 6, !kFin, &last_packet);
1499 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1500 creator->next_sequence_number_length());
1501 EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER,
1502 writer_->header().public_header.sequence_number_length);
1504 creator->set_sequence_number(100 * 256 * 256);
1506 SendStreamDataToPeer(1, "bar", 9, !kFin, &last_packet);
1507 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1508 creator->next_sequence_number_length());
1509 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1510 writer_->header().public_header.sequence_number_length);
1512 creator->set_sequence_number(100 * 256 * 256 * 256);
1514 SendStreamDataToPeer(1, "foo", 12, !kFin, &last_packet);
1515 EXPECT_EQ(PACKET_6BYTE_SEQUENCE_NUMBER,
1516 creator->next_sequence_number_length());
1517 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1518 writer_->header().public_header.sequence_number_length);
1521 TEST_P(QuicConnectionTest, BasicSending) {
1522 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1523 QuicPacketSequenceNumber last_packet;
1524 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet); // Packet 1
1525 EXPECT_EQ(1u, last_packet);
1526 SendAckPacketToPeer(); // Packet 2
1528 EXPECT_EQ(1u, least_unacked());
1530 SendAckPacketToPeer(); // Packet 3
1531 EXPECT_EQ(1u, least_unacked());
1533 SendStreamDataToPeer(1, "bar", 3, !kFin, &last_packet); // Packet 4
1534 EXPECT_EQ(4u, last_packet);
1535 SendAckPacketToPeer(); // Packet 5
1536 EXPECT_EQ(1u, least_unacked());
1538 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1540 // Peer acks up to packet 3.
1541 QuicAckFrame frame = InitAckFrame(3);
1542 ProcessAckPacket(&frame);
1543 SendAckPacketToPeer(); // Packet 6
1545 // As soon as we've acked one, we skip ack packets 2 and 3 and note lack of
1546 // ack for 4.
1547 EXPECT_EQ(4u, least_unacked());
1549 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1551 // Peer acks up to packet 4, the last packet.
1552 QuicAckFrame frame2 = InitAckFrame(6);
1553 ProcessAckPacket(&frame2); // Acks don't instigate acks.
1555 // Verify that we did not send an ack.
1556 EXPECT_EQ(6u, writer_->header().packet_sequence_number);
1558 // So the last ack has not changed.
1559 EXPECT_EQ(4u, least_unacked());
1561 // If we force an ack, we shouldn't change our retransmit state.
1562 SendAckPacketToPeer(); // Packet 7
1563 EXPECT_EQ(7u, least_unacked());
1565 // But if we send more data it should.
1566 SendStreamDataToPeer(1, "eep", 6, !kFin, &last_packet); // Packet 8
1567 EXPECT_EQ(8u, last_packet);
1568 SendAckPacketToPeer(); // Packet 9
1569 EXPECT_EQ(7u, least_unacked());
1572 // If FLAGS_quic_record_send_time_before_write is disabled, QuicConnection
1573 // should record the packet sen-tdime after the packet is sent.
1574 TEST_P(QuicConnectionTest, RecordSentTimeAfterPacketSent) {
1575 ValueRestore<bool> old_flag(&FLAGS_quic_record_send_time_before_write, false);
1576 // We're using a MockClock for the tests, so we have complete control over the
1577 // time.
1578 // Our recorded timestamp for the last packet sent time will be passed in to
1579 // the send_algorithm. Make sure that it is set to the correct value.
1580 QuicTime actual_recorded_send_time = QuicTime::Zero();
1581 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1582 .WillOnce(DoAll(SaveArg<0>(&actual_recorded_send_time), Return(true)));
1584 // First send without any pause and check the result.
1585 QuicTime expected_recorded_send_time = clock_.Now();
1586 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
1587 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
1588 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
1589 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
1591 // Now pause during the write, and check the results.
1592 actual_recorded_send_time = QuicTime::Zero();
1593 const QuicTime::Delta kWritePauseTimeDelta =
1594 QuicTime::Delta::FromMilliseconds(5000);
1595 SetWritePauseTimeDelta(kWritePauseTimeDelta);
1596 expected_recorded_send_time = clock_.Now().Add(kWritePauseTimeDelta);
1598 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1599 .WillOnce(DoAll(SaveArg<0>(&actual_recorded_send_time), Return(true)));
1600 connection_.SendStreamDataWithString(2, "baz", 0, !kFin, nullptr);
1601 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
1602 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
1603 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
1606 // If FLAGS_quic_record_send_time_before_write is enabled, QuicConnection should
1607 // record the the packet sent-time prior to sending the packet.
1608 TEST_P(QuicConnectionTest, RecordSentTimeBeforePacketSent) {
1609 ValueRestore<bool> old_flag(&FLAGS_quic_record_send_time_before_write, true);
1610 // We're using a MockClock for the tests, so we have complete control over the
1611 // time.
1612 // Our recorded timestamp for the last packet sent time will be passed in to
1613 // the send_algorithm. Make sure that it is set to the correct value.
1614 QuicTime actual_recorded_send_time = QuicTime::Zero();
1615 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1616 .WillOnce(DoAll(SaveArg<0>(&actual_recorded_send_time), Return(true)));
1618 // First send without any pause and check the result.
1619 QuicTime expected_recorded_send_time = clock_.Now();
1620 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
1621 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
1622 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
1623 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
1625 // Now pause during the write, and check the results.
1626 actual_recorded_send_time = QuicTime::Zero();
1627 const QuicTime::Delta kWritePauseTimeDelta =
1628 QuicTime::Delta::FromMilliseconds(5000);
1629 SetWritePauseTimeDelta(kWritePauseTimeDelta);
1630 expected_recorded_send_time = clock_.Now();
1632 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1633 .WillOnce(DoAll(SaveArg<0>(&actual_recorded_send_time), Return(true)));
1634 connection_.SendStreamDataWithString(2, "baz", 0, !kFin, nullptr);
1635 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
1636 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
1637 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
1640 TEST_P(QuicConnectionTest, FECSending) {
1641 // All packets carry version info till version is negotiated.
1642 QuicPacketCreator* creator =
1643 QuicConnectionPeer::GetPacketCreator(&connection_);
1644 size_t payload_length;
1645 // GetPacketLengthForOneStream() assumes a stream offset of 0 in determining
1646 // packet length. The size of the offset field in a stream frame is 0 for
1647 // offset 0, and 2 for non-zero offsets up through 64K. Increase
1648 // max_packet_length by 2 so that subsequent packets containing subsequent
1649 // stream frames with non-zero offets will fit within the packet length.
1650 size_t length = 2 + GetPacketLengthForOneStream(
1651 connection_.version(), kIncludeVersion,
1652 PACKET_8BYTE_CONNECTION_ID, PACKET_1BYTE_SEQUENCE_NUMBER,
1653 IN_FEC_GROUP, &payload_length);
1654 creator->set_max_packet_length(length);
1656 // Send 4 protected data packets, which should also trigger 1 FEC packet.
1657 EXPECT_CALL(*send_algorithm_,
1658 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(5);
1659 // The first stream frame will have 2 fewer overhead bytes than the other 3.
1660 const string payload(payload_length * 4 + 2, 'a');
1661 connection_.SendStreamDataWithStringWithFec(1, payload, 0, !kFin, nullptr);
1662 // Expect the FEC group to be closed after SendStreamDataWithString.
1663 EXPECT_FALSE(creator->IsFecGroupOpen());
1664 EXPECT_FALSE(creator->IsFecProtected());
1667 TEST_P(QuicConnectionTest, FECQueueing) {
1668 // All packets carry version info till version is negotiated.
1669 size_t payload_length;
1670 QuicPacketCreator* creator =
1671 QuicConnectionPeer::GetPacketCreator(&connection_);
1672 size_t length = GetPacketLengthForOneStream(
1673 connection_.version(), kIncludeVersion,
1674 PACKET_8BYTE_CONNECTION_ID, PACKET_1BYTE_SEQUENCE_NUMBER,
1675 IN_FEC_GROUP, &payload_length);
1676 creator->set_max_packet_length(length);
1677 EXPECT_TRUE(creator->IsFecEnabled());
1679 EXPECT_EQ(0u, connection_.NumQueuedPackets());
1680 BlockOnNextWrite();
1681 const string payload(payload_length, 'a');
1682 connection_.SendStreamDataWithStringWithFec(1, payload, 0, !kFin, nullptr);
1683 EXPECT_FALSE(creator->IsFecGroupOpen());
1684 EXPECT_FALSE(creator->IsFecProtected());
1685 // Expect the first data packet and the fec packet to be queued.
1686 EXPECT_EQ(2u, connection_.NumQueuedPackets());
1689 TEST_P(QuicConnectionTest, AbandonFECFromCongestionWindow) {
1690 EXPECT_TRUE(QuicConnectionPeer::GetPacketCreator(
1691 &connection_)->IsFecEnabled());
1693 // 1 Data and 1 FEC packet.
1694 EXPECT_CALL(*send_algorithm_,
1695 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(2);
1696 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, !kFin, nullptr);
1698 const QuicTime::Delta retransmission_time =
1699 QuicTime::Delta::FromMilliseconds(5000);
1700 clock_.AdvanceTime(retransmission_time);
1702 // Abandon FEC packet and data packet.
1703 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
1704 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1705 EXPECT_CALL(visitor_, OnCanWrite());
1706 connection_.OnRetransmissionTimeout();
1709 TEST_P(QuicConnectionTest, DontAbandonAckedFEC) {
1710 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1711 EXPECT_TRUE(QuicConnectionPeer::GetPacketCreator(
1712 &connection_)->IsFecEnabled());
1714 // 3 Data and 3 FEC packets.
1715 EXPECT_CALL(*send_algorithm_,
1716 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(6);
1717 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, !kFin, nullptr);
1718 // Send some more data afterwards to ensure early retransmit doesn't trigger.
1719 connection_.SendStreamDataWithStringWithFec(3, "foo", 3, !kFin, nullptr);
1720 connection_.SendStreamDataWithStringWithFec(3, "foo", 6, !kFin, nullptr);
1722 QuicAckFrame ack_fec = InitAckFrame(2);
1723 // Data packet missing.
1724 // TODO(ianswett): Note that this is not a sensible ack, since if the FEC was
1725 // received, it would cause the covered packet to be acked as well.
1726 NackPacket(1, &ack_fec);
1727 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1728 ProcessAckPacket(&ack_fec);
1729 clock_.AdvanceTime(DefaultRetransmissionTime());
1731 // Don't abandon the acked FEC packet, but it will abandon 2 the subsequent
1732 // FEC packets.
1733 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
1734 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
1735 connection_.GetRetransmissionAlarm()->Fire();
1738 TEST_P(QuicConnectionTest, AbandonAllFEC) {
1739 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1740 EXPECT_TRUE(QuicConnectionPeer::GetPacketCreator(
1741 &connection_)->IsFecEnabled());
1743 // 3 Data and 3 FEC packet.
1744 EXPECT_CALL(*send_algorithm_,
1745 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(6);
1746 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, !kFin, nullptr);
1747 // Send some more data afterwards to ensure early retransmit doesn't trigger.
1748 connection_.SendStreamDataWithStringWithFec(3, "foo", 3, !kFin, nullptr);
1749 // Advance the time so not all the FEC packets are abandoned.
1750 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(1));
1751 connection_.SendStreamDataWithStringWithFec(3, "foo", 6, !kFin, nullptr);
1753 QuicAckFrame ack_fec = InitAckFrame(5);
1754 // Ack all data packets, but no fec packets.
1755 NackPacket(2, &ack_fec);
1756 NackPacket(4, &ack_fec);
1758 // Lose the first FEC packet and ack the three data packets.
1759 SequenceNumberSet lost_packets;
1760 lost_packets.insert(2);
1761 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1762 .WillOnce(Return(lost_packets));
1763 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1764 ProcessAckPacket(&ack_fec);
1766 clock_.AdvanceTime(DefaultRetransmissionTime().Subtract(
1767 QuicTime::Delta::FromMilliseconds(1)));
1769 // Abandon all packets
1770 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(false));
1771 connection_.GetRetransmissionAlarm()->Fire();
1773 // Ensure the alarm is not set since all packets have been abandoned.
1774 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
1777 TEST_P(QuicConnectionTest, FramePacking) {
1778 CongestionBlockWrites();
1780 // Send an ack and two stream frames in 1 packet by queueing them.
1781 connection_.SendAck();
1782 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
1783 IgnoreResult(InvokeWithoutArgs(&connection_,
1784 &TestConnection::SendStreamData3)),
1785 IgnoreResult(InvokeWithoutArgs(&connection_,
1786 &TestConnection::SendStreamData5))));
1788 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1789 CongestionUnblockWrites();
1790 connection_.GetSendAlarm()->Fire();
1791 EXPECT_EQ(0u, connection_.NumQueuedPackets());
1792 EXPECT_FALSE(connection_.HasQueuedData());
1794 // Parse the last packet and ensure it's an ack and two stream frames from
1795 // two different streams.
1796 EXPECT_EQ(4u, writer_->frame_count());
1797 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
1798 EXPECT_FALSE(writer_->ack_frames().empty());
1799 ASSERT_EQ(2u, writer_->stream_frames().size());
1800 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id);
1801 EXPECT_EQ(kClientDataStreamId2, writer_->stream_frames()[1].stream_id);
1804 TEST_P(QuicConnectionTest, FramePackingNonCryptoThenCrypto) {
1805 CongestionBlockWrites();
1807 // Send an ack and two stream frames (one non-crypto, then one crypto) in 2
1808 // packets by queueing them.
1809 connection_.SendAck();
1810 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
1811 IgnoreResult(InvokeWithoutArgs(&connection_,
1812 &TestConnection::SendStreamData3)),
1813 IgnoreResult(InvokeWithoutArgs(&connection_,
1814 &TestConnection::SendCryptoStreamData))));
1816 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
1817 CongestionUnblockWrites();
1818 connection_.GetSendAlarm()->Fire();
1819 EXPECT_EQ(0u, connection_.NumQueuedPackets());
1820 EXPECT_FALSE(connection_.HasQueuedData());
1822 // Parse the last packet and ensure it's the crypto stream frame.
1823 EXPECT_EQ(1u, writer_->frame_count());
1824 ASSERT_EQ(1u, writer_->stream_frames().size());
1825 EXPECT_EQ(kCryptoStreamId, writer_->stream_frames()[0].stream_id);
1828 TEST_P(QuicConnectionTest, FramePackingCryptoThenNonCrypto) {
1829 CongestionBlockWrites();
1831 // Send an ack and two stream frames (one crypto, then one non-crypto) in 2
1832 // packets by queueing them.
1833 connection_.SendAck();
1834 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
1835 IgnoreResult(InvokeWithoutArgs(&connection_,
1836 &TestConnection::SendCryptoStreamData)),
1837 IgnoreResult(InvokeWithoutArgs(&connection_,
1838 &TestConnection::SendStreamData3))));
1840 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
1841 CongestionUnblockWrites();
1842 connection_.GetSendAlarm()->Fire();
1843 EXPECT_EQ(0u, connection_.NumQueuedPackets());
1844 EXPECT_FALSE(connection_.HasQueuedData());
1846 // Parse the last packet and ensure it's the stream frame from stream 3.
1847 EXPECT_EQ(1u, writer_->frame_count());
1848 ASSERT_EQ(1u, writer_->stream_frames().size());
1849 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id);
1852 TEST_P(QuicConnectionTest, FramePackingFEC) {
1853 EXPECT_TRUE(QuicConnectionPeer::GetPacketCreator(
1854 &connection_)->IsFecEnabled());
1856 CongestionBlockWrites();
1858 // Queue an ack and two stream frames. Ack gets flushed when FEC is turned on
1859 // for sending protected data; two stream frames are packing in 1 packet.
1860 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
1861 IgnoreResult(InvokeWithoutArgs(
1862 &connection_, &TestConnection::SendStreamData3WithFec)),
1863 IgnoreResult(InvokeWithoutArgs(
1864 &connection_, &TestConnection::SendStreamData5WithFec))));
1865 connection_.SendAck();
1867 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
1868 CongestionUnblockWrites();
1869 connection_.GetSendAlarm()->Fire();
1870 EXPECT_EQ(0u, connection_.NumQueuedPackets());
1871 EXPECT_FALSE(connection_.HasQueuedData());
1873 // Parse the last packet and ensure it's in an fec group.
1874 EXPECT_EQ(2u, writer_->header().fec_group);
1875 EXPECT_EQ(0u, writer_->frame_count());
1878 TEST_P(QuicConnectionTest, FramePackingAckResponse) {
1879 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1880 // Process a data packet to queue up a pending ack.
1881 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
1882 ProcessDataPacket(1, 1, kEntropyFlag);
1884 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
1885 IgnoreResult(InvokeWithoutArgs(&connection_,
1886 &TestConnection::SendStreamData3)),
1887 IgnoreResult(InvokeWithoutArgs(&connection_,
1888 &TestConnection::SendStreamData5))));
1890 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1892 // Process an ack to cause the visitor's OnCanWrite to be invoked.
1893 peer_creator_.set_sequence_number(2);
1894 QuicAckFrame ack_one = InitAckFrame(0);
1895 ProcessAckPacket(&ack_one);
1897 EXPECT_EQ(0u, connection_.NumQueuedPackets());
1898 EXPECT_FALSE(connection_.HasQueuedData());
1900 // Parse the last packet and ensure it's an ack and two stream frames from
1901 // two different streams.
1902 EXPECT_EQ(4u, writer_->frame_count());
1903 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
1904 EXPECT_FALSE(writer_->ack_frames().empty());
1905 ASSERT_EQ(2u, writer_->stream_frames().size());
1906 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id);
1907 EXPECT_EQ(kClientDataStreamId2, writer_->stream_frames()[1].stream_id);
1910 TEST_P(QuicConnectionTest, FramePackingSendv) {
1911 // Send data in 1 packet by writing multiple blocks in a single iovector
1912 // using writev.
1913 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
1915 char data[] = "ABCD";
1916 IOVector data_iov;
1917 data_iov.AppendNoCoalesce(data, 2);
1918 data_iov.AppendNoCoalesce(data + 2, 2);
1919 connection_.SendStreamData(1, data_iov, 0, !kFin, MAY_FEC_PROTECT, nullptr);
1921 EXPECT_EQ(0u, connection_.NumQueuedPackets());
1922 EXPECT_FALSE(connection_.HasQueuedData());
1924 // Parse the last packet and ensure multiple iovector blocks have
1925 // been packed into a single stream frame from one stream.
1926 EXPECT_EQ(1u, writer_->frame_count());
1927 EXPECT_EQ(1u, writer_->stream_frames().size());
1928 QuicStreamFrame frame = writer_->stream_frames()[0];
1929 EXPECT_EQ(1u, frame.stream_id);
1930 EXPECT_EQ("ABCD", string(static_cast<char*>
1931 (frame.data.iovec()[0].iov_base),
1932 (frame.data.iovec()[0].iov_len)));
1935 TEST_P(QuicConnectionTest, FramePackingSendvQueued) {
1936 // Try to send two stream frames in 1 packet by using writev.
1937 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
1939 BlockOnNextWrite();
1940 char data[] = "ABCD";
1941 IOVector data_iov;
1942 data_iov.AppendNoCoalesce(data, 2);
1943 data_iov.AppendNoCoalesce(data + 2, 2);
1944 connection_.SendStreamData(1, data_iov, 0, !kFin, MAY_FEC_PROTECT, nullptr);
1946 EXPECT_EQ(1u, connection_.NumQueuedPackets());
1947 EXPECT_TRUE(connection_.HasQueuedData());
1949 // Unblock the writes and actually send.
1950 writer_->SetWritable();
1951 connection_.OnCanWrite();
1952 EXPECT_EQ(0u, connection_.NumQueuedPackets());
1954 // Parse the last packet and ensure it's one stream frame from one stream.
1955 EXPECT_EQ(1u, writer_->frame_count());
1956 EXPECT_EQ(1u, writer_->stream_frames().size());
1957 EXPECT_EQ(1u, writer_->stream_frames()[0].stream_id);
1960 TEST_P(QuicConnectionTest, SendingZeroBytes) {
1961 // Send a zero byte write with a fin using writev.
1962 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
1963 IOVector empty_iov;
1964 connection_.SendStreamData(1, empty_iov, 0, kFin, MAY_FEC_PROTECT, nullptr);
1966 EXPECT_EQ(0u, connection_.NumQueuedPackets());
1967 EXPECT_FALSE(connection_.HasQueuedData());
1969 // Parse the last packet and ensure it's one stream frame from one stream.
1970 EXPECT_EQ(1u, writer_->frame_count());
1971 EXPECT_EQ(1u, writer_->stream_frames().size());
1972 EXPECT_EQ(1u, writer_->stream_frames()[0].stream_id);
1973 EXPECT_TRUE(writer_->stream_frames()[0].fin);
1976 TEST_P(QuicConnectionTest, OnCanWrite) {
1977 // Visitor's OnCanWrite will send data, but will have more pending writes.
1978 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
1979 IgnoreResult(InvokeWithoutArgs(&connection_,
1980 &TestConnection::SendStreamData3)),
1981 IgnoreResult(InvokeWithoutArgs(&connection_,
1982 &TestConnection::SendStreamData5))));
1983 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillOnce(Return(true));
1984 EXPECT_CALL(*send_algorithm_,
1985 TimeUntilSend(_, _, _)).WillRepeatedly(
1986 testing::Return(QuicTime::Delta::Zero()));
1988 connection_.OnCanWrite();
1990 // Parse the last packet and ensure it's the two stream frames from
1991 // two different streams.
1992 EXPECT_EQ(2u, writer_->frame_count());
1993 EXPECT_EQ(2u, writer_->stream_frames().size());
1994 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id);
1995 EXPECT_EQ(kClientDataStreamId2, writer_->stream_frames()[1].stream_id);
1998 TEST_P(QuicConnectionTest, RetransmitOnNack) {
1999 QuicPacketSequenceNumber last_packet;
2000 QuicByteCount second_packet_size;
2001 SendStreamDataToPeer(3, "foo", 0, !kFin, &last_packet); // Packet 1
2002 second_packet_size =
2003 SendStreamDataToPeer(3, "foos", 3, !kFin, &last_packet); // Packet 2
2004 SendStreamDataToPeer(3, "fooos", 7, !kFin, &last_packet); // Packet 3
2006 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2008 // Don't lose a packet on an ack, and nothing is retransmitted.
2009 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2010 QuicAckFrame ack_one = InitAckFrame(1);
2011 ProcessAckPacket(&ack_one);
2013 // Lose a packet and ensure it triggers retransmission.
2014 QuicAckFrame nack_two = InitAckFrame(3);
2015 NackPacket(2, &nack_two);
2016 SequenceNumberSet lost_packets;
2017 lost_packets.insert(2);
2018 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2019 .WillOnce(Return(lost_packets));
2020 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2021 EXPECT_CALL(*send_algorithm_,
2022 OnPacketSent(_, _, _, second_packet_size - kQuicVersionSize, _)).
2023 Times(1);
2024 ProcessAckPacket(&nack_two);
2027 TEST_P(QuicConnectionTest, DiscardRetransmit) {
2028 QuicPacketSequenceNumber last_packet;
2029 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet); // Packet 1
2030 SendStreamDataToPeer(1, "foos", 3, !kFin, &last_packet); // Packet 2
2031 SendStreamDataToPeer(1, "fooos", 7, !kFin, &last_packet); // Packet 3
2033 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2035 // Instigate a loss with an ack.
2036 QuicAckFrame nack_two = InitAckFrame(3);
2037 NackPacket(2, &nack_two);
2038 // The first nack should trigger a fast retransmission, but we'll be
2039 // write blocked, so the packet will be queued.
2040 BlockOnNextWrite();
2041 SequenceNumberSet lost_packets;
2042 lost_packets.insert(2);
2043 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2044 .WillOnce(Return(lost_packets));
2045 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2046 ProcessAckPacket(&nack_two);
2047 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2049 // Now, ack the previous transmission.
2050 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2051 .WillOnce(Return(SequenceNumberSet()));
2052 QuicAckFrame ack_all = InitAckFrame(3);
2053 ProcessAckPacket(&ack_all);
2055 // Unblock the socket and attempt to send the queued packets. However,
2056 // since the previous transmission has been acked, we will not
2057 // send the retransmission.
2058 EXPECT_CALL(*send_algorithm_,
2059 OnPacketSent(_, _, _, _, _)).Times(0);
2061 writer_->SetWritable();
2062 connection_.OnCanWrite();
2064 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2067 TEST_P(QuicConnectionTest, RetransmitNackedLargestObserved) {
2068 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2069 QuicPacketSequenceNumber largest_observed;
2070 QuicByteCount packet_size;
2071 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2072 .WillOnce(DoAll(SaveArg<2>(&largest_observed), SaveArg<3>(&packet_size),
2073 Return(true)));
2074 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
2076 QuicAckFrame frame = InitAckFrame(1);
2077 NackPacket(largest_observed, &frame);
2078 // The first nack should retransmit the largest observed packet.
2079 SequenceNumberSet lost_packets;
2080 lost_packets.insert(1);
2081 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2082 .WillOnce(Return(lost_packets));
2083 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2084 EXPECT_CALL(*send_algorithm_,
2085 OnPacketSent(_, _, _, packet_size - kQuicVersionSize, _));
2086 ProcessAckPacket(&frame);
2089 TEST_P(QuicConnectionTest, QueueAfterTwoRTOs) {
2090 for (int i = 0; i < 10; ++i) {
2091 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2092 connection_.SendStreamDataWithString(3, "foo", i * 3, !kFin, nullptr);
2095 // Block the congestion window and ensure they're queued.
2096 BlockOnNextWrite();
2097 clock_.AdvanceTime(DefaultRetransmissionTime());
2098 // Only one packet should be retransmitted.
2099 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
2100 connection_.GetRetransmissionAlarm()->Fire();
2101 EXPECT_TRUE(connection_.HasQueuedData());
2103 // Unblock the congestion window.
2104 writer_->SetWritable();
2105 clock_.AdvanceTime(QuicTime::Delta::FromMicroseconds(
2106 2 * DefaultRetransmissionTime().ToMicroseconds()));
2107 // Retransmit already retransmitted packets event though the sequence number
2108 // greater than the largest observed.
2109 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(10);
2110 connection_.GetRetransmissionAlarm()->Fire();
2111 connection_.OnCanWrite();
2114 TEST_P(QuicConnectionTest, WriteBlockedThenSent) {
2115 BlockOnNextWrite();
2116 writer_->set_is_write_blocked_data_buffered(true);
2117 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2118 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
2119 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2121 writer_->SetWritable();
2122 connection_.OnCanWrite();
2123 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2126 TEST_P(QuicConnectionTest, RetransmitWriteBlockedAckedOriginalThenSent) {
2127 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2128 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
2129 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2131 BlockOnNextWrite();
2132 writer_->set_is_write_blocked_data_buffered(true);
2133 // Simulate the retransmission alarm firing.
2134 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(_));
2135 clock_.AdvanceTime(DefaultRetransmissionTime());
2136 connection_.GetRetransmissionAlarm()->Fire();
2138 // Ack the sent packet before the callback returns, which happens in
2139 // rare circumstances with write blocked sockets.
2140 QuicAckFrame ack = InitAckFrame(1);
2141 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2142 EXPECT_CALL(*send_algorithm_, RevertRetransmissionTimeout());
2143 ProcessAckPacket(&ack);
2145 writer_->SetWritable();
2146 connection_.OnCanWrite();
2147 // There is now a pending packet, but with no retransmittable frames.
2148 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2149 EXPECT_FALSE(connection_.sent_packet_manager().HasRetransmittableFrames(2));
2152 TEST_P(QuicConnectionTest, AlarmsWhenWriteBlocked) {
2153 // Block the connection.
2154 BlockOnNextWrite();
2155 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
2156 EXPECT_EQ(1u, writer_->packets_write_attempts());
2157 EXPECT_TRUE(writer_->IsWriteBlocked());
2159 // Set the send and resumption alarms. Fire the alarms and ensure they don't
2160 // attempt to write.
2161 connection_.GetResumeWritesAlarm()->Set(clock_.ApproximateNow());
2162 connection_.GetSendAlarm()->Set(clock_.ApproximateNow());
2163 connection_.GetResumeWritesAlarm()->Fire();
2164 connection_.GetSendAlarm()->Fire();
2165 EXPECT_TRUE(writer_->IsWriteBlocked());
2166 EXPECT_EQ(1u, writer_->packets_write_attempts());
2169 TEST_P(QuicConnectionTest, NoLimitPacketsPerNack) {
2170 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2171 int offset = 0;
2172 // Send packets 1 to 15.
2173 for (int i = 0; i < 15; ++i) {
2174 SendStreamDataToPeer(1, "foo", offset, !kFin, nullptr);
2175 offset += 3;
2178 // Ack 15, nack 1-14.
2179 SequenceNumberSet lost_packets;
2180 QuicAckFrame nack = InitAckFrame(15);
2181 for (int i = 1; i < 15; ++i) {
2182 NackPacket(i, &nack);
2183 lost_packets.insert(i);
2186 // 14 packets have been NACK'd and lost. In TCP cubic, PRR limits
2187 // the retransmission rate in the case of burst losses.
2188 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2189 .WillOnce(Return(lost_packets));
2190 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2191 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(14);
2192 ProcessAckPacket(&nack);
2195 // Test sending multiple acks from the connection to the session.
2196 TEST_P(QuicConnectionTest, MultipleAcks) {
2197 QuicPacketSequenceNumber last_packet;
2198 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet); // Packet 1
2199 EXPECT_EQ(1u, last_packet);
2200 SendStreamDataToPeer(3, "foo", 0, !kFin, &last_packet); // Packet 2
2201 EXPECT_EQ(2u, last_packet);
2202 SendAckPacketToPeer(); // Packet 3
2203 SendStreamDataToPeer(5, "foo", 0, !kFin, &last_packet); // Packet 4
2204 EXPECT_EQ(4u, last_packet);
2205 SendStreamDataToPeer(1, "foo", 3, !kFin, &last_packet); // Packet 5
2206 EXPECT_EQ(5u, last_packet);
2207 SendStreamDataToPeer(3, "foo", 3, !kFin, &last_packet); // Packet 6
2208 EXPECT_EQ(6u, last_packet);
2210 // Client will ack packets 1, 2, [!3], 4, 5.
2211 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2212 QuicAckFrame frame1 = InitAckFrame(5);
2213 NackPacket(3, &frame1);
2214 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2215 ProcessAckPacket(&frame1);
2217 // Now the client implicitly acks 3, and explicitly acks 6.
2218 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2219 QuicAckFrame frame2 = InitAckFrame(6);
2220 ProcessAckPacket(&frame2);
2223 TEST_P(QuicConnectionTest, DontLatchUnackedPacket) {
2224 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr); // Packet 1;
2225 // From now on, we send acks, so the send algorithm won't mark them pending.
2226 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2227 .WillByDefault(Return(false));
2228 SendAckPacketToPeer(); // Packet 2
2230 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2231 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2232 QuicAckFrame frame = InitAckFrame(1);
2233 ProcessAckPacket(&frame);
2235 // Verify that our internal state has least-unacked as 2, because we're still
2236 // waiting for a potential ack for 2.
2238 EXPECT_EQ(2u, stop_waiting()->least_unacked);
2240 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2241 frame = InitAckFrame(2);
2242 ProcessAckPacket(&frame);
2243 EXPECT_EQ(3u, stop_waiting()->least_unacked);
2245 // When we send an ack, we make sure our least-unacked makes sense. In this
2246 // case since we're not waiting on an ack for 2 and all packets are acked, we
2247 // set it to 3.
2248 SendAckPacketToPeer(); // Packet 3
2249 // Least_unacked remains at 3 until another ack is received.
2250 EXPECT_EQ(3u, stop_waiting()->least_unacked);
2251 // Check that the outgoing ack had its sequence number as least_unacked.
2252 EXPECT_EQ(3u, least_unacked());
2254 // Ack the ack, which updates the rtt and raises the least unacked.
2255 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2256 frame = InitAckFrame(3);
2257 ProcessAckPacket(&frame);
2259 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2260 .WillByDefault(Return(true));
2261 SendStreamDataToPeer(1, "bar", 3, false, nullptr); // Packet 4
2262 EXPECT_EQ(4u, stop_waiting()->least_unacked);
2263 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2264 .WillByDefault(Return(false));
2265 SendAckPacketToPeer(); // Packet 5
2266 EXPECT_EQ(4u, least_unacked());
2268 // Send two data packets at the end, and ensure if the last one is acked,
2269 // the least unacked is raised above the ack packets.
2270 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2271 .WillByDefault(Return(true));
2272 SendStreamDataToPeer(1, "bar", 6, false, nullptr); // Packet 6
2273 SendStreamDataToPeer(1, "bar", 9, false, nullptr); // Packet 7
2275 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2276 frame = InitAckFrame(7);
2277 NackPacket(5, &frame);
2278 NackPacket(6, &frame);
2279 ProcessAckPacket(&frame);
2281 EXPECT_EQ(6u, stop_waiting()->least_unacked);
2284 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterFecPacket) {
2285 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2287 // Don't send missing packet 1.
2288 ProcessFecPacket(2, 1, true, !kEntropyFlag, nullptr);
2289 // Entropy flag should be false, so entropy should be 0.
2290 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2293 TEST_P(QuicConnectionTest, ReviveMissingPacketWithVaryingSeqNumLengths) {
2294 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2296 // Set up a debug visitor to the connection.
2297 FecQuicConnectionDebugVisitor* fec_visitor =
2298 new FecQuicConnectionDebugVisitor();
2299 connection_.set_debug_visitor(fec_visitor);
2301 QuicPacketSequenceNumber fec_packet = 0;
2302 QuicSequenceNumberLength lengths[] = {PACKET_6BYTE_SEQUENCE_NUMBER,
2303 PACKET_4BYTE_SEQUENCE_NUMBER,
2304 PACKET_2BYTE_SEQUENCE_NUMBER,
2305 PACKET_1BYTE_SEQUENCE_NUMBER};
2306 // For each sequence number length size, revive a packet and check sequence
2307 // number length in the revived packet.
2308 for (size_t i = 0; i < arraysize(lengths); ++i) {
2309 // Set sequence_number_length_ (for data and FEC packets).
2310 sequence_number_length_ = lengths[i];
2311 fec_packet += 2;
2312 // Don't send missing packet, but send fec packet right after it.
2313 ProcessFecPacket(fec_packet, fec_packet - 1, true, !kEntropyFlag, nullptr);
2314 // Sequence number length in the revived header should be the same as
2315 // in the original data/fec packet headers.
2316 EXPECT_EQ(sequence_number_length_, fec_visitor->revived_header().
2317 public_header.sequence_number_length);
2321 TEST_P(QuicConnectionTest, ReviveMissingPacketWithVaryingConnectionIdLengths) {
2322 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2324 // Set up a debug visitor to the connection.
2325 FecQuicConnectionDebugVisitor* fec_visitor =
2326 new FecQuicConnectionDebugVisitor();
2327 connection_.set_debug_visitor(fec_visitor);
2329 QuicPacketSequenceNumber fec_packet = 0;
2330 QuicConnectionIdLength lengths[] = {PACKET_8BYTE_CONNECTION_ID,
2331 PACKET_4BYTE_CONNECTION_ID,
2332 PACKET_1BYTE_CONNECTION_ID,
2333 PACKET_0BYTE_CONNECTION_ID};
2334 // For each connection id length size, revive a packet and check connection
2335 // id length in the revived packet.
2336 for (size_t i = 0; i < arraysize(lengths); ++i) {
2337 // Set connection id length (for data and FEC packets).
2338 connection_id_length_ = lengths[i];
2339 fec_packet += 2;
2340 // Don't send missing packet, but send fec packet right after it.
2341 ProcessFecPacket(fec_packet, fec_packet - 1, true, !kEntropyFlag, nullptr);
2342 // Connection id length in the revived header should be the same as
2343 // in the original data/fec packet headers.
2344 EXPECT_EQ(connection_id_length_,
2345 fec_visitor->revived_header().public_header.connection_id_length);
2349 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPacketThenFecPacket) {
2350 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2352 ProcessFecProtectedPacket(1, false, kEntropyFlag);
2353 // Don't send missing packet 2.
2354 ProcessFecPacket(3, 1, true, !kEntropyFlag, nullptr);
2355 // Entropy flag should be true, so entropy should not be 0.
2356 EXPECT_NE(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2359 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPacketsThenFecPacket) {
2360 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2362 ProcessFecProtectedPacket(1, false, !kEntropyFlag);
2363 // Don't send missing packet 2.
2364 ProcessFecProtectedPacket(3, false, !kEntropyFlag);
2365 ProcessFecPacket(4, 1, true, kEntropyFlag, nullptr);
2366 // Ensure QUIC no longer revives entropy for lost packets.
2367 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2368 EXPECT_NE(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 4));
2371 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPacket) {
2372 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2374 // Don't send missing packet 1.
2375 ProcessFecPacket(3, 1, false, !kEntropyFlag, nullptr);
2376 // Out of order.
2377 ProcessFecProtectedPacket(2, true, !kEntropyFlag);
2378 // Entropy flag should be false, so entropy should be 0.
2379 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2382 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPackets) {
2383 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2385 ProcessFecProtectedPacket(1, false, !kEntropyFlag);
2386 // Don't send missing packet 2.
2387 ProcessFecPacket(6, 1, false, kEntropyFlag, nullptr);
2388 ProcessFecProtectedPacket(3, false, kEntropyFlag);
2389 ProcessFecProtectedPacket(4, false, kEntropyFlag);
2390 ProcessFecProtectedPacket(5, true, !kEntropyFlag);
2391 // Ensure entropy is not revived for the missing packet.
2392 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2393 EXPECT_NE(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 3));
2396 TEST_P(QuicConnectionTest, TLP) {
2397 QuicSentPacketManagerPeer::SetMaxTailLossProbes(
2398 QuicConnectionPeer::GetSentPacketManager(&connection_), 1);
2400 SendStreamDataToPeer(3, "foo", 0, !kFin, nullptr);
2401 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2402 QuicTime retransmission_time =
2403 connection_.GetRetransmissionAlarm()->deadline();
2404 EXPECT_NE(QuicTime::Zero(), retransmission_time);
2406 EXPECT_EQ(1u, writer_->header().packet_sequence_number);
2407 // Simulate the retransmission alarm firing and sending a tlp,
2408 // so send algorithm's OnRetransmissionTimeout is not called.
2409 clock_.AdvanceTime(retransmission_time.Subtract(clock_.Now()));
2410 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 2u, _, _));
2411 connection_.GetRetransmissionAlarm()->Fire();
2412 EXPECT_EQ(2u, writer_->header().packet_sequence_number);
2413 // We do not raise the high water mark yet.
2414 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2417 TEST_P(QuicConnectionTest, RTO) {
2418 QuicTime default_retransmission_time = clock_.ApproximateNow().Add(
2419 DefaultRetransmissionTime());
2420 SendStreamDataToPeer(3, "foo", 0, !kFin, nullptr);
2421 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2423 EXPECT_EQ(1u, writer_->header().packet_sequence_number);
2424 EXPECT_EQ(default_retransmission_time,
2425 connection_.GetRetransmissionAlarm()->deadline());
2426 // Simulate the retransmission alarm firing.
2427 clock_.AdvanceTime(DefaultRetransmissionTime());
2428 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
2429 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 2u, _, _));
2430 connection_.GetRetransmissionAlarm()->Fire();
2431 EXPECT_EQ(2u, writer_->header().packet_sequence_number);
2432 // We do not raise the high water mark yet.
2433 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2436 TEST_P(QuicConnectionTest, RTOWithSameEncryptionLevel) {
2437 QuicTime default_retransmission_time = clock_.ApproximateNow().Add(
2438 DefaultRetransmissionTime());
2439 use_tagging_decrypter();
2441 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
2442 // the end of the packet. We can test this to check which encrypter was used.
2443 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2444 SendStreamDataToPeer(3, "foo", 0, !kFin, nullptr);
2445 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
2447 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2448 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2449 SendStreamDataToPeer(3, "foo", 0, !kFin, nullptr);
2450 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2452 EXPECT_EQ(default_retransmission_time,
2453 connection_.GetRetransmissionAlarm()->deadline());
2455 InSequence s;
2456 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
2457 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 3, _, _));
2458 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 4, _, _));
2461 // Simulate the retransmission alarm firing.
2462 clock_.AdvanceTime(DefaultRetransmissionTime());
2463 connection_.GetRetransmissionAlarm()->Fire();
2465 // Packet should have been sent with ENCRYPTION_NONE.
2466 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_previous_packet());
2468 // Packet should have been sent with ENCRYPTION_INITIAL.
2469 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2472 TEST_P(QuicConnectionTest, SendHandshakeMessages) {
2473 use_tagging_decrypter();
2474 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
2475 // the end of the packet. We can test this to check which encrypter was used.
2476 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2478 // Attempt to send a handshake message and have the socket block.
2479 EXPECT_CALL(*send_algorithm_,
2480 TimeUntilSend(_, _, _)).WillRepeatedly(
2481 testing::Return(QuicTime::Delta::Zero()));
2482 BlockOnNextWrite();
2483 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
2484 // The packet should be serialized, but not queued.
2485 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2487 // Switch to the new encrypter.
2488 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2489 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2491 // Now become writeable and flush the packets.
2492 writer_->SetWritable();
2493 EXPECT_CALL(visitor_, OnCanWrite());
2494 connection_.OnCanWrite();
2495 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2497 // Verify that the handshake packet went out at the null encryption.
2498 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
2501 TEST_P(QuicConnectionTest,
2502 DropRetransmitsForNullEncryptedPacketAfterForwardSecure) {
2503 use_tagging_decrypter();
2504 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2505 QuicPacketSequenceNumber sequence_number;
2506 SendStreamDataToPeer(3, "foo", 0, !kFin, &sequence_number);
2508 // Simulate the retransmission alarm firing and the socket blocking.
2509 BlockOnNextWrite();
2510 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
2511 clock_.AdvanceTime(DefaultRetransmissionTime());
2512 connection_.GetRetransmissionAlarm()->Fire();
2514 // Go forward secure.
2515 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
2516 new TaggingEncrypter(0x02));
2517 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2518 connection_.NeuterUnencryptedPackets();
2520 EXPECT_EQ(QuicTime::Zero(),
2521 connection_.GetRetransmissionAlarm()->deadline());
2522 // Unblock the socket and ensure that no packets are sent.
2523 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
2524 writer_->SetWritable();
2525 connection_.OnCanWrite();
2528 TEST_P(QuicConnectionTest, RetransmitPacketsWithInitialEncryption) {
2529 use_tagging_decrypter();
2530 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2531 connection_.SetDefaultEncryptionLevel(ENCRYPTION_NONE);
2533 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr);
2535 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2536 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2538 SendStreamDataToPeer(2, "bar", 0, !kFin, nullptr);
2539 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2541 connection_.RetransmitUnackedPackets(ALL_INITIAL_RETRANSMISSION);
2544 TEST_P(QuicConnectionTest, DelayForwardSecureEncryptionUntilClientIsReady) {
2545 ValueRestore<bool> old_flag(&FLAGS_enable_quic_delay_forward_security, true);
2547 // A TaggingEncrypter puts kTagSize copies of the given byte (0x02 here) at
2548 // the end of the packet. We can test this to check which encrypter was used.
2549 use_tagging_decrypter();
2550 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2551 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2552 SendAckPacketToPeer();
2553 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2555 // Set a forward-secure encrypter but do not make it the default, and verify
2556 // that it is not yet used.
2557 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
2558 new TaggingEncrypter(0x03));
2559 SendAckPacketToPeer();
2560 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2562 // Now simulate receipt of a forward-secure packet and verify that the
2563 // forward-secure encrypter is now used.
2564 connection_.OnDecryptedPacket(ENCRYPTION_FORWARD_SECURE);
2565 SendAckPacketToPeer();
2566 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
2569 TEST_P(QuicConnectionTest, DelayForwardSecureEncryptionUntilManyPacketSent) {
2570 ValueRestore<bool> old_flag(&FLAGS_enable_quic_delay_forward_security, true);
2572 // Set a congestion window of 10 packets.
2573 QuicPacketCount congestion_window = 10;
2574 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
2575 Return(congestion_window * kDefaultMaxPacketSize));
2577 // A TaggingEncrypter puts kTagSize copies of the given byte (0x02 here) at
2578 // the end of the packet. We can test this to check which encrypter was used.
2579 use_tagging_decrypter();
2580 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2581 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2582 SendAckPacketToPeer();
2583 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2585 // Set a forward-secure encrypter but do not make it the default, and
2586 // verify that it is not yet used.
2587 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
2588 new TaggingEncrypter(0x03));
2589 SendAckPacketToPeer();
2590 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2592 // Now send a packet "Far enough" after the encrypter was set and verify that
2593 // the forward-secure encrypter is now used.
2594 for (uint64 i = 0; i < 3 * congestion_window - 1; ++i) {
2595 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2596 SendAckPacketToPeer();
2598 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
2601 TEST_P(QuicConnectionTest, BufferNonDecryptablePackets) {
2602 // SetFromConfig is always called after construction from InitializeSession.
2603 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _, _));
2604 QuicConfig config;
2605 connection_.SetFromConfig(config);
2606 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2607 use_tagging_decrypter();
2609 const uint8 tag = 0x07;
2610 framer_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
2612 // Process an encrypted packet which can not yet be decrypted which should
2613 // result in the packet being buffered.
2614 ProcessDataPacketAtLevel(1, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2616 // Transition to the new encryption state and process another encrypted packet
2617 // which should result in the original packet being processed.
2618 connection_.SetDecrypter(new StrictTaggingDecrypter(tag),
2619 ENCRYPTION_INITIAL);
2620 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2621 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
2622 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(2);
2623 ProcessDataPacketAtLevel(2, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2625 // Finally, process a third packet and note that we do not reprocess the
2626 // buffered packet.
2627 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
2628 ProcessDataPacketAtLevel(3, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2631 TEST_P(QuicConnectionTest, Buffer100NonDecryptablePackets) {
2632 // SetFromConfig is always called after construction from InitializeSession.
2633 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _, _));
2634 QuicConfig config;
2635 config.set_max_undecryptable_packets(100);
2636 connection_.SetFromConfig(config);
2637 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2638 use_tagging_decrypter();
2640 const uint8 tag = 0x07;
2641 framer_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
2643 // Process an encrypted packet which can not yet be decrypted which should
2644 // result in the packet being buffered.
2645 for (QuicPacketSequenceNumber i = 1; i <= 100; ++i) {
2646 ProcessDataPacketAtLevel(i, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2649 // Transition to the new encryption state and process another encrypted packet
2650 // which should result in the original packets being processed.
2651 connection_.SetDecrypter(new StrictTaggingDecrypter(tag), ENCRYPTION_INITIAL);
2652 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2653 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
2654 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(101);
2655 ProcessDataPacketAtLevel(101, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2657 // Finally, process a third packet and note that we do not reprocess the
2658 // buffered packet.
2659 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
2660 ProcessDataPacketAtLevel(102, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2663 TEST_P(QuicConnectionTest, TestRetransmitOrder) {
2664 QuicByteCount first_packet_size;
2665 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).WillOnce(
2666 DoAll(SaveArg<3>(&first_packet_size), Return(true)));
2668 connection_.SendStreamDataWithString(3, "first_packet", 0, !kFin, nullptr);
2669 QuicByteCount second_packet_size;
2670 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).WillOnce(
2671 DoAll(SaveArg<3>(&second_packet_size), Return(true)));
2672 connection_.SendStreamDataWithString(3, "second_packet", 12, !kFin, nullptr);
2673 EXPECT_NE(first_packet_size, second_packet_size);
2674 // Advance the clock by huge time to make sure packets will be retransmitted.
2675 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
2676 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
2678 InSequence s;
2679 EXPECT_CALL(*send_algorithm_,
2680 OnPacketSent(_, _, _, first_packet_size, _));
2681 EXPECT_CALL(*send_algorithm_,
2682 OnPacketSent(_, _, _, second_packet_size, _));
2684 connection_.GetRetransmissionAlarm()->Fire();
2686 // Advance again and expect the packets to be sent again in the same order.
2687 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(20));
2688 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
2690 InSequence s;
2691 EXPECT_CALL(*send_algorithm_,
2692 OnPacketSent(_, _, _, first_packet_size, _));
2693 EXPECT_CALL(*send_algorithm_,
2694 OnPacketSent(_, _, _, second_packet_size, _));
2696 connection_.GetRetransmissionAlarm()->Fire();
2699 TEST_P(QuicConnectionTest, RetransmissionCountCalculation) {
2700 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2701 QuicPacketSequenceNumber original_sequence_number;
2702 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2703 .WillOnce(DoAll(SaveArg<2>(&original_sequence_number), Return(true)));
2704 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
2706 EXPECT_TRUE(QuicConnectionPeer::IsSavedForRetransmission(
2707 &connection_, original_sequence_number));
2708 EXPECT_FALSE(QuicConnectionPeer::IsRetransmission(
2709 &connection_, original_sequence_number));
2710 // Force retransmission due to RTO.
2711 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
2712 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
2713 QuicPacketSequenceNumber rto_sequence_number;
2714 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2715 .WillOnce(DoAll(SaveArg<2>(&rto_sequence_number), Return(true)));
2716 connection_.GetRetransmissionAlarm()->Fire();
2717 EXPECT_FALSE(QuicConnectionPeer::IsSavedForRetransmission(
2718 &connection_, original_sequence_number));
2719 ASSERT_TRUE(QuicConnectionPeer::IsSavedForRetransmission(
2720 &connection_, rto_sequence_number));
2721 EXPECT_TRUE(QuicConnectionPeer::IsRetransmission(
2722 &connection_, rto_sequence_number));
2723 // Once by explicit nack.
2724 SequenceNumberSet lost_packets;
2725 lost_packets.insert(rto_sequence_number);
2726 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2727 .WillOnce(Return(lost_packets));
2728 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2729 QuicPacketSequenceNumber nack_sequence_number = 0;
2730 // Ack packets might generate some other packets, which are not
2731 // retransmissions. (More ack packets).
2732 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2733 .Times(AnyNumber());
2734 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2735 .WillOnce(DoAll(SaveArg<2>(&nack_sequence_number), Return(true)));
2736 QuicAckFrame ack = InitAckFrame(rto_sequence_number);
2737 // Nack the retransmitted packet.
2738 NackPacket(original_sequence_number, &ack);
2739 NackPacket(rto_sequence_number, &ack);
2740 ProcessAckPacket(&ack);
2742 ASSERT_NE(0u, nack_sequence_number);
2743 EXPECT_FALSE(QuicConnectionPeer::IsSavedForRetransmission(
2744 &connection_, rto_sequence_number));
2745 ASSERT_TRUE(QuicConnectionPeer::IsSavedForRetransmission(
2746 &connection_, nack_sequence_number));
2747 EXPECT_TRUE(QuicConnectionPeer::IsRetransmission(
2748 &connection_, nack_sequence_number));
2751 TEST_P(QuicConnectionTest, SetRTOAfterWritingToSocket) {
2752 BlockOnNextWrite();
2753 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
2754 // Make sure that RTO is not started when the packet is queued.
2755 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
2757 // Test that RTO is started once we write to the socket.
2758 writer_->SetWritable();
2759 connection_.OnCanWrite();
2760 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2763 TEST_P(QuicConnectionTest, DelayRTOWithAckReceipt) {
2764 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2765 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2766 .Times(2);
2767 connection_.SendStreamDataWithString(2, "foo", 0, !kFin, nullptr);
2768 connection_.SendStreamDataWithString(3, "bar", 0, !kFin, nullptr);
2769 QuicAlarm* retransmission_alarm = connection_.GetRetransmissionAlarm();
2770 EXPECT_TRUE(retransmission_alarm->IsSet());
2771 EXPECT_EQ(clock_.Now().Add(DefaultRetransmissionTime()),
2772 retransmission_alarm->deadline());
2774 // Advance the time right before the RTO, then receive an ack for the first
2775 // packet to delay the RTO.
2776 clock_.AdvanceTime(DefaultRetransmissionTime());
2777 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2778 QuicAckFrame ack = InitAckFrame(1);
2779 ProcessAckPacket(&ack);
2780 EXPECT_TRUE(retransmission_alarm->IsSet());
2781 EXPECT_GT(retransmission_alarm->deadline(), clock_.Now());
2783 // Move forward past the original RTO and ensure the RTO is still pending.
2784 clock_.AdvanceTime(DefaultRetransmissionTime().Multiply(2));
2786 // Ensure the second packet gets retransmitted when it finally fires.
2787 EXPECT_TRUE(retransmission_alarm->IsSet());
2788 EXPECT_LT(retransmission_alarm->deadline(), clock_.ApproximateNow());
2789 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
2790 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2791 // Manually cancel the alarm to simulate a real test.
2792 connection_.GetRetransmissionAlarm()->Fire();
2794 // The new retransmitted sequence number should set the RTO to a larger value
2795 // than previously.
2796 EXPECT_TRUE(retransmission_alarm->IsSet());
2797 QuicTime next_rto_time = retransmission_alarm->deadline();
2798 QuicTime expected_rto_time =
2799 connection_.sent_packet_manager().GetRetransmissionTime();
2800 EXPECT_EQ(next_rto_time, expected_rto_time);
2803 TEST_P(QuicConnectionTest, TestQueued) {
2804 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2805 BlockOnNextWrite();
2806 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
2807 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2809 // Unblock the writes and actually send.
2810 writer_->SetWritable();
2811 connection_.OnCanWrite();
2812 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2815 TEST_P(QuicConnectionTest, CloseFecGroup) {
2816 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2817 // Don't send missing packet 1.
2818 // Don't send missing packet 2.
2819 ProcessFecProtectedPacket(3, false, !kEntropyFlag);
2820 // Don't send missing FEC packet 3.
2821 ASSERT_EQ(1u, connection_.NumFecGroups());
2823 // Now send non-fec protected ack packet and close the group.
2824 peer_creator_.set_sequence_number(4);
2825 QuicStopWaitingFrame frame = InitStopWaitingFrame(5);
2826 ProcessStopWaitingPacket(&frame);
2827 ASSERT_EQ(0u, connection_.NumFecGroups());
2830 TEST_P(QuicConnectionTest, NoQuicCongestionFeedbackFrame) {
2831 SendAckPacketToPeer();
2832 EXPECT_TRUE(writer_->feedback_frames().empty());
2835 TEST_P(QuicConnectionTest, WithQuicCongestionFeedbackFrame) {
2836 QuicCongestionFeedbackFrame info;
2837 info.type = kTCP;
2838 info.tcp.receive_window = 0x4030;
2840 // After QUIC_VERSION_22, do not send TCP Congestion Feedback Frames anymore.
2841 if (version() > QUIC_VERSION_22) {
2842 SendAckPacketToPeer();
2843 ASSERT_TRUE(writer_->feedback_frames().empty());
2844 } else {
2845 // Only SetFeedback in this case because SetFeedback will create a receive
2846 // algorithm which is how the received_packet_manager checks if it should be
2847 // creating TCP Congestion Feedback Frames.
2848 SetFeedback(&info);
2849 SendAckPacketToPeer();
2850 ASSERT_FALSE(writer_->feedback_frames().empty());
2851 ASSERT_EQ(kTCP, writer_->feedback_frames()[0].type);
2855 TEST_P(QuicConnectionTest, UpdateQuicCongestionFeedbackFrame) {
2856 SendAckPacketToPeer();
2857 EXPECT_CALL(*receive_algorithm_, RecordIncomingPacket(_, _, _));
2858 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2859 ProcessPacket(1);
2862 TEST_P(QuicConnectionTest, DontUpdateQuicCongestionFeedbackFrameForRevived) {
2863 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2864 SendAckPacketToPeer();
2865 // Process an FEC packet, and revive the missing data packet
2866 // but only contact the receive_algorithm once.
2867 EXPECT_CALL(*receive_algorithm_, RecordIncomingPacket(_, _, _));
2868 ProcessFecPacket(2, 1, true, !kEntropyFlag, nullptr);
2871 TEST_P(QuicConnectionTest, InitialTimeout) {
2872 EXPECT_TRUE(connection_.connected());
2873 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
2874 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
2876 // SetFromConfig sets the initial timeouts before negotiation.
2877 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _, _));
2878 QuicConfig config;
2879 connection_.SetFromConfig(config);
2880 // Subtract a second from the idle timeout on the client side.
2881 QuicTime default_timeout = clock_.ApproximateNow().Add(
2882 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1));
2883 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
2885 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_CONNECTION_TIMED_OUT, false));
2886 // Simulate the timeout alarm firing.
2887 clock_.AdvanceTime(
2888 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1));
2889 connection_.GetTimeoutAlarm()->Fire();
2891 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
2892 EXPECT_FALSE(connection_.connected());
2894 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
2895 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
2896 EXPECT_FALSE(connection_.GetResumeWritesAlarm()->IsSet());
2897 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
2898 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
2901 TEST_P(QuicConnectionTest, OverallTimeout) {
2902 // Use a shorter overall connection timeout than idle timeout for this test.
2903 const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(5);
2904 connection_.SetNetworkTimeouts(timeout, timeout);
2905 EXPECT_TRUE(connection_.connected());
2906 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
2908 QuicTime overall_timeout = clock_.ApproximateNow().Add(timeout).Subtract(
2909 QuicTime::Delta::FromSeconds(1));
2910 EXPECT_EQ(overall_timeout, connection_.GetTimeoutAlarm()->deadline());
2911 EXPECT_TRUE(connection_.connected());
2913 // Send and ack new data 3 seconds later to lengthen the idle timeout.
2914 SendStreamDataToPeer(1, "GET /", 0, kFin, nullptr);
2915 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(3));
2916 QuicAckFrame frame = InitAckFrame(1);
2917 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2918 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2919 ProcessAckPacket(&frame);
2921 // Fire early to verify it wouldn't timeout yet.
2922 connection_.GetTimeoutAlarm()->Fire();
2923 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
2924 EXPECT_TRUE(connection_.connected());
2926 clock_.AdvanceTime(timeout.Subtract(QuicTime::Delta::FromSeconds(2)));
2928 EXPECT_CALL(visitor_,
2929 OnConnectionClosed(QUIC_CONNECTION_OVERALL_TIMED_OUT, false));
2930 // Simulate the timeout alarm firing.
2931 connection_.GetTimeoutAlarm()->Fire();
2933 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
2934 EXPECT_FALSE(connection_.connected());
2936 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
2937 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
2938 EXPECT_FALSE(connection_.GetResumeWritesAlarm()->IsSet());
2939 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
2940 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
2943 TEST_P(QuicConnectionTest, PingAfterSend) {
2944 EXPECT_TRUE(connection_.connected());
2945 EXPECT_CALL(visitor_, HasOpenDataStreams()).WillRepeatedly(Return(true));
2946 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
2948 // Advance to 5ms, and send a packet to the peer, which will set
2949 // the ping alarm.
2950 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
2951 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
2952 SendStreamDataToPeer(1, "GET /", 0, kFin, nullptr);
2953 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
2954 EXPECT_EQ(clock_.ApproximateNow().Add(QuicTime::Delta::FromSeconds(15)),
2955 connection_.GetPingAlarm()->deadline());
2957 // Now recevie and ACK of the previous packet, which will move the
2958 // ping alarm forward.
2959 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
2960 QuicAckFrame frame = InitAckFrame(1);
2961 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2962 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2963 ProcessAckPacket(&frame);
2964 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
2965 // The ping timer is set slightly less than 15 seconds in the future, because
2966 // of the 1s ping timer alarm granularity.
2967 EXPECT_EQ(clock_.ApproximateNow().Add(QuicTime::Delta::FromSeconds(15))
2968 .Subtract(QuicTime::Delta::FromMilliseconds(5)),
2969 connection_.GetPingAlarm()->deadline());
2971 writer_->Reset();
2972 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15));
2973 connection_.GetPingAlarm()->Fire();
2974 EXPECT_EQ(1u, writer_->frame_count());
2975 ASSERT_EQ(1u, writer_->ping_frames().size());
2976 writer_->Reset();
2978 EXPECT_CALL(visitor_, HasOpenDataStreams()).WillRepeatedly(Return(false));
2979 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
2980 SendAckPacketToPeer();
2982 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
2985 TEST_P(QuicConnectionTest, TimeoutAfterSend) {
2986 EXPECT_TRUE(connection_.connected());
2987 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _, _));
2988 QuicConfig config;
2989 connection_.SetFromConfig(config);
2991 const QuicTime::Delta initial_idle_timeout =
2992 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
2993 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
2994 QuicTime default_timeout = clock_.ApproximateNow().Add(initial_idle_timeout);
2996 // When we send a packet, the timeout will change to 5ms +
2997 // kInitialIdleTimeoutSecs.
2998 clock_.AdvanceTime(five_ms);
3000 // Send an ack so we don't set the retransmission alarm.
3001 SendAckPacketToPeer();
3002 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
3004 // The original alarm will fire. We should not time out because we had a
3005 // network event at t=5ms. The alarm will reregister.
3006 clock_.AdvanceTime(initial_idle_timeout.Subtract(five_ms));
3007 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
3008 connection_.GetTimeoutAlarm()->Fire();
3009 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
3010 EXPECT_TRUE(connection_.connected());
3011 EXPECT_EQ(default_timeout.Add(five_ms),
3012 connection_.GetTimeoutAlarm()->deadline());
3014 // This time, we should time out.
3015 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_CONNECTION_TIMED_OUT, false));
3016 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3017 clock_.AdvanceTime(five_ms);
3018 EXPECT_EQ(default_timeout.Add(five_ms), clock_.ApproximateNow());
3019 connection_.GetTimeoutAlarm()->Fire();
3020 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3021 EXPECT_FALSE(connection_.connected());
3024 TEST_P(QuicConnectionTest, SendScheduler) {
3025 // Test that if we send a packet without delay, it is not queued.
3026 QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
3027 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3028 connection_.SendPacket(
3029 ENCRYPTION_NONE, 1, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA);
3030 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3033 TEST_P(QuicConnectionTest, SendSchedulerEAGAIN) {
3034 QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
3035 BlockOnNextWrite();
3036 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 1, _, _)).Times(0);
3037 connection_.SendPacket(
3038 ENCRYPTION_NONE, 1, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA);
3039 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3042 TEST_P(QuicConnectionTest, TestQueueLimitsOnSendStreamData) {
3043 // All packets carry version info till version is negotiated.
3044 size_t payload_length;
3045 size_t length = GetPacketLengthForOneStream(
3046 connection_.version(), kIncludeVersion,
3047 PACKET_8BYTE_CONNECTION_ID, PACKET_1BYTE_SEQUENCE_NUMBER,
3048 NOT_IN_FEC_GROUP, &payload_length);
3049 QuicConnectionPeer::GetPacketCreator(&connection_)->set_max_packet_length(
3050 length);
3052 // Queue the first packet.
3053 EXPECT_CALL(*send_algorithm_,
3054 TimeUntilSend(_, _, _)).WillOnce(
3055 testing::Return(QuicTime::Delta::FromMicroseconds(10)));
3056 const string payload(payload_length, 'a');
3057 EXPECT_EQ(0u, connection_.SendStreamDataWithString(3, payload, 0, !kFin,
3058 nullptr).bytes_consumed);
3059 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3062 TEST_P(QuicConnectionTest, LoopThroughSendingPackets) {
3063 // All packets carry version info till version is negotiated.
3064 size_t payload_length;
3065 // GetPacketLengthForOneStream() assumes a stream offset of 0 in determining
3066 // packet length. The size of the offset field in a stream frame is 0 for
3067 // offset 0, and 2 for non-zero offsets up through 16K. Increase
3068 // max_packet_length by 2 so that subsequent packets containing subsequent
3069 // stream frames with non-zero offets will fit within the packet length.
3070 size_t length = 2 + GetPacketLengthForOneStream(
3071 connection_.version(), kIncludeVersion,
3072 PACKET_8BYTE_CONNECTION_ID, PACKET_1BYTE_SEQUENCE_NUMBER,
3073 NOT_IN_FEC_GROUP, &payload_length);
3074 QuicConnectionPeer::GetPacketCreator(&connection_)->set_max_packet_length(
3075 length);
3077 // Queue the first packet.
3078 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(7);
3079 // The first stream frame will have 2 fewer overhead bytes than the other six.
3080 const string payload(payload_length * 7 + 2, 'a');
3081 EXPECT_EQ(payload.size(),
3082 connection_.SendStreamDataWithString(1, payload, 0, !kFin, nullptr)
3083 .bytes_consumed);
3086 TEST_P(QuicConnectionTest, LoopThroughSendingPacketsWithTruncation) {
3087 ValueRestore<bool> old_flag(&FLAGS_allow_truncated_connection_ids_for_quic,
3088 true);
3090 // Set up a larger payload than will fit in one packet.
3091 const string payload(connection_.max_packet_length(), 'a');
3092 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _, _)).Times(AnyNumber());
3094 // Now send some packets with no truncation.
3095 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3096 EXPECT_EQ(payload.size(),
3097 connection_.SendStreamDataWithString(
3098 3, payload, 0, !kFin, nullptr).bytes_consumed);
3099 // Track the size of the second packet here. The overhead will be the largest
3100 // we see in this test, due to the non-truncated CID.
3101 size_t non_truncated_packet_size = writer_->last_packet_size();
3103 // Change to a 4 byte CID.
3104 QuicConfig config;
3105 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 4);
3106 connection_.SetFromConfig(config);
3107 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3108 EXPECT_EQ(payload.size(),
3109 connection_.SendStreamDataWithString(
3110 3, payload, 0, !kFin, nullptr).bytes_consumed);
3111 // Verify that we have 8 fewer bytes than in the non-truncated case. The
3112 // first packet got 4 bytes of extra payload due to the truncation, and the
3113 // headers here are also 4 byte smaller.
3114 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() + 8);
3117 // Change to a 1 byte CID.
3118 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 1);
3119 connection_.SetFromConfig(config);
3120 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3121 EXPECT_EQ(payload.size(),
3122 connection_.SendStreamDataWithString(
3123 3, payload, 0, !kFin, nullptr).bytes_consumed);
3124 // Just like above, we save 7 bytes on payload, and 7 on truncation.
3125 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() + 7 * 2);
3127 // Change to a 0 byte CID.
3128 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
3129 connection_.SetFromConfig(config);
3130 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3131 EXPECT_EQ(payload.size(),
3132 connection_.SendStreamDataWithString(
3133 3, payload, 0, !kFin, nullptr).bytes_consumed);
3134 // Just like above, we save 8 bytes on payload, and 8 on truncation.
3135 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() + 8 * 2);
3138 TEST_P(QuicConnectionTest, SendDelayedAck) {
3139 QuicTime ack_time = clock_.ApproximateNow().Add(DefaultDelayedAckTime());
3140 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3141 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3142 const uint8 tag = 0x07;
3143 connection_.SetDecrypter(new StrictTaggingDecrypter(tag),
3144 ENCRYPTION_INITIAL);
3145 framer_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
3146 // Process a packet from the non-crypto stream.
3147 frame1_.stream_id = 3;
3149 // The same as ProcessPacket(1) except that ENCRYPTION_INITIAL is used
3150 // instead of ENCRYPTION_NONE.
3151 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
3152 ProcessDataPacketAtLevel(1, 0, !kEntropyFlag, ENCRYPTION_INITIAL);
3154 // Check if delayed ack timer is running for the expected interval.
3155 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3156 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
3157 // Simulate delayed ack alarm firing.
3158 connection_.GetAckAlarm()->Fire();
3159 // Check that ack is sent and that delayed ack alarm is reset.
3160 EXPECT_EQ(2u, writer_->frame_count());
3161 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3162 EXPECT_FALSE(writer_->ack_frames().empty());
3163 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3166 TEST_P(QuicConnectionTest, SendDelayedAckOnHandshakeConfirmed) {
3167 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3168 ProcessPacket(1);
3169 // Check that ack is sent and that delayed ack alarm is set.
3170 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3171 QuicTime ack_time = clock_.ApproximateNow().Add(DefaultDelayedAckTime());
3172 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
3174 // Completing the handshake as the server does nothing.
3175 QuicConnectionPeer::SetIsServer(&connection_, true);
3176 connection_.OnHandshakeComplete();
3177 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3178 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
3180 // Complete the handshake as the client decreases the delayed ack time to 0ms.
3181 QuicConnectionPeer::SetIsServer(&connection_, false);
3182 connection_.OnHandshakeComplete();
3183 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3184 EXPECT_EQ(clock_.ApproximateNow(), connection_.GetAckAlarm()->deadline());
3187 TEST_P(QuicConnectionTest, SendDelayedAckOnSecondPacket) {
3188 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3189 ProcessPacket(1);
3190 ProcessPacket(2);
3191 // Check that ack is sent and that delayed ack alarm is reset.
3192 EXPECT_EQ(2u, writer_->frame_count());
3193 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3194 EXPECT_FALSE(writer_->ack_frames().empty());
3195 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3198 TEST_P(QuicConnectionTest, NoAckOnOldNacks) {
3199 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3200 // Drop one packet, triggering a sequence of acks.
3201 ProcessPacket(2);
3202 size_t frames_per_ack = 2;
3203 EXPECT_EQ(frames_per_ack, writer_->frame_count());
3204 EXPECT_FALSE(writer_->ack_frames().empty());
3205 writer_->Reset();
3206 ProcessPacket(3);
3207 EXPECT_EQ(frames_per_ack, writer_->frame_count());
3208 EXPECT_FALSE(writer_->ack_frames().empty());
3209 writer_->Reset();
3210 ProcessPacket(4);
3211 EXPECT_EQ(frames_per_ack, writer_->frame_count());
3212 EXPECT_FALSE(writer_->ack_frames().empty());
3213 writer_->Reset();
3214 ProcessPacket(5);
3215 EXPECT_EQ(frames_per_ack, writer_->frame_count());
3216 EXPECT_FALSE(writer_->ack_frames().empty());
3217 writer_->Reset();
3218 // Now only set the timer on the 6th packet, instead of sending another ack.
3219 ProcessPacket(6);
3220 EXPECT_EQ(0u, writer_->frame_count());
3221 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3224 TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingPacket) {
3225 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3226 ProcessPacket(1);
3227 connection_.SendStreamDataWithString(kClientDataStreamId1, "foo", 0, !kFin,
3228 nullptr);
3229 // Check that ack is bundled with outgoing data and that delayed ack
3230 // alarm is reset.
3231 EXPECT_EQ(3u, writer_->frame_count());
3232 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3233 EXPECT_FALSE(writer_->ack_frames().empty());
3234 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3237 TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingCryptoPacket) {
3238 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3239 ProcessPacket(1);
3240 connection_.SendStreamDataWithString(kCryptoStreamId, "foo", 0, !kFin,
3241 nullptr);
3242 // Check that ack is bundled with outgoing crypto data.
3243 EXPECT_EQ(3u, writer_->frame_count());
3244 EXPECT_FALSE(writer_->ack_frames().empty());
3245 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3248 TEST_P(QuicConnectionTest, BlockAndBufferOnFirstCHLOPacketOfTwo) {
3249 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3250 ProcessPacket(1);
3251 BlockOnNextWrite();
3252 writer_->set_is_write_blocked_data_buffered(true);
3253 connection_.SendStreamDataWithString(kCryptoStreamId, "foo", 0, !kFin,
3254 nullptr);
3255 EXPECT_TRUE(writer_->IsWriteBlocked());
3256 EXPECT_FALSE(connection_.HasQueuedData());
3257 connection_.SendStreamDataWithString(kCryptoStreamId, "bar", 3, !kFin,
3258 nullptr);
3259 EXPECT_TRUE(writer_->IsWriteBlocked());
3260 EXPECT_TRUE(connection_.HasQueuedData());
3263 TEST_P(QuicConnectionTest, BundleAckForSecondCHLO) {
3264 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3265 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3266 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(
3267 IgnoreResult(InvokeWithoutArgs(&connection_,
3268 &TestConnection::SendCryptoStreamData)));
3269 // Process a packet from the crypto stream, which is frame1_'s default.
3270 // Receiving the CHLO as packet 2 first will cause the connection to
3271 // immediately send an ack, due to the packet gap.
3272 ProcessPacket(2);
3273 // Check that ack is sent and that delayed ack alarm is reset.
3274 EXPECT_EQ(3u, writer_->frame_count());
3275 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3276 EXPECT_EQ(1u, writer_->stream_frames().size());
3277 EXPECT_FALSE(writer_->ack_frames().empty());
3278 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3281 TEST_P(QuicConnectionTest, BundleAckWithDataOnIncomingAck) {
3282 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3283 connection_.SendStreamDataWithString(kClientDataStreamId1, "foo", 0, !kFin,
3284 nullptr);
3285 connection_.SendStreamDataWithString(kClientDataStreamId1, "foo", 3, !kFin,
3286 nullptr);
3287 // Ack the second packet, which will retransmit the first packet.
3288 QuicAckFrame ack = InitAckFrame(2);
3289 NackPacket(1, &ack);
3290 SequenceNumberSet lost_packets;
3291 lost_packets.insert(1);
3292 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3293 .WillOnce(Return(lost_packets));
3294 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3295 ProcessAckPacket(&ack);
3296 EXPECT_EQ(1u, writer_->frame_count());
3297 EXPECT_EQ(1u, writer_->stream_frames().size());
3298 writer_->Reset();
3300 // Now ack the retransmission, which will both raise the high water mark
3301 // and see if there is more data to send.
3302 ack = InitAckFrame(3);
3303 NackPacket(1, &ack);
3304 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3305 .WillOnce(Return(SequenceNumberSet()));
3306 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3307 ProcessAckPacket(&ack);
3309 // Check that no packet is sent and the ack alarm isn't set.
3310 EXPECT_EQ(0u, writer_->frame_count());
3311 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3312 writer_->Reset();
3314 // Send the same ack, but send both data and an ack together.
3315 ack = InitAckFrame(3);
3316 NackPacket(1, &ack);
3317 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3318 .WillOnce(Return(SequenceNumberSet()));
3319 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(
3320 IgnoreResult(InvokeWithoutArgs(
3321 &connection_,
3322 &TestConnection::EnsureWritableAndSendStreamData5)));
3323 ProcessAckPacket(&ack);
3325 // Check that ack is bundled with outgoing data and the delayed ack
3326 // alarm is reset.
3327 EXPECT_EQ(3u, writer_->frame_count());
3328 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3329 EXPECT_FALSE(writer_->ack_frames().empty());
3330 EXPECT_EQ(1u, writer_->stream_frames().size());
3331 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3334 TEST_P(QuicConnectionTest, NoAckSentForClose) {
3335 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3336 ProcessPacket(1);
3337 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, true));
3338 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3339 ProcessClosePacket(2, 0);
3342 TEST_P(QuicConnectionTest, SendWhenDisconnected) {
3343 EXPECT_TRUE(connection_.connected());
3344 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, false));
3345 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, false);
3346 EXPECT_FALSE(connection_.connected());
3347 EXPECT_FALSE(connection_.CanWriteStreamData());
3348 QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
3349 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 1, _, _)).Times(0);
3350 connection_.SendPacket(
3351 ENCRYPTION_NONE, 1, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA);
3354 TEST_P(QuicConnectionTest, PublicReset) {
3355 QuicPublicResetPacket header;
3356 header.public_header.connection_id = connection_id_;
3357 header.public_header.reset_flag = true;
3358 header.public_header.version_flag = false;
3359 header.rejected_sequence_number = 10101;
3360 scoped_ptr<QuicEncryptedPacket> packet(
3361 framer_.BuildPublicResetPacket(header));
3362 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PUBLIC_RESET, true));
3363 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *packet);
3366 TEST_P(QuicConnectionTest, GoAway) {
3367 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3369 QuicGoAwayFrame goaway;
3370 goaway.last_good_stream_id = 1;
3371 goaway.error_code = QUIC_PEER_GOING_AWAY;
3372 goaway.reason_phrase = "Going away.";
3373 EXPECT_CALL(visitor_, OnGoAway(_));
3374 ProcessGoAwayPacket(&goaway);
3377 TEST_P(QuicConnectionTest, WindowUpdate) {
3378 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3380 QuicWindowUpdateFrame window_update;
3381 window_update.stream_id = 3;
3382 window_update.byte_offset = 1234;
3383 EXPECT_CALL(visitor_, OnWindowUpdateFrames(_));
3384 ProcessFramePacket(QuicFrame(&window_update));
3387 TEST_P(QuicConnectionTest, Blocked) {
3388 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3390 QuicBlockedFrame blocked;
3391 blocked.stream_id = 3;
3392 EXPECT_CALL(visitor_, OnBlockedFrames(_));
3393 ProcessFramePacket(QuicFrame(&blocked));
3396 TEST_P(QuicConnectionTest, ZeroBytePacket) {
3397 // Don't close the connection for zero byte packets.
3398 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
3399 QuicEncryptedPacket encrypted(nullptr, 0);
3400 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), encrypted);
3403 TEST_P(QuicConnectionTest, MissingPacketsBeforeLeastUnacked) {
3404 // Set the sequence number of the ack packet to be least unacked (4).
3405 peer_creator_.set_sequence_number(3);
3406 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3407 QuicStopWaitingFrame frame = InitStopWaitingFrame(4);
3408 ProcessStopWaitingPacket(&frame);
3409 EXPECT_TRUE(outgoing_ack()->missing_packets.empty());
3412 TEST_P(QuicConnectionTest, ReceivedEntropyHashCalculation) {
3413 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(AtLeast(1));
3414 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3415 ProcessDataPacket(1, 1, kEntropyFlag);
3416 ProcessDataPacket(4, 1, kEntropyFlag);
3417 ProcessDataPacket(3, 1, !kEntropyFlag);
3418 ProcessDataPacket(7, 1, kEntropyFlag);
3419 EXPECT_EQ(146u, outgoing_ack()->entropy_hash);
3422 TEST_P(QuicConnectionTest, ReceivedEntropyHashCalculationHalfFEC) {
3423 // FEC packets should not change the entropy hash calculation.
3424 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(AtLeast(1));
3425 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3426 ProcessDataPacket(1, 1, kEntropyFlag);
3427 ProcessFecPacket(4, 1, false, kEntropyFlag, nullptr);
3428 ProcessDataPacket(3, 3, !kEntropyFlag);
3429 ProcessFecPacket(7, 3, false, kEntropyFlag, nullptr);
3430 EXPECT_EQ(146u, outgoing_ack()->entropy_hash);
3433 TEST_P(QuicConnectionTest, UpdateEntropyForReceivedPackets) {
3434 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(AtLeast(1));
3435 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3436 ProcessDataPacket(1, 1, kEntropyFlag);
3437 ProcessDataPacket(5, 1, kEntropyFlag);
3438 ProcessDataPacket(4, 1, !kEntropyFlag);
3439 EXPECT_EQ(34u, outgoing_ack()->entropy_hash);
3440 // Make 4th packet my least unacked, and update entropy for 2, 3 packets.
3441 peer_creator_.set_sequence_number(5);
3442 QuicPacketEntropyHash six_packet_entropy_hash = 0;
3443 QuicPacketEntropyHash kRandomEntropyHash = 129u;
3444 QuicStopWaitingFrame frame = InitStopWaitingFrame(4);
3445 frame.entropy_hash = kRandomEntropyHash;
3446 if (ProcessStopWaitingPacket(&frame)) {
3447 six_packet_entropy_hash = 1 << 6;
3450 EXPECT_EQ((kRandomEntropyHash + (1 << 5) + six_packet_entropy_hash),
3451 outgoing_ack()->entropy_hash);
3454 TEST_P(QuicConnectionTest, UpdateEntropyHashUptoCurrentPacket) {
3455 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(AtLeast(1));
3456 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3457 ProcessDataPacket(1, 1, kEntropyFlag);
3458 ProcessDataPacket(5, 1, !kEntropyFlag);
3459 ProcessDataPacket(22, 1, kEntropyFlag);
3460 EXPECT_EQ(66u, outgoing_ack()->entropy_hash);
3461 peer_creator_.set_sequence_number(22);
3462 QuicPacketEntropyHash kRandomEntropyHash = 85u;
3463 // Current packet is the least unacked packet.
3464 QuicPacketEntropyHash ack_entropy_hash;
3465 QuicStopWaitingFrame frame = InitStopWaitingFrame(23);
3466 frame.entropy_hash = kRandomEntropyHash;
3467 ack_entropy_hash = ProcessStopWaitingPacket(&frame);
3468 EXPECT_EQ((kRandomEntropyHash + ack_entropy_hash),
3469 outgoing_ack()->entropy_hash);
3470 ProcessDataPacket(25, 1, kEntropyFlag);
3471 EXPECT_EQ((kRandomEntropyHash + ack_entropy_hash + (1 << (25 % 8))),
3472 outgoing_ack()->entropy_hash);
3475 TEST_P(QuicConnectionTest, EntropyCalculationForTruncatedAck) {
3476 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(AtLeast(1));
3477 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3478 QuicPacketEntropyHash entropy[51];
3479 entropy[0] = 0;
3480 for (int i = 1; i < 51; ++i) {
3481 bool should_send = i % 10 != 1;
3482 bool entropy_flag = (i & (i - 1)) != 0;
3483 if (!should_send) {
3484 entropy[i] = entropy[i - 1];
3485 continue;
3487 if (entropy_flag) {
3488 entropy[i] = entropy[i - 1] ^ (1 << (i % 8));
3489 } else {
3490 entropy[i] = entropy[i - 1];
3492 ProcessDataPacket(i, 1, entropy_flag);
3494 for (int i = 1; i < 50; ++i) {
3495 EXPECT_EQ(entropy[i], QuicConnectionPeer::ReceivedEntropyHash(
3496 &connection_, i));
3500 TEST_P(QuicConnectionTest, ServerSendsVersionNegotiationPacket) {
3501 connection_.SetSupportedVersions(QuicSupportedVersions());
3502 framer_.set_version_for_tests(QUIC_VERSION_UNSUPPORTED);
3504 QuicPacketHeader header;
3505 header.public_header.connection_id = connection_id_;
3506 header.public_header.reset_flag = false;
3507 header.public_header.version_flag = true;
3508 header.entropy_flag = false;
3509 header.fec_flag = false;
3510 header.packet_sequence_number = 12;
3511 header.fec_group = 0;
3513 QuicFrames frames;
3514 QuicFrame frame(&frame1_);
3515 frames.push_back(frame);
3516 scoped_ptr<QuicPacket> packet(
3517 BuildUnsizedDataPacket(&framer_, header, frames).packet);
3518 scoped_ptr<QuicEncryptedPacket> encrypted(
3519 framer_.EncryptPacket(ENCRYPTION_NONE, 12, *packet));
3521 framer_.set_version(version());
3522 connection_.set_is_server(true);
3523 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3524 EXPECT_TRUE(writer_->version_negotiation_packet() != nullptr);
3526 size_t num_versions = arraysize(kSupportedQuicVersions);
3527 ASSERT_EQ(num_versions,
3528 writer_->version_negotiation_packet()->versions.size());
3530 // We expect all versions in kSupportedQuicVersions to be
3531 // included in the packet.
3532 for (size_t i = 0; i < num_versions; ++i) {
3533 EXPECT_EQ(kSupportedQuicVersions[i],
3534 writer_->version_negotiation_packet()->versions[i]);
3538 TEST_P(QuicConnectionTest, ServerSendsVersionNegotiationPacketSocketBlocked) {
3539 connection_.SetSupportedVersions(QuicSupportedVersions());
3540 framer_.set_version_for_tests(QUIC_VERSION_UNSUPPORTED);
3542 QuicPacketHeader header;
3543 header.public_header.connection_id = connection_id_;
3544 header.public_header.reset_flag = false;
3545 header.public_header.version_flag = true;
3546 header.entropy_flag = false;
3547 header.fec_flag = false;
3548 header.packet_sequence_number = 12;
3549 header.fec_group = 0;
3551 QuicFrames frames;
3552 QuicFrame frame(&frame1_);
3553 frames.push_back(frame);
3554 scoped_ptr<QuicPacket> packet(
3555 BuildUnsizedDataPacket(&framer_, header, frames).packet);
3556 scoped_ptr<QuicEncryptedPacket> encrypted(
3557 framer_.EncryptPacket(ENCRYPTION_NONE, 12, *packet));
3559 framer_.set_version(version());
3560 connection_.set_is_server(true);
3561 BlockOnNextWrite();
3562 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3563 EXPECT_EQ(0u, writer_->last_packet_size());
3564 EXPECT_TRUE(connection_.HasQueuedData());
3566 writer_->SetWritable();
3567 connection_.OnCanWrite();
3568 EXPECT_TRUE(writer_->version_negotiation_packet() != nullptr);
3570 size_t num_versions = arraysize(kSupportedQuicVersions);
3571 ASSERT_EQ(num_versions,
3572 writer_->version_negotiation_packet()->versions.size());
3574 // We expect all versions in kSupportedQuicVersions to be
3575 // included in the packet.
3576 for (size_t i = 0; i < num_versions; ++i) {
3577 EXPECT_EQ(kSupportedQuicVersions[i],
3578 writer_->version_negotiation_packet()->versions[i]);
3582 TEST_P(QuicConnectionTest,
3583 ServerSendsVersionNegotiationPacketSocketBlockedDataBuffered) {
3584 connection_.SetSupportedVersions(QuicSupportedVersions());
3585 framer_.set_version_for_tests(QUIC_VERSION_UNSUPPORTED);
3587 QuicPacketHeader header;
3588 header.public_header.connection_id = connection_id_;
3589 header.public_header.reset_flag = false;
3590 header.public_header.version_flag = true;
3591 header.entropy_flag = false;
3592 header.fec_flag = false;
3593 header.packet_sequence_number = 12;
3594 header.fec_group = 0;
3596 QuicFrames frames;
3597 QuicFrame frame(&frame1_);
3598 frames.push_back(frame);
3599 scoped_ptr<QuicPacket> packet(
3600 BuildUnsizedDataPacket(&framer_, header, frames).packet);
3601 scoped_ptr<QuicEncryptedPacket> encrypted(
3602 framer_.EncryptPacket(ENCRYPTION_NONE, 12, *packet));
3604 framer_.set_version(version());
3605 connection_.set_is_server(true);
3606 BlockOnNextWrite();
3607 writer_->set_is_write_blocked_data_buffered(true);
3608 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3609 EXPECT_EQ(0u, writer_->last_packet_size());
3610 EXPECT_FALSE(connection_.HasQueuedData());
3613 TEST_P(QuicConnectionTest, ClientHandlesVersionNegotiation) {
3614 // Start out with some unsupported version.
3615 QuicConnectionPeer::GetFramer(&connection_)->set_version_for_tests(
3616 QUIC_VERSION_UNSUPPORTED);
3618 QuicPacketHeader header;
3619 header.public_header.connection_id = connection_id_;
3620 header.public_header.reset_flag = false;
3621 header.public_header.version_flag = true;
3622 header.entropy_flag = false;
3623 header.fec_flag = false;
3624 header.packet_sequence_number = 12;
3625 header.fec_group = 0;
3627 QuicVersionVector supported_versions;
3628 for (size_t i = 0; i < arraysize(kSupportedQuicVersions); ++i) {
3629 supported_versions.push_back(kSupportedQuicVersions[i]);
3632 // Send a version negotiation packet.
3633 scoped_ptr<QuicEncryptedPacket> encrypted(
3634 framer_.BuildVersionNegotiationPacket(
3635 header.public_header, supported_versions));
3636 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3638 // Now force another packet. The connection should transition into
3639 // NEGOTIATED_VERSION state and tell the packet creator to StopSendingVersion.
3640 header.public_header.version_flag = false;
3641 QuicFrames frames;
3642 QuicFrame frame(&frame1_);
3643 frames.push_back(frame);
3644 scoped_ptr<QuicPacket> packet(
3645 BuildUnsizedDataPacket(&framer_, header, frames).packet);
3646 encrypted.reset(framer_.EncryptPacket(ENCRYPTION_NONE, 12, *packet));
3647 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
3648 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3649 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3651 ASSERT_FALSE(QuicPacketCreatorPeer::SendVersionInPacket(
3652 QuicConnectionPeer::GetPacketCreator(&connection_)));
3655 TEST_P(QuicConnectionTest, BadVersionNegotiation) {
3656 QuicPacketHeader header;
3657 header.public_header.connection_id = connection_id_;
3658 header.public_header.reset_flag = false;
3659 header.public_header.version_flag = true;
3660 header.entropy_flag = false;
3661 header.fec_flag = false;
3662 header.packet_sequence_number = 12;
3663 header.fec_group = 0;
3665 QuicVersionVector supported_versions;
3666 for (size_t i = 0; i < arraysize(kSupportedQuicVersions); ++i) {
3667 supported_versions.push_back(kSupportedQuicVersions[i]);
3670 // Send a version negotiation packet with the version the client started with.
3671 // It should be rejected.
3672 EXPECT_CALL(visitor_,
3673 OnConnectionClosed(QUIC_INVALID_VERSION_NEGOTIATION_PACKET,
3674 false));
3675 scoped_ptr<QuicEncryptedPacket> encrypted(
3676 framer_.BuildVersionNegotiationPacket(
3677 header.public_header, supported_versions));
3678 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3681 TEST_P(QuicConnectionTest, CheckSendStats) {
3682 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3683 connection_.SendStreamDataWithString(3, "first", 0, !kFin, nullptr);
3684 size_t first_packet_size = writer_->last_packet_size();
3686 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3687 connection_.SendStreamDataWithString(5, "second", 0, !kFin, nullptr);
3688 size_t second_packet_size = writer_->last_packet_size();
3690 // 2 retransmissions due to rto, 1 due to explicit nack.
3691 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
3692 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
3694 // Retransmit due to RTO.
3695 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
3696 connection_.GetRetransmissionAlarm()->Fire();
3698 // Retransmit due to explicit nacks.
3699 QuicAckFrame nack_three = InitAckFrame(4);
3700 NackPacket(3, &nack_three);
3701 NackPacket(1, &nack_three);
3702 SequenceNumberSet lost_packets;
3703 lost_packets.insert(1);
3704 lost_packets.insert(3);
3705 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3706 .WillOnce(Return(lost_packets));
3707 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3708 EXPECT_CALL(visitor_, OnCanWrite()).Times(2);
3709 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3710 EXPECT_CALL(*send_algorithm_, RevertRetransmissionTimeout());
3711 ProcessAckPacket(&nack_three);
3713 EXPECT_CALL(*send_algorithm_, BandwidthEstimate()).WillOnce(
3714 Return(QuicBandwidth::Zero()));
3716 const QuicConnectionStats& stats = connection_.GetStats();
3717 EXPECT_EQ(3 * first_packet_size + 2 * second_packet_size - kQuicVersionSize,
3718 stats.bytes_sent);
3719 EXPECT_EQ(5u, stats.packets_sent);
3720 EXPECT_EQ(2 * first_packet_size + second_packet_size - kQuicVersionSize,
3721 stats.bytes_retransmitted);
3722 EXPECT_EQ(3u, stats.packets_retransmitted);
3723 EXPECT_EQ(1u, stats.rto_count);
3724 EXPECT_EQ(kDefaultMaxPacketSize, stats.max_packet_size);
3727 TEST_P(QuicConnectionTest, CheckReceiveStats) {
3728 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3730 size_t received_bytes = 0;
3731 received_bytes += ProcessFecProtectedPacket(1, false, !kEntropyFlag);
3732 received_bytes += ProcessFecProtectedPacket(3, false, !kEntropyFlag);
3733 // Should be counted against dropped packets.
3734 received_bytes += ProcessDataPacket(3, 1, !kEntropyFlag);
3735 received_bytes += ProcessFecPacket(4, 1, true, !kEntropyFlag, nullptr);
3737 EXPECT_CALL(*send_algorithm_, BandwidthEstimate()).WillOnce(
3738 Return(QuicBandwidth::Zero()));
3740 const QuicConnectionStats& stats = connection_.GetStats();
3741 EXPECT_EQ(received_bytes, stats.bytes_received);
3742 EXPECT_EQ(4u, stats.packets_received);
3744 EXPECT_EQ(1u, stats.packets_revived);
3745 EXPECT_EQ(1u, stats.packets_dropped);
3748 TEST_P(QuicConnectionTest, TestFecGroupLimits) {
3749 // Create and return a group for 1.
3750 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 1) != nullptr);
3752 // Create and return a group for 2.
3753 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 2) != nullptr);
3755 // Create and return a group for 4. This should remove 1 but not 2.
3756 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 4) != nullptr);
3757 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 1) == nullptr);
3758 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 2) != nullptr);
3760 // Create and return a group for 3. This will kill off 2.
3761 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 3) != nullptr);
3762 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 2) == nullptr);
3764 // Verify that adding 5 kills off 3, despite 4 being created before 3.
3765 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 5) != nullptr);
3766 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 4) != nullptr);
3767 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 3) == nullptr);
3770 TEST_P(QuicConnectionTest, ProcessFramesIfPacketClosedConnection) {
3771 // Construct a packet with stream frame and connection close frame.
3772 header_.public_header.connection_id = connection_id_;
3773 header_.packet_sequence_number = 1;
3774 header_.public_header.reset_flag = false;
3775 header_.public_header.version_flag = false;
3776 header_.entropy_flag = false;
3777 header_.fec_flag = false;
3778 header_.fec_group = 0;
3780 QuicConnectionCloseFrame qccf;
3781 qccf.error_code = QUIC_PEER_GOING_AWAY;
3782 QuicFrame close_frame(&qccf);
3783 QuicFrame stream_frame(&frame1_);
3785 QuicFrames frames;
3786 frames.push_back(stream_frame);
3787 frames.push_back(close_frame);
3788 scoped_ptr<QuicPacket> packet(
3789 BuildUnsizedDataPacket(&framer_, header_, frames).packet);
3790 EXPECT_TRUE(nullptr != packet.get());
3791 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPacket(
3792 ENCRYPTION_NONE, 1, *packet));
3794 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, true));
3795 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
3796 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3798 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3801 TEST_P(QuicConnectionTest, SelectMutualVersion) {
3802 connection_.SetSupportedVersions(QuicSupportedVersions());
3803 // Set the connection to speak the lowest quic version.
3804 connection_.set_version(QuicVersionMin());
3805 EXPECT_EQ(QuicVersionMin(), connection_.version());
3807 // Pass in available versions which includes a higher mutually supported
3808 // version. The higher mutually supported version should be selected.
3809 QuicVersionVector supported_versions;
3810 for (size_t i = 0; i < arraysize(kSupportedQuicVersions); ++i) {
3811 supported_versions.push_back(kSupportedQuicVersions[i]);
3813 EXPECT_TRUE(connection_.SelectMutualVersion(supported_versions));
3814 EXPECT_EQ(QuicVersionMax(), connection_.version());
3816 // Expect that the lowest version is selected.
3817 // Ensure the lowest supported version is less than the max, unless they're
3818 // the same.
3819 EXPECT_LE(QuicVersionMin(), QuicVersionMax());
3820 QuicVersionVector lowest_version_vector;
3821 lowest_version_vector.push_back(QuicVersionMin());
3822 EXPECT_TRUE(connection_.SelectMutualVersion(lowest_version_vector));
3823 EXPECT_EQ(QuicVersionMin(), connection_.version());
3825 // Shouldn't be able to find a mutually supported version.
3826 QuicVersionVector unsupported_version;
3827 unsupported_version.push_back(QUIC_VERSION_UNSUPPORTED);
3828 EXPECT_FALSE(connection_.SelectMutualVersion(unsupported_version));
3831 TEST_P(QuicConnectionTest, ConnectionCloseWhenWritable) {
3832 EXPECT_FALSE(writer_->IsWriteBlocked());
3834 // Send a packet.
3835 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
3836 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3837 EXPECT_EQ(1u, writer_->packets_write_attempts());
3839 TriggerConnectionClose();
3840 EXPECT_EQ(2u, writer_->packets_write_attempts());
3843 TEST_P(QuicConnectionTest, ConnectionCloseGettingWriteBlocked) {
3844 BlockOnNextWrite();
3845 TriggerConnectionClose();
3846 EXPECT_EQ(1u, writer_->packets_write_attempts());
3847 EXPECT_TRUE(writer_->IsWriteBlocked());
3850 TEST_P(QuicConnectionTest, ConnectionCloseWhenWriteBlocked) {
3851 BlockOnNextWrite();
3852 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
3853 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3854 EXPECT_EQ(1u, writer_->packets_write_attempts());
3855 EXPECT_TRUE(writer_->IsWriteBlocked());
3856 TriggerConnectionClose();
3857 EXPECT_EQ(1u, writer_->packets_write_attempts());
3860 TEST_P(QuicConnectionTest, AckNotifierTriggerCallback) {
3861 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3863 // Create a delegate which we expect to be called.
3864 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
3865 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _, _, _)).Times(1);
3867 // Send some data, which will register the delegate to be notified.
3868 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
3870 // Process an ACK from the server which should trigger the callback.
3871 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3872 QuicAckFrame frame = InitAckFrame(1);
3873 ProcessAckPacket(&frame);
3876 TEST_P(QuicConnectionTest, AckNotifierFailToTriggerCallback) {
3877 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3879 // Create a delegate which we don't expect to be called.
3880 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
3881 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _, _, _)).Times(0);
3883 // Send some data, which will register the delegate to be notified. This will
3884 // not be ACKed and so the delegate should never be called.
3885 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
3887 // Send some other data which we will ACK.
3888 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
3889 connection_.SendStreamDataWithString(1, "bar", 0, !kFin, nullptr);
3891 // Now we receive ACK for packets 2 and 3, but importantly missing packet 1
3892 // which we registered to be notified about.
3893 QuicAckFrame frame = InitAckFrame(3);
3894 NackPacket(1, &frame);
3895 SequenceNumberSet lost_packets;
3896 lost_packets.insert(1);
3897 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3898 .WillOnce(Return(lost_packets));
3899 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3900 ProcessAckPacket(&frame);
3903 TEST_P(QuicConnectionTest, AckNotifierCallbackAfterRetransmission) {
3904 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3906 // Create a delegate which we expect to be called.
3907 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
3908 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _, _, _)).Times(1);
3910 // Send four packets, and register to be notified on ACK of packet 2.
3911 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
3912 connection_.SendStreamDataWithString(3, "bar", 0, !kFin, delegate.get());
3913 connection_.SendStreamDataWithString(3, "baz", 0, !kFin, nullptr);
3914 connection_.SendStreamDataWithString(3, "qux", 0, !kFin, nullptr);
3916 // Now we receive ACK for packets 1, 3, and 4 and lose 2.
3917 QuicAckFrame frame = InitAckFrame(4);
3918 NackPacket(2, &frame);
3919 SequenceNumberSet lost_packets;
3920 lost_packets.insert(2);
3921 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3922 .WillOnce(Return(lost_packets));
3923 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3924 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3925 ProcessAckPacket(&frame);
3927 // Now we get an ACK for packet 5 (retransmitted packet 2), which should
3928 // trigger the callback.
3929 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3930 .WillRepeatedly(Return(SequenceNumberSet()));
3931 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3932 QuicAckFrame second_ack_frame = InitAckFrame(5);
3933 ProcessAckPacket(&second_ack_frame);
3936 // AckNotifierCallback is triggered by the ack of a packet that timed
3937 // out and was retransmitted, even though the retransmission has a
3938 // different sequence number.
3939 TEST_P(QuicConnectionTest, AckNotifierCallbackForAckAfterRTO) {
3940 InSequence s;
3942 // Create a delegate which we expect to be called.
3943 scoped_refptr<MockAckNotifierDelegate> delegate(
3944 new StrictMock<MockAckNotifierDelegate>);
3946 QuicTime default_retransmission_time = clock_.ApproximateNow().Add(
3947 DefaultRetransmissionTime());
3948 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, delegate.get());
3949 EXPECT_EQ(1u, stop_waiting()->least_unacked);
3951 EXPECT_EQ(1u, writer_->header().packet_sequence_number);
3952 EXPECT_EQ(default_retransmission_time,
3953 connection_.GetRetransmissionAlarm()->deadline());
3954 // Simulate the retransmission alarm firing.
3955 clock_.AdvanceTime(DefaultRetransmissionTime());
3956 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
3957 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 2u, _, _));
3958 connection_.GetRetransmissionAlarm()->Fire();
3959 EXPECT_EQ(2u, writer_->header().packet_sequence_number);
3960 // We do not raise the high water mark yet.
3961 EXPECT_EQ(1u, stop_waiting()->least_unacked);
3963 // Ack the original packet, which will revert the RTO.
3964 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3965 EXPECT_CALL(*delegate.get(), OnAckNotification(1, _, 1, _, _));
3966 EXPECT_CALL(*send_algorithm_, RevertRetransmissionTimeout());
3967 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3968 QuicAckFrame ack_frame = InitAckFrame(1);
3969 ProcessAckPacket(&ack_frame);
3971 // Delegate is not notified again when the retransmit is acked.
3972 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3973 QuicAckFrame second_ack_frame = InitAckFrame(2);
3974 ProcessAckPacket(&second_ack_frame);
3977 // AckNotifierCallback is triggered by the ack of a packet that was
3978 // previously nacked, even though the retransmission has a different
3979 // sequence number.
3980 TEST_P(QuicConnectionTest, AckNotifierCallbackForAckOfNackedPacket) {
3981 InSequence s;
3983 // Create a delegate which we expect to be called.
3984 scoped_refptr<MockAckNotifierDelegate> delegate(
3985 new StrictMock<MockAckNotifierDelegate>);
3987 // Send four packets, and register to be notified on ACK of packet 2.
3988 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
3989 connection_.SendStreamDataWithString(3, "bar", 0, !kFin, delegate.get());
3990 connection_.SendStreamDataWithString(3, "baz", 0, !kFin, nullptr);
3991 connection_.SendStreamDataWithString(3, "qux", 0, !kFin, nullptr);
3993 // Now we receive ACK for packets 1, 3, and 4 and lose 2.
3994 QuicAckFrame frame = InitAckFrame(4);
3995 NackPacket(2, &frame);
3996 SequenceNumberSet lost_packets;
3997 lost_packets.insert(2);
3998 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3999 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4000 .WillOnce(Return(lost_packets));
4001 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4002 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4003 ProcessAckPacket(&frame);
4005 // Now we get an ACK for packet 2, which was previously nacked.
4006 SequenceNumberSet no_lost_packets;
4007 EXPECT_CALL(*delegate.get(), OnAckNotification(1, _, 1, _, _));
4008 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4009 .WillOnce(Return(no_lost_packets));
4010 QuicAckFrame second_ack_frame = InitAckFrame(4);
4011 ProcessAckPacket(&second_ack_frame);
4013 // Verify that the delegate is not notified again when the
4014 // retransmit is acked.
4015 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4016 .WillOnce(Return(no_lost_packets));
4017 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4018 QuicAckFrame third_ack_frame = InitAckFrame(5);
4019 ProcessAckPacket(&third_ack_frame);
4022 TEST_P(QuicConnectionTest, AckNotifierFECTriggerCallback) {
4023 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4025 // Create a delegate which we expect to be called.
4026 scoped_refptr<MockAckNotifierDelegate> delegate(
4027 new MockAckNotifierDelegate);
4028 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _, _, _)).Times(1);
4030 // Send some data, which will register the delegate to be notified.
4031 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
4032 connection_.SendStreamDataWithString(2, "bar", 0, !kFin, nullptr);
4034 // Process an ACK from the server with a revived packet, which should trigger
4035 // the callback.
4036 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4037 QuicAckFrame frame = InitAckFrame(2);
4038 NackPacket(1, &frame);
4039 frame.revived_packets.insert(1);
4040 ProcessAckPacket(&frame);
4041 // If the ack is processed again, the notifier should not be called again.
4042 ProcessAckPacket(&frame);
4045 TEST_P(QuicConnectionTest, AckNotifierCallbackAfterFECRecovery) {
4046 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4047 EXPECT_CALL(visitor_, OnCanWrite());
4049 // Create a delegate which we expect to be called.
4050 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4051 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _, _, _)).Times(1);
4053 // Expect ACKs for 1 packet.
4054 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4056 // Send one packet, and register to be notified on ACK.
4057 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
4059 // Ack packet gets dropped, but we receive an FEC packet that covers it.
4060 // Should recover the Ack packet and trigger the notification callback.
4061 QuicFrames frames;
4063 QuicAckFrame ack_frame = InitAckFrame(1);
4064 frames.push_back(QuicFrame(&ack_frame));
4066 // Dummy stream frame to satisfy expectations set elsewhere.
4067 frames.push_back(QuicFrame(&frame1_));
4069 QuicPacketHeader ack_header;
4070 ack_header.public_header.connection_id = connection_id_;
4071 ack_header.public_header.reset_flag = false;
4072 ack_header.public_header.version_flag = false;
4073 ack_header.entropy_flag = !kEntropyFlag;
4074 ack_header.fec_flag = true;
4075 ack_header.packet_sequence_number = 1;
4076 ack_header.is_in_fec_group = IN_FEC_GROUP;
4077 ack_header.fec_group = 1;
4079 QuicPacket* packet =
4080 BuildUnsizedDataPacket(&framer_, ack_header, frames).packet;
4082 // Take the packet which contains the ACK frame, and construct and deliver an
4083 // FEC packet which allows the ACK packet to be recovered.
4084 ProcessFecPacket(2, 1, true, !kEntropyFlag, packet);
4087 TEST_P(QuicConnectionTest, NetworkChangeVisitorCallbacksChangeFecState) {
4088 QuicPacketCreator* creator =
4089 QuicConnectionPeer::GetPacketCreator(&connection_);
4090 size_t max_packets_per_fec_group = creator->max_packets_per_fec_group();
4092 QuicSentPacketManager::NetworkChangeVisitor* visitor =
4093 QuicSentPacketManagerPeer::GetNetworkChangeVisitor(
4094 QuicConnectionPeer::GetSentPacketManager(&connection_));
4095 EXPECT_TRUE(visitor);
4097 // Increase FEC group size by increasing congestion window to a large number.
4098 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
4099 Return(1000 * kDefaultTCPMSS));
4100 visitor->OnCongestionWindowChange();
4101 EXPECT_LT(max_packets_per_fec_group, creator->max_packets_per_fec_group());
4104 class MockQuicConnectionDebugVisitor
4105 : public QuicConnectionDebugVisitor {
4106 public:
4107 MOCK_METHOD1(OnFrameAddedToPacket,
4108 void(const QuicFrame&));
4110 MOCK_METHOD6(OnPacketSent,
4111 void(const SerializedPacket&,
4112 QuicPacketSequenceNumber,
4113 EncryptionLevel,
4114 TransmissionType,
4115 const QuicEncryptedPacket&,
4116 QuicTime));
4118 MOCK_METHOD3(OnPacketReceived,
4119 void(const IPEndPoint&,
4120 const IPEndPoint&,
4121 const QuicEncryptedPacket&));
4123 MOCK_METHOD1(OnProtocolVersionMismatch,
4124 void(QuicVersion));
4126 MOCK_METHOD1(OnPacketHeader,
4127 void(const QuicPacketHeader& header));
4129 MOCK_METHOD1(OnStreamFrame,
4130 void(const QuicStreamFrame&));
4132 MOCK_METHOD1(OnAckFrame,
4133 void(const QuicAckFrame& frame));
4135 MOCK_METHOD1(OnCongestionFeedbackFrame,
4136 void(const QuicCongestionFeedbackFrame&));
4138 MOCK_METHOD1(OnStopWaitingFrame,
4139 void(const QuicStopWaitingFrame&));
4141 MOCK_METHOD1(OnRstStreamFrame,
4142 void(const QuicRstStreamFrame&));
4144 MOCK_METHOD1(OnConnectionCloseFrame,
4145 void(const QuicConnectionCloseFrame&));
4147 MOCK_METHOD1(OnPublicResetPacket,
4148 void(const QuicPublicResetPacket&));
4150 MOCK_METHOD1(OnVersionNegotiationPacket,
4151 void(const QuicVersionNegotiationPacket&));
4153 MOCK_METHOD2(OnRevivedPacket,
4154 void(const QuicPacketHeader&, StringPiece payload));
4157 TEST_P(QuicConnectionTest, OnPacketHeaderDebugVisitor) {
4158 QuicPacketHeader header;
4160 MockQuicConnectionDebugVisitor* debug_visitor =
4161 new MockQuicConnectionDebugVisitor();
4162 connection_.set_debug_visitor(debug_visitor);
4163 EXPECT_CALL(*debug_visitor, OnPacketHeader(Ref(header))).Times(1);
4164 connection_.OnPacketHeader(header);
4167 TEST_P(QuicConnectionTest, Pacing) {
4168 TestConnection server(connection_id_, IPEndPoint(), helper_.get(),
4169 factory_, /* is_server= */ true, version());
4170 TestConnection client(connection_id_, IPEndPoint(), helper_.get(),
4171 factory_, /* is_server= */ false, version());
4172 EXPECT_FALSE(client.sent_packet_manager().using_pacing());
4173 EXPECT_FALSE(server.sent_packet_manager().using_pacing());
4176 TEST_P(QuicConnectionTest, ControlFramesInstigateAcks) {
4177 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4179 // Send a WINDOW_UPDATE frame.
4180 QuicWindowUpdateFrame window_update;
4181 window_update.stream_id = 3;
4182 window_update.byte_offset = 1234;
4183 EXPECT_CALL(visitor_, OnWindowUpdateFrames(_));
4184 ProcessFramePacket(QuicFrame(&window_update));
4186 // Ensure that this has caused the ACK alarm to be set.
4187 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
4188 EXPECT_TRUE(ack_alarm->IsSet());
4190 // Cancel alarm, and try again with BLOCKED frame.
4191 ack_alarm->Cancel();
4192 QuicBlockedFrame blocked;
4193 blocked.stream_id = 3;
4194 EXPECT_CALL(visitor_, OnBlockedFrames(_));
4195 ProcessFramePacket(QuicFrame(&blocked));
4196 EXPECT_TRUE(ack_alarm->IsSet());
4199 } // namespace
4200 } // namespace test
4201 } // namespace net