Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / net / quic / quic_connection_test.cc
bloba5c817a2862aedea53b9363e0f702e95cb219a8e
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 <ostream>
9 #include "base/basictypes.h"
10 #include "base/bind.h"
11 #include "base/memory/scoped_ptr.h"
12 #include "base/stl_util.h"
13 #include "net/base/net_errors.h"
14 #include "net/quic/congestion_control/loss_detection_interface.h"
15 #include "net/quic/congestion_control/send_algorithm_interface.h"
16 #include "net/quic/crypto/null_encrypter.h"
17 #include "net/quic/crypto/quic_decrypter.h"
18 #include "net/quic/crypto/quic_encrypter.h"
19 #include "net/quic/quic_ack_notifier.h"
20 #include "net/quic/quic_flags.h"
21 #include "net/quic/quic_protocol.h"
22 #include "net/quic/quic_utils.h"
23 #include "net/quic/test_tools/mock_clock.h"
24 #include "net/quic/test_tools/mock_random.h"
25 #include "net/quic/test_tools/quic_config_peer.h"
26 #include "net/quic/test_tools/quic_connection_peer.h"
27 #include "net/quic/test_tools/quic_framer_peer.h"
28 #include "net/quic/test_tools/quic_packet_creator_peer.h"
29 #include "net/quic/test_tools/quic_packet_generator_peer.h"
30 #include "net/quic/test_tools/quic_sent_packet_manager_peer.h"
31 #include "net/quic/test_tools/quic_test_utils.h"
32 #include "net/quic/test_tools/simple_quic_framer.h"
33 #include "net/test/gtest_util.h"
34 #include "testing/gmock/include/gmock/gmock.h"
35 #include "testing/gtest/include/gtest/gtest.h"
37 using base::StringPiece;
38 using std::map;
39 using std::ostream;
40 using std::string;
41 using std::vector;
42 using testing::AnyNumber;
43 using testing::AtLeast;
44 using testing::Contains;
45 using testing::DoAll;
46 using testing::InSequence;
47 using testing::InvokeWithoutArgs;
48 using testing::NiceMock;
49 using testing::Ref;
50 using testing::Return;
51 using testing::SaveArg;
52 using testing::StrictMock;
53 using testing::_;
55 namespace net {
56 namespace test {
57 namespace {
59 const char data1[] = "foo";
60 const char data2[] = "bar";
62 const bool kFin = true;
63 const bool kEntropyFlag = true;
65 const QuicPacketEntropyHash kTestEntropyHash = 76;
67 const int kDefaultRetransmissionTimeMs = 500;
69 // TaggingEncrypter appends kTagSize bytes of |tag| to the end of each message.
70 class TaggingEncrypter : public QuicEncrypter {
71 public:
72 explicit TaggingEncrypter(uint8 tag)
73 : tag_(tag) {
76 ~TaggingEncrypter() override {}
78 // QuicEncrypter interface.
79 bool SetKey(StringPiece key) override { return true; }
81 bool SetNoncePrefix(StringPiece nonce_prefix) override { return true; }
83 bool EncryptPacket(QuicPacketSequenceNumber sequence_number,
84 StringPiece associated_data,
85 StringPiece plaintext,
86 char* output,
87 size_t* output_length,
88 size_t max_output_length) override {
89 const size_t len = plaintext.size() + kTagSize;
90 if (max_output_length < len) {
91 return false;
93 memcpy(output, plaintext.data(), plaintext.size());
94 output += plaintext.size();
95 memset(output, tag_, kTagSize);
96 *output_length = len;
97 return true;
100 size_t GetKeySize() const override { return 0; }
101 size_t GetNoncePrefixSize() const override { return 0; }
103 size_t GetMaxPlaintextSize(size_t ciphertext_size) const override {
104 return ciphertext_size - kTagSize;
107 size_t GetCiphertextSize(size_t plaintext_size) const override {
108 return plaintext_size + kTagSize;
111 StringPiece GetKey() const override { return StringPiece(); }
113 StringPiece GetNoncePrefix() const override { return StringPiece(); }
115 private:
116 enum {
117 kTagSize = 12,
120 const uint8 tag_;
122 DISALLOW_COPY_AND_ASSIGN(TaggingEncrypter);
125 // TaggingDecrypter ensures that the final kTagSize bytes of the message all
126 // have the same value and then removes them.
127 class TaggingDecrypter : public QuicDecrypter {
128 public:
129 ~TaggingDecrypter() override {}
131 // QuicDecrypter interface
132 bool SetKey(StringPiece key) override { return true; }
134 bool SetNoncePrefix(StringPiece nonce_prefix) override { return true; }
136 bool DecryptPacket(QuicPacketSequenceNumber sequence_number,
137 const StringPiece& associated_data,
138 const StringPiece& ciphertext,
139 char* output,
140 size_t* output_length,
141 size_t max_output_length) override {
142 if (ciphertext.size() < kTagSize) {
143 return false;
145 if (!CheckTag(ciphertext, GetTag(ciphertext))) {
146 return false;
148 *output_length = ciphertext.size() - kTagSize;
149 memcpy(output, ciphertext.data(), *output_length);
150 return true;
153 StringPiece GetKey() const override { return StringPiece(); }
154 StringPiece GetNoncePrefix() const override { return StringPiece(); }
155 const char* cipher_name() const override { return "Tagging"; }
156 // Use a distinct value starting with 0xFFFFFF, which is never used by TLS.
157 uint32 cipher_id() const override { return 0xFFFFFFF0; }
159 protected:
160 virtual uint8 GetTag(StringPiece ciphertext) {
161 return ciphertext.data()[ciphertext.size()-1];
164 private:
165 enum {
166 kTagSize = 12,
169 bool CheckTag(StringPiece ciphertext, uint8 tag) {
170 for (size_t i = ciphertext.size() - kTagSize; i < ciphertext.size(); i++) {
171 if (ciphertext.data()[i] != tag) {
172 return false;
176 return true;
180 // StringTaggingDecrypter ensures that the final kTagSize bytes of the message
181 // match the expected value.
182 class StrictTaggingDecrypter : public TaggingDecrypter {
183 public:
184 explicit StrictTaggingDecrypter(uint8 tag) : tag_(tag) {}
185 ~StrictTaggingDecrypter() override {}
187 // TaggingQuicDecrypter
188 uint8 GetTag(StringPiece ciphertext) override { return tag_; }
190 const char* cipher_name() const override { return "StrictTagging"; }
191 // Use a distinct value starting with 0xFFFFFF, which is never used by TLS.
192 uint32 cipher_id() const override { return 0xFFFFFFF1; }
194 private:
195 const uint8 tag_;
198 class TestConnectionHelper : public QuicConnectionHelperInterface {
199 public:
200 class TestAlarm : public QuicAlarm {
201 public:
202 explicit TestAlarm(QuicAlarm::Delegate* delegate)
203 : QuicAlarm(delegate) {
206 void SetImpl() override {}
207 void CancelImpl() override {}
208 using QuicAlarm::Fire;
211 TestConnectionHelper(MockClock* clock, MockRandom* random_generator)
212 : clock_(clock),
213 random_generator_(random_generator) {
214 clock_->AdvanceTime(QuicTime::Delta::FromSeconds(1));
217 // QuicConnectionHelperInterface
218 const QuicClock* GetClock() const override { return clock_; }
220 QuicRandom* GetRandomGenerator() override { return random_generator_; }
222 QuicAlarm* CreateAlarm(QuicAlarm::Delegate* delegate) override {
223 return new TestAlarm(delegate);
226 private:
227 MockClock* clock_;
228 MockRandom* random_generator_;
230 DISALLOW_COPY_AND_ASSIGN(TestConnectionHelper);
233 class TestPacketWriter : public QuicPacketWriter {
234 public:
235 TestPacketWriter(QuicVersion version, MockClock *clock)
236 : version_(version),
237 framer_(SupportedVersions(version_)),
238 last_packet_size_(0),
239 write_blocked_(false),
240 block_on_next_write_(false),
241 is_write_blocked_data_buffered_(false),
242 final_bytes_of_last_packet_(0),
243 final_bytes_of_previous_packet_(0),
244 use_tagging_decrypter_(false),
245 packets_write_attempts_(0),
246 clock_(clock),
247 write_pause_time_delta_(QuicTime::Delta::Zero()) {
250 // QuicPacketWriter interface
251 WriteResult WritePacket(const char* buffer,
252 size_t buf_len,
253 const IPAddressNumber& self_address,
254 const IPEndPoint& peer_address) override {
255 QuicEncryptedPacket packet(buffer, buf_len);
256 ++packets_write_attempts_;
258 if (packet.length() >= sizeof(final_bytes_of_last_packet_)) {
259 final_bytes_of_previous_packet_ = final_bytes_of_last_packet_;
260 memcpy(&final_bytes_of_last_packet_, packet.data() + packet.length() - 4,
261 sizeof(final_bytes_of_last_packet_));
264 if (use_tagging_decrypter_) {
265 framer_.framer()->SetDecrypter(ENCRYPTION_NONE, new TaggingDecrypter);
267 EXPECT_TRUE(framer_.ProcessPacket(packet));
268 if (block_on_next_write_) {
269 write_blocked_ = true;
270 block_on_next_write_ = false;
272 if (IsWriteBlocked()) {
273 return WriteResult(WRITE_STATUS_BLOCKED, -1);
275 last_packet_size_ = packet.length();
277 if (!write_pause_time_delta_.IsZero()) {
278 clock_->AdvanceTime(write_pause_time_delta_);
280 return WriteResult(WRITE_STATUS_OK, last_packet_size_);
283 bool IsWriteBlockedDataBuffered() const override {
284 return is_write_blocked_data_buffered_;
287 bool IsWriteBlocked() const override { return write_blocked_; }
289 void SetWritable() override { write_blocked_ = false; }
291 void BlockOnNextWrite() { block_on_next_write_ = true; }
293 // Sets the amount of time that the writer should before the actual write.
294 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
295 write_pause_time_delta_ = delta;
298 const QuicPacketHeader& header() { return framer_.header(); }
300 size_t frame_count() const { return framer_.num_frames(); }
302 const vector<QuicAckFrame>& ack_frames() const {
303 return framer_.ack_frames();
306 const vector<QuicStopWaitingFrame>& stop_waiting_frames() const {
307 return framer_.stop_waiting_frames();
310 const vector<QuicConnectionCloseFrame>& connection_close_frames() const {
311 return framer_.connection_close_frames();
314 const vector<QuicRstStreamFrame>& rst_stream_frames() const {
315 return framer_.rst_stream_frames();
318 const vector<QuicStreamFrame>& stream_frames() const {
319 return framer_.stream_frames();
322 const vector<QuicPingFrame>& ping_frames() const {
323 return framer_.ping_frames();
326 size_t last_packet_size() {
327 return last_packet_size_;
330 const QuicVersionNegotiationPacket* version_negotiation_packet() {
331 return framer_.version_negotiation_packet();
334 void set_is_write_blocked_data_buffered(bool buffered) {
335 is_write_blocked_data_buffered_ = buffered;
338 void set_perspective(Perspective perspective) {
339 // We invert perspective here, because the framer needs to parse packets
340 // we send.
341 perspective = perspective == Perspective::IS_CLIENT
342 ? Perspective::IS_SERVER
343 : Perspective::IS_CLIENT;
344 QuicFramerPeer::SetPerspective(framer_.framer(), perspective);
347 // final_bytes_of_last_packet_ returns the last four bytes of the previous
348 // packet as a little-endian, uint32. This is intended to be used with a
349 // TaggingEncrypter so that tests can determine which encrypter was used for
350 // a given packet.
351 uint32 final_bytes_of_last_packet() { return final_bytes_of_last_packet_; }
353 // Returns the final bytes of the second to last packet.
354 uint32 final_bytes_of_previous_packet() {
355 return final_bytes_of_previous_packet_;
358 void use_tagging_decrypter() {
359 use_tagging_decrypter_ = true;
362 uint32 packets_write_attempts() { return packets_write_attempts_; }
364 void Reset() { framer_.Reset(); }
366 void SetSupportedVersions(const QuicVersionVector& versions) {
367 framer_.SetSupportedVersions(versions);
370 private:
371 QuicVersion version_;
372 SimpleQuicFramer framer_;
373 size_t last_packet_size_;
374 bool write_blocked_;
375 bool block_on_next_write_;
376 bool is_write_blocked_data_buffered_;
377 uint32 final_bytes_of_last_packet_;
378 uint32 final_bytes_of_previous_packet_;
379 bool use_tagging_decrypter_;
380 uint32 packets_write_attempts_;
381 MockClock *clock_;
382 // If non-zero, the clock will pause during WritePacket for this amount of
383 // time.
384 QuicTime::Delta write_pause_time_delta_;
386 DISALLOW_COPY_AND_ASSIGN(TestPacketWriter);
389 class TestConnection : public QuicConnection {
390 public:
391 TestConnection(QuicConnectionId connection_id,
392 IPEndPoint address,
393 TestConnectionHelper* helper,
394 const PacketWriterFactory& factory,
395 Perspective perspective,
396 QuicVersion version)
397 : QuicConnection(connection_id,
398 address,
399 helper,
400 factory,
401 /* owns_writer= */ false,
402 perspective,
403 /* is_secure= */ false,
404 SupportedVersions(version)) {
405 // Disable tail loss probes for most tests.
406 QuicSentPacketManagerPeer::SetMaxTailLossProbes(
407 QuicConnectionPeer::GetSentPacketManager(this), 0);
408 writer()->set_perspective(perspective);
411 void SendAck() {
412 QuicConnectionPeer::SendAck(this);
415 void SetSendAlgorithm(SendAlgorithmInterface* send_algorithm) {
416 QuicConnectionPeer::SetSendAlgorithm(this, send_algorithm);
419 void SetLossAlgorithm(LossDetectionInterface* loss_algorithm) {
420 QuicSentPacketManagerPeer::SetLossAlgorithm(
421 QuicConnectionPeer::GetSentPacketManager(this), loss_algorithm);
424 void SendPacket(EncryptionLevel level,
425 QuicPacketSequenceNumber sequence_number,
426 QuicPacket* packet,
427 QuicPacketEntropyHash entropy_hash,
428 HasRetransmittableData retransmittable) {
429 RetransmittableFrames* retransmittable_frames =
430 retransmittable == HAS_RETRANSMITTABLE_DATA
431 ? new RetransmittableFrames(ENCRYPTION_NONE)
432 : nullptr;
433 char buffer[kMaxPacketSize];
434 QuicEncryptedPacket* encrypted =
435 QuicConnectionPeer::GetFramer(this)->EncryptPayload(
436 ENCRYPTION_NONE, sequence_number, *packet, buffer, kMaxPacketSize);
437 delete packet;
438 OnSerializedPacket(SerializedPacket(sequence_number,
439 PACKET_6BYTE_SEQUENCE_NUMBER, encrypted,
440 entropy_hash, retransmittable_frames));
443 QuicConsumedData SendStreamDataWithString(
444 QuicStreamId id,
445 StringPiece data,
446 QuicStreamOffset offset,
447 bool fin,
448 QuicAckNotifier::DelegateInterface* delegate) {
449 return SendStreamDataWithStringHelper(id, data, offset, fin,
450 MAY_FEC_PROTECT, delegate);
453 QuicConsumedData SendStreamDataWithStringWithFec(
454 QuicStreamId id,
455 StringPiece data,
456 QuicStreamOffset offset,
457 bool fin,
458 QuicAckNotifier::DelegateInterface* delegate) {
459 return SendStreamDataWithStringHelper(id, data, offset, fin,
460 MUST_FEC_PROTECT, delegate);
463 QuicConsumedData SendStreamDataWithStringHelper(
464 QuicStreamId id,
465 StringPiece data,
466 QuicStreamOffset offset,
467 bool fin,
468 FecProtection fec_protection,
469 QuicAckNotifier::DelegateInterface* delegate) {
470 struct iovec iov;
471 QuicIOVector data_iov(MakeIOVector(data, &iov));
472 return QuicConnection::SendStreamData(id, data_iov, offset, fin,
473 fec_protection, delegate);
476 QuicConsumedData SendStreamData3() {
477 return SendStreamDataWithString(kClientDataStreamId1, "food", 0, !kFin,
478 nullptr);
481 QuicConsumedData SendStreamData3WithFec() {
482 return SendStreamDataWithStringWithFec(kClientDataStreamId1, "food", 0,
483 !kFin, nullptr);
486 QuicConsumedData SendStreamData5() {
487 return SendStreamDataWithString(kClientDataStreamId2, "food2", 0, !kFin,
488 nullptr);
491 QuicConsumedData SendStreamData5WithFec() {
492 return SendStreamDataWithStringWithFec(kClientDataStreamId2, "food2", 0,
493 !kFin, nullptr);
495 // Ensures the connection can write stream data before writing.
496 QuicConsumedData EnsureWritableAndSendStreamData5() {
497 EXPECT_TRUE(CanWriteStreamData());
498 return SendStreamData5();
501 // The crypto stream has special semantics so that it is not blocked by a
502 // congestion window limitation, and also so that it gets put into a separate
503 // packet (so that it is easier to reason about a crypto frame not being
504 // split needlessly across packet boundaries). As a result, we have separate
505 // tests for some cases for this stream.
506 QuicConsumedData SendCryptoStreamData() {
507 return SendStreamDataWithString(kCryptoStreamId, "chlo", 0, !kFin, nullptr);
510 void set_version(QuicVersion version) {
511 QuicConnectionPeer::GetFramer(this)->set_version(version);
514 void SetSupportedVersions(const QuicVersionVector& versions) {
515 QuicConnectionPeer::GetFramer(this)->SetSupportedVersions(versions);
516 writer()->SetSupportedVersions(versions);
519 void set_perspective(Perspective perspective) {
520 writer()->set_perspective(perspective);
521 QuicConnectionPeer::SetPerspective(this, perspective);
524 // Enable path MTU discovery. Assumes that the test is performed from the
525 // client perspective and the higher value of MTU target is used.
526 void EnablePathMtuDiscovery(MockSendAlgorithm* send_algorithm) {
527 ASSERT_EQ(Perspective::IS_CLIENT, perspective());
529 FLAGS_quic_do_path_mtu_discovery = true;
531 QuicConfig config;
532 QuicTagVector connection_options;
533 connection_options.push_back(kMTUH);
534 config.SetConnectionOptionsToSend(connection_options);
535 EXPECT_CALL(*send_algorithm, SetFromConfig(_, _));
536 SetFromConfig(config);
538 // Normally, the pacing would be disabled in the test, but calling
539 // SetFromConfig enables it. Set nearly-infinite bandwidth to make the
540 // pacing algorithm work.
541 EXPECT_CALL(*send_algorithm, PacingRate())
542 .WillRepeatedly(Return(QuicBandwidth::FromKBytesPerSecond(10000)));
545 TestConnectionHelper::TestAlarm* GetAckAlarm() {
546 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
547 QuicConnectionPeer::GetAckAlarm(this));
550 TestConnectionHelper::TestAlarm* GetPingAlarm() {
551 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
552 QuicConnectionPeer::GetPingAlarm(this));
555 TestConnectionHelper::TestAlarm* GetFecAlarm() {
556 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
557 QuicConnectionPeer::GetFecAlarm(this));
560 TestConnectionHelper::TestAlarm* GetResumeWritesAlarm() {
561 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
562 QuicConnectionPeer::GetResumeWritesAlarm(this));
565 TestConnectionHelper::TestAlarm* GetRetransmissionAlarm() {
566 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
567 QuicConnectionPeer::GetRetransmissionAlarm(this));
570 TestConnectionHelper::TestAlarm* GetSendAlarm() {
571 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
572 QuicConnectionPeer::GetSendAlarm(this));
575 TestConnectionHelper::TestAlarm* GetTimeoutAlarm() {
576 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
577 QuicConnectionPeer::GetTimeoutAlarm(this));
580 TestConnectionHelper::TestAlarm* GetMtuDiscoveryAlarm() {
581 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
582 QuicConnectionPeer::GetMtuDiscoveryAlarm(this));
585 using QuicConnection::SelectMutualVersion;
587 private:
588 TestPacketWriter* writer() {
589 return static_cast<TestPacketWriter*>(QuicConnection::writer());
592 DISALLOW_COPY_AND_ASSIGN(TestConnection);
595 // Used for testing packets revived from FEC packets.
596 class FecQuicConnectionDebugVisitor
597 : public QuicConnectionDebugVisitor {
598 public:
599 void OnRevivedPacket(const QuicPacketHeader& header,
600 StringPiece data) override {
601 revived_header_ = header;
604 // Public accessor method.
605 QuicPacketHeader revived_header() const {
606 return revived_header_;
609 private:
610 QuicPacketHeader revived_header_;
613 class MockPacketWriterFactory : public QuicConnection::PacketWriterFactory {
614 public:
615 explicit MockPacketWriterFactory(QuicPacketWriter* writer) {
616 ON_CALL(*this, Create(_)).WillByDefault(Return(writer));
618 ~MockPacketWriterFactory() override {}
620 MOCK_CONST_METHOD1(Create, QuicPacketWriter*(QuicConnection* connection));
623 // Run tests with combinations of {QuicVersion, fec_send_policy}.
624 struct TestParams {
625 TestParams(QuicVersion version, FecSendPolicy fec_send_policy)
626 : version(version), fec_send_policy(fec_send_policy) {}
628 friend ostream& operator<<(ostream& os, const TestParams& p) {
629 os << "{ client_version: " << QuicVersionToString(p.version)
630 << " fec_send_policy: " << p.fec_send_policy << " }";
631 return os;
634 QuicVersion version;
635 FecSendPolicy fec_send_policy;
638 // Constructs various test permutations.
639 vector<TestParams> GetTestParams() {
640 vector<TestParams> params;
641 QuicVersionVector all_supported_versions = QuicSupportedVersions();
642 for (size_t i = 0; i < all_supported_versions.size(); ++i) {
643 params.push_back(TestParams(all_supported_versions[i], FEC_ANY_TRIGGER));
644 params.push_back(TestParams(all_supported_versions[i], FEC_ALARM_TRIGGER));
646 return params;
649 class QuicConnectionTest : public ::testing::TestWithParam<TestParams> {
650 protected:
651 QuicConnectionTest()
652 : connection_id_(42),
653 framer_(SupportedVersions(version()),
654 QuicTime::Zero(),
655 Perspective::IS_CLIENT),
656 peer_creator_(connection_id_, &framer_, &random_generator_),
657 send_algorithm_(new StrictMock<MockSendAlgorithm>),
658 loss_algorithm_(new MockLossAlgorithm()),
659 helper_(new TestConnectionHelper(&clock_, &random_generator_)),
660 writer_(new TestPacketWriter(version(), &clock_)),
661 factory_(writer_.get()),
662 connection_(connection_id_,
663 IPEndPoint(),
664 helper_.get(),
665 factory_,
666 Perspective::IS_CLIENT,
667 version()),
668 creator_(QuicConnectionPeer::GetPacketCreator(&connection_)),
669 generator_(QuicConnectionPeer::GetPacketGenerator(&connection_)),
670 manager_(QuicConnectionPeer::GetSentPacketManager(&connection_)),
671 frame1_(1, false, 0, StringPiece(data1)),
672 frame2_(1, false, 3, StringPiece(data2)),
673 sequence_number_length_(PACKET_6BYTE_SEQUENCE_NUMBER),
674 connection_id_length_(PACKET_8BYTE_CONNECTION_ID) {
675 connection_.set_visitor(&visitor_);
676 connection_.SetSendAlgorithm(send_algorithm_);
677 connection_.SetLossAlgorithm(loss_algorithm_);
678 framer_.set_received_entropy_calculator(&entropy_calculator_);
679 generator_->set_fec_send_policy(GetParam().fec_send_policy);
680 EXPECT_CALL(
681 *send_algorithm_, TimeUntilSend(_, _, _)).WillRepeatedly(Return(
682 QuicTime::Delta::Zero()));
683 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
684 .Times(AnyNumber());
685 EXPECT_CALL(*send_algorithm_, RetransmissionDelay()).WillRepeatedly(
686 Return(QuicTime::Delta::Zero()));
687 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
688 Return(kMaxPacketSize));
689 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
690 .WillByDefault(Return(true));
691 EXPECT_CALL(*send_algorithm_, HasReliableBandwidthEstimate())
692 .Times(AnyNumber());
693 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
694 .Times(AnyNumber())
695 .WillRepeatedly(Return(QuicBandwidth::Zero()));
696 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
697 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
698 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).Times(AnyNumber());
699 EXPECT_CALL(visitor_, HasPendingHandshake()).Times(AnyNumber());
700 EXPECT_CALL(visitor_, OnCanWrite()).Times(AnyNumber());
701 EXPECT_CALL(visitor_, HasOpenDynamicStreams())
702 .WillRepeatedly(Return(false));
703 EXPECT_CALL(visitor_, OnCongestionWindowChange(_)).Times(AnyNumber());
705 EXPECT_CALL(*loss_algorithm_, GetLossTimeout())
706 .WillRepeatedly(Return(QuicTime::Zero()));
707 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
708 .WillRepeatedly(Return(SequenceNumberSet()));
711 QuicVersion version() { return GetParam().version; }
713 QuicAckFrame* outgoing_ack() {
714 QuicConnectionPeer::PopulateAckFrame(&connection_, &ack_);
715 return &ack_;
718 QuicStopWaitingFrame* stop_waiting() {
719 QuicConnectionPeer::PopulateStopWaitingFrame(&connection_, &stop_waiting_);
720 return &stop_waiting_;
723 QuicPacketSequenceNumber least_unacked() {
724 if (writer_->stop_waiting_frames().empty()) {
725 return 0;
727 return writer_->stop_waiting_frames()[0].least_unacked;
730 void use_tagging_decrypter() {
731 writer_->use_tagging_decrypter();
734 void ProcessPacket(QuicPacketSequenceNumber number) {
735 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
736 ProcessDataPacket(number, 0, !kEntropyFlag);
739 QuicPacketEntropyHash ProcessFramePacket(QuicFrame frame) {
740 QuicFrames frames;
741 frames.push_back(QuicFrame(frame));
742 QuicPacketCreatorPeer::SetSendVersionInPacket(
743 &peer_creator_, connection_.perspective() == Perspective::IS_SERVER);
745 char buffer[kMaxPacketSize];
746 SerializedPacket serialized_packet =
747 peer_creator_.SerializeAllFrames(frames, buffer, kMaxPacketSize);
748 scoped_ptr<QuicEncryptedPacket> encrypted(serialized_packet.packet);
749 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
750 return serialized_packet.entropy_hash;
753 size_t ProcessDataPacket(QuicPacketSequenceNumber number,
754 QuicFecGroupNumber fec_group,
755 bool entropy_flag) {
756 return ProcessDataPacketAtLevel(number, fec_group, entropy_flag,
757 ENCRYPTION_NONE);
760 size_t ProcessDataPacketAtLevel(QuicPacketSequenceNumber number,
761 QuicFecGroupNumber fec_group,
762 bool entropy_flag,
763 EncryptionLevel level) {
764 scoped_ptr<QuicPacket> packet(ConstructDataPacket(number, fec_group,
765 entropy_flag));
766 char buffer[kMaxPacketSize];
767 scoped_ptr<QuicEncryptedPacket> encrypted(
768 framer_.EncryptPayload(level, number, *packet, buffer, kMaxPacketSize));
769 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
770 return encrypted->length();
773 void ProcessClosePacket(QuicPacketSequenceNumber number,
774 QuicFecGroupNumber fec_group) {
775 scoped_ptr<QuicPacket> packet(ConstructClosePacket(number, fec_group));
776 char buffer[kMaxPacketSize];
777 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPayload(
778 ENCRYPTION_NONE, number, *packet, buffer, kMaxPacketSize));
779 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
782 size_t ProcessFecProtectedPacket(QuicPacketSequenceNumber number,
783 bool expect_revival, bool entropy_flag) {
784 if (expect_revival) {
785 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
787 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1).RetiresOnSaturation();
788 return ProcessDataPacket(number, 1, entropy_flag);
791 // Processes an FEC packet that covers the packets that would have been
792 // received.
793 size_t ProcessFecPacket(QuicPacketSequenceNumber number,
794 QuicPacketSequenceNumber min_protected_packet,
795 bool expect_revival,
796 bool entropy_flag,
797 QuicPacket* packet) {
798 if (expect_revival) {
799 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
802 // Construct the decrypted data packet so we can compute the correct
803 // redundancy. If |packet| has been provided then use that, otherwise
804 // construct a default data packet.
805 scoped_ptr<QuicPacket> data_packet;
806 if (packet) {
807 data_packet.reset(packet);
808 } else {
809 data_packet.reset(ConstructDataPacket(number, 1, !kEntropyFlag));
812 QuicPacketHeader header;
813 header.public_header.connection_id = connection_id_;
814 header.public_header.sequence_number_length = sequence_number_length_;
815 header.public_header.connection_id_length = connection_id_length_;
816 header.packet_sequence_number = number;
817 header.entropy_flag = entropy_flag;
818 header.fec_flag = true;
819 header.is_in_fec_group = IN_FEC_GROUP;
820 header.fec_group = min_protected_packet;
821 QuicFecData fec_data;
822 fec_data.fec_group = header.fec_group;
824 // Since all data packets in this test have the same payload, the
825 // redundancy is either equal to that payload or the xor of that payload
826 // with itself, depending on the number of packets.
827 if (((number - min_protected_packet) % 2) == 0) {
828 for (size_t i = GetStartOfFecProtectedData(
829 header.public_header.connection_id_length,
830 header.public_header.version_flag,
831 header.public_header.sequence_number_length);
832 i < data_packet->length(); ++i) {
833 data_packet->mutable_data()[i] ^= data_packet->data()[i];
836 fec_data.redundancy = data_packet->FecProtectedData();
838 scoped_ptr<QuicPacket> fec_packet(framer_.BuildFecPacket(header, fec_data));
839 char buffer[kMaxPacketSize];
840 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPayload(
841 ENCRYPTION_NONE, number, *fec_packet, buffer, kMaxPacketSize));
843 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
844 return encrypted->length();
847 QuicByteCount SendStreamDataToPeer(QuicStreamId id,
848 StringPiece data,
849 QuicStreamOffset offset,
850 bool fin,
851 QuicPacketSequenceNumber* last_packet) {
852 QuicByteCount packet_size;
853 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
854 .WillOnce(DoAll(SaveArg<3>(&packet_size), Return(true)));
855 connection_.SendStreamDataWithString(id, data, offset, fin, nullptr);
856 if (last_packet != nullptr) {
857 *last_packet = creator_->sequence_number();
859 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
860 .Times(AnyNumber());
861 return packet_size;
864 void SendAckPacketToPeer() {
865 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
866 connection_.SendAck();
867 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
868 .Times(AnyNumber());
871 void ProcessAckPacket(QuicPacketSequenceNumber packet_number,
872 QuicAckFrame* frame) {
873 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, packet_number - 1);
874 ProcessFramePacket(QuicFrame(frame));
877 QuicPacketEntropyHash ProcessAckPacket(QuicAckFrame* frame) {
878 return ProcessFramePacket(QuicFrame(frame));
881 QuicPacketEntropyHash ProcessStopWaitingPacket(QuicStopWaitingFrame* frame) {
882 return ProcessFramePacket(QuicFrame(frame));
885 QuicPacketEntropyHash ProcessGoAwayPacket(QuicGoAwayFrame* frame) {
886 return ProcessFramePacket(QuicFrame(frame));
889 bool IsMissing(QuicPacketSequenceNumber number) {
890 return IsAwaitingPacket(*outgoing_ack(), number);
893 QuicPacket* ConstructPacket(QuicPacketHeader header, QuicFrames frames) {
894 QuicPacket* packet = BuildUnsizedDataPacket(&framer_, header, frames);
895 EXPECT_NE(nullptr, packet);
896 return packet;
899 QuicPacket* ConstructDataPacket(QuicPacketSequenceNumber number,
900 QuicFecGroupNumber fec_group,
901 bool entropy_flag) {
902 QuicPacketHeader header;
903 header.public_header.connection_id = connection_id_;
904 header.public_header.sequence_number_length = sequence_number_length_;
905 header.public_header.connection_id_length = connection_id_length_;
906 header.entropy_flag = entropy_flag;
907 header.packet_sequence_number = number;
908 header.is_in_fec_group = fec_group == 0u ? NOT_IN_FEC_GROUP : IN_FEC_GROUP;
909 header.fec_group = fec_group;
911 QuicFrames frames;
912 frames.push_back(QuicFrame(&frame1_));
913 return ConstructPacket(header, frames);
916 QuicPacket* ConstructClosePacket(QuicPacketSequenceNumber number,
917 QuicFecGroupNumber fec_group) {
918 QuicPacketHeader header;
919 header.public_header.connection_id = connection_id_;
920 header.packet_sequence_number = number;
921 header.is_in_fec_group = fec_group == 0u ? NOT_IN_FEC_GROUP : IN_FEC_GROUP;
922 header.fec_group = fec_group;
924 QuicConnectionCloseFrame qccf;
925 qccf.error_code = QUIC_PEER_GOING_AWAY;
927 QuicFrames frames;
928 frames.push_back(QuicFrame(&qccf));
929 return ConstructPacket(header, frames);
932 QuicTime::Delta DefaultRetransmissionTime() {
933 return QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
936 QuicTime::Delta DefaultDelayedAckTime() {
937 return QuicTime::Delta::FromMilliseconds(kMaxDelayedAckTimeMs);
940 // Initialize a frame acknowledging all packets up to largest_observed.
941 const QuicAckFrame InitAckFrame(QuicPacketSequenceNumber largest_observed) {
942 QuicAckFrame frame(MakeAckFrame(largest_observed));
943 if (largest_observed > 0) {
944 frame.entropy_hash =
945 QuicConnectionPeer::GetSentEntropyHash(&connection_,
946 largest_observed);
948 return frame;
951 const QuicStopWaitingFrame InitStopWaitingFrame(
952 QuicPacketSequenceNumber least_unacked) {
953 QuicStopWaitingFrame frame;
954 frame.least_unacked = least_unacked;
955 return frame;
958 // Explicitly nack a packet.
959 void NackPacket(QuicPacketSequenceNumber missing, QuicAckFrame* frame) {
960 frame->missing_packets.insert(missing);
961 frame->entropy_hash ^=
962 QuicConnectionPeer::PacketEntropy(&connection_, missing);
965 // Undo nacking a packet within the frame.
966 void AckPacket(QuicPacketSequenceNumber arrived, QuicAckFrame* frame) {
967 EXPECT_THAT(frame->missing_packets, Contains(arrived));
968 frame->missing_packets.erase(arrived);
969 frame->entropy_hash ^=
970 QuicConnectionPeer::PacketEntropy(&connection_, arrived);
973 void TriggerConnectionClose() {
974 // Send an erroneous packet to close the connection.
975 EXPECT_CALL(visitor_,
976 OnConnectionClosed(QUIC_INVALID_PACKET_HEADER, false));
977 // Call ProcessDataPacket rather than ProcessPacket, as we should not get a
978 // packet call to the visitor.
979 ProcessDataPacket(6000, 0, !kEntropyFlag);
980 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
981 nullptr);
984 void BlockOnNextWrite() {
985 writer_->BlockOnNextWrite();
986 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
989 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
990 writer_->SetWritePauseTimeDelta(delta);
993 void CongestionBlockWrites() {
994 EXPECT_CALL(*send_algorithm_,
995 TimeUntilSend(_, _, _)).WillRepeatedly(
996 testing::Return(QuicTime::Delta::FromSeconds(1)));
999 void CongestionUnblockWrites() {
1000 EXPECT_CALL(*send_algorithm_,
1001 TimeUntilSend(_, _, _)).WillRepeatedly(
1002 testing::Return(QuicTime::Delta::Zero()));
1005 QuicConnectionId connection_id_;
1006 QuicFramer framer_;
1007 QuicPacketCreator peer_creator_;
1008 MockEntropyCalculator entropy_calculator_;
1010 MockSendAlgorithm* send_algorithm_;
1011 MockLossAlgorithm* loss_algorithm_;
1012 MockClock clock_;
1013 MockRandom random_generator_;
1014 scoped_ptr<TestConnectionHelper> helper_;
1015 scoped_ptr<TestPacketWriter> writer_;
1016 NiceMock<MockPacketWriterFactory> factory_;
1017 TestConnection connection_;
1018 QuicPacketCreator* creator_;
1019 QuicPacketGenerator* generator_;
1020 QuicSentPacketManager* manager_;
1021 StrictMock<MockConnectionVisitor> visitor_;
1023 QuicStreamFrame frame1_;
1024 QuicStreamFrame frame2_;
1025 QuicAckFrame ack_;
1026 QuicStopWaitingFrame stop_waiting_;
1027 QuicSequenceNumberLength sequence_number_length_;
1028 QuicConnectionIdLength connection_id_length_;
1030 private:
1031 DISALLOW_COPY_AND_ASSIGN(QuicConnectionTest);
1034 // Run all end to end tests with all supported versions.
1035 INSTANTIATE_TEST_CASE_P(SupportedVersion,
1036 QuicConnectionTest,
1037 ::testing::ValuesIn(GetTestParams()));
1039 TEST_P(QuicConnectionTest, MaxPacketSize) {
1040 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
1041 EXPECT_EQ(1350u, connection_.max_packet_length());
1044 TEST_P(QuicConnectionTest, SmallerServerMaxPacketSize) {
1045 QuicConnectionId connection_id = 42;
1046 TestConnection connection(connection_id, IPEndPoint(), helper_.get(),
1047 factory_, Perspective::IS_SERVER, version());
1048 EXPECT_EQ(Perspective::IS_SERVER, connection.perspective());
1049 EXPECT_EQ(1000u, connection.max_packet_length());
1052 TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSize) {
1053 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1055 connection_.set_perspective(Perspective::IS_SERVER);
1056 connection_.set_max_packet_length(1000);
1058 QuicPacketHeader header;
1059 header.public_header.connection_id = connection_id_;
1060 header.public_header.version_flag = true;
1061 header.packet_sequence_number = 1;
1063 QuicFrames frames;
1064 QuicPaddingFrame padding;
1065 frames.push_back(QuicFrame(&frame1_));
1066 frames.push_back(QuicFrame(&padding));
1067 scoped_ptr<QuicPacket> packet(ConstructPacket(header, frames));
1068 char buffer[kMaxPacketSize];
1069 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPayload(
1070 ENCRYPTION_NONE, 12, *packet, buffer, kMaxPacketSize));
1071 EXPECT_EQ(kMaxPacketSize, encrypted->length());
1073 framer_.set_version(version());
1074 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
1075 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
1077 EXPECT_EQ(kMaxPacketSize, connection_.max_packet_length());
1080 TEST_P(QuicConnectionTest, PacketsInOrder) {
1081 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1083 ProcessPacket(1);
1084 EXPECT_EQ(1u, outgoing_ack()->largest_observed);
1085 EXPECT_EQ(0u, outgoing_ack()->missing_packets.size());
1087 ProcessPacket(2);
1088 EXPECT_EQ(2u, outgoing_ack()->largest_observed);
1089 EXPECT_EQ(0u, outgoing_ack()->missing_packets.size());
1091 ProcessPacket(3);
1092 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1093 EXPECT_EQ(0u, outgoing_ack()->missing_packets.size());
1096 TEST_P(QuicConnectionTest, PacketsOutOfOrder) {
1097 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1099 ProcessPacket(3);
1100 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1101 EXPECT_TRUE(IsMissing(2));
1102 EXPECT_TRUE(IsMissing(1));
1104 ProcessPacket(2);
1105 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1106 EXPECT_FALSE(IsMissing(2));
1107 EXPECT_TRUE(IsMissing(1));
1109 ProcessPacket(1);
1110 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1111 EXPECT_FALSE(IsMissing(2));
1112 EXPECT_FALSE(IsMissing(1));
1115 TEST_P(QuicConnectionTest, DuplicatePacket) {
1116 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1118 ProcessPacket(3);
1119 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1120 EXPECT_TRUE(IsMissing(2));
1121 EXPECT_TRUE(IsMissing(1));
1123 // Send packet 3 again, but do not set the expectation that
1124 // the visitor OnStreamFrame() will be called.
1125 ProcessDataPacket(3, 0, !kEntropyFlag);
1126 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1127 EXPECT_TRUE(IsMissing(2));
1128 EXPECT_TRUE(IsMissing(1));
1131 TEST_P(QuicConnectionTest, PacketsOutOfOrderWithAdditionsAndLeastAwaiting) {
1132 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1134 ProcessPacket(3);
1135 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1136 EXPECT_TRUE(IsMissing(2));
1137 EXPECT_TRUE(IsMissing(1));
1139 ProcessPacket(2);
1140 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1141 EXPECT_TRUE(IsMissing(1));
1143 ProcessPacket(5);
1144 EXPECT_EQ(5u, outgoing_ack()->largest_observed);
1145 EXPECT_TRUE(IsMissing(1));
1146 EXPECT_TRUE(IsMissing(4));
1148 // Pretend at this point the client has gotten acks for 2 and 3 and 1 is a
1149 // packet the peer will not retransmit. It indicates this by sending 'least
1150 // awaiting' is 4. The connection should then realize 1 will not be
1151 // retransmitted, and will remove it from the missing list.
1152 QuicAckFrame frame = InitAckFrame(1);
1153 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _));
1154 ProcessAckPacket(6, &frame);
1156 // Force an ack to be sent.
1157 SendAckPacketToPeer();
1158 EXPECT_TRUE(IsMissing(4));
1161 TEST_P(QuicConnectionTest, RejectPacketTooFarOut) {
1162 EXPECT_CALL(visitor_,
1163 OnConnectionClosed(QUIC_INVALID_PACKET_HEADER, false));
1164 // Call ProcessDataPacket rather than ProcessPacket, as we should not get a
1165 // packet call to the visitor.
1166 ProcessDataPacket(6000, 0, !kEntropyFlag);
1167 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1168 nullptr);
1171 TEST_P(QuicConnectionTest, RejectUnencryptedStreamData) {
1172 // Process an unencrypted packet from the non-crypto stream.
1173 frame1_.stream_id = 3;
1174 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1175 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_UNENCRYPTED_STREAM_DATA,
1176 false));
1177 ProcessDataPacket(1, 0, !kEntropyFlag);
1178 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1179 nullptr);
1180 const vector<QuicConnectionCloseFrame>& connection_close_frames =
1181 writer_->connection_close_frames();
1182 EXPECT_EQ(1u, connection_close_frames.size());
1183 EXPECT_EQ(QUIC_UNENCRYPTED_STREAM_DATA,
1184 connection_close_frames[0].error_code);
1187 TEST_P(QuicConnectionTest, TruncatedAck) {
1188 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1189 QuicPacketSequenceNumber num_packets = 256 * 2 + 1;
1190 for (QuicPacketSequenceNumber i = 0; i < num_packets; ++i) {
1191 SendStreamDataToPeer(3, "foo", i * 3, !kFin, nullptr);
1194 QuicAckFrame frame = InitAckFrame(num_packets);
1195 SequenceNumberSet lost_packets;
1196 // Create an ack with 256 nacks, none adjacent to one another.
1197 for (QuicPacketSequenceNumber i = 1; i <= 256; ++i) {
1198 NackPacket(i * 2, &frame);
1199 if (i < 256) { // Last packet is nacked, but not lost.
1200 lost_packets.insert(i * 2);
1203 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1204 .WillOnce(Return(lost_packets));
1205 EXPECT_CALL(entropy_calculator_, EntropyHash(511))
1206 .WillOnce(Return(static_cast<QuicPacketEntropyHash>(0)));
1207 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1208 ProcessAckPacket(&frame);
1210 // A truncated ack will not have the true largest observed.
1211 EXPECT_GT(num_packets, manager_->largest_observed());
1213 AckPacket(192, &frame);
1215 // Removing one missing packet allows us to ack 192 and one more range, but
1216 // 192 has already been declared lost, so it doesn't register as an ack.
1217 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1218 .WillOnce(Return(SequenceNumberSet()));
1219 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1220 ProcessAckPacket(&frame);
1221 EXPECT_EQ(num_packets, manager_->largest_observed());
1224 TEST_P(QuicConnectionTest, AckReceiptCausesAckSendBadEntropy) {
1225 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1227 ProcessPacket(1);
1228 // Delay sending, then queue up an ack.
1229 EXPECT_CALL(*send_algorithm_,
1230 TimeUntilSend(_, _, _)).WillOnce(
1231 testing::Return(QuicTime::Delta::FromMicroseconds(1)));
1232 QuicConnectionPeer::SendAck(&connection_);
1234 // Process an ack with a least unacked of the received ack.
1235 // This causes an ack to be sent when TimeUntilSend returns 0.
1236 EXPECT_CALL(*send_algorithm_,
1237 TimeUntilSend(_, _, _)).WillRepeatedly(
1238 testing::Return(QuicTime::Delta::Zero()));
1239 // Skip a packet and then record an ack.
1240 QuicAckFrame frame = InitAckFrame(0);
1241 ProcessAckPacket(3, &frame);
1244 TEST_P(QuicConnectionTest, OutOfOrderReceiptCausesAckSend) {
1245 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1247 ProcessPacket(3);
1248 // Should ack immediately since we have missing packets.
1249 EXPECT_EQ(1u, writer_->packets_write_attempts());
1251 ProcessPacket(2);
1252 // Should ack immediately since we have missing packets.
1253 EXPECT_EQ(2u, writer_->packets_write_attempts());
1255 ProcessPacket(1);
1256 // Should ack immediately, since this fills the last hole.
1257 EXPECT_EQ(3u, writer_->packets_write_attempts());
1259 ProcessPacket(4);
1260 // Should not cause an ack.
1261 EXPECT_EQ(3u, writer_->packets_write_attempts());
1264 TEST_P(QuicConnectionTest, OutOfOrderAckReceiptCausesNoAck) {
1265 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1267 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr);
1268 SendStreamDataToPeer(1, "bar", 3, !kFin, nullptr);
1269 EXPECT_EQ(2u, writer_->packets_write_attempts());
1271 QuicAckFrame ack1 = InitAckFrame(1);
1272 QuicAckFrame ack2 = InitAckFrame(2);
1273 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1274 ProcessAckPacket(2, &ack2);
1275 // Should ack immediately since we have missing packets.
1276 EXPECT_EQ(2u, writer_->packets_write_attempts());
1278 ProcessAckPacket(1, &ack1);
1279 // Should not ack an ack filling a missing packet.
1280 EXPECT_EQ(2u, writer_->packets_write_attempts());
1283 TEST_P(QuicConnectionTest, AckReceiptCausesAckSend) {
1284 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1286 QuicPacketSequenceNumber original;
1287 QuicByteCount packet_size;
1288 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1289 .WillOnce(DoAll(SaveArg<2>(&original), SaveArg<3>(&packet_size),
1290 Return(true)));
1291 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
1292 QuicAckFrame frame = InitAckFrame(original);
1293 NackPacket(original, &frame);
1294 // First nack triggers early retransmit.
1295 SequenceNumberSet lost_packets;
1296 lost_packets.insert(1);
1297 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1298 .WillOnce(Return(lost_packets));
1299 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1300 QuicPacketSequenceNumber retransmission;
1301 EXPECT_CALL(*send_algorithm_,
1302 OnPacketSent(_, _, _, packet_size - kQuicVersionSize, _))
1303 .WillOnce(DoAll(SaveArg<2>(&retransmission), Return(true)));
1305 ProcessAckPacket(&frame);
1307 QuicAckFrame frame2 = InitAckFrame(retransmission);
1308 NackPacket(original, &frame2);
1309 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1310 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1311 .WillOnce(Return(SequenceNumberSet()));
1312 ProcessAckPacket(&frame2);
1314 // Now if the peer sends an ack which still reports the retransmitted packet
1315 // as missing, that will bundle an ack with data after two acks in a row
1316 // indicate the high water mark needs to be raised.
1317 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _,
1318 HAS_RETRANSMITTABLE_DATA));
1319 connection_.SendStreamDataWithString(3, "foo", 3, !kFin, nullptr);
1320 // No ack sent.
1321 EXPECT_EQ(1u, writer_->frame_count());
1322 EXPECT_EQ(1u, writer_->stream_frames().size());
1324 // No more packet loss for the rest of the test.
1325 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1326 .WillRepeatedly(Return(SequenceNumberSet()));
1327 ProcessAckPacket(&frame2);
1328 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _,
1329 HAS_RETRANSMITTABLE_DATA));
1330 connection_.SendStreamDataWithString(3, "foo", 3, !kFin, nullptr);
1331 // Ack bundled.
1332 EXPECT_EQ(3u, writer_->frame_count());
1333 EXPECT_EQ(1u, writer_->stream_frames().size());
1334 EXPECT_FALSE(writer_->ack_frames().empty());
1336 // But an ack with no missing packets will not send an ack.
1337 AckPacket(original, &frame2);
1338 ProcessAckPacket(&frame2);
1339 ProcessAckPacket(&frame2);
1342 TEST_P(QuicConnectionTest, 20AcksCausesAckSend) {
1343 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1345 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr);
1347 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
1348 // But an ack with no missing packets will not send an ack.
1349 QuicAckFrame frame = InitAckFrame(1);
1350 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1351 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1352 .WillRepeatedly(Return(SequenceNumberSet()));
1353 for (int i = 0; i < 20; ++i) {
1354 EXPECT_FALSE(ack_alarm->IsSet());
1355 ProcessAckPacket(&frame);
1357 EXPECT_TRUE(ack_alarm->IsSet());
1360 TEST_P(QuicConnectionTest, LeastUnackedLower) {
1361 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1363 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr);
1364 SendStreamDataToPeer(1, "bar", 3, !kFin, nullptr);
1365 SendStreamDataToPeer(1, "eep", 6, !kFin, nullptr);
1367 // Start out saying the least unacked is 2.
1368 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 5);
1369 QuicStopWaitingFrame frame = InitStopWaitingFrame(2);
1370 ProcessStopWaitingPacket(&frame);
1372 // Change it to 1, but lower the sequence number to fake out-of-order packets.
1373 // This should be fine.
1374 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 1);
1375 // The scheduler will not process out of order acks, but all packet processing
1376 // causes the connection to try to write.
1377 EXPECT_CALL(visitor_, OnCanWrite());
1378 QuicStopWaitingFrame frame2 = InitStopWaitingFrame(1);
1379 ProcessStopWaitingPacket(&frame2);
1381 // Now claim it's one, but set the ordering so it was sent "after" the first
1382 // one. This should cause a connection error.
1383 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
1384 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 7);
1385 EXPECT_CALL(visitor_,
1386 OnConnectionClosed(QUIC_INVALID_STOP_WAITING_DATA, false));
1387 QuicStopWaitingFrame frame3 = InitStopWaitingFrame(1);
1388 ProcessStopWaitingPacket(&frame3);
1391 TEST_P(QuicConnectionTest, TooManySentPackets) {
1392 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1394 const int num_packets = kMaxTrackedPackets + 100;
1395 for (int i = 0; i < num_packets; ++i) {
1396 SendStreamDataToPeer(1, "foo", 3 * i, !kFin, nullptr);
1399 // Ack packet 1, which leaves more than the limit outstanding.
1400 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1401 EXPECT_CALL(visitor_, OnConnectionClosed(
1402 QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS, false));
1403 // We're receive buffer limited, so the connection won't try to write more.
1404 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
1406 // Nack the first packet and ack the rest, leaving a huge gap.
1407 QuicAckFrame frame1 = InitAckFrame(num_packets);
1408 NackPacket(1, &frame1);
1409 ProcessAckPacket(&frame1);
1412 TEST_P(QuicConnectionTest, TooManyReceivedPackets) {
1413 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1414 EXPECT_CALL(visitor_, OnConnectionClosed(
1415 QUIC_TOO_MANY_OUTSTANDING_RECEIVED_PACKETS, false));
1417 // Miss 99 of every 100 packets for 5500 packets.
1418 for (QuicPacketSequenceNumber i = 1; i < kMaxTrackedPackets + 500; i += 100) {
1419 ProcessPacket(i);
1420 if (!connection_.connected()) {
1421 break;
1426 TEST_P(QuicConnectionTest, LargestObservedLower) {
1427 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1429 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr);
1430 SendStreamDataToPeer(1, "bar", 3, !kFin, nullptr);
1431 SendStreamDataToPeer(1, "eep", 6, !kFin, nullptr);
1432 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1434 // Start out saying the largest observed is 2.
1435 QuicAckFrame frame1 = InitAckFrame(1);
1436 QuicAckFrame frame2 = InitAckFrame(2);
1437 ProcessAckPacket(&frame2);
1439 // Now change it to 1, and it should cause a connection error.
1440 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, false));
1441 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
1442 ProcessAckPacket(&frame1);
1445 TEST_P(QuicConnectionTest, AckUnsentData) {
1446 // Ack a packet which has not been sent.
1447 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, false));
1448 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1449 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
1450 QuicAckFrame frame(MakeAckFrame(1));
1451 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
1452 ProcessAckPacket(&frame);
1455 TEST_P(QuicConnectionTest, AckAll) {
1456 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1457 ProcessPacket(1);
1459 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 1);
1460 QuicAckFrame frame1 = InitAckFrame(0);
1461 ProcessAckPacket(&frame1);
1464 TEST_P(QuicConnectionTest, SendingDifferentSequenceNumberLengthsBandwidth) {
1465 QuicPacketSequenceNumber last_packet;
1466 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet);
1467 EXPECT_EQ(1u, last_packet);
1468 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1469 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1470 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1471 writer_->header().public_header.sequence_number_length);
1473 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
1474 Return(kMaxPacketSize * 256));
1476 SendStreamDataToPeer(1, "bar", 3, !kFin, &last_packet);
1477 EXPECT_EQ(2u, last_packet);
1478 EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER,
1479 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1480 // The 1 packet lag is due to the sequence number length being recalculated in
1481 // QuicConnection after a packet is sent.
1482 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1483 writer_->header().public_header.sequence_number_length);
1485 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
1486 Return(kMaxPacketSize * 256 * 256));
1488 SendStreamDataToPeer(1, "foo", 6, !kFin, &last_packet);
1489 EXPECT_EQ(3u, last_packet);
1490 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1491 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1492 EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER,
1493 writer_->header().public_header.sequence_number_length);
1495 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
1496 Return(kMaxPacketSize * 256 * 256 * 256));
1498 SendStreamDataToPeer(1, "bar", 9, !kFin, &last_packet);
1499 EXPECT_EQ(4u, last_packet);
1500 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1501 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1502 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1503 writer_->header().public_header.sequence_number_length);
1505 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
1506 Return(kMaxPacketSize * 256 * 256 * 256 * 256));
1508 SendStreamDataToPeer(1, "foo", 12, !kFin, &last_packet);
1509 EXPECT_EQ(5u, last_packet);
1510 EXPECT_EQ(PACKET_6BYTE_SEQUENCE_NUMBER,
1511 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1512 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1513 writer_->header().public_header.sequence_number_length);
1516 // TODO(ianswett): Re-enable this test by finding a good way to test different
1517 // sequence number lengths without sending packets with giant gaps.
1518 TEST_P(QuicConnectionTest,
1519 DISABLED_SendingDifferentSequenceNumberLengthsUnackedDelta) {
1520 QuicPacketSequenceNumber last_packet;
1521 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet);
1522 EXPECT_EQ(1u, last_packet);
1523 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1524 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1525 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1526 writer_->header().public_header.sequence_number_length);
1528 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 100);
1530 SendStreamDataToPeer(1, "bar", 3, !kFin, &last_packet);
1531 EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER,
1532 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1533 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1534 writer_->header().public_header.sequence_number_length);
1536 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 100 * 256);
1538 SendStreamDataToPeer(1, "foo", 6, !kFin, &last_packet);
1539 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1540 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1541 EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER,
1542 writer_->header().public_header.sequence_number_length);
1544 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 100 * 256 * 256);
1546 SendStreamDataToPeer(1, "bar", 9, !kFin, &last_packet);
1547 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1548 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1549 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1550 writer_->header().public_header.sequence_number_length);
1552 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_,
1553 100 * 256 * 256 * 256);
1555 SendStreamDataToPeer(1, "foo", 12, !kFin, &last_packet);
1556 EXPECT_EQ(PACKET_6BYTE_SEQUENCE_NUMBER,
1557 QuicPacketCreatorPeer::NextSequenceNumberLength(creator_));
1558 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1559 writer_->header().public_header.sequence_number_length);
1562 TEST_P(QuicConnectionTest, BasicSending) {
1563 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1564 QuicPacketSequenceNumber last_packet;
1565 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet); // Packet 1
1566 EXPECT_EQ(1u, last_packet);
1567 SendAckPacketToPeer(); // Packet 2
1569 EXPECT_EQ(1u, least_unacked());
1571 SendAckPacketToPeer(); // Packet 3
1572 EXPECT_EQ(1u, least_unacked());
1574 SendStreamDataToPeer(1, "bar", 3, !kFin, &last_packet); // Packet 4
1575 EXPECT_EQ(4u, last_packet);
1576 SendAckPacketToPeer(); // Packet 5
1577 EXPECT_EQ(1u, least_unacked());
1579 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1581 // Peer acks up to packet 3.
1582 QuicAckFrame frame = InitAckFrame(3);
1583 ProcessAckPacket(&frame);
1584 SendAckPacketToPeer(); // Packet 6
1586 // As soon as we've acked one, we skip ack packets 2 and 3 and note lack of
1587 // ack for 4.
1588 EXPECT_EQ(4u, least_unacked());
1590 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1592 // Peer acks up to packet 4, the last packet.
1593 QuicAckFrame frame2 = InitAckFrame(6);
1594 ProcessAckPacket(&frame2); // Acks don't instigate acks.
1596 // Verify that we did not send an ack.
1597 EXPECT_EQ(6u, writer_->header().packet_sequence_number);
1599 // So the last ack has not changed.
1600 EXPECT_EQ(4u, least_unacked());
1602 // If we force an ack, we shouldn't change our retransmit state.
1603 SendAckPacketToPeer(); // Packet 7
1604 EXPECT_EQ(7u, least_unacked());
1606 // But if we send more data it should.
1607 SendStreamDataToPeer(1, "eep", 6, !kFin, &last_packet); // Packet 8
1608 EXPECT_EQ(8u, last_packet);
1609 SendAckPacketToPeer(); // Packet 9
1610 EXPECT_EQ(7u, least_unacked());
1613 // QuicConnection should record the the packet sent-time prior to sending the
1614 // packet.
1615 TEST_P(QuicConnectionTest, RecordSentTimeBeforePacketSent) {
1616 // We're using a MockClock for the tests, so we have complete control over the
1617 // time.
1618 // Our recorded timestamp for the last packet sent time will be passed in to
1619 // the send_algorithm. Make sure that it is set to the correct value.
1620 QuicTime actual_recorded_send_time = QuicTime::Zero();
1621 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1622 .WillOnce(DoAll(SaveArg<0>(&actual_recorded_send_time), Return(true)));
1624 // First send without any pause and check the result.
1625 QuicTime expected_recorded_send_time = clock_.Now();
1626 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
1627 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
1628 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
1629 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
1631 // Now pause during the write, and check the results.
1632 actual_recorded_send_time = QuicTime::Zero();
1633 const QuicTime::Delta write_pause_time_delta =
1634 QuicTime::Delta::FromMilliseconds(5000);
1635 SetWritePauseTimeDelta(write_pause_time_delta);
1636 expected_recorded_send_time = clock_.Now();
1638 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1639 .WillOnce(DoAll(SaveArg<0>(&actual_recorded_send_time), Return(true)));
1640 connection_.SendStreamDataWithString(2, "baz", 0, !kFin, nullptr);
1641 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
1642 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
1643 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
1646 TEST_P(QuicConnectionTest, FECSending) {
1647 // All packets carry version info till version is negotiated.
1648 size_t payload_length;
1649 // GetPacketLengthForOneStream() assumes a stream offset of 0 in determining
1650 // packet length. The size of the offset field in a stream frame is 0 for
1651 // offset 0, and 2 for non-zero offsets up through 64K. Increase
1652 // max_packet_length by 2 so that subsequent packets containing subsequent
1653 // stream frames with non-zero offets will fit within the packet length.
1654 size_t length = 2 + GetPacketLengthForOneStream(
1655 connection_.version(), kIncludeVersion,
1656 PACKET_8BYTE_CONNECTION_ID, PACKET_1BYTE_SEQUENCE_NUMBER,
1657 IN_FEC_GROUP, &payload_length);
1658 connection_.set_max_packet_length(length);
1660 if (generator_->fec_send_policy() == FEC_ALARM_TRIGGER) {
1661 // Send 4 protected data packets. FEC packet is not sent.
1662 EXPECT_CALL(*send_algorithm_,
1663 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(4);
1664 } else {
1665 // Send 4 protected data packets, which should also trigger 1 FEC packet.
1666 EXPECT_CALL(*send_algorithm_,
1667 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(5);
1669 // The first stream frame will have 2 fewer overhead bytes than the other 3.
1670 const string payload(payload_length * 4 + 2, 'a');
1671 connection_.SendStreamDataWithStringWithFec(1, payload, 0, !kFin, nullptr);
1672 // Expect the FEC group to be closed after SendStreamDataWithString.
1673 EXPECT_FALSE(creator_->IsFecGroupOpen());
1674 EXPECT_FALSE(creator_->IsFecProtected());
1677 TEST_P(QuicConnectionTest, FECQueueing) {
1678 // All packets carry version info till version is negotiated.
1679 size_t payload_length;
1680 size_t length = GetPacketLengthForOneStream(
1681 connection_.version(), kIncludeVersion,
1682 PACKET_8BYTE_CONNECTION_ID, PACKET_1BYTE_SEQUENCE_NUMBER,
1683 IN_FEC_GROUP, &payload_length);
1684 connection_.set_max_packet_length(length);
1685 EXPECT_TRUE(creator_->IsFecEnabled());
1687 EXPECT_EQ(0u, connection_.NumQueuedPackets());
1688 BlockOnNextWrite();
1689 const string payload(payload_length, 'a');
1690 connection_.SendStreamDataWithStringWithFec(1, payload, 0, !kFin, nullptr);
1691 EXPECT_FALSE(creator_->IsFecGroupOpen());
1692 EXPECT_FALSE(creator_->IsFecProtected());
1693 if (generator_->fec_send_policy() == FEC_ALARM_TRIGGER) {
1694 // Expect the first data packet to be queued and not the FEC packet.
1695 EXPECT_EQ(1u, connection_.NumQueuedPackets());
1696 } else {
1697 // Expect the first data packet and the fec packet to be queued.
1698 EXPECT_EQ(2u, connection_.NumQueuedPackets());
1702 TEST_P(QuicConnectionTest, FECAlarmStoppedWhenFECPacketSent) {
1703 EXPECT_TRUE(creator_->IsFecEnabled());
1704 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1705 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1707 creator_->set_max_packets_per_fec_group(2);
1709 // 1 Data packet. FEC alarm should be set.
1710 EXPECT_CALL(*send_algorithm_,
1711 OnPacketSent(_, _, 1u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1712 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, true, nullptr);
1713 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1715 if (generator_->fec_send_policy() == FEC_ALARM_TRIGGER) {
1716 // If FEC send policy is FEC_ALARM_TRIGGER, FEC packet is not sent.
1717 // FEC alarm should not be set.
1718 EXPECT_CALL(*send_algorithm_,
1719 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1720 } else {
1721 // Second data packet triggers FEC packet out. FEC alarm should not be set.
1722 EXPECT_CALL(*send_algorithm_,
1723 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(2);
1725 connection_.SendStreamDataWithStringWithFec(5, "foo", 0, true, nullptr);
1726 if (generator_->fec_send_policy() == FEC_ANY_TRIGGER) {
1727 EXPECT_TRUE(writer_->header().fec_flag);
1729 EXPECT_FALSE(creator_->IsFecGroupOpen());
1730 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1733 TEST_P(QuicConnectionTest, FECAlarmStoppedOnConnectionClose) {
1734 EXPECT_TRUE(creator_->IsFecEnabled());
1735 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1736 creator_->set_max_packets_per_fec_group(100);
1738 // 1 Data packet. FEC alarm should be set.
1739 EXPECT_CALL(*send_algorithm_,
1740 OnPacketSent(_, _, 1u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1741 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, kFin, nullptr);
1742 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1744 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NO_ERROR, false));
1745 // Closing connection should stop the FEC alarm.
1746 connection_.CloseConnection(QUIC_NO_ERROR, /*from_peer=*/false);
1747 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1750 TEST_P(QuicConnectionTest, RemoveFECFromInflightOnRetransmissionTimeout) {
1751 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1752 EXPECT_TRUE(creator_->IsFecEnabled());
1753 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1754 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1756 // 1 Data packet. FEC alarm should be set.
1757 EXPECT_CALL(*send_algorithm_,
1758 OnPacketSent(_, _, 1u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1759 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, !kFin, nullptr);
1760 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1761 size_t protected_packet =
1762 QuicSentPacketManagerPeer::GetBytesInFlight(manager_);
1764 // Force FEC timeout to send FEC packet out.
1765 EXPECT_CALL(*send_algorithm_,
1766 OnPacketSent(_, _, 2u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1767 connection_.GetFecAlarm()->Fire();
1768 EXPECT_TRUE(writer_->header().fec_flag);
1770 size_t fec_packet = protected_packet;
1771 EXPECT_EQ(protected_packet + fec_packet,
1772 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1773 clock_.AdvanceTime(DefaultRetransmissionTime());
1775 // On RTO, both data and FEC packets are removed from inflight, only the data
1776 // packet is retransmitted, and this retransmission (but not FEC) gets added
1777 // back into the inflight.
1778 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
1779 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1780 connection_.GetRetransmissionAlarm()->Fire();
1782 // The retransmission of packet 1 will be 3 bytes smaller than packet 1, since
1783 // the first transmission will have 1 byte for FEC group number and 2 bytes of
1784 // stream frame size, which are absent in the retransmission.
1785 size_t retransmitted_packet = protected_packet - 3;
1786 EXPECT_EQ(protected_packet + retransmitted_packet,
1787 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1788 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1790 // Receive ack for the retransmission. No data should be outstanding.
1791 QuicAckFrame ack = InitAckFrame(3);
1792 NackPacket(1, &ack);
1793 NackPacket(2, &ack);
1794 SequenceNumberSet lost_packets;
1795 lost_packets.insert(1);
1796 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1797 .WillOnce(Return(lost_packets));
1798 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1799 ProcessAckPacket(&ack);
1801 // Ensure the alarm is not set since all packets have been acked or abandoned.
1802 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
1803 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1806 TEST_P(QuicConnectionTest, RemoveFECFromInflightOnLossRetransmission) {
1807 EXPECT_TRUE(creator_->IsFecEnabled());
1808 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1810 // 1 FEC-protected data packet. FEC alarm should be set.
1811 EXPECT_CALL(*send_algorithm_,
1812 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1813 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, kFin, nullptr);
1814 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1815 size_t protected_packet =
1816 QuicSentPacketManagerPeer::GetBytesInFlight(manager_);
1818 // Force FEC timeout to send FEC packet out.
1819 EXPECT_CALL(*send_algorithm_,
1820 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1821 connection_.GetFecAlarm()->Fire();
1822 EXPECT_TRUE(writer_->header().fec_flag);
1823 size_t fec_packet = protected_packet;
1824 EXPECT_EQ(protected_packet + fec_packet,
1825 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1827 // Send more data to trigger NACKs. Note that all data starts at stream offset
1828 // 0 to ensure the same packet size, for ease of testing.
1829 EXPECT_CALL(*send_algorithm_,
1830 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(4);
1831 connection_.SendStreamDataWithString(5, "foo", 0, kFin, nullptr);
1832 connection_.SendStreamDataWithString(7, "foo", 0, kFin, nullptr);
1833 connection_.SendStreamDataWithString(9, "foo", 0, kFin, nullptr);
1834 connection_.SendStreamDataWithString(11, "foo", 0, kFin, nullptr);
1836 // An unprotected packet will be 3 bytes smaller than an FEC-protected packet,
1837 // since the protected packet will have 1 byte for FEC group number and
1838 // 2 bytes of stream frame size, which are absent in the unprotected packet.
1839 size_t unprotected_packet = protected_packet - 3;
1840 EXPECT_EQ(protected_packet + fec_packet + 4 * unprotected_packet,
1841 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1842 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1844 // Ack data packets, and NACK FEC packet and one data packet. Triggers
1845 // NACK-based loss detection of both packets, but only data packet is
1846 // retransmitted and considered oustanding.
1847 QuicAckFrame ack = InitAckFrame(6);
1848 NackPacket(2, &ack);
1849 NackPacket(3, &ack);
1850 SequenceNumberSet lost_packets;
1851 lost_packets.insert(2);
1852 lost_packets.insert(3);
1853 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1854 .WillOnce(Return(lost_packets));
1855 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1856 EXPECT_CALL(*send_algorithm_,
1857 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1858 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1859 ProcessAckPacket(&ack);
1860 // On receiving this ack from the server, the client will no longer send
1861 // version number in subsequent packets, including in this retransmission.
1862 size_t unprotected_packet_no_version = unprotected_packet - 4;
1863 EXPECT_EQ(unprotected_packet_no_version,
1864 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1866 // Receive ack for the retransmission. No data should be outstanding.
1867 QuicAckFrame ack2 = InitAckFrame(7);
1868 NackPacket(2, &ack2);
1869 NackPacket(3, &ack2);
1870 SequenceNumberSet lost_packets2;
1871 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1872 .WillOnce(Return(lost_packets2));
1873 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1874 ProcessAckPacket(&ack2);
1875 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1878 TEST_P(QuicConnectionTest, FECRemainsInflightOnTLPOfEarlierData) {
1879 // This test checks if TLP is sent correctly when a data and an FEC packet
1880 // are outstanding. TLP should be sent for the data packet when the
1881 // retransmission alarm fires.
1882 // Turn on TLP for this test.
1883 QuicSentPacketManagerPeer::SetMaxTailLossProbes(manager_, 1);
1884 EXPECT_TRUE(creator_->IsFecEnabled());
1885 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1886 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1888 // 1 Data packet. FEC alarm should be set.
1889 EXPECT_CALL(*send_algorithm_,
1890 OnPacketSent(_, _, 1u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1891 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, kFin, nullptr);
1892 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1893 size_t protected_packet =
1894 QuicSentPacketManagerPeer::GetBytesInFlight(manager_);
1895 EXPECT_LT(0u, protected_packet);
1897 // Force FEC timeout to send FEC packet out.
1898 EXPECT_CALL(*send_algorithm_,
1899 OnPacketSent(_, _, 2u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1900 connection_.GetFecAlarm()->Fire();
1901 EXPECT_TRUE(writer_->header().fec_flag);
1902 size_t fec_packet = protected_packet;
1903 EXPECT_EQ(protected_packet + fec_packet,
1904 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1906 // TLP alarm should be set.
1907 QuicTime retransmission_time =
1908 connection_.GetRetransmissionAlarm()->deadline();
1909 EXPECT_NE(QuicTime::Zero(), retransmission_time);
1910 // Simulate the retransmission alarm firing and sending a TLP, so send
1911 // algorithm's OnRetransmissionTimeout is not called.
1912 clock_.AdvanceTime(retransmission_time.Subtract(clock_.Now()));
1913 EXPECT_CALL(*send_algorithm_,
1914 OnPacketSent(_, _, 3u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1915 connection_.GetRetransmissionAlarm()->Fire();
1916 // The TLP retransmission of packet 1 will be 3 bytes smaller than packet 1,
1917 // since packet 1 will have 1 byte for FEC group number and 2 bytes of stream
1918 // frame size, which are absent in the the TLP retransmission.
1919 size_t tlp_packet = protected_packet - 3;
1920 EXPECT_EQ(protected_packet + fec_packet + tlp_packet,
1921 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1924 TEST_P(QuicConnectionTest, FECRemainsInflightOnTLPOfLaterData) {
1925 // Tests if TLP is sent correctly when data packet 1 and an FEC packet are
1926 // sent followed by data packet 2, and data packet 1 is acked. TLP should be
1927 // sent for data packet 2 when the retransmission alarm fires. Turn on TLP for
1928 // this test.
1929 QuicSentPacketManagerPeer::SetMaxTailLossProbes(manager_, 1);
1930 EXPECT_TRUE(creator_->IsFecEnabled());
1931 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1932 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1934 // 1 Data packet. FEC alarm should be set.
1935 EXPECT_CALL(*send_algorithm_,
1936 OnPacketSent(_, _, 1u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1937 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, kFin, nullptr);
1938 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1939 size_t protected_packet =
1940 QuicSentPacketManagerPeer::GetBytesInFlight(manager_);
1941 EXPECT_LT(0u, protected_packet);
1943 // Force FEC timeout to send FEC packet out.
1944 EXPECT_CALL(*send_algorithm_,
1945 OnPacketSent(_, _, 2u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1946 connection_.GetFecAlarm()->Fire();
1947 EXPECT_TRUE(writer_->header().fec_flag);
1948 // Protected data packet and FEC packet oustanding.
1949 size_t fec_packet = protected_packet;
1950 EXPECT_EQ(protected_packet + fec_packet,
1951 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1953 // Send 1 unprotected data packet. No FEC alarm should be set.
1954 EXPECT_CALL(*send_algorithm_,
1955 OnPacketSent(_, _, 3u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1956 connection_.SendStreamDataWithString(5, "foo", 0, kFin, nullptr);
1957 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1958 // Protected data packet, FEC packet, and unprotected data packet oustanding.
1959 // An unprotected packet will be 3 bytes smaller than an FEC-protected packet,
1960 // since the protected packet will have 1 byte for FEC group number and
1961 // 2 bytes of stream frame size, which are absent in the unprotected packet.
1962 size_t unprotected_packet = protected_packet - 3;
1963 EXPECT_EQ(protected_packet + fec_packet + unprotected_packet,
1964 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1966 // Receive ack for first data packet. FEC and second data packet are still
1967 // outstanding.
1968 QuicAckFrame ack = InitAckFrame(1);
1969 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1970 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1971 ProcessAckPacket(&ack);
1972 // FEC packet and unprotected data packet oustanding.
1973 EXPECT_EQ(fec_packet + unprotected_packet,
1974 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1976 // TLP alarm should be set.
1977 QuicTime retransmission_time =
1978 connection_.GetRetransmissionAlarm()->deadline();
1979 EXPECT_NE(QuicTime::Zero(), retransmission_time);
1980 // Simulate the retransmission alarm firing and sending a TLP, so send
1981 // algorithm's OnRetransmissionTimeout is not called.
1982 clock_.AdvanceTime(retransmission_time.Subtract(clock_.Now()));
1983 EXPECT_CALL(*send_algorithm_,
1984 OnPacketSent(_, _, 4u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1985 connection_.GetRetransmissionAlarm()->Fire();
1987 // Having received an ack from the server, the client will no longer send
1988 // version number in subsequent packets, including in this retransmission.
1989 size_t tlp_packet_no_version = unprotected_packet - 4;
1990 EXPECT_EQ(fec_packet + unprotected_packet + tlp_packet_no_version,
1991 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1994 TEST_P(QuicConnectionTest, NoTLPForFECPacket) {
1995 // Turn on TLP for this test.
1996 QuicSentPacketManagerPeer::SetMaxTailLossProbes(manager_, 1);
1997 EXPECT_TRUE(creator_->IsFecEnabled());
1998 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2000 // Send 1 FEC-protected data packet. FEC alarm should be set.
2001 EXPECT_CALL(*send_algorithm_,
2002 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
2003 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, !kFin, nullptr);
2004 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
2005 // Force FEC timeout to send FEC packet out.
2006 EXPECT_CALL(*send_algorithm_,
2007 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
2008 connection_.GetFecAlarm()->Fire();
2009 EXPECT_TRUE(writer_->header().fec_flag);
2011 // Ack data packet, but not FEC packet.
2012 QuicAckFrame ack = InitAckFrame(1);
2013 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2014 ProcessAckPacket(&ack);
2016 // No TLP alarm for FEC, but retransmission alarm should be set for an RTO.
2017 EXPECT_LT(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
2018 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2019 QuicTime rto_time = connection_.GetRetransmissionAlarm()->deadline();
2020 EXPECT_NE(QuicTime::Zero(), rto_time);
2022 // Simulate the retransmission alarm firing. FEC packet is no longer
2023 // outstanding.
2024 clock_.AdvanceTime(rto_time.Subtract(clock_.Now()));
2025 connection_.GetRetransmissionAlarm()->Fire();
2027 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
2028 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
2031 TEST_P(QuicConnectionTest, FramePacking) {
2032 CongestionBlockWrites();
2034 // Send an ack and two stream frames in 1 packet by queueing them.
2035 connection_.SendAck();
2036 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
2037 IgnoreResult(InvokeWithoutArgs(&connection_,
2038 &TestConnection::SendStreamData3)),
2039 IgnoreResult(InvokeWithoutArgs(&connection_,
2040 &TestConnection::SendStreamData5))));
2042 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2043 CongestionUnblockWrites();
2044 connection_.GetSendAlarm()->Fire();
2045 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2046 EXPECT_FALSE(connection_.HasQueuedData());
2048 // Parse the last packet and ensure it's an ack and two stream frames from
2049 // two different streams.
2050 EXPECT_EQ(4u, writer_->frame_count());
2051 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
2052 EXPECT_FALSE(writer_->ack_frames().empty());
2053 ASSERT_EQ(2u, writer_->stream_frames().size());
2054 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id);
2055 EXPECT_EQ(kClientDataStreamId2, writer_->stream_frames()[1].stream_id);
2058 TEST_P(QuicConnectionTest, FramePackingNonCryptoThenCrypto) {
2059 CongestionBlockWrites();
2061 // Send an ack and two stream frames (one non-crypto, then one crypto) in 2
2062 // packets by queueing them.
2063 connection_.SendAck();
2064 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
2065 IgnoreResult(InvokeWithoutArgs(&connection_,
2066 &TestConnection::SendStreamData3)),
2067 IgnoreResult(InvokeWithoutArgs(&connection_,
2068 &TestConnection::SendCryptoStreamData))));
2070 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
2071 CongestionUnblockWrites();
2072 connection_.GetSendAlarm()->Fire();
2073 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2074 EXPECT_FALSE(connection_.HasQueuedData());
2076 // Parse the last packet and ensure it's the crypto stream frame.
2077 EXPECT_EQ(1u, writer_->frame_count());
2078 ASSERT_EQ(1u, writer_->stream_frames().size());
2079 EXPECT_EQ(kCryptoStreamId, writer_->stream_frames()[0].stream_id);
2082 TEST_P(QuicConnectionTest, FramePackingCryptoThenNonCrypto) {
2083 CongestionBlockWrites();
2085 // Send an ack and two stream frames (one crypto, then one non-crypto) in 2
2086 // packets by queueing them.
2087 connection_.SendAck();
2088 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
2089 IgnoreResult(InvokeWithoutArgs(&connection_,
2090 &TestConnection::SendCryptoStreamData)),
2091 IgnoreResult(InvokeWithoutArgs(&connection_,
2092 &TestConnection::SendStreamData3))));
2094 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
2095 CongestionUnblockWrites();
2096 connection_.GetSendAlarm()->Fire();
2097 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2098 EXPECT_FALSE(connection_.HasQueuedData());
2100 // Parse the last packet and ensure it's the stream frame from stream 3.
2101 EXPECT_EQ(1u, writer_->frame_count());
2102 ASSERT_EQ(1u, writer_->stream_frames().size());
2103 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id);
2106 TEST_P(QuicConnectionTest, FramePackingFEC) {
2107 EXPECT_TRUE(creator_->IsFecEnabled());
2109 CongestionBlockWrites();
2111 // Queue an ack and two stream frames. Ack gets flushed when FEC is turned on
2112 // for sending protected data; two stream frames are packed in 1 packet.
2113 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
2114 IgnoreResult(InvokeWithoutArgs(
2115 &connection_, &TestConnection::SendStreamData3WithFec)),
2116 IgnoreResult(InvokeWithoutArgs(
2117 &connection_, &TestConnection::SendStreamData5WithFec))));
2118 connection_.SendAck();
2120 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
2121 CongestionUnblockWrites();
2122 connection_.GetSendAlarm()->Fire();
2123 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2124 EXPECT_FALSE(connection_.HasQueuedData());
2126 // Parse the last packet and ensure it's in an fec group.
2127 EXPECT_EQ(2u, writer_->header().fec_group);
2128 EXPECT_EQ(2u, writer_->frame_count());
2130 // FEC alarm should be set.
2131 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
2134 TEST_P(QuicConnectionTest, FramePackingAckResponse) {
2135 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2136 // Process a data packet to queue up a pending ack.
2137 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2138 ProcessDataPacket(1, 1, kEntropyFlag);
2140 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
2141 IgnoreResult(InvokeWithoutArgs(&connection_,
2142 &TestConnection::SendStreamData3)),
2143 IgnoreResult(InvokeWithoutArgs(&connection_,
2144 &TestConnection::SendStreamData5))));
2146 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2148 // Process an ack to cause the visitor's OnCanWrite to be invoked.
2149 QuicAckFrame ack_one = InitAckFrame(0);
2150 ProcessAckPacket(3, &ack_one);
2152 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2153 EXPECT_FALSE(connection_.HasQueuedData());
2155 // Parse the last packet and ensure it's an ack and two stream frames from
2156 // two different streams.
2157 EXPECT_EQ(4u, writer_->frame_count());
2158 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
2159 EXPECT_FALSE(writer_->ack_frames().empty());
2160 ASSERT_EQ(2u, writer_->stream_frames().size());
2161 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id);
2162 EXPECT_EQ(kClientDataStreamId2, writer_->stream_frames()[1].stream_id);
2165 TEST_P(QuicConnectionTest, FramePackingSendv) {
2166 // Send data in 1 packet by writing multiple blocks in a single iovector
2167 // using writev.
2168 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2170 char data[] = "ABCD";
2171 struct iovec iov[2];
2172 iov[0].iov_base = data;
2173 iov[0].iov_len = 2;
2174 iov[1].iov_base = data + 2;
2175 iov[1].iov_len = 2;
2176 connection_.SendStreamData(1, QuicIOVector(iov, 2, 4), 0, !kFin,
2177 MAY_FEC_PROTECT, nullptr);
2179 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2180 EXPECT_FALSE(connection_.HasQueuedData());
2182 // Parse the last packet and ensure multiple iovector blocks have
2183 // been packed into a single stream frame from one stream.
2184 EXPECT_EQ(1u, writer_->frame_count());
2185 EXPECT_EQ(1u, writer_->stream_frames().size());
2186 QuicStreamFrame frame = writer_->stream_frames()[0];
2187 EXPECT_EQ(1u, frame.stream_id);
2188 EXPECT_EQ("ABCD", frame.data);
2191 TEST_P(QuicConnectionTest, FramePackingSendvQueued) {
2192 // Try to send two stream frames in 1 packet by using writev.
2193 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2195 BlockOnNextWrite();
2196 char data[] = "ABCD";
2197 struct iovec iov[2];
2198 iov[0].iov_base = data;
2199 iov[0].iov_len = 2;
2200 iov[1].iov_base = data + 2;
2201 iov[1].iov_len = 2;
2202 connection_.SendStreamData(1, QuicIOVector(iov, 2, 4), 0, !kFin,
2203 MAY_FEC_PROTECT, nullptr);
2205 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2206 EXPECT_TRUE(connection_.HasQueuedData());
2208 // Unblock the writes and actually send.
2209 writer_->SetWritable();
2210 connection_.OnCanWrite();
2211 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2213 // Parse the last packet and ensure it's one stream frame from one stream.
2214 EXPECT_EQ(1u, writer_->frame_count());
2215 EXPECT_EQ(1u, writer_->stream_frames().size());
2216 EXPECT_EQ(1u, writer_->stream_frames()[0].stream_id);
2219 TEST_P(QuicConnectionTest, SendingZeroBytes) {
2220 // Send a zero byte write with a fin using writev.
2221 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2222 QuicIOVector empty_iov(nullptr, 0, 0);
2223 connection_.SendStreamData(1, empty_iov, 0, kFin, MAY_FEC_PROTECT, nullptr);
2225 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2226 EXPECT_FALSE(connection_.HasQueuedData());
2228 // Parse the last packet and ensure it's one stream frame from one stream.
2229 EXPECT_EQ(1u, writer_->frame_count());
2230 EXPECT_EQ(1u, writer_->stream_frames().size());
2231 EXPECT_EQ(1u, writer_->stream_frames()[0].stream_id);
2232 EXPECT_TRUE(writer_->stream_frames()[0].fin);
2235 TEST_P(QuicConnectionTest, OnCanWrite) {
2236 // Visitor's OnCanWrite will send data, but will have more pending writes.
2237 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
2238 IgnoreResult(InvokeWithoutArgs(&connection_,
2239 &TestConnection::SendStreamData3)),
2240 IgnoreResult(InvokeWithoutArgs(&connection_,
2241 &TestConnection::SendStreamData5))));
2242 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillOnce(Return(true));
2243 EXPECT_CALL(*send_algorithm_,
2244 TimeUntilSend(_, _, _)).WillRepeatedly(
2245 testing::Return(QuicTime::Delta::Zero()));
2247 connection_.OnCanWrite();
2249 // Parse the last packet and ensure it's the two stream frames from
2250 // two different streams.
2251 EXPECT_EQ(2u, writer_->frame_count());
2252 EXPECT_EQ(2u, writer_->stream_frames().size());
2253 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id);
2254 EXPECT_EQ(kClientDataStreamId2, writer_->stream_frames()[1].stream_id);
2257 TEST_P(QuicConnectionTest, RetransmitOnNack) {
2258 QuicPacketSequenceNumber last_packet;
2259 QuicByteCount second_packet_size;
2260 SendStreamDataToPeer(3, "foo", 0, !kFin, &last_packet); // Packet 1
2261 second_packet_size =
2262 SendStreamDataToPeer(3, "foos", 3, !kFin, &last_packet); // Packet 2
2263 SendStreamDataToPeer(3, "fooos", 7, !kFin, &last_packet); // Packet 3
2265 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2267 // Don't lose a packet on an ack, and nothing is retransmitted.
2268 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2269 QuicAckFrame ack_one = InitAckFrame(1);
2270 ProcessAckPacket(&ack_one);
2272 // Lose a packet and ensure it triggers retransmission.
2273 QuicAckFrame nack_two = InitAckFrame(3);
2274 NackPacket(2, &nack_two);
2275 SequenceNumberSet lost_packets;
2276 lost_packets.insert(2);
2277 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2278 .WillOnce(Return(lost_packets));
2279 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2280 EXPECT_CALL(*send_algorithm_,
2281 OnPacketSent(_, _, _, second_packet_size - kQuicVersionSize, _)).
2282 Times(1);
2283 ProcessAckPacket(&nack_two);
2286 TEST_P(QuicConnectionTest, DoNotSendQueuedPacketForResetStream) {
2287 // Block the connection to queue the packet.
2288 BlockOnNextWrite();
2290 QuicStreamId stream_id = 2;
2291 connection_.SendStreamDataWithString(stream_id, "foo", 0, !kFin, nullptr);
2293 // Now that there is a queued packet, reset the stream.
2294 connection_.SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 14);
2296 // Unblock the connection and verify that only the RST_STREAM is sent.
2297 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2298 writer_->SetWritable();
2299 connection_.OnCanWrite();
2300 EXPECT_EQ(1u, writer_->frame_count());
2301 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
2304 TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnNack) {
2305 QuicStreamId stream_id = 2;
2306 QuicPacketSequenceNumber last_packet;
2307 SendStreamDataToPeer(stream_id, "foo", 0, !kFin, &last_packet);
2308 SendStreamDataToPeer(stream_id, "foos", 3, !kFin, &last_packet);
2309 SendStreamDataToPeer(stream_id, "fooos", 7, !kFin, &last_packet);
2311 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2312 connection_.SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 14);
2314 // Lose a packet and ensure it does not trigger retransmission.
2315 QuicAckFrame nack_two = InitAckFrame(last_packet);
2316 NackPacket(last_packet - 1, &nack_two);
2317 SequenceNumberSet lost_packets;
2318 lost_packets.insert(last_packet - 1);
2319 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2320 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2321 .WillOnce(Return(lost_packets));
2322 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2323 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
2324 ProcessAckPacket(&nack_two);
2327 TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnRTO) {
2328 QuicStreamId stream_id = 2;
2329 QuicPacketSequenceNumber last_packet;
2330 SendStreamDataToPeer(stream_id, "foo", 0, !kFin, &last_packet);
2332 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2333 connection_.SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 14);
2335 // Fire the RTO and verify that the RST_STREAM is resent, not stream data.
2336 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2337 clock_.AdvanceTime(DefaultRetransmissionTime());
2338 connection_.GetRetransmissionAlarm()->Fire();
2339 EXPECT_EQ(1u, writer_->frame_count());
2340 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
2341 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
2344 TEST_P(QuicConnectionTest, DoNotSendPendingRetransmissionForResetStream) {
2345 QuicStreamId stream_id = 2;
2346 QuicPacketSequenceNumber last_packet;
2347 SendStreamDataToPeer(stream_id, "foo", 0, !kFin, &last_packet);
2348 SendStreamDataToPeer(stream_id, "foos", 3, !kFin, &last_packet);
2349 BlockOnNextWrite();
2350 connection_.SendStreamDataWithString(stream_id, "fooos", 7, !kFin, nullptr);
2352 // Lose a packet which will trigger a pending retransmission.
2353 QuicAckFrame ack = InitAckFrame(last_packet);
2354 NackPacket(last_packet - 1, &ack);
2355 SequenceNumberSet lost_packets;
2356 lost_packets.insert(last_packet - 1);
2357 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2358 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2359 .WillOnce(Return(lost_packets));
2360 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2361 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
2362 ProcessAckPacket(&ack);
2364 connection_.SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 14);
2366 // Unblock the connection and verify that the RST_STREAM is sent but not the
2367 // second data packet nor a retransmit.
2368 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2369 writer_->SetWritable();
2370 connection_.OnCanWrite();
2371 EXPECT_EQ(1u, writer_->frame_count());
2372 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
2373 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
2376 TEST_P(QuicConnectionTest, DiscardRetransmit) {
2377 QuicPacketSequenceNumber last_packet;
2378 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet); // Packet 1
2379 SendStreamDataToPeer(1, "foos", 3, !kFin, &last_packet); // Packet 2
2380 SendStreamDataToPeer(1, "fooos", 7, !kFin, &last_packet); // Packet 3
2382 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2384 // Instigate a loss with an ack.
2385 QuicAckFrame nack_two = InitAckFrame(3);
2386 NackPacket(2, &nack_two);
2387 // The first nack should trigger a fast retransmission, but we'll be
2388 // write blocked, so the packet will be queued.
2389 BlockOnNextWrite();
2390 SequenceNumberSet lost_packets;
2391 lost_packets.insert(2);
2392 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2393 .WillOnce(Return(lost_packets));
2394 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2395 ProcessAckPacket(&nack_two);
2396 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2398 // Now, ack the previous transmission.
2399 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2400 .WillOnce(Return(SequenceNumberSet()));
2401 QuicAckFrame ack_all = InitAckFrame(3);
2402 ProcessAckPacket(&ack_all);
2404 // Unblock the socket and attempt to send the queued packets. However,
2405 // since the previous transmission has been acked, we will not
2406 // send the retransmission.
2407 EXPECT_CALL(*send_algorithm_,
2408 OnPacketSent(_, _, _, _, _)).Times(0);
2410 writer_->SetWritable();
2411 connection_.OnCanWrite();
2413 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2416 TEST_P(QuicConnectionTest, RetransmitNackedLargestObserved) {
2417 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2418 QuicPacketSequenceNumber largest_observed;
2419 QuicByteCount packet_size;
2420 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2421 .WillOnce(DoAll(SaveArg<2>(&largest_observed), SaveArg<3>(&packet_size),
2422 Return(true)));
2423 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
2425 QuicAckFrame frame = InitAckFrame(1);
2426 NackPacket(largest_observed, &frame);
2427 // The first nack should retransmit the largest observed packet.
2428 SequenceNumberSet lost_packets;
2429 lost_packets.insert(1);
2430 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2431 .WillOnce(Return(lost_packets));
2432 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2433 EXPECT_CALL(*send_algorithm_,
2434 OnPacketSent(_, _, _, packet_size - kQuicVersionSize, _));
2435 ProcessAckPacket(&frame);
2438 TEST_P(QuicConnectionTest, QueueAfterTwoRTOs) {
2439 for (int i = 0; i < 10; ++i) {
2440 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2441 connection_.SendStreamDataWithString(3, "foo", i * 3, !kFin, nullptr);
2444 // Block the writer and ensure they're queued.
2445 BlockOnNextWrite();
2446 clock_.AdvanceTime(DefaultRetransmissionTime());
2447 // Only one packet should be retransmitted.
2448 connection_.GetRetransmissionAlarm()->Fire();
2449 EXPECT_TRUE(connection_.HasQueuedData());
2451 // Unblock the writer.
2452 writer_->SetWritable();
2453 clock_.AdvanceTime(QuicTime::Delta::FromMicroseconds(
2454 2 * DefaultRetransmissionTime().ToMicroseconds()));
2455 // Retransmit already retransmitted packets event though the sequence number
2456 // greater than the largest observed.
2457 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
2458 connection_.GetRetransmissionAlarm()->Fire();
2459 connection_.OnCanWrite();
2462 TEST_P(QuicConnectionTest, WriteBlockedThenSent) {
2463 BlockOnNextWrite();
2464 writer_->set_is_write_blocked_data_buffered(true);
2465 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2466 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
2467 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2469 writer_->SetWritable();
2470 connection_.OnCanWrite();
2471 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2474 TEST_P(QuicConnectionTest, RetransmitWriteBlockedAckedOriginalThenSent) {
2475 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2476 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
2477 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2479 BlockOnNextWrite();
2480 writer_->set_is_write_blocked_data_buffered(true);
2481 // Simulate the retransmission alarm firing.
2482 clock_.AdvanceTime(DefaultRetransmissionTime());
2483 connection_.GetRetransmissionAlarm()->Fire();
2485 // Ack the sent packet before the callback returns, which happens in
2486 // rare circumstances with write blocked sockets.
2487 QuicAckFrame ack = InitAckFrame(1);
2488 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2489 ProcessAckPacket(&ack);
2491 writer_->SetWritable();
2492 connection_.OnCanWrite();
2493 // There is now a pending packet, but with no retransmittable frames.
2494 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2495 EXPECT_FALSE(connection_.sent_packet_manager().HasRetransmittableFrames(2));
2498 TEST_P(QuicConnectionTest, AlarmsWhenWriteBlocked) {
2499 // Block the connection.
2500 BlockOnNextWrite();
2501 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
2502 EXPECT_EQ(1u, writer_->packets_write_attempts());
2503 EXPECT_TRUE(writer_->IsWriteBlocked());
2505 // Set the send and resumption alarms. Fire the alarms and ensure they don't
2506 // attempt to write.
2507 connection_.GetResumeWritesAlarm()->Set(clock_.ApproximateNow());
2508 connection_.GetSendAlarm()->Set(clock_.ApproximateNow());
2509 connection_.GetResumeWritesAlarm()->Fire();
2510 connection_.GetSendAlarm()->Fire();
2511 EXPECT_TRUE(writer_->IsWriteBlocked());
2512 EXPECT_EQ(1u, writer_->packets_write_attempts());
2515 TEST_P(QuicConnectionTest, NoLimitPacketsPerNack) {
2516 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2517 int offset = 0;
2518 // Send packets 1 to 15.
2519 for (int i = 0; i < 15; ++i) {
2520 SendStreamDataToPeer(1, "foo", offset, !kFin, nullptr);
2521 offset += 3;
2524 // Ack 15, nack 1-14.
2525 SequenceNumberSet lost_packets;
2526 QuicAckFrame nack = InitAckFrame(15);
2527 for (int i = 1; i < 15; ++i) {
2528 NackPacket(i, &nack);
2529 lost_packets.insert(i);
2532 // 14 packets have been NACK'd and lost. In TCP cubic, PRR limits
2533 // the retransmission rate in the case of burst losses.
2534 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2535 .WillOnce(Return(lost_packets));
2536 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2537 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(14);
2538 ProcessAckPacket(&nack);
2541 // Test sending multiple acks from the connection to the session.
2542 TEST_P(QuicConnectionTest, MultipleAcks) {
2543 QuicPacketSequenceNumber last_packet;
2544 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet); // Packet 1
2545 EXPECT_EQ(1u, last_packet);
2546 SendStreamDataToPeer(3, "foo", 0, !kFin, &last_packet); // Packet 2
2547 EXPECT_EQ(2u, last_packet);
2548 SendAckPacketToPeer(); // Packet 3
2549 SendStreamDataToPeer(5, "foo", 0, !kFin, &last_packet); // Packet 4
2550 EXPECT_EQ(4u, last_packet);
2551 SendStreamDataToPeer(1, "foo", 3, !kFin, &last_packet); // Packet 5
2552 EXPECT_EQ(5u, last_packet);
2553 SendStreamDataToPeer(3, "foo", 3, !kFin, &last_packet); // Packet 6
2554 EXPECT_EQ(6u, last_packet);
2556 // Client will ack packets 1, 2, [!3], 4, 5.
2557 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2558 QuicAckFrame frame1 = InitAckFrame(5);
2559 NackPacket(3, &frame1);
2560 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2561 ProcessAckPacket(&frame1);
2563 // Now the client implicitly acks 3, and explicitly acks 6.
2564 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2565 QuicAckFrame frame2 = InitAckFrame(6);
2566 ProcessAckPacket(&frame2);
2569 TEST_P(QuicConnectionTest, DontLatchUnackedPacket) {
2570 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr); // Packet 1;
2571 // From now on, we send acks, so the send algorithm won't mark them pending.
2572 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2573 .WillByDefault(Return(false));
2574 SendAckPacketToPeer(); // Packet 2
2576 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2577 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2578 QuicAckFrame frame = InitAckFrame(1);
2579 ProcessAckPacket(&frame);
2581 // Verify that our internal state has least-unacked as 2, because we're still
2582 // waiting for a potential ack for 2.
2584 EXPECT_EQ(2u, stop_waiting()->least_unacked);
2586 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2587 frame = InitAckFrame(2);
2588 ProcessAckPacket(&frame);
2589 EXPECT_EQ(3u, stop_waiting()->least_unacked);
2591 // When we send an ack, we make sure our least-unacked makes sense. In this
2592 // case since we're not waiting on an ack for 2 and all packets are acked, we
2593 // set it to 3.
2594 SendAckPacketToPeer(); // Packet 3
2595 // Least_unacked remains at 3 until another ack is received.
2596 EXPECT_EQ(3u, stop_waiting()->least_unacked);
2597 // Check that the outgoing ack had its sequence number as least_unacked.
2598 EXPECT_EQ(3u, least_unacked());
2600 // Ack the ack, which updates the rtt and raises the least unacked.
2601 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2602 frame = InitAckFrame(3);
2603 ProcessAckPacket(&frame);
2605 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2606 .WillByDefault(Return(true));
2607 SendStreamDataToPeer(1, "bar", 3, false, nullptr); // Packet 4
2608 EXPECT_EQ(4u, stop_waiting()->least_unacked);
2609 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2610 .WillByDefault(Return(false));
2611 SendAckPacketToPeer(); // Packet 5
2612 EXPECT_EQ(4u, least_unacked());
2614 // Send two data packets at the end, and ensure if the last one is acked,
2615 // the least unacked is raised above the ack packets.
2616 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2617 .WillByDefault(Return(true));
2618 SendStreamDataToPeer(1, "bar", 6, false, nullptr); // Packet 6
2619 SendStreamDataToPeer(1, "bar", 9, false, nullptr); // Packet 7
2621 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2622 frame = InitAckFrame(7);
2623 NackPacket(5, &frame);
2624 NackPacket(6, &frame);
2625 ProcessAckPacket(&frame);
2627 EXPECT_EQ(6u, stop_waiting()->least_unacked);
2630 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterFecPacket) {
2631 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2633 // Don't send missing packet 1.
2634 ProcessFecPacket(2, 1, true, !kEntropyFlag, nullptr);
2635 // Entropy flag should be false, so entropy should be 0.
2636 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2639 TEST_P(QuicConnectionTest, ReviveMissingPacketWithVaryingSeqNumLengths) {
2640 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2642 // Set up a debug visitor to the connection.
2643 scoped_ptr<FecQuicConnectionDebugVisitor> fec_visitor(
2644 new FecQuicConnectionDebugVisitor());
2645 connection_.set_debug_visitor(fec_visitor.get());
2647 QuicPacketSequenceNumber fec_packet = 0;
2648 QuicSequenceNumberLength lengths[] = {PACKET_6BYTE_SEQUENCE_NUMBER,
2649 PACKET_4BYTE_SEQUENCE_NUMBER,
2650 PACKET_2BYTE_SEQUENCE_NUMBER,
2651 PACKET_1BYTE_SEQUENCE_NUMBER};
2652 // For each sequence number length size, revive a packet and check sequence
2653 // number length in the revived packet.
2654 for (size_t i = 0; i < arraysize(lengths); ++i) {
2655 // Set sequence_number_length_ (for data and FEC packets).
2656 sequence_number_length_ = lengths[i];
2657 fec_packet += 2;
2658 // Don't send missing packet, but send fec packet right after it.
2659 ProcessFecPacket(fec_packet, fec_packet - 1, true, !kEntropyFlag, nullptr);
2660 // Sequence number length in the revived header should be the same as
2661 // in the original data/fec packet headers.
2662 EXPECT_EQ(sequence_number_length_, fec_visitor->revived_header().
2663 public_header.sequence_number_length);
2667 TEST_P(QuicConnectionTest, ReviveMissingPacketWithVaryingConnectionIdLengths) {
2668 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2670 // Set up a debug visitor to the connection.
2671 scoped_ptr<FecQuicConnectionDebugVisitor> fec_visitor(
2672 new FecQuicConnectionDebugVisitor());
2673 connection_.set_debug_visitor(fec_visitor.get());
2675 QuicPacketSequenceNumber fec_packet = 0;
2676 QuicConnectionIdLength lengths[] = {PACKET_8BYTE_CONNECTION_ID,
2677 PACKET_4BYTE_CONNECTION_ID,
2678 PACKET_1BYTE_CONNECTION_ID,
2679 PACKET_0BYTE_CONNECTION_ID};
2680 // For each connection id length size, revive a packet and check connection
2681 // id length in the revived packet.
2682 for (size_t i = 0; i < arraysize(lengths); ++i) {
2683 // Set connection id length (for data and FEC packets).
2684 connection_id_length_ = lengths[i];
2685 fec_packet += 2;
2686 // Don't send missing packet, but send fec packet right after it.
2687 ProcessFecPacket(fec_packet, fec_packet - 1, true, !kEntropyFlag, nullptr);
2688 // Connection id length in the revived header should be the same as
2689 // in the original data/fec packet headers.
2690 EXPECT_EQ(connection_id_length_,
2691 fec_visitor->revived_header().public_header.connection_id_length);
2695 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPacketThenFecPacket) {
2696 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2698 ProcessFecProtectedPacket(1, false, kEntropyFlag);
2699 // Don't send missing packet 2.
2700 ProcessFecPacket(3, 1, true, !kEntropyFlag, nullptr);
2701 // Entropy flag should be true, so entropy should not be 0.
2702 EXPECT_NE(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2705 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPacketsThenFecPacket) {
2706 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2708 ProcessFecProtectedPacket(1, false, !kEntropyFlag);
2709 // Don't send missing packet 2.
2710 ProcessFecProtectedPacket(3, false, !kEntropyFlag);
2711 ProcessFecPacket(4, 1, true, kEntropyFlag, nullptr);
2712 // Ensure QUIC no longer revives entropy for lost packets.
2713 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2714 EXPECT_NE(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 4));
2717 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPacket) {
2718 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2720 // Don't send missing packet 1.
2721 ProcessFecPacket(3, 1, false, !kEntropyFlag, nullptr);
2722 // Out of order.
2723 ProcessFecProtectedPacket(2, true, !kEntropyFlag);
2724 // Entropy flag should be false, so entropy should be 0.
2725 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2728 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPackets) {
2729 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2731 ProcessFecProtectedPacket(1, false, !kEntropyFlag);
2732 // Don't send missing packet 2.
2733 ProcessFecPacket(6, 1, false, kEntropyFlag, nullptr);
2734 ProcessFecProtectedPacket(3, false, kEntropyFlag);
2735 ProcessFecProtectedPacket(4, false, kEntropyFlag);
2736 ProcessFecProtectedPacket(5, true, !kEntropyFlag);
2737 // Ensure entropy is not revived for the missing packet.
2738 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2739 EXPECT_NE(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 3));
2742 TEST_P(QuicConnectionTest, TLP) {
2743 QuicSentPacketManagerPeer::SetMaxTailLossProbes(manager_, 1);
2745 SendStreamDataToPeer(3, "foo", 0, !kFin, nullptr);
2746 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2747 QuicTime retransmission_time =
2748 connection_.GetRetransmissionAlarm()->deadline();
2749 EXPECT_NE(QuicTime::Zero(), retransmission_time);
2751 EXPECT_EQ(1u, writer_->header().packet_sequence_number);
2752 // Simulate the retransmission alarm firing and sending a tlp,
2753 // so send algorithm's OnRetransmissionTimeout is not called.
2754 clock_.AdvanceTime(retransmission_time.Subtract(clock_.Now()));
2755 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 2u, _, _));
2756 connection_.GetRetransmissionAlarm()->Fire();
2757 EXPECT_EQ(2u, writer_->header().packet_sequence_number);
2758 // We do not raise the high water mark yet.
2759 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2762 TEST_P(QuicConnectionTest, RTO) {
2763 QuicTime default_retransmission_time = clock_.ApproximateNow().Add(
2764 DefaultRetransmissionTime());
2765 SendStreamDataToPeer(3, "foo", 0, !kFin, nullptr);
2766 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2768 EXPECT_EQ(1u, writer_->header().packet_sequence_number);
2769 EXPECT_EQ(default_retransmission_time,
2770 connection_.GetRetransmissionAlarm()->deadline());
2771 // Simulate the retransmission alarm firing.
2772 clock_.AdvanceTime(DefaultRetransmissionTime());
2773 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 2u, _, _));
2774 connection_.GetRetransmissionAlarm()->Fire();
2775 EXPECT_EQ(2u, writer_->header().packet_sequence_number);
2776 // We do not raise the high water mark yet.
2777 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2780 TEST_P(QuicConnectionTest, RTOWithSameEncryptionLevel) {
2781 QuicTime default_retransmission_time = clock_.ApproximateNow().Add(
2782 DefaultRetransmissionTime());
2783 use_tagging_decrypter();
2785 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
2786 // the end of the packet. We can test this to check which encrypter was used.
2787 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2788 SendStreamDataToPeer(3, "foo", 0, !kFin, nullptr);
2789 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
2791 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2792 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2793 SendStreamDataToPeer(3, "foo", 0, !kFin, nullptr);
2794 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2796 EXPECT_EQ(default_retransmission_time,
2797 connection_.GetRetransmissionAlarm()->deadline());
2799 InSequence s;
2800 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 3, _, _));
2801 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 4, _, _));
2804 // Simulate the retransmission alarm firing.
2805 clock_.AdvanceTime(DefaultRetransmissionTime());
2806 connection_.GetRetransmissionAlarm()->Fire();
2808 // Packet should have been sent with ENCRYPTION_NONE.
2809 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_previous_packet());
2811 // Packet should have been sent with ENCRYPTION_INITIAL.
2812 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2815 TEST_P(QuicConnectionTest, SendHandshakeMessages) {
2816 use_tagging_decrypter();
2817 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
2818 // the end of the packet. We can test this to check which encrypter was used.
2819 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2821 // Attempt to send a handshake message and have the socket block.
2822 EXPECT_CALL(*send_algorithm_,
2823 TimeUntilSend(_, _, _)).WillRepeatedly(
2824 testing::Return(QuicTime::Delta::Zero()));
2825 BlockOnNextWrite();
2826 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
2827 // The packet should be serialized, but not queued.
2828 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2830 // Switch to the new encrypter.
2831 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2832 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2834 // Now become writeable and flush the packets.
2835 writer_->SetWritable();
2836 EXPECT_CALL(visitor_, OnCanWrite());
2837 connection_.OnCanWrite();
2838 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2840 // Verify that the handshake packet went out at the null encryption.
2841 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
2844 TEST_P(QuicConnectionTest,
2845 DropRetransmitsForNullEncryptedPacketAfterForwardSecure) {
2846 use_tagging_decrypter();
2847 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2848 QuicPacketSequenceNumber sequence_number;
2849 SendStreamDataToPeer(3, "foo", 0, !kFin, &sequence_number);
2851 // Simulate the retransmission alarm firing and the socket blocking.
2852 BlockOnNextWrite();
2853 clock_.AdvanceTime(DefaultRetransmissionTime());
2854 connection_.GetRetransmissionAlarm()->Fire();
2856 // Go forward secure.
2857 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
2858 new TaggingEncrypter(0x02));
2859 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2860 connection_.NeuterUnencryptedPackets();
2862 EXPECT_EQ(QuicTime::Zero(),
2863 connection_.GetRetransmissionAlarm()->deadline());
2864 // Unblock the socket and ensure that no packets are sent.
2865 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
2866 writer_->SetWritable();
2867 connection_.OnCanWrite();
2870 TEST_P(QuicConnectionTest, RetransmitPacketsWithInitialEncryption) {
2871 use_tagging_decrypter();
2872 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2873 connection_.SetDefaultEncryptionLevel(ENCRYPTION_NONE);
2875 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr);
2877 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2878 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2880 SendStreamDataToPeer(2, "bar", 0, !kFin, nullptr);
2881 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2883 connection_.RetransmitUnackedPackets(ALL_INITIAL_RETRANSMISSION);
2886 TEST_P(QuicConnectionTest, DelayForwardSecureEncryptionUntilClientIsReady) {
2887 // A TaggingEncrypter puts kTagSize copies of the given byte (0x02 here) at
2888 // the end of the packet. We can test this to check which encrypter was used.
2889 use_tagging_decrypter();
2890 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2891 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2892 SendAckPacketToPeer();
2893 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2895 // Set a forward-secure encrypter but do not make it the default, and verify
2896 // that it is not yet used.
2897 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
2898 new TaggingEncrypter(0x03));
2899 SendAckPacketToPeer();
2900 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2902 // Now simulate receipt of a forward-secure packet and verify that the
2903 // forward-secure encrypter is now used.
2904 connection_.OnDecryptedPacket(ENCRYPTION_FORWARD_SECURE);
2905 SendAckPacketToPeer();
2906 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
2909 TEST_P(QuicConnectionTest, DelayForwardSecureEncryptionUntilManyPacketSent) {
2910 // Set a congestion window of 10 packets.
2911 QuicPacketCount congestion_window = 10;
2912 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
2913 Return(congestion_window * kDefaultMaxPacketSize));
2915 // A TaggingEncrypter puts kTagSize copies of the given byte (0x02 here) at
2916 // the end of the packet. We can test this to check which encrypter was used.
2917 use_tagging_decrypter();
2918 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2919 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2920 SendAckPacketToPeer();
2921 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2923 // Set a forward-secure encrypter but do not make it the default, and
2924 // verify that it is not yet used.
2925 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
2926 new TaggingEncrypter(0x03));
2927 SendAckPacketToPeer();
2928 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2930 // Now send a packet "Far enough" after the encrypter was set and verify that
2931 // the forward-secure encrypter is now used.
2932 for (uint64 i = 0; i < 3 * congestion_window - 1; ++i) {
2933 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2934 SendAckPacketToPeer();
2936 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
2939 TEST_P(QuicConnectionTest, BufferNonDecryptablePackets) {
2940 // SetFromConfig is always called after construction from InitializeSession.
2941 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
2942 QuicConfig config;
2943 connection_.SetFromConfig(config);
2944 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2945 use_tagging_decrypter();
2947 const uint8 tag = 0x07;
2948 framer_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
2950 // Process an encrypted packet which can not yet be decrypted which should
2951 // result in the packet being buffered.
2952 ProcessDataPacketAtLevel(1, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2954 // Transition to the new encryption state and process another encrypted packet
2955 // which should result in the original packet being processed.
2956 connection_.SetDecrypter(ENCRYPTION_INITIAL, new StrictTaggingDecrypter(tag));
2957 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2958 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
2959 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(2);
2960 ProcessDataPacketAtLevel(2, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2962 // Finally, process a third packet and note that we do not reprocess the
2963 // buffered packet.
2964 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2965 ProcessDataPacketAtLevel(3, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2968 TEST_P(QuicConnectionTest, Buffer100NonDecryptablePackets) {
2969 // SetFromConfig is always called after construction from InitializeSession.
2970 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
2971 QuicConfig config;
2972 config.set_max_undecryptable_packets(100);
2973 connection_.SetFromConfig(config);
2974 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2975 use_tagging_decrypter();
2977 const uint8 tag = 0x07;
2978 framer_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
2980 // Process an encrypted packet which can not yet be decrypted which should
2981 // result in the packet being buffered.
2982 for (QuicPacketSequenceNumber i = 1; i <= 100; ++i) {
2983 ProcessDataPacketAtLevel(i, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2986 // Transition to the new encryption state and process another encrypted packet
2987 // which should result in the original packets being processed.
2988 connection_.SetDecrypter(ENCRYPTION_INITIAL, new StrictTaggingDecrypter(tag));
2989 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2990 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
2991 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(101);
2992 ProcessDataPacketAtLevel(101, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2994 // Finally, process a third packet and note that we do not reprocess the
2995 // buffered packet.
2996 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2997 ProcessDataPacketAtLevel(102, 0, kEntropyFlag, ENCRYPTION_INITIAL);
3000 TEST_P(QuicConnectionTest, TestRetransmitOrder) {
3001 QuicByteCount first_packet_size;
3002 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).WillOnce(
3003 DoAll(SaveArg<3>(&first_packet_size), Return(true)));
3005 connection_.SendStreamDataWithString(3, "first_packet", 0, !kFin, nullptr);
3006 QuicByteCount second_packet_size;
3007 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).WillOnce(
3008 DoAll(SaveArg<3>(&second_packet_size), Return(true)));
3009 connection_.SendStreamDataWithString(3, "second_packet", 12, !kFin, nullptr);
3010 EXPECT_NE(first_packet_size, second_packet_size);
3011 // Advance the clock by huge time to make sure packets will be retransmitted.
3012 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
3014 InSequence s;
3015 EXPECT_CALL(*send_algorithm_,
3016 OnPacketSent(_, _, _, first_packet_size, _));
3017 EXPECT_CALL(*send_algorithm_,
3018 OnPacketSent(_, _, _, second_packet_size, _));
3020 connection_.GetRetransmissionAlarm()->Fire();
3022 // Advance again and expect the packets to be sent again in the same order.
3023 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(20));
3025 InSequence s;
3026 EXPECT_CALL(*send_algorithm_,
3027 OnPacketSent(_, _, _, first_packet_size, _));
3028 EXPECT_CALL(*send_algorithm_,
3029 OnPacketSent(_, _, _, second_packet_size, _));
3031 connection_.GetRetransmissionAlarm()->Fire();
3034 TEST_P(QuicConnectionTest, SetRTOAfterWritingToSocket) {
3035 BlockOnNextWrite();
3036 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
3037 // Make sure that RTO is not started when the packet is queued.
3038 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3040 // Test that RTO is started once we write to the socket.
3041 writer_->SetWritable();
3042 connection_.OnCanWrite();
3043 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3046 TEST_P(QuicConnectionTest, DelayRTOWithAckReceipt) {
3047 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3048 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3049 .Times(2);
3050 connection_.SendStreamDataWithString(2, "foo", 0, !kFin, nullptr);
3051 connection_.SendStreamDataWithString(3, "bar", 0, !kFin, nullptr);
3052 QuicAlarm* retransmission_alarm = connection_.GetRetransmissionAlarm();
3053 EXPECT_TRUE(retransmission_alarm->IsSet());
3054 EXPECT_EQ(clock_.Now().Add(DefaultRetransmissionTime()),
3055 retransmission_alarm->deadline());
3057 // Advance the time right before the RTO, then receive an ack for the first
3058 // packet to delay the RTO.
3059 clock_.AdvanceTime(DefaultRetransmissionTime());
3060 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3061 QuicAckFrame ack = InitAckFrame(1);
3062 ProcessAckPacket(&ack);
3063 EXPECT_TRUE(retransmission_alarm->IsSet());
3064 EXPECT_GT(retransmission_alarm->deadline(), clock_.Now());
3066 // Move forward past the original RTO and ensure the RTO is still pending.
3067 clock_.AdvanceTime(DefaultRetransmissionTime().Multiply(2));
3069 // Ensure the second packet gets retransmitted when it finally fires.
3070 EXPECT_TRUE(retransmission_alarm->IsSet());
3071 EXPECT_LT(retransmission_alarm->deadline(), clock_.ApproximateNow());
3072 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3073 // Manually cancel the alarm to simulate a real test.
3074 connection_.GetRetransmissionAlarm()->Fire();
3076 // The new retransmitted sequence number should set the RTO to a larger value
3077 // than previously.
3078 EXPECT_TRUE(retransmission_alarm->IsSet());
3079 QuicTime next_rto_time = retransmission_alarm->deadline();
3080 QuicTime expected_rto_time =
3081 connection_.sent_packet_manager().GetRetransmissionTime();
3082 EXPECT_EQ(next_rto_time, expected_rto_time);
3085 TEST_P(QuicConnectionTest, TestQueued) {
3086 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3087 BlockOnNextWrite();
3088 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
3089 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3091 // Unblock the writes and actually send.
3092 writer_->SetWritable();
3093 connection_.OnCanWrite();
3094 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3097 TEST_P(QuicConnectionTest, CloseFecGroup) {
3098 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3099 // Don't send missing packet 1.
3100 // Don't send missing packet 2.
3101 ProcessFecProtectedPacket(3, false, !kEntropyFlag);
3102 // Don't send missing FEC packet 3.
3103 ASSERT_EQ(1u, connection_.NumFecGroups());
3105 // Now send non-fec protected ack packet and close the group.
3106 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 4);
3107 QuicStopWaitingFrame frame = InitStopWaitingFrame(5);
3108 ProcessStopWaitingPacket(&frame);
3109 ASSERT_EQ(0u, connection_.NumFecGroups());
3112 TEST_P(QuicConnectionTest, InitialTimeout) {
3113 EXPECT_TRUE(connection_.connected());
3114 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
3115 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3117 // SetFromConfig sets the initial timeouts before negotiation.
3118 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3119 QuicConfig config;
3120 connection_.SetFromConfig(config);
3121 // Subtract a second from the idle timeout on the client side.
3122 QuicTime default_timeout = clock_.ApproximateNow().Add(
3123 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1));
3124 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
3126 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_CONNECTION_TIMED_OUT, false));
3127 // Simulate the timeout alarm firing.
3128 clock_.AdvanceTime(
3129 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1));
3130 connection_.GetTimeoutAlarm()->Fire();
3132 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3133 EXPECT_FALSE(connection_.connected());
3135 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3136 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
3137 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
3138 EXPECT_FALSE(connection_.GetResumeWritesAlarm()->IsSet());
3139 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3140 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
3141 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
3144 TEST_P(QuicConnectionTest, OverallTimeout) {
3145 // Use a shorter overall connection timeout than idle timeout for this test.
3146 const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(5);
3147 connection_.SetNetworkTimeouts(timeout, timeout);
3148 EXPECT_TRUE(connection_.connected());
3149 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
3151 QuicTime overall_timeout = clock_.ApproximateNow().Add(timeout).Subtract(
3152 QuicTime::Delta::FromSeconds(1));
3153 EXPECT_EQ(overall_timeout, connection_.GetTimeoutAlarm()->deadline());
3154 EXPECT_TRUE(connection_.connected());
3156 // Send and ack new data 3 seconds later to lengthen the idle timeout.
3157 SendStreamDataToPeer(1, "GET /", 0, kFin, nullptr);
3158 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(3));
3159 QuicAckFrame frame = InitAckFrame(1);
3160 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3161 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3162 ProcessAckPacket(&frame);
3164 // Fire early to verify it wouldn't timeout yet.
3165 connection_.GetTimeoutAlarm()->Fire();
3166 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
3167 EXPECT_TRUE(connection_.connected());
3169 clock_.AdvanceTime(timeout.Subtract(QuicTime::Delta::FromSeconds(2)));
3171 EXPECT_CALL(visitor_,
3172 OnConnectionClosed(QUIC_CONNECTION_OVERALL_TIMED_OUT, false));
3173 // Simulate the timeout alarm firing.
3174 connection_.GetTimeoutAlarm()->Fire();
3176 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3177 EXPECT_FALSE(connection_.connected());
3179 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3180 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
3181 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
3182 EXPECT_FALSE(connection_.GetResumeWritesAlarm()->IsSet());
3183 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3184 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
3187 TEST_P(QuicConnectionTest, PingAfterSend) {
3188 EXPECT_TRUE(connection_.connected());
3189 EXPECT_CALL(visitor_, HasOpenDynamicStreams()).WillRepeatedly(Return(true));
3190 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
3192 // Advance to 5ms, and send a packet to the peer, which will set
3193 // the ping alarm.
3194 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
3195 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3196 SendStreamDataToPeer(1, "GET /", 0, kFin, nullptr);
3197 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
3198 EXPECT_EQ(clock_.ApproximateNow().Add(QuicTime::Delta::FromSeconds(15)),
3199 connection_.GetPingAlarm()->deadline());
3201 // Now recevie and ACK of the previous packet, which will move the
3202 // ping alarm forward.
3203 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
3204 QuicAckFrame frame = InitAckFrame(1);
3205 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3206 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3207 ProcessAckPacket(&frame);
3208 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
3209 // The ping timer is set slightly less than 15 seconds in the future, because
3210 // of the 1s ping timer alarm granularity.
3211 EXPECT_EQ(clock_.ApproximateNow().Add(QuicTime::Delta::FromSeconds(15))
3212 .Subtract(QuicTime::Delta::FromMilliseconds(5)),
3213 connection_.GetPingAlarm()->deadline());
3215 writer_->Reset();
3216 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15));
3217 connection_.GetPingAlarm()->Fire();
3218 EXPECT_EQ(1u, writer_->frame_count());
3219 ASSERT_EQ(1u, writer_->ping_frames().size());
3220 writer_->Reset();
3222 EXPECT_CALL(visitor_, HasOpenDynamicStreams()).WillRepeatedly(Return(false));
3223 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
3224 SendAckPacketToPeer();
3226 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
3229 // Tests whether sending an MTU discovery packet to peer successfully causes the
3230 // maximum packet size to increase.
3231 TEST_P(QuicConnectionTest, SendMtuDiscoveryPacket) {
3232 EXPECT_TRUE(connection_.connected());
3234 // Send an MTU probe.
3235 const size_t new_mtu = kDefaultMaxPacketSize + 100;
3236 QuicByteCount mtu_probe_size;
3237 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3238 .WillOnce(DoAll(SaveArg<3>(&mtu_probe_size), Return(true)));
3239 connection_.SendMtuDiscoveryPacket(new_mtu);
3240 EXPECT_EQ(new_mtu, mtu_probe_size);
3241 EXPECT_EQ(1u, creator_->sequence_number());
3243 // Send more than MTU worth of data. No acknowledgement was received so far,
3244 // so the MTU should be at its old value.
3245 const string data(kDefaultMaxPacketSize + 1, '.');
3246 QuicByteCount size_before_mtu_change;
3247 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3248 .WillOnce(DoAll(SaveArg<3>(&size_before_mtu_change), Return(true)))
3249 .WillOnce(Return(true));
3250 connection_.SendStreamDataWithString(3, data, 0, kFin, nullptr);
3251 EXPECT_EQ(3u, creator_->sequence_number());
3252 EXPECT_EQ(kDefaultMaxPacketSize, size_before_mtu_change);
3254 // Acknowledge all packets so far.
3255 QuicAckFrame probe_ack = InitAckFrame(3);
3256 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3257 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3258 ProcessAckPacket(&probe_ack);
3259 EXPECT_EQ(new_mtu, connection_.max_packet_length());
3261 // Send the same data again. Check that it fits into a single packet now.
3262 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3263 connection_.SendStreamDataWithString(3, data, 0, kFin, nullptr);
3264 EXPECT_EQ(4u, creator_->sequence_number());
3267 // Tests whether MTU discovery does not happen when it is not explicitly enabled
3268 // by the connection options.
3269 TEST_P(QuicConnectionTest, MtuDiscoveryDisabled) {
3270 EXPECT_TRUE(connection_.connected());
3272 // Restore the current value FLAGS_quic_do_path_mtu_discovery after the test.
3273 ValueRestore<bool> old_flag(&FLAGS_quic_do_path_mtu_discovery, true);
3275 const QuicPacketCount number_of_packets = kPacketsBetweenMtuProbesBase * 2;
3276 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
3277 SendStreamDataToPeer(3, ".", i, /*fin=*/false, nullptr);
3278 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
3282 // Tests whether MTU discovery works when the probe gets acknowledged on the
3283 // first try.
3284 TEST_P(QuicConnectionTest, MtuDiscoveryEnabled) {
3285 EXPECT_TRUE(connection_.connected());
3287 // Restore the current value FLAGS_quic_do_path_mtu_discovery after the test.
3288 ValueRestore<bool> old_flag(&FLAGS_quic_do_path_mtu_discovery, true);
3289 connection_.EnablePathMtuDiscovery(send_algorithm_);
3291 // Send enough packets so that the next one triggers path MTU discovery.
3292 for (QuicPacketCount i = 0; i < kPacketsBetweenMtuProbesBase - 1; i++) {
3293 SendStreamDataToPeer(3, ".", i, /*fin=*/false, nullptr);
3294 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
3297 // Trigger the probe.
3298 SendStreamDataToPeer(3, "!", kPacketsBetweenMtuProbesBase,
3299 /*fin=*/false, nullptr);
3300 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
3301 QuicByteCount probe_size;
3302 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3303 .WillOnce(DoAll(SaveArg<3>(&probe_size), Return(true)));
3304 connection_.GetMtuDiscoveryAlarm()->Fire();
3305 EXPECT_EQ(kMtuDiscoveryTargetPacketSizeHigh, probe_size);
3307 const QuicPacketCount probe_sequence_number =
3308 kPacketsBetweenMtuProbesBase + 1;
3309 ASSERT_EQ(probe_sequence_number, creator_->sequence_number());
3311 // Acknowledge all packets sent so far.
3312 QuicAckFrame probe_ack = InitAckFrame(probe_sequence_number);
3313 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3314 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3315 ProcessAckPacket(&probe_ack);
3316 EXPECT_EQ(kMtuDiscoveryTargetPacketSizeHigh, connection_.max_packet_length());
3318 // Send more packets, and ensure that none of them sets the alarm.
3319 for (QuicPacketCount i = 0; i < 4 * kPacketsBetweenMtuProbesBase; i++) {
3320 SendStreamDataToPeer(3, ".", i, /*fin=*/false, nullptr);
3321 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
3325 // Tests whether MTU discovery works correctly when the probes never get
3326 // acknowledged.
3327 TEST_P(QuicConnectionTest, MtuDiscoveryFailed) {
3328 EXPECT_TRUE(connection_.connected());
3330 // Restore the current value FLAGS_quic_do_path_mtu_discovery after the test.
3331 ValueRestore<bool> old_flag(&FLAGS_quic_do_path_mtu_discovery, true);
3332 connection_.EnablePathMtuDiscovery(send_algorithm_);
3334 const QuicTime::Delta rtt = QuicTime::Delta::FromMilliseconds(100);
3336 // This tests sends more packets than strictly necessary to make sure that if
3337 // the connection was to send more discovery packets than needed, those would
3338 // get caught as well.
3339 const QuicPacketCount number_of_packets =
3340 kPacketsBetweenMtuProbesBase * (1 << (kMtuDiscoveryAttempts + 1));
3341 vector<QuicPacketSequenceNumber> mtu_discovery_packets;
3342 // Called by the first ack.
3343 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3344 // Called on many acks.
3345 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _))
3346 .Times(AnyNumber());
3347 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
3348 SendStreamDataToPeer(3, "!", i, /*fin=*/false, nullptr);
3349 clock_.AdvanceTime(rtt);
3351 // Receive an ACK, which marks all data packets as received, and all MTU
3352 // discovery packets as missing.
3353 QuicAckFrame ack = InitAckFrame(creator_->sequence_number());
3354 ack.missing_packets = SequenceNumberSet(mtu_discovery_packets.begin(),
3355 mtu_discovery_packets.end());
3356 ProcessAckPacket(&ack);
3358 // Trigger MTU probe if it would be scheduled now.
3359 if (!connection_.GetMtuDiscoveryAlarm()->IsSet()) {
3360 continue;
3363 // Fire the alarm. The alarm should cause a packet to be sent.
3364 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3365 .WillOnce(Return(true));
3366 connection_.GetMtuDiscoveryAlarm()->Fire();
3367 // Record the sequence number of the MTU discovery packet in order to
3368 // mark it as NACK'd.
3369 mtu_discovery_packets.push_back(creator_->sequence_number());
3372 // Ensure the number of packets between probes grows exponentially by checking
3373 // it against the closed-form expression for the sequence number.
3374 ASSERT_EQ(kMtuDiscoveryAttempts, mtu_discovery_packets.size());
3375 for (QuicPacketSequenceNumber i = 0; i < kMtuDiscoveryAttempts; i++) {
3376 // 2^0 + 2^1 + 2^2 + ... + 2^n = 2^(n + 1) - 1
3377 const QuicPacketCount packets_between_probes =
3378 kPacketsBetweenMtuProbesBase * ((1 << (i + 1)) - 1);
3379 EXPECT_EQ(packets_between_probes + (i + 1), mtu_discovery_packets[i]);
3382 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
3383 EXPECT_EQ(kDefaultMaxPacketSize, connection_.max_packet_length());
3386 TEST_P(QuicConnectionTest, NoMtuDiscoveryAfterConnectionClosed) {
3387 EXPECT_TRUE(connection_.connected());
3389 // Restore the current value FLAGS_quic_do_path_mtu_discovery after the test.
3390 ValueRestore<bool> old_flag(&FLAGS_quic_do_path_mtu_discovery, true);
3391 connection_.EnablePathMtuDiscovery(send_algorithm_);
3393 // Send enough packets so that the next one triggers path MTU discovery.
3394 for (QuicPacketCount i = 0; i < kPacketsBetweenMtuProbesBase - 1; i++) {
3395 SendStreamDataToPeer(3, ".", i, /*fin=*/false, nullptr);
3396 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
3399 SendStreamDataToPeer(3, "!", kPacketsBetweenMtuProbesBase,
3400 /*fin=*/false, nullptr);
3401 EXPECT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
3403 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
3404 connection_.CloseConnection(QUIC_INTERNAL_ERROR, /*from_peer=*/false);
3405 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
3408 TEST_P(QuicConnectionTest, TimeoutAfterSend) {
3409 EXPECT_TRUE(connection_.connected());
3410 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3411 QuicConfig config;
3412 connection_.SetFromConfig(config);
3413 EXPECT_FALSE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
3415 const QuicTime::Delta initial_idle_timeout =
3416 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
3417 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
3418 QuicTime default_timeout = clock_.ApproximateNow().Add(initial_idle_timeout);
3420 // When we send a packet, the timeout will change to 5ms +
3421 // kInitialIdleTimeoutSecs.
3422 clock_.AdvanceTime(five_ms);
3424 // Send an ack so we don't set the retransmission alarm.
3425 SendAckPacketToPeer();
3426 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
3428 // The original alarm will fire. We should not time out because we had a
3429 // network event at t=5ms. The alarm will reregister.
3430 clock_.AdvanceTime(initial_idle_timeout.Subtract(five_ms));
3431 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
3432 connection_.GetTimeoutAlarm()->Fire();
3433 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
3434 EXPECT_TRUE(connection_.connected());
3435 EXPECT_EQ(default_timeout.Add(five_ms),
3436 connection_.GetTimeoutAlarm()->deadline());
3438 // This time, we should time out.
3439 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_CONNECTION_TIMED_OUT, false));
3440 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3441 clock_.AdvanceTime(five_ms);
3442 EXPECT_EQ(default_timeout.Add(five_ms), clock_.ApproximateNow());
3443 connection_.GetTimeoutAlarm()->Fire();
3444 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3445 EXPECT_FALSE(connection_.connected());
3448 TEST_P(QuicConnectionTest, TimeoutAfterSendSilentClose) {
3449 // Same test as above, but complete a handshake which enables silent close,
3450 // causing no connection close packet to be sent.
3451 EXPECT_TRUE(connection_.connected());
3452 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3453 QuicConfig config;
3455 // Create a handshake message that also enables silent close.
3456 CryptoHandshakeMessage msg;
3457 string error_details;
3458 QuicConfig client_config;
3459 client_config.SetInitialStreamFlowControlWindowToSend(
3460 kInitialStreamFlowControlWindowForTest);
3461 client_config.SetInitialSessionFlowControlWindowToSend(
3462 kInitialSessionFlowControlWindowForTest);
3463 client_config.SetIdleConnectionStateLifetime(
3464 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs),
3465 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs));
3466 client_config.ToHandshakeMessage(&msg);
3467 const QuicErrorCode error =
3468 config.ProcessPeerHello(msg, CLIENT, &error_details);
3469 EXPECT_EQ(QUIC_NO_ERROR, error);
3471 connection_.SetFromConfig(config);
3472 EXPECT_TRUE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
3474 const QuicTime::Delta default_idle_timeout =
3475 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs - 1);
3476 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
3477 QuicTime default_timeout = clock_.ApproximateNow().Add(default_idle_timeout);
3479 // When we send a packet, the timeout will change to 5ms +
3480 // kInitialIdleTimeoutSecs.
3481 clock_.AdvanceTime(five_ms);
3483 // Send an ack so we don't set the retransmission alarm.
3484 SendAckPacketToPeer();
3485 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
3487 // The original alarm will fire. We should not time out because we had a
3488 // network event at t=5ms. The alarm will reregister.
3489 clock_.AdvanceTime(default_idle_timeout.Subtract(five_ms));
3490 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
3491 connection_.GetTimeoutAlarm()->Fire();
3492 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
3493 EXPECT_TRUE(connection_.connected());
3494 EXPECT_EQ(default_timeout.Add(five_ms),
3495 connection_.GetTimeoutAlarm()->deadline());
3497 // This time, we should time out.
3498 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_CONNECTION_TIMED_OUT, false));
3499 clock_.AdvanceTime(five_ms);
3500 EXPECT_EQ(default_timeout.Add(five_ms), clock_.ApproximateNow());
3501 connection_.GetTimeoutAlarm()->Fire();
3502 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3503 EXPECT_FALSE(connection_.connected());
3506 TEST_P(QuicConnectionTest, SendScheduler) {
3507 // Test that if we send a packet without delay, it is not queued.
3508 QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
3509 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3510 connection_.SendPacket(
3511 ENCRYPTION_NONE, 1, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA);
3512 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3515 TEST_P(QuicConnectionTest, SendSchedulerEAGAIN) {
3516 QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
3517 BlockOnNextWrite();
3518 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 1, _, _)).Times(0);
3519 connection_.SendPacket(
3520 ENCRYPTION_NONE, 1, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA);
3521 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3524 TEST_P(QuicConnectionTest, TestQueueLimitsOnSendStreamData) {
3525 // All packets carry version info till version is negotiated.
3526 size_t payload_length;
3527 size_t length = GetPacketLengthForOneStream(
3528 connection_.version(), kIncludeVersion,
3529 PACKET_8BYTE_CONNECTION_ID, PACKET_1BYTE_SEQUENCE_NUMBER,
3530 NOT_IN_FEC_GROUP, &payload_length);
3531 connection_.set_max_packet_length(length);
3533 // Queue the first packet.
3534 EXPECT_CALL(*send_algorithm_,
3535 TimeUntilSend(_, _, _)).WillOnce(
3536 testing::Return(QuicTime::Delta::FromMicroseconds(10)));
3537 const string payload(payload_length, 'a');
3538 EXPECT_EQ(0u, connection_.SendStreamDataWithString(3, payload, 0, !kFin,
3539 nullptr).bytes_consumed);
3540 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3543 TEST_P(QuicConnectionTest, LoopThroughSendingPackets) {
3544 // All packets carry version info till version is negotiated.
3545 size_t payload_length;
3546 // GetPacketLengthForOneStream() assumes a stream offset of 0 in determining
3547 // packet length. The size of the offset field in a stream frame is 0 for
3548 // offset 0, and 2 for non-zero offsets up through 16K. Increase
3549 // max_packet_length by 2 so that subsequent packets containing subsequent
3550 // stream frames with non-zero offets will fit within the packet length.
3551 size_t length = 2 + GetPacketLengthForOneStream(
3552 connection_.version(), kIncludeVersion,
3553 PACKET_8BYTE_CONNECTION_ID, PACKET_1BYTE_SEQUENCE_NUMBER,
3554 NOT_IN_FEC_GROUP, &payload_length);
3555 connection_.set_max_packet_length(length);
3557 // Queue the first packet.
3558 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(7);
3559 // The first stream frame will have 2 fewer overhead bytes than the other six.
3560 const string payload(payload_length * 7 + 2, 'a');
3561 EXPECT_EQ(payload.size(),
3562 connection_.SendStreamDataWithString(1, payload, 0, !kFin, nullptr)
3563 .bytes_consumed);
3566 TEST_P(QuicConnectionTest, LoopThroughSendingPacketsWithTruncation) {
3567 // Set up a larger payload than will fit in one packet.
3568 const string payload(connection_.max_packet_length(), 'a');
3569 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
3571 // Now send some packets with no truncation.
3572 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3573 EXPECT_EQ(payload.size(),
3574 connection_.SendStreamDataWithString(
3575 3, payload, 0, !kFin, nullptr).bytes_consumed);
3576 // Track the size of the second packet here. The overhead will be the largest
3577 // we see in this test, due to the non-truncated connection id.
3578 size_t non_truncated_packet_size = writer_->last_packet_size();
3580 // Change to a 4 byte connection id.
3581 QuicConfig config;
3582 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 4);
3583 connection_.SetFromConfig(config);
3584 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3585 EXPECT_EQ(payload.size(),
3586 connection_.SendStreamDataWithString(
3587 3, payload, 0, !kFin, nullptr).bytes_consumed);
3588 // Verify that we have 8 fewer bytes than in the non-truncated case. The
3589 // first packet got 4 bytes of extra payload due to the truncation, and the
3590 // headers here are also 4 byte smaller.
3591 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() + 8);
3593 // Change to a 1 byte connection id.
3594 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 1);
3595 connection_.SetFromConfig(config);
3596 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3597 EXPECT_EQ(payload.size(),
3598 connection_.SendStreamDataWithString(
3599 3, payload, 0, !kFin, nullptr).bytes_consumed);
3600 // Just like above, we save 7 bytes on payload, and 7 on truncation.
3601 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() + 7 * 2);
3603 // Change to a 0 byte connection id.
3604 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
3605 connection_.SetFromConfig(config);
3606 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3607 EXPECT_EQ(payload.size(),
3608 connection_.SendStreamDataWithString(
3609 3, payload, 0, !kFin, nullptr).bytes_consumed);
3610 // Just like above, we save 8 bytes on payload, and 8 on truncation.
3611 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() + 8 * 2);
3614 TEST_P(QuicConnectionTest, SendDelayedAck) {
3615 QuicTime ack_time = clock_.ApproximateNow().Add(DefaultDelayedAckTime());
3616 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3617 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3618 const uint8 tag = 0x07;
3619 connection_.SetDecrypter(ENCRYPTION_INITIAL, new StrictTaggingDecrypter(tag));
3620 framer_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
3621 // Process a packet from the non-crypto stream.
3622 frame1_.stream_id = 3;
3624 // The same as ProcessPacket(1) except that ENCRYPTION_INITIAL is used
3625 // instead of ENCRYPTION_NONE.
3626 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3627 ProcessDataPacketAtLevel(1, 0, !kEntropyFlag, ENCRYPTION_INITIAL);
3629 // Check if delayed ack timer is running for the expected interval.
3630 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3631 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
3632 // Simulate delayed ack alarm firing.
3633 connection_.GetAckAlarm()->Fire();
3634 // Check that ack is sent and that delayed ack alarm is reset.
3635 EXPECT_EQ(2u, writer_->frame_count());
3636 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3637 EXPECT_FALSE(writer_->ack_frames().empty());
3638 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3641 TEST_P(QuicConnectionTest, SendDelayedAckOnHandshakeConfirmed) {
3642 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3643 ProcessPacket(1);
3644 // Check that ack is sent and that delayed ack alarm is set.
3645 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3646 QuicTime ack_time = clock_.ApproximateNow().Add(DefaultDelayedAckTime());
3647 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
3649 // Completing the handshake as the server does nothing.
3650 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_SERVER);
3651 connection_.OnHandshakeComplete();
3652 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3653 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
3655 // Complete the handshake as the client decreases the delayed ack time to 0ms.
3656 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_CLIENT);
3657 connection_.OnHandshakeComplete();
3658 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3659 EXPECT_EQ(clock_.ApproximateNow(), connection_.GetAckAlarm()->deadline());
3662 TEST_P(QuicConnectionTest, SendDelayedAckOnSecondPacket) {
3663 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3664 ProcessPacket(1);
3665 ProcessPacket(2);
3666 // Check that ack is sent and that delayed ack alarm is reset.
3667 EXPECT_EQ(2u, writer_->frame_count());
3668 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3669 EXPECT_FALSE(writer_->ack_frames().empty());
3670 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3673 TEST_P(QuicConnectionTest, NoAckOnOldNacks) {
3674 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3675 // Drop one packet, triggering a sequence of acks.
3676 ProcessPacket(2);
3677 size_t frames_per_ack = 2;
3678 EXPECT_EQ(frames_per_ack, writer_->frame_count());
3679 EXPECT_FALSE(writer_->ack_frames().empty());
3680 writer_->Reset();
3681 ProcessPacket(3);
3682 EXPECT_EQ(frames_per_ack, writer_->frame_count());
3683 EXPECT_FALSE(writer_->ack_frames().empty());
3684 writer_->Reset();
3685 ProcessPacket(4);
3686 EXPECT_EQ(frames_per_ack, writer_->frame_count());
3687 EXPECT_FALSE(writer_->ack_frames().empty());
3688 writer_->Reset();
3689 ProcessPacket(5);
3690 EXPECT_EQ(frames_per_ack, writer_->frame_count());
3691 EXPECT_FALSE(writer_->ack_frames().empty());
3692 writer_->Reset();
3693 // Now only set the timer on the 6th packet, instead of sending another ack.
3694 ProcessPacket(6);
3695 EXPECT_EQ(0u, writer_->frame_count());
3696 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3699 TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingPacket) {
3700 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3701 ProcessPacket(1);
3702 connection_.SendStreamDataWithString(kClientDataStreamId1, "foo", 0, !kFin,
3703 nullptr);
3704 // Check that ack is bundled with outgoing data and that delayed ack
3705 // alarm is reset.
3706 EXPECT_EQ(3u, writer_->frame_count());
3707 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3708 EXPECT_FALSE(writer_->ack_frames().empty());
3709 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3712 TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingCryptoPacket) {
3713 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3714 ProcessPacket(1);
3715 connection_.SendStreamDataWithString(kCryptoStreamId, "foo", 0, !kFin,
3716 nullptr);
3717 // Check that ack is bundled with outgoing crypto data.
3718 EXPECT_EQ(3u, writer_->frame_count());
3719 EXPECT_FALSE(writer_->ack_frames().empty());
3720 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3723 TEST_P(QuicConnectionTest, BlockAndBufferOnFirstCHLOPacketOfTwo) {
3724 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3725 ProcessPacket(1);
3726 BlockOnNextWrite();
3727 writer_->set_is_write_blocked_data_buffered(true);
3728 connection_.SendStreamDataWithString(kCryptoStreamId, "foo", 0, !kFin,
3729 nullptr);
3730 EXPECT_TRUE(writer_->IsWriteBlocked());
3731 EXPECT_FALSE(connection_.HasQueuedData());
3732 connection_.SendStreamDataWithString(kCryptoStreamId, "bar", 3, !kFin,
3733 nullptr);
3734 EXPECT_TRUE(writer_->IsWriteBlocked());
3735 EXPECT_TRUE(connection_.HasQueuedData());
3738 TEST_P(QuicConnectionTest, BundleAckForSecondCHLO) {
3739 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3740 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3741 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(
3742 IgnoreResult(InvokeWithoutArgs(&connection_,
3743 &TestConnection::SendCryptoStreamData)));
3744 // Process a packet from the crypto stream, which is frame1_'s default.
3745 // Receiving the CHLO as packet 2 first will cause the connection to
3746 // immediately send an ack, due to the packet gap.
3747 ProcessPacket(2);
3748 // Check that ack is sent and that delayed ack alarm is reset.
3749 EXPECT_EQ(3u, writer_->frame_count());
3750 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3751 EXPECT_EQ(1u, writer_->stream_frames().size());
3752 EXPECT_FALSE(writer_->ack_frames().empty());
3753 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3756 TEST_P(QuicConnectionTest, BundleAckWithDataOnIncomingAck) {
3757 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3758 connection_.SendStreamDataWithString(kClientDataStreamId1, "foo", 0, !kFin,
3759 nullptr);
3760 connection_.SendStreamDataWithString(kClientDataStreamId1, "foo", 3, !kFin,
3761 nullptr);
3762 // Ack the second packet, which will retransmit the first packet.
3763 QuicAckFrame ack = InitAckFrame(2);
3764 NackPacket(1, &ack);
3765 SequenceNumberSet lost_packets;
3766 lost_packets.insert(1);
3767 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3768 .WillOnce(Return(lost_packets));
3769 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3770 ProcessAckPacket(&ack);
3771 EXPECT_EQ(1u, writer_->frame_count());
3772 EXPECT_EQ(1u, writer_->stream_frames().size());
3773 writer_->Reset();
3775 // Now ack the retransmission, which will both raise the high water mark
3776 // and see if there is more data to send.
3777 ack = InitAckFrame(3);
3778 NackPacket(1, &ack);
3779 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3780 .WillOnce(Return(SequenceNumberSet()));
3781 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3782 ProcessAckPacket(&ack);
3784 // Check that no packet is sent and the ack alarm isn't set.
3785 EXPECT_EQ(0u, writer_->frame_count());
3786 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3787 writer_->Reset();
3789 // Send the same ack, but send both data and an ack together.
3790 ack = InitAckFrame(3);
3791 NackPacket(1, &ack);
3792 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3793 .WillOnce(Return(SequenceNumberSet()));
3794 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(
3795 IgnoreResult(InvokeWithoutArgs(
3796 &connection_,
3797 &TestConnection::EnsureWritableAndSendStreamData5)));
3798 ProcessAckPacket(&ack);
3800 // Check that ack is bundled with outgoing data and the delayed ack
3801 // alarm is reset.
3802 EXPECT_EQ(3u, writer_->frame_count());
3803 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3804 EXPECT_FALSE(writer_->ack_frames().empty());
3805 EXPECT_EQ(1u, writer_->stream_frames().size());
3806 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3809 TEST_P(QuicConnectionTest, NoAckSentForClose) {
3810 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3811 ProcessPacket(1);
3812 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, true));
3813 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3814 ProcessClosePacket(2, 0);
3817 TEST_P(QuicConnectionTest, SendWhenDisconnected) {
3818 EXPECT_TRUE(connection_.connected());
3819 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, false));
3820 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, false);
3821 EXPECT_FALSE(connection_.connected());
3822 EXPECT_FALSE(connection_.CanWriteStreamData());
3823 QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
3824 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 1, _, _)).Times(0);
3825 connection_.SendPacket(
3826 ENCRYPTION_NONE, 1, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA);
3829 TEST_P(QuicConnectionTest, PublicReset) {
3830 QuicPublicResetPacket header;
3831 header.public_header.connection_id = connection_id_;
3832 header.public_header.reset_flag = true;
3833 header.public_header.version_flag = false;
3834 header.rejected_sequence_number = 10101;
3835 scoped_ptr<QuicEncryptedPacket> packet(
3836 framer_.BuildPublicResetPacket(header));
3837 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PUBLIC_RESET, true));
3838 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *packet);
3841 TEST_P(QuicConnectionTest, GoAway) {
3842 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3844 QuicGoAwayFrame goaway;
3845 goaway.last_good_stream_id = 1;
3846 goaway.error_code = QUIC_PEER_GOING_AWAY;
3847 goaway.reason_phrase = "Going away.";
3848 EXPECT_CALL(visitor_, OnGoAway(_));
3849 ProcessGoAwayPacket(&goaway);
3852 TEST_P(QuicConnectionTest, WindowUpdate) {
3853 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3855 QuicWindowUpdateFrame window_update;
3856 window_update.stream_id = 3;
3857 window_update.byte_offset = 1234;
3858 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
3859 ProcessFramePacket(QuicFrame(&window_update));
3862 TEST_P(QuicConnectionTest, Blocked) {
3863 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3865 QuicBlockedFrame blocked;
3866 blocked.stream_id = 3;
3867 EXPECT_CALL(visitor_, OnBlockedFrame(_));
3868 ProcessFramePacket(QuicFrame(&blocked));
3871 TEST_P(QuicConnectionTest, ZeroBytePacket) {
3872 // Don't close the connection for zero byte packets.
3873 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
3874 QuicEncryptedPacket encrypted(nullptr, 0);
3875 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), encrypted);
3878 TEST_P(QuicConnectionTest, MissingPacketsBeforeLeastUnacked) {
3879 // Set the sequence number of the ack packet to be least unacked (4).
3880 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 3);
3881 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3882 QuicStopWaitingFrame frame = InitStopWaitingFrame(4);
3883 ProcessStopWaitingPacket(&frame);
3884 EXPECT_TRUE(outgoing_ack()->missing_packets.empty());
3887 TEST_P(QuicConnectionTest, ReceivedEntropyHashCalculation) {
3888 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AtLeast(1));
3889 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3890 ProcessDataPacket(1, 1, kEntropyFlag);
3891 ProcessDataPacket(4, 1, kEntropyFlag);
3892 ProcessDataPacket(3, 1, !kEntropyFlag);
3893 ProcessDataPacket(7, 1, kEntropyFlag);
3894 EXPECT_EQ(146u, outgoing_ack()->entropy_hash);
3897 TEST_P(QuicConnectionTest, ReceivedEntropyHashCalculationHalfFEC) {
3898 // FEC packets should not change the entropy hash calculation.
3899 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AtLeast(1));
3900 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3901 ProcessDataPacket(1, 1, kEntropyFlag);
3902 ProcessFecPacket(4, 1, false, kEntropyFlag, nullptr);
3903 ProcessDataPacket(3, 3, !kEntropyFlag);
3904 ProcessFecPacket(7, 3, false, kEntropyFlag, nullptr);
3905 EXPECT_EQ(146u, outgoing_ack()->entropy_hash);
3908 TEST_P(QuicConnectionTest, UpdateEntropyForReceivedPackets) {
3909 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AtLeast(1));
3910 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3911 ProcessDataPacket(1, 1, kEntropyFlag);
3912 ProcessDataPacket(5, 1, kEntropyFlag);
3913 ProcessDataPacket(4, 1, !kEntropyFlag);
3914 EXPECT_EQ(34u, outgoing_ack()->entropy_hash);
3915 // Make 4th packet my least unacked, and update entropy for 2, 3 packets.
3916 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 5);
3917 QuicPacketEntropyHash six_packet_entropy_hash = 0;
3918 QuicPacketEntropyHash random_entropy_hash = 129u;
3919 QuicStopWaitingFrame frame = InitStopWaitingFrame(4);
3920 frame.entropy_hash = random_entropy_hash;
3921 if (ProcessStopWaitingPacket(&frame)) {
3922 six_packet_entropy_hash = 1 << 6;
3925 EXPECT_EQ((random_entropy_hash + (1 << 5) + six_packet_entropy_hash),
3926 outgoing_ack()->entropy_hash);
3929 TEST_P(QuicConnectionTest, UpdateEntropyHashUptoCurrentPacket) {
3930 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AtLeast(1));
3931 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3932 ProcessDataPacket(1, 1, kEntropyFlag);
3933 ProcessDataPacket(5, 1, !kEntropyFlag);
3934 ProcessDataPacket(22, 1, kEntropyFlag);
3935 EXPECT_EQ(66u, outgoing_ack()->entropy_hash);
3936 QuicPacketCreatorPeer::SetSequenceNumber(&peer_creator_, 22);
3937 QuicPacketEntropyHash random_entropy_hash = 85u;
3938 // Current packet is the least unacked packet.
3939 QuicPacketEntropyHash ack_entropy_hash;
3940 QuicStopWaitingFrame frame = InitStopWaitingFrame(23);
3941 frame.entropy_hash = random_entropy_hash;
3942 ack_entropy_hash = ProcessStopWaitingPacket(&frame);
3943 EXPECT_EQ((random_entropy_hash + ack_entropy_hash),
3944 outgoing_ack()->entropy_hash);
3945 ProcessDataPacket(25, 1, kEntropyFlag);
3946 EXPECT_EQ((random_entropy_hash + ack_entropy_hash + (1 << (25 % 8))),
3947 outgoing_ack()->entropy_hash);
3950 TEST_P(QuicConnectionTest, EntropyCalculationForTruncatedAck) {
3951 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AtLeast(1));
3952 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3953 QuicPacketEntropyHash entropy[51];
3954 entropy[0] = 0;
3955 for (int i = 1; i < 51; ++i) {
3956 bool should_send = i % 10 != 1;
3957 bool entropy_flag = (i & (i - 1)) != 0;
3958 if (!should_send) {
3959 entropy[i] = entropy[i - 1];
3960 continue;
3962 if (entropy_flag) {
3963 entropy[i] = entropy[i - 1] ^ (1 << (i % 8));
3964 } else {
3965 entropy[i] = entropy[i - 1];
3967 ProcessDataPacket(i, 1, entropy_flag);
3969 for (int i = 1; i < 50; ++i) {
3970 EXPECT_EQ(entropy[i], QuicConnectionPeer::ReceivedEntropyHash(
3971 &connection_, i));
3975 TEST_P(QuicConnectionTest, ServerSendsVersionNegotiationPacket) {
3976 connection_.SetSupportedVersions(QuicSupportedVersions());
3977 framer_.set_version_for_tests(QUIC_VERSION_UNSUPPORTED);
3979 QuicPacketHeader header;
3980 header.public_header.connection_id = connection_id_;
3981 header.public_header.version_flag = true;
3982 header.packet_sequence_number = 12;
3984 QuicFrames frames;
3985 frames.push_back(QuicFrame(&frame1_));
3986 scoped_ptr<QuicPacket> packet(ConstructPacket(header, frames));
3987 char buffer[kMaxPacketSize];
3988 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPayload(
3989 ENCRYPTION_NONE, 12, *packet, buffer, kMaxPacketSize));
3991 framer_.set_version(version());
3992 connection_.set_perspective(Perspective::IS_SERVER);
3993 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3994 EXPECT_TRUE(writer_->version_negotiation_packet() != nullptr);
3996 size_t num_versions = arraysize(kSupportedQuicVersions);
3997 ASSERT_EQ(num_versions,
3998 writer_->version_negotiation_packet()->versions.size());
4000 // We expect all versions in kSupportedQuicVersions to be
4001 // included in the packet.
4002 for (size_t i = 0; i < num_versions; ++i) {
4003 EXPECT_EQ(kSupportedQuicVersions[i],
4004 writer_->version_negotiation_packet()->versions[i]);
4008 TEST_P(QuicConnectionTest, ServerSendsVersionNegotiationPacketSocketBlocked) {
4009 connection_.SetSupportedVersions(QuicSupportedVersions());
4010 framer_.set_version_for_tests(QUIC_VERSION_UNSUPPORTED);
4012 QuicPacketHeader header;
4013 header.public_header.connection_id = connection_id_;
4014 header.public_header.version_flag = true;
4015 header.packet_sequence_number = 12;
4017 QuicFrames frames;
4018 frames.push_back(QuicFrame(&frame1_));
4019 scoped_ptr<QuicPacket> packet(ConstructPacket(header, frames));
4020 char buffer[kMaxPacketSize];
4021 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPayload(
4022 ENCRYPTION_NONE, 12, *packet, buffer, kMaxPacketSize));
4024 framer_.set_version(version());
4025 connection_.set_perspective(Perspective::IS_SERVER);
4026 BlockOnNextWrite();
4027 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
4028 EXPECT_EQ(0u, writer_->last_packet_size());
4029 EXPECT_TRUE(connection_.HasQueuedData());
4031 writer_->SetWritable();
4032 connection_.OnCanWrite();
4033 EXPECT_TRUE(writer_->version_negotiation_packet() != nullptr);
4035 size_t num_versions = arraysize(kSupportedQuicVersions);
4036 ASSERT_EQ(num_versions,
4037 writer_->version_negotiation_packet()->versions.size());
4039 // We expect all versions in kSupportedQuicVersions to be
4040 // included in the packet.
4041 for (size_t i = 0; i < num_versions; ++i) {
4042 EXPECT_EQ(kSupportedQuicVersions[i],
4043 writer_->version_negotiation_packet()->versions[i]);
4047 TEST_P(QuicConnectionTest,
4048 ServerSendsVersionNegotiationPacketSocketBlockedDataBuffered) {
4049 connection_.SetSupportedVersions(QuicSupportedVersions());
4050 framer_.set_version_for_tests(QUIC_VERSION_UNSUPPORTED);
4052 QuicPacketHeader header;
4053 header.public_header.connection_id = connection_id_;
4054 header.public_header.version_flag = true;
4055 header.packet_sequence_number = 12;
4057 QuicFrames frames;
4058 frames.push_back(QuicFrame(&frame1_));
4059 scoped_ptr<QuicPacket> packet(ConstructPacket(header, frames));
4060 char buffer[kMaxPacketSize];
4061 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPayload(
4062 ENCRYPTION_NONE, 12, *packet, buffer, kMaxPacketSize));
4064 framer_.set_version(version());
4065 connection_.set_perspective(Perspective::IS_SERVER);
4066 BlockOnNextWrite();
4067 writer_->set_is_write_blocked_data_buffered(true);
4068 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
4069 EXPECT_EQ(0u, writer_->last_packet_size());
4070 EXPECT_FALSE(connection_.HasQueuedData());
4073 TEST_P(QuicConnectionTest, ClientHandlesVersionNegotiation) {
4074 // Start out with some unsupported version.
4075 QuicConnectionPeer::GetFramer(&connection_)->set_version_for_tests(
4076 QUIC_VERSION_UNSUPPORTED);
4078 QuicPacketHeader header;
4079 header.public_header.connection_id = connection_id_;
4080 header.public_header.version_flag = true;
4081 header.packet_sequence_number = 12;
4083 QuicVersionVector supported_versions;
4084 for (size_t i = 0; i < arraysize(kSupportedQuicVersions); ++i) {
4085 supported_versions.push_back(kSupportedQuicVersions[i]);
4088 // Send a version negotiation packet.
4089 scoped_ptr<QuicEncryptedPacket> encrypted(
4090 framer_.BuildVersionNegotiationPacket(
4091 header.public_header, supported_versions));
4092 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
4094 // Now force another packet. The connection should transition into
4095 // NEGOTIATED_VERSION state and tell the packet creator to StopSendingVersion.
4096 header.public_header.version_flag = false;
4097 QuicFrames frames;
4098 frames.push_back(QuicFrame(&frame1_));
4099 scoped_ptr<QuicPacket> packet(ConstructPacket(header, frames));
4100 char buffer[kMaxPacketSize];
4101 encrypted.reset(framer_.EncryptPayload(ENCRYPTION_NONE, 12, *packet, buffer,
4102 kMaxPacketSize));
4103 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4104 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4105 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
4107 ASSERT_FALSE(QuicPacketCreatorPeer::SendVersionInPacket(creator_));
4110 TEST_P(QuicConnectionTest, BadVersionNegotiation) {
4111 QuicPacketHeader header;
4112 header.public_header.connection_id = connection_id_;
4113 header.public_header.version_flag = true;
4114 header.packet_sequence_number = 12;
4116 QuicVersionVector supported_versions;
4117 for (size_t i = 0; i < arraysize(kSupportedQuicVersions); ++i) {
4118 supported_versions.push_back(kSupportedQuicVersions[i]);
4121 // Send a version negotiation packet with the version the client started with.
4122 // It should be rejected.
4123 EXPECT_CALL(visitor_,
4124 OnConnectionClosed(QUIC_INVALID_VERSION_NEGOTIATION_PACKET,
4125 false));
4126 scoped_ptr<QuicEncryptedPacket> encrypted(
4127 framer_.BuildVersionNegotiationPacket(
4128 header.public_header, supported_versions));
4129 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
4132 TEST_P(QuicConnectionTest, CheckSendStats) {
4133 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4134 connection_.SendStreamDataWithString(3, "first", 0, !kFin, nullptr);
4135 size_t first_packet_size = writer_->last_packet_size();
4137 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4138 connection_.SendStreamDataWithString(5, "second", 0, !kFin, nullptr);
4139 size_t second_packet_size = writer_->last_packet_size();
4141 // 2 retransmissions due to rto, 1 due to explicit nack.
4142 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
4143 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
4145 // Retransmit due to RTO.
4146 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
4147 connection_.GetRetransmissionAlarm()->Fire();
4149 // Retransmit due to explicit nacks.
4150 QuicAckFrame nack_three = InitAckFrame(4);
4151 NackPacket(3, &nack_three);
4152 NackPacket(1, &nack_three);
4153 SequenceNumberSet lost_packets;
4154 lost_packets.insert(1);
4155 lost_packets.insert(3);
4156 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4157 .WillOnce(Return(lost_packets));
4158 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4159 EXPECT_CALL(visitor_, OnCanWrite());
4160 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4161 ProcessAckPacket(&nack_three);
4163 EXPECT_CALL(*send_algorithm_, BandwidthEstimate()).WillOnce(
4164 Return(QuicBandwidth::Zero()));
4166 const QuicConnectionStats& stats = connection_.GetStats();
4167 EXPECT_EQ(3 * first_packet_size + 2 * second_packet_size - kQuicVersionSize,
4168 stats.bytes_sent);
4169 EXPECT_EQ(5u, stats.packets_sent);
4170 EXPECT_EQ(2 * first_packet_size + second_packet_size - kQuicVersionSize,
4171 stats.bytes_retransmitted);
4172 EXPECT_EQ(3u, stats.packets_retransmitted);
4173 EXPECT_EQ(1u, stats.rto_count);
4174 EXPECT_EQ(kDefaultMaxPacketSize, stats.max_packet_size);
4177 TEST_P(QuicConnectionTest, CheckReceiveStats) {
4178 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4180 size_t received_bytes = 0;
4181 received_bytes += ProcessFecProtectedPacket(1, false, !kEntropyFlag);
4182 received_bytes += ProcessFecProtectedPacket(3, false, !kEntropyFlag);
4183 // Should be counted against dropped packets.
4184 received_bytes += ProcessDataPacket(3, 1, !kEntropyFlag);
4185 received_bytes += ProcessFecPacket(4, 1, true, !kEntropyFlag, nullptr);
4187 EXPECT_CALL(*send_algorithm_, BandwidthEstimate()).WillOnce(
4188 Return(QuicBandwidth::Zero()));
4190 const QuicConnectionStats& stats = connection_.GetStats();
4191 EXPECT_EQ(received_bytes, stats.bytes_received);
4192 EXPECT_EQ(4u, stats.packets_received);
4194 EXPECT_EQ(1u, stats.packets_revived);
4195 EXPECT_EQ(1u, stats.packets_dropped);
4198 TEST_P(QuicConnectionTest, TestFecGroupLimits) {
4199 // Create and return a group for 1.
4200 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 1) != nullptr);
4202 // Create and return a group for 2.
4203 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 2) != nullptr);
4205 // Create and return a group for 4. This should remove 1 but not 2.
4206 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 4) != nullptr);
4207 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 1) == nullptr);
4208 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 2) != nullptr);
4210 // Create and return a group for 3. This will kill off 2.
4211 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 3) != nullptr);
4212 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 2) == nullptr);
4214 // Verify that adding 5 kills off 3, despite 4 being created before 3.
4215 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 5) != nullptr);
4216 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 4) != nullptr);
4217 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 3) == nullptr);
4220 TEST_P(QuicConnectionTest, ProcessFramesIfPacketClosedConnection) {
4221 // Construct a packet with stream frame and connection close frame.
4222 QuicPacketHeader header;
4223 header.public_header.connection_id = connection_id_;
4224 header.packet_sequence_number = 1;
4225 header.public_header.version_flag = false;
4227 QuicConnectionCloseFrame qccf;
4228 qccf.error_code = QUIC_PEER_GOING_AWAY;
4230 QuicFrames frames;
4231 frames.push_back(QuicFrame(&frame1_));
4232 frames.push_back(QuicFrame(&qccf));
4233 scoped_ptr<QuicPacket> packet(ConstructPacket(header, frames));
4234 EXPECT_TRUE(nullptr != packet.get());
4235 char buffer[kMaxPacketSize];
4236 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPayload(
4237 ENCRYPTION_NONE, 1, *packet, buffer, kMaxPacketSize));
4239 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, true));
4240 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4241 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4243 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
4246 TEST_P(QuicConnectionTest, SelectMutualVersion) {
4247 connection_.SetSupportedVersions(QuicSupportedVersions());
4248 // Set the connection to speak the lowest quic version.
4249 connection_.set_version(QuicVersionMin());
4250 EXPECT_EQ(QuicVersionMin(), connection_.version());
4252 // Pass in available versions which includes a higher mutually supported
4253 // version. The higher mutually supported version should be selected.
4254 QuicVersionVector supported_versions;
4255 for (size_t i = 0; i < arraysize(kSupportedQuicVersions); ++i) {
4256 supported_versions.push_back(kSupportedQuicVersions[i]);
4258 EXPECT_TRUE(connection_.SelectMutualVersion(supported_versions));
4259 EXPECT_EQ(QuicVersionMax(), connection_.version());
4261 // Expect that the lowest version is selected.
4262 // Ensure the lowest supported version is less than the max, unless they're
4263 // the same.
4264 EXPECT_LE(QuicVersionMin(), QuicVersionMax());
4265 QuicVersionVector lowest_version_vector;
4266 lowest_version_vector.push_back(QuicVersionMin());
4267 EXPECT_TRUE(connection_.SelectMutualVersion(lowest_version_vector));
4268 EXPECT_EQ(QuicVersionMin(), connection_.version());
4270 // Shouldn't be able to find a mutually supported version.
4271 QuicVersionVector unsupported_version;
4272 unsupported_version.push_back(QUIC_VERSION_UNSUPPORTED);
4273 EXPECT_FALSE(connection_.SelectMutualVersion(unsupported_version));
4276 TEST_P(QuicConnectionTest, ConnectionCloseWhenWritable) {
4277 EXPECT_FALSE(writer_->IsWriteBlocked());
4279 // Send a packet.
4280 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
4281 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4282 EXPECT_EQ(1u, writer_->packets_write_attempts());
4284 TriggerConnectionClose();
4285 EXPECT_EQ(2u, writer_->packets_write_attempts());
4288 TEST_P(QuicConnectionTest, ConnectionCloseGettingWriteBlocked) {
4289 BlockOnNextWrite();
4290 TriggerConnectionClose();
4291 EXPECT_EQ(1u, writer_->packets_write_attempts());
4292 EXPECT_TRUE(writer_->IsWriteBlocked());
4295 TEST_P(QuicConnectionTest, ConnectionCloseWhenWriteBlocked) {
4296 BlockOnNextWrite();
4297 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
4298 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4299 EXPECT_EQ(1u, writer_->packets_write_attempts());
4300 EXPECT_TRUE(writer_->IsWriteBlocked());
4301 TriggerConnectionClose();
4302 EXPECT_EQ(1u, writer_->packets_write_attempts());
4305 TEST_P(QuicConnectionTest, AckNotifierTriggerCallback) {
4306 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4308 // Create a delegate which we expect to be called.
4309 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4310 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(1);
4312 // Send some data, which will register the delegate to be notified.
4313 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
4315 // Process an ACK from the server which should trigger the callback.
4316 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4317 QuicAckFrame frame = InitAckFrame(1);
4318 ProcessAckPacket(&frame);
4321 TEST_P(QuicConnectionTest, AckNotifierFailToTriggerCallback) {
4322 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4324 // Create a delegate which we don't expect to be called.
4325 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4326 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(0);
4328 // Send some data, which will register the delegate to be notified. This will
4329 // not be ACKed and so the delegate should never be called.
4330 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
4332 // Send some other data which we will ACK.
4333 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
4334 connection_.SendStreamDataWithString(1, "bar", 0, !kFin, nullptr);
4336 // Now we receive ACK for packets 2 and 3, but importantly missing packet 1
4337 // which we registered to be notified about.
4338 QuicAckFrame frame = InitAckFrame(3);
4339 NackPacket(1, &frame);
4340 SequenceNumberSet lost_packets;
4341 lost_packets.insert(1);
4342 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4343 .WillOnce(Return(lost_packets));
4344 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4345 ProcessAckPacket(&frame);
4348 TEST_P(QuicConnectionTest, AckNotifierCallbackAfterRetransmission) {
4349 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4351 // Create a delegate which we expect to be called.
4352 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4353 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(1);
4355 // Send four packets, and register to be notified on ACK of packet 2.
4356 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
4357 connection_.SendStreamDataWithString(3, "bar", 0, !kFin, delegate.get());
4358 connection_.SendStreamDataWithString(3, "baz", 0, !kFin, nullptr);
4359 connection_.SendStreamDataWithString(3, "qux", 0, !kFin, nullptr);
4361 // Now we receive ACK for packets 1, 3, and 4 and lose 2.
4362 QuicAckFrame frame = InitAckFrame(4);
4363 NackPacket(2, &frame);
4364 SequenceNumberSet lost_packets;
4365 lost_packets.insert(2);
4366 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4367 .WillOnce(Return(lost_packets));
4368 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4369 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4370 ProcessAckPacket(&frame);
4372 // Now we get an ACK for packet 5 (retransmitted packet 2), which should
4373 // trigger the callback.
4374 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4375 .WillRepeatedly(Return(SequenceNumberSet()));
4376 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4377 QuicAckFrame second_ack_frame = InitAckFrame(5);
4378 ProcessAckPacket(&second_ack_frame);
4381 // AckNotifierCallback is triggered by the ack of a packet that timed
4382 // out and was retransmitted, even though the retransmission has a
4383 // different sequence number.
4384 TEST_P(QuicConnectionTest, AckNotifierCallbackForAckAfterRTO) {
4385 InSequence s;
4387 // Create a delegate which we expect to be called.
4388 scoped_refptr<MockAckNotifierDelegate> delegate(
4389 new StrictMock<MockAckNotifierDelegate>);
4391 QuicTime default_retransmission_time = clock_.ApproximateNow().Add(
4392 DefaultRetransmissionTime());
4393 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, delegate.get());
4394 EXPECT_EQ(1u, stop_waiting()->least_unacked);
4396 EXPECT_EQ(1u, writer_->header().packet_sequence_number);
4397 EXPECT_EQ(default_retransmission_time,
4398 connection_.GetRetransmissionAlarm()->deadline());
4399 // Simulate the retransmission alarm firing.
4400 clock_.AdvanceTime(DefaultRetransmissionTime());
4401 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 2u, _, _));
4402 connection_.GetRetransmissionAlarm()->Fire();
4403 EXPECT_EQ(2u, writer_->header().packet_sequence_number);
4404 // We do not raise the high water mark yet.
4405 EXPECT_EQ(1u, stop_waiting()->least_unacked);
4407 // Ack the original packet, which will revert the RTO.
4408 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4409 EXPECT_CALL(*delegate, OnAckNotification(1, _, _));
4410 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4411 QuicAckFrame ack_frame = InitAckFrame(1);
4412 ProcessAckPacket(&ack_frame);
4414 // Delegate is not notified again when the retransmit is acked.
4415 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4416 QuicAckFrame second_ack_frame = InitAckFrame(2);
4417 ProcessAckPacket(&second_ack_frame);
4420 // AckNotifierCallback is triggered by the ack of a packet that was
4421 // previously nacked, even though the retransmission has a different
4422 // sequence number.
4423 TEST_P(QuicConnectionTest, AckNotifierCallbackForAckOfNackedPacket) {
4424 InSequence s;
4426 // Create a delegate which we expect to be called.
4427 scoped_refptr<MockAckNotifierDelegate> delegate(
4428 new StrictMock<MockAckNotifierDelegate>);
4430 // Send four packets, and register to be notified on ACK of packet 2.
4431 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
4432 connection_.SendStreamDataWithString(3, "bar", 0, !kFin, delegate.get());
4433 connection_.SendStreamDataWithString(3, "baz", 0, !kFin, nullptr);
4434 connection_.SendStreamDataWithString(3, "qux", 0, !kFin, nullptr);
4436 // Now we receive ACK for packets 1, 3, and 4 and lose 2.
4437 QuicAckFrame frame = InitAckFrame(4);
4438 NackPacket(2, &frame);
4439 SequenceNumberSet lost_packets;
4440 lost_packets.insert(2);
4441 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4442 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4443 .WillOnce(Return(lost_packets));
4444 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4445 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4446 ProcessAckPacket(&frame);
4448 // Now we get an ACK for packet 2, which was previously nacked.
4449 SequenceNumberSet no_lost_packets;
4450 EXPECT_CALL(*delegate.get(), OnAckNotification(1, _, _));
4451 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4452 .WillOnce(Return(no_lost_packets));
4453 QuicAckFrame second_ack_frame = InitAckFrame(4);
4454 ProcessAckPacket(&second_ack_frame);
4456 // Verify that the delegate is not notified again when the
4457 // retransmit is acked.
4458 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4459 .WillOnce(Return(no_lost_packets));
4460 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4461 QuicAckFrame third_ack_frame = InitAckFrame(5);
4462 ProcessAckPacket(&third_ack_frame);
4465 TEST_P(QuicConnectionTest, AckNotifierFECTriggerCallback) {
4466 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4468 // Create a delegate which we expect to be called.
4469 scoped_refptr<MockAckNotifierDelegate> delegate(
4470 new MockAckNotifierDelegate);
4471 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(1);
4473 // Send some data, which will register the delegate to be notified.
4474 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
4475 connection_.SendStreamDataWithString(2, "bar", 0, !kFin, nullptr);
4477 // Process an ACK from the server with a revived packet, which should trigger
4478 // the callback.
4479 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4480 QuicAckFrame frame = InitAckFrame(2);
4481 NackPacket(1, &frame);
4482 frame.revived_packets.insert(1);
4483 ProcessAckPacket(&frame);
4484 // If the ack is processed again, the notifier should not be called again.
4485 ProcessAckPacket(&frame);
4488 TEST_P(QuicConnectionTest, AckNotifierCallbackAfterFECRecovery) {
4489 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4490 EXPECT_CALL(visitor_, OnCanWrite());
4492 // Create a delegate which we expect to be called.
4493 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4494 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(1);
4496 // Expect ACKs for 1 packet.
4497 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4499 // Send one packet, and register to be notified on ACK.
4500 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
4502 // Ack packet gets dropped, but we receive an FEC packet that covers it.
4503 // Should recover the Ack packet and trigger the notification callback.
4504 QuicFrames frames;
4506 QuicAckFrame ack_frame = InitAckFrame(1);
4507 frames.push_back(QuicFrame(&ack_frame));
4509 // Dummy stream frame to satisfy expectations set elsewhere.
4510 frames.push_back(QuicFrame(&frame1_));
4512 QuicPacketHeader ack_header;
4513 ack_header.public_header.connection_id = connection_id_;
4514 ack_header.public_header.reset_flag = false;
4515 ack_header.public_header.version_flag = false;
4516 ack_header.entropy_flag = !kEntropyFlag;
4517 ack_header.fec_flag = true;
4518 ack_header.packet_sequence_number = 1;
4519 ack_header.is_in_fec_group = IN_FEC_GROUP;
4520 ack_header.fec_group = 1;
4522 QuicPacket* packet = BuildUnsizedDataPacket(&framer_, ack_header, frames);
4524 // Take the packet which contains the ACK frame, and construct and deliver an
4525 // FEC packet which allows the ACK packet to be recovered.
4526 ProcessFecPacket(2, 1, true, !kEntropyFlag, packet);
4529 TEST_P(QuicConnectionTest, NetworkChangeVisitorCwndCallbackChangesFecState) {
4530 size_t max_packets_per_fec_group = creator_->max_packets_per_fec_group();
4532 QuicSentPacketManager::NetworkChangeVisitor* visitor =
4533 QuicSentPacketManagerPeer::GetNetworkChangeVisitor(manager_);
4534 EXPECT_TRUE(visitor);
4536 // Increase FEC group size by increasing congestion window to a large number.
4537 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
4538 Return(1000 * kDefaultTCPMSS));
4539 visitor->OnCongestionWindowChange();
4540 EXPECT_LT(max_packets_per_fec_group, creator_->max_packets_per_fec_group());
4543 TEST_P(QuicConnectionTest, NetworkChangeVisitorConfigCallbackChangesFecState) {
4544 QuicSentPacketManager::NetworkChangeVisitor* visitor =
4545 QuicSentPacketManagerPeer::GetNetworkChangeVisitor(manager_);
4546 EXPECT_TRUE(visitor);
4547 EXPECT_EQ(QuicTime::Delta::Zero(),
4548 QuicPacketGeneratorPeer::GetFecTimeout(generator_));
4550 // Verify that sending a config with a new initial rtt changes fec timeout.
4551 // Create and process a config with a non-zero initial RTT.
4552 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4553 QuicConfig config;
4554 config.SetInitialRoundTripTimeUsToSend(300000);
4555 connection_.SetFromConfig(config);
4556 EXPECT_LT(QuicTime::Delta::Zero(),
4557 QuicPacketGeneratorPeer::GetFecTimeout(generator_));
4560 TEST_P(QuicConnectionTest, NetworkChangeVisitorRttCallbackChangesFecState) {
4561 // Verify that sending a config with a new initial rtt changes fec timeout.
4562 QuicSentPacketManager::NetworkChangeVisitor* visitor =
4563 QuicSentPacketManagerPeer::GetNetworkChangeVisitor(manager_);
4564 EXPECT_TRUE(visitor);
4565 EXPECT_EQ(QuicTime::Delta::Zero(),
4566 QuicPacketGeneratorPeer::GetFecTimeout(generator_));
4568 // Increase FEC timeout by increasing RTT.
4569 RttStats* rtt_stats = QuicSentPacketManagerPeer::GetRttStats(manager_);
4570 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(300),
4571 QuicTime::Delta::Zero(), QuicTime::Zero());
4572 visitor->OnRttChange();
4573 EXPECT_LT(QuicTime::Delta::Zero(),
4574 QuicPacketGeneratorPeer::GetFecTimeout(generator_));
4577 TEST_P(QuicConnectionTest, OnPacketHeaderDebugVisitor) {
4578 QuicPacketHeader header;
4580 scoped_ptr<MockQuicConnectionDebugVisitor> debug_visitor(
4581 new MockQuicConnectionDebugVisitor());
4582 connection_.set_debug_visitor(debug_visitor.get());
4583 EXPECT_CALL(*debug_visitor, OnPacketHeader(Ref(header))).Times(1);
4584 connection_.OnPacketHeader(header);
4587 TEST_P(QuicConnectionTest, Pacing) {
4588 TestConnection server(connection_id_, IPEndPoint(), helper_.get(), factory_,
4589 Perspective::IS_SERVER, version());
4590 TestConnection client(connection_id_, IPEndPoint(), helper_.get(), factory_,
4591 Perspective::IS_CLIENT, version());
4592 EXPECT_FALSE(client.sent_packet_manager().using_pacing());
4593 EXPECT_FALSE(server.sent_packet_manager().using_pacing());
4596 TEST_P(QuicConnectionTest, ControlFramesInstigateAcks) {
4597 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4599 // Send a WINDOW_UPDATE frame.
4600 QuicWindowUpdateFrame window_update;
4601 window_update.stream_id = 3;
4602 window_update.byte_offset = 1234;
4603 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
4604 ProcessFramePacket(QuicFrame(&window_update));
4606 // Ensure that this has caused the ACK alarm to be set.
4607 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
4608 EXPECT_TRUE(ack_alarm->IsSet());
4610 // Cancel alarm, and try again with BLOCKED frame.
4611 ack_alarm->Cancel();
4612 QuicBlockedFrame blocked;
4613 blocked.stream_id = 3;
4614 EXPECT_CALL(visitor_, OnBlockedFrame(_));
4615 ProcessFramePacket(QuicFrame(&blocked));
4616 EXPECT_TRUE(ack_alarm->IsSet());
4619 TEST_P(QuicConnectionTest, NoDataNoFin) {
4620 // Make sure that a call to SendStreamWithData, with no data and no FIN, does
4621 // not result in a QuicAckNotifier being used-after-free (fail under ASAN).
4622 // Regression test for b/18594622
4623 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4624 EXPECT_DFATAL(
4625 connection_.SendStreamDataWithString(3, "", 0, !kFin, delegate.get()),
4626 "Attempt to send empty stream frame");
4629 TEST_P(QuicConnectionTest, FecSendPolicyReceivedConnectionOption) {
4630 // Test sending SetReceivedConnectionOptions when FEC send policy is
4631 // FEC_ANY_TRIGGER.
4632 if (GetParam().fec_send_policy == FEC_ALARM_TRIGGER) {
4633 return;
4635 ValueRestore<bool> old_flag(&FLAGS_quic_send_fec_packet_only_on_fec_alarm,
4636 true);
4637 connection_.set_perspective(Perspective::IS_SERVER);
4639 // Test ReceivedConnectionOptions.
4640 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4641 QuicConfig config;
4642 QuicTagVector copt;
4643 copt.push_back(kFSPA);
4644 QuicConfigPeer::SetReceivedConnectionOptions(&config, copt);
4645 EXPECT_EQ(FEC_ANY_TRIGGER, generator_->fec_send_policy());
4646 connection_.SetFromConfig(config);
4647 EXPECT_EQ(FEC_ALARM_TRIGGER, generator_->fec_send_policy());
4650 } // namespace
4651 } // namespace test
4652 } // namespace net