Updating trunk VERSION from 2139.0 to 2140.0
[chromium-blink-merge.git] / net / quic / quic_connection_test.cc
blob5befba789063c8ffd551fe2a6115df1dea2f16ed
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/quic/quic_connection.h"
7 #include "base/basictypes.h"
8 #include "base/bind.h"
9 #include "base/stl_util.h"
10 #include "net/base/net_errors.h"
11 #include "net/quic/congestion_control/loss_detection_interface.h"
12 #include "net/quic/congestion_control/receive_algorithm_interface.h"
13 #include "net/quic/congestion_control/send_algorithm_interface.h"
14 #include "net/quic/crypto/null_encrypter.h"
15 #include "net/quic/crypto/quic_decrypter.h"
16 #include "net/quic/crypto/quic_encrypter.h"
17 #include "net/quic/quic_flags.h"
18 #include "net/quic/quic_protocol.h"
19 #include "net/quic/quic_utils.h"
20 #include "net/quic/test_tools/mock_clock.h"
21 #include "net/quic/test_tools/mock_random.h"
22 #include "net/quic/test_tools/quic_connection_peer.h"
23 #include "net/quic/test_tools/quic_framer_peer.h"
24 #include "net/quic/test_tools/quic_packet_creator_peer.h"
25 #include "net/quic/test_tools/quic_sent_packet_manager_peer.h"
26 #include "net/quic/test_tools/quic_test_utils.h"
27 #include "net/quic/test_tools/simple_quic_framer.h"
28 #include "testing/gmock/include/gmock/gmock.h"
29 #include "testing/gtest/include/gtest/gtest.h"
31 using base::StringPiece;
32 using std::map;
33 using std::vector;
34 using testing::AnyNumber;
35 using testing::AtLeast;
36 using testing::ContainerEq;
37 using testing::Contains;
38 using testing::DoAll;
39 using testing::InSequence;
40 using testing::InvokeWithoutArgs;
41 using testing::NiceMock;
42 using testing::Ref;
43 using testing::Return;
44 using testing::SaveArg;
45 using testing::StrictMock;
46 using testing::_;
48 namespace net {
49 namespace test {
50 namespace {
52 const char data1[] = "foo";
53 const char data2[] = "bar";
55 const bool kFin = true;
56 const bool kEntropyFlag = true;
58 const QuicPacketEntropyHash kTestEntropyHash = 76;
60 const int kDefaultRetransmissionTimeMs = 500;
62 class TestReceiveAlgorithm : public ReceiveAlgorithmInterface {
63 public:
64 explicit TestReceiveAlgorithm(QuicCongestionFeedbackFrame* feedback)
65 : feedback_(feedback) {
68 bool GenerateCongestionFeedback(
69 QuicCongestionFeedbackFrame* congestion_feedback) {
70 if (feedback_ == NULL) {
71 return false;
73 *congestion_feedback = *feedback_;
74 return true;
77 MOCK_METHOD3(RecordIncomingPacket,
78 void(QuicByteCount, QuicPacketSequenceNumber, QuicTime));
80 private:
81 QuicCongestionFeedbackFrame* feedback_;
83 DISALLOW_COPY_AND_ASSIGN(TestReceiveAlgorithm);
86 // TaggingEncrypter appends kTagSize bytes of |tag| to the end of each message.
87 class TaggingEncrypter : public QuicEncrypter {
88 public:
89 explicit TaggingEncrypter(uint8 tag)
90 : tag_(tag) {
93 virtual ~TaggingEncrypter() {}
95 // QuicEncrypter interface.
96 virtual bool SetKey(StringPiece key) OVERRIDE { return true; }
97 virtual bool SetNoncePrefix(StringPiece nonce_prefix) OVERRIDE {
98 return true;
101 virtual bool Encrypt(StringPiece nonce,
102 StringPiece associated_data,
103 StringPiece plaintext,
104 unsigned char* output) OVERRIDE {
105 memcpy(output, plaintext.data(), plaintext.size());
106 output += plaintext.size();
107 memset(output, tag_, kTagSize);
108 return true;
111 virtual QuicData* EncryptPacket(QuicPacketSequenceNumber sequence_number,
112 StringPiece associated_data,
113 StringPiece plaintext) OVERRIDE {
114 const size_t len = plaintext.size() + kTagSize;
115 uint8* buffer = new uint8[len];
116 Encrypt(StringPiece(), associated_data, plaintext, buffer);
117 return new QuicData(reinterpret_cast<char*>(buffer), len, true);
120 virtual size_t GetKeySize() const OVERRIDE { return 0; }
121 virtual size_t GetNoncePrefixSize() const OVERRIDE { return 0; }
123 virtual size_t GetMaxPlaintextSize(size_t ciphertext_size) const OVERRIDE {
124 return ciphertext_size - kTagSize;
127 virtual size_t GetCiphertextSize(size_t plaintext_size) const OVERRIDE {
128 return plaintext_size + kTagSize;
131 virtual StringPiece GetKey() const OVERRIDE {
132 return StringPiece();
135 virtual StringPiece GetNoncePrefix() const OVERRIDE {
136 return StringPiece();
139 private:
140 enum {
141 kTagSize = 12,
144 const uint8 tag_;
146 DISALLOW_COPY_AND_ASSIGN(TaggingEncrypter);
149 // TaggingDecrypter ensures that the final kTagSize bytes of the message all
150 // have the same value and then removes them.
151 class TaggingDecrypter : public QuicDecrypter {
152 public:
153 virtual ~TaggingDecrypter() {}
155 // QuicDecrypter interface
156 virtual bool SetKey(StringPiece key) OVERRIDE { return true; }
157 virtual bool SetNoncePrefix(StringPiece nonce_prefix) OVERRIDE {
158 return true;
161 virtual bool Decrypt(StringPiece nonce,
162 StringPiece associated_data,
163 StringPiece ciphertext,
164 unsigned char* output,
165 size_t* output_length) OVERRIDE {
166 if (ciphertext.size() < kTagSize) {
167 return false;
169 if (!CheckTag(ciphertext, GetTag(ciphertext))) {
170 return false;
172 *output_length = ciphertext.size() - kTagSize;
173 memcpy(output, ciphertext.data(), *output_length);
174 return true;
177 virtual QuicData* DecryptPacket(QuicPacketSequenceNumber sequence_number,
178 StringPiece associated_data,
179 StringPiece ciphertext) OVERRIDE {
180 if (ciphertext.size() < kTagSize) {
181 return NULL;
183 if (!CheckTag(ciphertext, GetTag(ciphertext))) {
184 return NULL;
186 const size_t len = ciphertext.size() - kTagSize;
187 uint8* buf = new uint8[len];
188 memcpy(buf, ciphertext.data(), len);
189 return new QuicData(reinterpret_cast<char*>(buf), len,
190 true /* owns buffer */);
193 virtual StringPiece GetKey() const OVERRIDE { return StringPiece(); }
194 virtual StringPiece GetNoncePrefix() const OVERRIDE { return StringPiece(); }
196 protected:
197 virtual uint8 GetTag(StringPiece ciphertext) {
198 return ciphertext.data()[ciphertext.size()-1];
201 private:
202 enum {
203 kTagSize = 12,
206 bool CheckTag(StringPiece ciphertext, uint8 tag) {
207 for (size_t i = ciphertext.size() - kTagSize; i < ciphertext.size(); i++) {
208 if (ciphertext.data()[i] != tag) {
209 return false;
213 return true;
217 // StringTaggingDecrypter ensures that the final kTagSize bytes of the message
218 // match the expected value.
219 class StrictTaggingDecrypter : public TaggingDecrypter {
220 public:
221 explicit StrictTaggingDecrypter(uint8 tag) : tag_(tag) {}
222 virtual ~StrictTaggingDecrypter() {}
224 // TaggingQuicDecrypter
225 virtual uint8 GetTag(StringPiece ciphertext) OVERRIDE {
226 return tag_;
229 private:
230 const uint8 tag_;
233 class TestConnectionHelper : public QuicConnectionHelperInterface {
234 public:
235 class TestAlarm : public QuicAlarm {
236 public:
237 explicit TestAlarm(QuicAlarm::Delegate* delegate)
238 : QuicAlarm(delegate) {
241 virtual void SetImpl() OVERRIDE {}
242 virtual void CancelImpl() OVERRIDE {}
243 using QuicAlarm::Fire;
246 TestConnectionHelper(MockClock* clock, MockRandom* random_generator)
247 : clock_(clock),
248 random_generator_(random_generator) {
249 clock_->AdvanceTime(QuicTime::Delta::FromSeconds(1));
252 // QuicConnectionHelperInterface
253 virtual const QuicClock* GetClock() const OVERRIDE {
254 return clock_;
257 virtual QuicRandom* GetRandomGenerator() OVERRIDE {
258 return random_generator_;
261 virtual QuicAlarm* CreateAlarm(QuicAlarm::Delegate* delegate) OVERRIDE {
262 return new TestAlarm(delegate);
265 private:
266 MockClock* clock_;
267 MockRandom* random_generator_;
269 DISALLOW_COPY_AND_ASSIGN(TestConnectionHelper);
272 class TestPacketWriter : public QuicPacketWriter {
273 public:
274 explicit TestPacketWriter(QuicVersion version)
275 : version_(version),
276 framer_(SupportedVersions(version_)),
277 last_packet_size_(0),
278 write_blocked_(false),
279 block_on_next_write_(false),
280 is_write_blocked_data_buffered_(false),
281 final_bytes_of_last_packet_(0),
282 final_bytes_of_previous_packet_(0),
283 use_tagging_decrypter_(false),
284 packets_write_attempts_(0) {
287 // QuicPacketWriter interface
288 virtual WriteResult WritePacket(
289 const char* buffer, size_t buf_len,
290 const IPAddressNumber& self_address,
291 const IPEndPoint& peer_address) OVERRIDE {
292 QuicEncryptedPacket packet(buffer, buf_len);
293 ++packets_write_attempts_;
295 if (packet.length() >= sizeof(final_bytes_of_last_packet_)) {
296 final_bytes_of_previous_packet_ = final_bytes_of_last_packet_;
297 memcpy(&final_bytes_of_last_packet_, packet.data() + packet.length() - 4,
298 sizeof(final_bytes_of_last_packet_));
301 if (use_tagging_decrypter_) {
302 framer_.framer()->SetDecrypter(new TaggingDecrypter, ENCRYPTION_NONE);
304 EXPECT_TRUE(framer_.ProcessPacket(packet));
305 if (block_on_next_write_) {
306 write_blocked_ = true;
307 block_on_next_write_ = false;
309 if (IsWriteBlocked()) {
310 return WriteResult(WRITE_STATUS_BLOCKED, -1);
312 last_packet_size_ = packet.length();
313 return WriteResult(WRITE_STATUS_OK, last_packet_size_);
316 virtual bool IsWriteBlockedDataBuffered() const OVERRIDE {
317 return is_write_blocked_data_buffered_;
320 virtual bool IsWriteBlocked() const OVERRIDE { return write_blocked_; }
322 virtual void SetWritable() OVERRIDE { write_blocked_ = false; }
324 void BlockOnNextWrite() { block_on_next_write_ = true; }
326 const QuicPacketHeader& header() { return framer_.header(); }
328 size_t frame_count() const { return framer_.num_frames(); }
330 const vector<QuicAckFrame>& ack_frames() const {
331 return framer_.ack_frames();
334 const vector<QuicCongestionFeedbackFrame>& feedback_frames() const {
335 return framer_.feedback_frames();
338 const vector<QuicStopWaitingFrame>& stop_waiting_frames() const {
339 return framer_.stop_waiting_frames();
342 const vector<QuicConnectionCloseFrame>& connection_close_frames() const {
343 return framer_.connection_close_frames();
346 const vector<QuicStreamFrame>& stream_frames() const {
347 return framer_.stream_frames();
350 const vector<QuicPingFrame>& ping_frames() const {
351 return framer_.ping_frames();
354 size_t last_packet_size() {
355 return last_packet_size_;
358 const QuicVersionNegotiationPacket* version_negotiation_packet() {
359 return framer_.version_negotiation_packet();
362 void set_is_write_blocked_data_buffered(bool buffered) {
363 is_write_blocked_data_buffered_ = buffered;
366 void set_is_server(bool is_server) {
367 // We invert is_server here, because the framer needs to parse packets
368 // we send.
369 QuicFramerPeer::SetIsServer(framer_.framer(), !is_server);
372 // final_bytes_of_last_packet_ returns the last four bytes of the previous
373 // packet as a little-endian, uint32. This is intended to be used with a
374 // TaggingEncrypter so that tests can determine which encrypter was used for
375 // a given packet.
376 uint32 final_bytes_of_last_packet() { return final_bytes_of_last_packet_; }
378 // Returns the final bytes of the second to last packet.
379 uint32 final_bytes_of_previous_packet() {
380 return final_bytes_of_previous_packet_;
383 void use_tagging_decrypter() {
384 use_tagging_decrypter_ = true;
387 uint32 packets_write_attempts() { return packets_write_attempts_; }
389 void Reset() { framer_.Reset(); }
391 void SetSupportedVersions(const QuicVersionVector& versions) {
392 framer_.SetSupportedVersions(versions);
395 private:
396 QuicVersion version_;
397 SimpleQuicFramer framer_;
398 size_t last_packet_size_;
399 bool write_blocked_;
400 bool block_on_next_write_;
401 bool is_write_blocked_data_buffered_;
402 uint32 final_bytes_of_last_packet_;
403 uint32 final_bytes_of_previous_packet_;
404 bool use_tagging_decrypter_;
405 uint32 packets_write_attempts_;
407 DISALLOW_COPY_AND_ASSIGN(TestPacketWriter);
410 class TestConnection : public QuicConnection {
411 public:
412 TestConnection(QuicConnectionId connection_id,
413 IPEndPoint address,
414 TestConnectionHelper* helper,
415 const PacketWriterFactory& factory,
416 bool is_server,
417 QuicVersion version)
418 : QuicConnection(connection_id,
419 address,
420 helper,
421 factory,
422 /* owns_writer= */ false,
423 is_server,
424 SupportedVersions(version)) {
425 // Disable tail loss probes for most tests.
426 QuicSentPacketManagerPeer::SetMaxTailLossProbes(
427 QuicConnectionPeer::GetSentPacketManager(this), 0);
428 writer()->set_is_server(is_server);
431 void SendAck() {
432 QuicConnectionPeer::SendAck(this);
435 void SetReceiveAlgorithm(TestReceiveAlgorithm* receive_algorithm) {
436 QuicConnectionPeer::SetReceiveAlgorithm(this, receive_algorithm);
439 void SetSendAlgorithm(SendAlgorithmInterface* send_algorithm) {
440 QuicConnectionPeer::SetSendAlgorithm(this, send_algorithm);
443 void SetLossAlgorithm(LossDetectionInterface* loss_algorithm) {
444 QuicSentPacketManagerPeer::SetLossAlgorithm(
445 QuicConnectionPeer::GetSentPacketManager(this), loss_algorithm);
448 void SendPacket(EncryptionLevel level,
449 QuicPacketSequenceNumber sequence_number,
450 QuicPacket* packet,
451 QuicPacketEntropyHash entropy_hash,
452 HasRetransmittableData retransmittable) {
453 RetransmittableFrames* retransmittable_frames =
454 retransmittable == HAS_RETRANSMITTABLE_DATA ?
455 new RetransmittableFrames() : NULL;
456 OnSerializedPacket(
457 SerializedPacket(sequence_number, PACKET_6BYTE_SEQUENCE_NUMBER,
458 packet, entropy_hash, retransmittable_frames));
461 QuicConsumedData SendStreamDataWithString(
462 QuicStreamId id,
463 StringPiece data,
464 QuicStreamOffset offset,
465 bool fin,
466 QuicAckNotifier::DelegateInterface* delegate) {
467 return SendStreamDataWithStringHelper(id, data, offset, fin,
468 MAY_FEC_PROTECT, delegate);
471 QuicConsumedData SendStreamDataWithStringWithFec(
472 QuicStreamId id,
473 StringPiece data,
474 QuicStreamOffset offset,
475 bool fin,
476 QuicAckNotifier::DelegateInterface* delegate) {
477 return SendStreamDataWithStringHelper(id, data, offset, fin,
478 MUST_FEC_PROTECT, delegate);
481 QuicConsumedData SendStreamDataWithStringHelper(
482 QuicStreamId id,
483 StringPiece data,
484 QuicStreamOffset offset,
485 bool fin,
486 FecProtection fec_protection,
487 QuicAckNotifier::DelegateInterface* delegate) {
488 IOVector data_iov;
489 if (!data.empty()) {
490 data_iov.Append(const_cast<char*>(data.data()), data.size());
492 return QuicConnection::SendStreamData(id, data_iov, offset, fin,
493 fec_protection, delegate);
496 QuicConsumedData SendStreamData3() {
497 return SendStreamDataWithString(kClientDataStreamId1, "food", 0, !kFin,
498 NULL);
501 QuicConsumedData SendStreamData3WithFec() {
502 return SendStreamDataWithStringWithFec(kClientDataStreamId1, "food", 0,
503 !kFin, NULL);
506 QuicConsumedData SendStreamData5() {
507 return SendStreamDataWithString(kClientDataStreamId2, "food2", 0,
508 !kFin, NULL);
511 QuicConsumedData SendStreamData5WithFec() {
512 return SendStreamDataWithStringWithFec(kClientDataStreamId2, "food2", 0,
513 !kFin, NULL);
515 // Ensures the connection can write stream data before writing.
516 QuicConsumedData EnsureWritableAndSendStreamData5() {
517 EXPECT_TRUE(CanWriteStreamData());
518 return SendStreamData5();
521 // The crypto stream has special semantics so that it is not blocked by a
522 // congestion window limitation, and also so that it gets put into a separate
523 // packet (so that it is easier to reason about a crypto frame not being
524 // split needlessly across packet boundaries). As a result, we have separate
525 // tests for some cases for this stream.
526 QuicConsumedData SendCryptoStreamData() {
527 return SendStreamDataWithString(kCryptoStreamId, "chlo", 0, !kFin, NULL);
530 bool is_server() {
531 return QuicConnectionPeer::IsServer(this);
534 void set_version(QuicVersion version) {
535 QuicConnectionPeer::GetFramer(this)->set_version(version);
538 void SetSupportedVersions(const QuicVersionVector& versions) {
539 QuicConnectionPeer::GetFramer(this)->SetSupportedVersions(versions);
540 writer()->SetSupportedVersions(versions);
543 void set_is_server(bool is_server) {
544 writer()->set_is_server(is_server);
545 QuicConnectionPeer::SetIsServer(this, is_server);
548 TestConnectionHelper::TestAlarm* GetAckAlarm() {
549 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
550 QuicConnectionPeer::GetAckAlarm(this));
553 TestConnectionHelper::TestAlarm* GetPingAlarm() {
554 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
555 QuicConnectionPeer::GetPingAlarm(this));
558 TestConnectionHelper::TestAlarm* GetResumeWritesAlarm() {
559 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
560 QuicConnectionPeer::GetResumeWritesAlarm(this));
563 TestConnectionHelper::TestAlarm* GetRetransmissionAlarm() {
564 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
565 QuicConnectionPeer::GetRetransmissionAlarm(this));
568 TestConnectionHelper::TestAlarm* GetSendAlarm() {
569 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
570 QuicConnectionPeer::GetSendAlarm(this));
573 TestConnectionHelper::TestAlarm* GetTimeoutAlarm() {
574 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
575 QuicConnectionPeer::GetTimeoutAlarm(this));
578 using QuicConnection::SelectMutualVersion;
580 private:
581 TestPacketWriter* writer() {
582 return static_cast<TestPacketWriter*>(QuicConnection::writer());
585 DISALLOW_COPY_AND_ASSIGN(TestConnection);
588 // Used for testing packets revived from FEC packets.
589 class FecQuicConnectionDebugVisitor
590 : public QuicConnectionDebugVisitor {
591 public:
592 virtual void OnRevivedPacket(const QuicPacketHeader& header,
593 StringPiece data) OVERRIDE {
594 revived_header_ = header;
597 // Public accessor method.
598 QuicPacketHeader revived_header() const {
599 return revived_header_;
602 private:
603 QuicPacketHeader revived_header_;
606 class MockPacketWriterFactory : public QuicConnection::PacketWriterFactory {
607 public:
608 MockPacketWriterFactory(QuicPacketWriter* writer) {
609 ON_CALL(*this, Create(_)).WillByDefault(Return(writer));
611 virtual ~MockPacketWriterFactory() {}
613 MOCK_CONST_METHOD1(Create, QuicPacketWriter*(QuicConnection* connection));
616 class QuicConnectionTest : public ::testing::TestWithParam<QuicVersion> {
617 protected:
618 QuicConnectionTest()
619 : connection_id_(42),
620 framer_(SupportedVersions(version()), QuicTime::Zero(), false),
621 peer_creator_(connection_id_, &framer_, &random_generator_),
622 send_algorithm_(new StrictMock<MockSendAlgorithm>),
623 loss_algorithm_(new MockLossAlgorithm()),
624 helper_(new TestConnectionHelper(&clock_, &random_generator_)),
625 writer_(new TestPacketWriter(version())),
626 factory_(writer_.get()),
627 connection_(connection_id_, IPEndPoint(), helper_.get(),
628 factory_, false, version()),
629 frame1_(1, false, 0, MakeIOVector(data1)),
630 frame2_(1, false, 3, MakeIOVector(data2)),
631 sequence_number_length_(PACKET_6BYTE_SEQUENCE_NUMBER),
632 connection_id_length_(PACKET_8BYTE_CONNECTION_ID) {
633 connection_.set_visitor(&visitor_);
634 connection_.SetSendAlgorithm(send_algorithm_);
635 connection_.SetLossAlgorithm(loss_algorithm_);
636 framer_.set_received_entropy_calculator(&entropy_calculator_);
637 // Simplify tests by not sending feedback unless specifically configured.
638 SetFeedback(NULL);
639 EXPECT_CALL(
640 *send_algorithm_, TimeUntilSend(_, _, _)).WillRepeatedly(Return(
641 QuicTime::Delta::Zero()));
642 EXPECT_CALL(*receive_algorithm_,
643 RecordIncomingPacket(_, _, _)).Times(AnyNumber());
644 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
645 .Times(AnyNumber());
646 EXPECT_CALL(*send_algorithm_, RetransmissionDelay()).WillRepeatedly(
647 Return(QuicTime::Delta::Zero()));
648 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
649 Return(kMaxPacketSize));
650 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
651 .WillByDefault(Return(true));
652 EXPECT_CALL(*send_algorithm_, HasReliableBandwidthEstimate())
653 .Times(AnyNumber());
654 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
655 .Times(AnyNumber())
656 .WillRepeatedly(Return(QuicBandwidth::Zero()));
657 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
658 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
659 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).Times(AnyNumber());
660 EXPECT_CALL(visitor_, HasPendingHandshake()).Times(AnyNumber());
661 EXPECT_CALL(visitor_, OnCanWrite()).Times(AnyNumber());
662 EXPECT_CALL(visitor_, HasOpenDataStreams()).WillRepeatedly(Return(false));
663 EXPECT_CALL(visitor_, OnCongestionWindowChange(_)).Times(AnyNumber());
665 EXPECT_CALL(*loss_algorithm_, GetLossTimeout())
666 .WillRepeatedly(Return(QuicTime::Zero()));
667 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
668 .WillRepeatedly(Return(SequenceNumberSet()));
671 QuicVersion version() {
672 return GetParam();
675 QuicAckFrame* outgoing_ack() {
676 outgoing_ack_.reset(QuicConnectionPeer::CreateAckFrame(&connection_));
677 return outgoing_ack_.get();
680 QuicStopWaitingFrame* stop_waiting() {
681 stop_waiting_.reset(
682 QuicConnectionPeer::CreateStopWaitingFrame(&connection_));
683 return stop_waiting_.get();
686 QuicPacketSequenceNumber least_unacked() {
687 if (writer_->stop_waiting_frames().empty()) {
688 return 0;
690 return writer_->stop_waiting_frames()[0].least_unacked;
693 void use_tagging_decrypter() {
694 writer_->use_tagging_decrypter();
697 void ProcessPacket(QuicPacketSequenceNumber number) {
698 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
699 ProcessDataPacket(number, 0, !kEntropyFlag);
702 QuicPacketEntropyHash ProcessFramePacket(QuicFrame frame) {
703 QuicFrames frames;
704 frames.push_back(QuicFrame(frame));
705 QuicPacketCreatorPeer::SetSendVersionInPacket(&peer_creator_,
706 connection_.is_server());
707 SerializedPacket serialized_packet =
708 peer_creator_.SerializeAllFrames(frames);
709 scoped_ptr<QuicPacket> packet(serialized_packet.packet);
710 scoped_ptr<QuicEncryptedPacket> encrypted(
711 framer_.EncryptPacket(ENCRYPTION_NONE,
712 serialized_packet.sequence_number, *packet));
713 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
714 return serialized_packet.entropy_hash;
717 size_t ProcessDataPacket(QuicPacketSequenceNumber number,
718 QuicFecGroupNumber fec_group,
719 bool entropy_flag) {
720 return ProcessDataPacketAtLevel(number, fec_group, entropy_flag,
721 ENCRYPTION_NONE);
724 size_t ProcessDataPacketAtLevel(QuicPacketSequenceNumber number,
725 QuicFecGroupNumber fec_group,
726 bool entropy_flag,
727 EncryptionLevel level) {
728 scoped_ptr<QuicPacket> packet(ConstructDataPacket(number, fec_group,
729 entropy_flag));
730 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPacket(
731 level, number, *packet));
732 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
733 return encrypted->length();
736 void ProcessClosePacket(QuicPacketSequenceNumber number,
737 QuicFecGroupNumber fec_group) {
738 scoped_ptr<QuicPacket> packet(ConstructClosePacket(number, fec_group));
739 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPacket(
740 ENCRYPTION_NONE, number, *packet));
741 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
744 size_t ProcessFecProtectedPacket(QuicPacketSequenceNumber number,
745 bool expect_revival, bool entropy_flag) {
746 if (expect_revival) {
747 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
749 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1).
750 RetiresOnSaturation();
751 return ProcessDataPacket(number, 1, entropy_flag);
754 // Processes an FEC packet that covers the packets that would have been
755 // received.
756 size_t ProcessFecPacket(QuicPacketSequenceNumber number,
757 QuicPacketSequenceNumber min_protected_packet,
758 bool expect_revival,
759 bool entropy_flag,
760 QuicPacket* packet) {
761 if (expect_revival) {
762 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
765 // Construct the decrypted data packet so we can compute the correct
766 // redundancy. If |packet| has been provided then use that, otherwise
767 // construct a default data packet.
768 scoped_ptr<QuicPacket> data_packet;
769 if (packet) {
770 data_packet.reset(packet);
771 } else {
772 data_packet.reset(ConstructDataPacket(number, 1, !kEntropyFlag));
775 header_.public_header.connection_id = connection_id_;
776 header_.public_header.reset_flag = false;
777 header_.public_header.version_flag = false;
778 header_.public_header.sequence_number_length = sequence_number_length_;
779 header_.public_header.connection_id_length = connection_id_length_;
780 header_.packet_sequence_number = number;
781 header_.entropy_flag = entropy_flag;
782 header_.fec_flag = true;
783 header_.is_in_fec_group = IN_FEC_GROUP;
784 header_.fec_group = min_protected_packet;
785 QuicFecData fec_data;
786 fec_data.fec_group = header_.fec_group;
788 // Since all data packets in this test have the same payload, the
789 // redundancy is either equal to that payload or the xor of that payload
790 // with itself, depending on the number of packets.
791 if (((number - min_protected_packet) % 2) == 0) {
792 for (size_t i = GetStartOfFecProtectedData(
793 header_.public_header.connection_id_length,
794 header_.public_header.version_flag,
795 header_.public_header.sequence_number_length);
796 i < data_packet->length(); ++i) {
797 data_packet->mutable_data()[i] ^= data_packet->data()[i];
800 fec_data.redundancy = data_packet->FecProtectedData();
802 scoped_ptr<QuicPacket> fec_packet(
803 framer_.BuildFecPacket(header_, fec_data).packet);
804 scoped_ptr<QuicEncryptedPacket> encrypted(
805 framer_.EncryptPacket(ENCRYPTION_NONE, number, *fec_packet));
807 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
808 return encrypted->length();
811 QuicByteCount SendStreamDataToPeer(QuicStreamId id,
812 StringPiece data,
813 QuicStreamOffset offset,
814 bool fin,
815 QuicPacketSequenceNumber* last_packet) {
816 QuicByteCount packet_size;
817 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
818 .WillOnce(DoAll(SaveArg<3>(&packet_size), Return(true)));
819 connection_.SendStreamDataWithString(id, data, offset, fin, NULL);
820 if (last_packet != NULL) {
821 *last_packet =
822 QuicConnectionPeer::GetPacketCreator(&connection_)->sequence_number();
824 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
825 .Times(AnyNumber());
826 return packet_size;
829 void SendAckPacketToPeer() {
830 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
831 connection_.SendAck();
832 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
833 .Times(AnyNumber());
836 QuicPacketEntropyHash ProcessAckPacket(QuicAckFrame* frame) {
837 return ProcessFramePacket(QuicFrame(frame));
840 QuicPacketEntropyHash ProcessStopWaitingPacket(QuicStopWaitingFrame* frame) {
841 return ProcessFramePacket(QuicFrame(frame));
844 QuicPacketEntropyHash ProcessGoAwayPacket(QuicGoAwayFrame* frame) {
845 return ProcessFramePacket(QuicFrame(frame));
848 bool IsMissing(QuicPacketSequenceNumber number) {
849 return IsAwaitingPacket(*outgoing_ack(), number);
852 QuicPacket* ConstructDataPacket(QuicPacketSequenceNumber number,
853 QuicFecGroupNumber fec_group,
854 bool entropy_flag) {
855 header_.public_header.connection_id = connection_id_;
856 header_.public_header.reset_flag = false;
857 header_.public_header.version_flag = false;
858 header_.public_header.sequence_number_length = sequence_number_length_;
859 header_.public_header.connection_id_length = connection_id_length_;
860 header_.entropy_flag = entropy_flag;
861 header_.fec_flag = false;
862 header_.packet_sequence_number = number;
863 header_.is_in_fec_group = fec_group == 0u ? NOT_IN_FEC_GROUP : IN_FEC_GROUP;
864 header_.fec_group = fec_group;
866 QuicFrames frames;
867 QuicFrame frame(&frame1_);
868 frames.push_back(frame);
869 QuicPacket* packet =
870 BuildUnsizedDataPacket(&framer_, header_, frames).packet;
871 EXPECT_TRUE(packet != NULL);
872 return packet;
875 QuicPacket* ConstructClosePacket(QuicPacketSequenceNumber number,
876 QuicFecGroupNumber fec_group) {
877 header_.public_header.connection_id = connection_id_;
878 header_.packet_sequence_number = number;
879 header_.public_header.reset_flag = false;
880 header_.public_header.version_flag = false;
881 header_.entropy_flag = false;
882 header_.fec_flag = false;
883 header_.is_in_fec_group = fec_group == 0u ? NOT_IN_FEC_GROUP : IN_FEC_GROUP;
884 header_.fec_group = fec_group;
886 QuicConnectionCloseFrame qccf;
887 qccf.error_code = QUIC_PEER_GOING_AWAY;
889 QuicFrames frames;
890 QuicFrame frame(&qccf);
891 frames.push_back(frame);
892 QuicPacket* packet =
893 BuildUnsizedDataPacket(&framer_, header_, frames).packet;
894 EXPECT_TRUE(packet != NULL);
895 return packet;
898 void SetFeedback(QuicCongestionFeedbackFrame* feedback) {
899 receive_algorithm_ = new TestReceiveAlgorithm(feedback);
900 connection_.SetReceiveAlgorithm(receive_algorithm_);
903 QuicTime::Delta DefaultRetransmissionTime() {
904 return QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
907 QuicTime::Delta DefaultDelayedAckTime() {
908 return QuicTime::Delta::FromMilliseconds(kMaxDelayedAckTimeMs);
911 // Initialize a frame acknowledging all packets up to largest_observed.
912 const QuicAckFrame InitAckFrame(QuicPacketSequenceNumber largest_observed) {
913 QuicAckFrame frame(MakeAckFrame(largest_observed));
914 if (largest_observed > 0) {
915 frame.entropy_hash =
916 QuicConnectionPeer::GetSentEntropyHash(&connection_,
917 largest_observed);
919 return frame;
922 const QuicStopWaitingFrame InitStopWaitingFrame(
923 QuicPacketSequenceNumber least_unacked) {
924 QuicStopWaitingFrame frame;
925 frame.least_unacked = least_unacked;
926 return frame;
929 // Explicitly nack a packet.
930 void NackPacket(QuicPacketSequenceNumber missing, QuicAckFrame* frame) {
931 frame->missing_packets.insert(missing);
932 frame->entropy_hash ^=
933 QuicConnectionPeer::PacketEntropy(&connection_, missing);
936 // Undo nacking a packet within the frame.
937 void AckPacket(QuicPacketSequenceNumber arrived, QuicAckFrame* frame) {
938 EXPECT_THAT(frame->missing_packets, Contains(arrived));
939 frame->missing_packets.erase(arrived);
940 frame->entropy_hash ^=
941 QuicConnectionPeer::PacketEntropy(&connection_, arrived);
944 void TriggerConnectionClose() {
945 // Send an erroneous packet to close the connection.
946 EXPECT_CALL(visitor_,
947 OnConnectionClosed(QUIC_INVALID_PACKET_HEADER, false));
948 // Call ProcessDataPacket rather than ProcessPacket, as we should not get a
949 // packet call to the visitor.
950 ProcessDataPacket(6000, 0, !kEntropyFlag);
951 EXPECT_FALSE(
952 QuicConnectionPeer::GetConnectionClosePacket(&connection_) == NULL);
955 void BlockOnNextWrite() {
956 writer_->BlockOnNextWrite();
957 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
960 void CongestionBlockWrites() {
961 EXPECT_CALL(*send_algorithm_,
962 TimeUntilSend(_, _, _)).WillRepeatedly(
963 testing::Return(QuicTime::Delta::FromSeconds(1)));
966 void CongestionUnblockWrites() {
967 EXPECT_CALL(*send_algorithm_,
968 TimeUntilSend(_, _, _)).WillRepeatedly(
969 testing::Return(QuicTime::Delta::Zero()));
972 QuicConnectionId connection_id_;
973 QuicFramer framer_;
974 QuicPacketCreator peer_creator_;
975 MockEntropyCalculator entropy_calculator_;
977 MockSendAlgorithm* send_algorithm_;
978 MockLossAlgorithm* loss_algorithm_;
979 TestReceiveAlgorithm* receive_algorithm_;
980 MockClock clock_;
981 MockRandom random_generator_;
982 scoped_ptr<TestConnectionHelper> helper_;
983 scoped_ptr<TestPacketWriter> writer_;
984 NiceMock<MockPacketWriterFactory> factory_;
985 TestConnection connection_;
986 StrictMock<MockConnectionVisitor> visitor_;
988 QuicPacketHeader header_;
989 QuicStreamFrame frame1_;
990 QuicStreamFrame frame2_;
991 scoped_ptr<QuicAckFrame> outgoing_ack_;
992 scoped_ptr<QuicStopWaitingFrame> stop_waiting_;
993 QuicSequenceNumberLength sequence_number_length_;
994 QuicConnectionIdLength connection_id_length_;
996 private:
997 DISALLOW_COPY_AND_ASSIGN(QuicConnectionTest);
1000 // Run all end to end tests with all supported versions.
1001 INSTANTIATE_TEST_CASE_P(SupportedVersion,
1002 QuicConnectionTest,
1003 ::testing::ValuesIn(QuicSupportedVersions()));
1005 TEST_P(QuicConnectionTest, PacketsInOrder) {
1006 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1008 ProcessPacket(1);
1009 EXPECT_EQ(1u, outgoing_ack()->largest_observed);
1010 EXPECT_EQ(0u, outgoing_ack()->missing_packets.size());
1012 ProcessPacket(2);
1013 EXPECT_EQ(2u, outgoing_ack()->largest_observed);
1014 EXPECT_EQ(0u, outgoing_ack()->missing_packets.size());
1016 ProcessPacket(3);
1017 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1018 EXPECT_EQ(0u, outgoing_ack()->missing_packets.size());
1021 TEST_P(QuicConnectionTest, PacketsOutOfOrder) {
1022 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1024 ProcessPacket(3);
1025 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1026 EXPECT_TRUE(IsMissing(2));
1027 EXPECT_TRUE(IsMissing(1));
1029 ProcessPacket(2);
1030 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1031 EXPECT_FALSE(IsMissing(2));
1032 EXPECT_TRUE(IsMissing(1));
1034 ProcessPacket(1);
1035 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1036 EXPECT_FALSE(IsMissing(2));
1037 EXPECT_FALSE(IsMissing(1));
1040 TEST_P(QuicConnectionTest, DuplicatePacket) {
1041 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1043 ProcessPacket(3);
1044 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1045 EXPECT_TRUE(IsMissing(2));
1046 EXPECT_TRUE(IsMissing(1));
1048 // Send packet 3 again, but do not set the expectation that
1049 // the visitor OnStreamFrames() will be called.
1050 ProcessDataPacket(3, 0, !kEntropyFlag);
1051 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1052 EXPECT_TRUE(IsMissing(2));
1053 EXPECT_TRUE(IsMissing(1));
1056 TEST_P(QuicConnectionTest, PacketsOutOfOrderWithAdditionsAndLeastAwaiting) {
1057 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1059 ProcessPacket(3);
1060 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1061 EXPECT_TRUE(IsMissing(2));
1062 EXPECT_TRUE(IsMissing(1));
1064 ProcessPacket(2);
1065 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1066 EXPECT_TRUE(IsMissing(1));
1068 ProcessPacket(5);
1069 EXPECT_EQ(5u, outgoing_ack()->largest_observed);
1070 EXPECT_TRUE(IsMissing(1));
1071 EXPECT_TRUE(IsMissing(4));
1073 // Pretend at this point the client has gotten acks for 2 and 3 and 1 is a
1074 // packet the peer will not retransmit. It indicates this by sending 'least
1075 // awaiting' is 4. The connection should then realize 1 will not be
1076 // retransmitted, and will remove it from the missing list.
1077 peer_creator_.set_sequence_number(5);
1078 QuicAckFrame frame = InitAckFrame(1);
1079 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _));
1080 ProcessAckPacket(&frame);
1082 // Force an ack to be sent.
1083 SendAckPacketToPeer();
1084 EXPECT_TRUE(IsMissing(4));
1087 TEST_P(QuicConnectionTest, RejectPacketTooFarOut) {
1088 EXPECT_CALL(visitor_,
1089 OnConnectionClosed(QUIC_INVALID_PACKET_HEADER, false));
1090 // Call ProcessDataPacket rather than ProcessPacket, as we should not get a
1091 // packet call to the visitor.
1092 ProcessDataPacket(6000, 0, !kEntropyFlag);
1093 EXPECT_FALSE(
1094 QuicConnectionPeer::GetConnectionClosePacket(&connection_) == NULL);
1097 TEST_P(QuicConnectionTest, RejectUnencryptedStreamData) {
1098 // Process an unencrypted packet from the non-crypto stream.
1099 frame1_.stream_id = 3;
1100 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1101 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_UNENCRYPTED_STREAM_DATA,
1102 false));
1103 ProcessDataPacket(1, 0, !kEntropyFlag);
1104 EXPECT_FALSE(
1105 QuicConnectionPeer::GetConnectionClosePacket(&connection_) == NULL);
1106 const vector<QuicConnectionCloseFrame>& connection_close_frames =
1107 writer_->connection_close_frames();
1108 EXPECT_EQ(1u, connection_close_frames.size());
1109 EXPECT_EQ(QUIC_UNENCRYPTED_STREAM_DATA,
1110 connection_close_frames[0].error_code);
1113 TEST_P(QuicConnectionTest, TruncatedAck) {
1114 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1115 QuicPacketSequenceNumber num_packets = 256 * 2 + 1;
1116 for (QuicPacketSequenceNumber i = 0; i < num_packets; ++i) {
1117 SendStreamDataToPeer(3, "foo", i * 3, !kFin, NULL);
1120 QuicAckFrame frame = InitAckFrame(num_packets);
1121 SequenceNumberSet lost_packets;
1122 // Create an ack with 256 nacks, none adjacent to one another.
1123 for (QuicPacketSequenceNumber i = 1; i <= 256; ++i) {
1124 NackPacket(i * 2, &frame);
1125 if (i < 256) { // Last packet is nacked, but not lost.
1126 lost_packets.insert(i * 2);
1129 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1130 .WillOnce(Return(lost_packets));
1131 EXPECT_CALL(entropy_calculator_,
1132 EntropyHash(511)).WillOnce(testing::Return(0));
1133 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1134 ProcessAckPacket(&frame);
1136 const QuicSentPacketManager& sent_packet_manager =
1137 connection_.sent_packet_manager();
1138 // A truncated ack will not have the true largest observed.
1139 EXPECT_GT(num_packets, sent_packet_manager.largest_observed());
1141 AckPacket(192, &frame);
1143 // Removing one missing packet allows us to ack 192 and one more range, but
1144 // 192 has already been declared lost, so it doesn't register as an ack.
1145 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1146 .WillOnce(Return(SequenceNumberSet()));
1147 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1148 ProcessAckPacket(&frame);
1149 EXPECT_EQ(num_packets, sent_packet_manager.largest_observed());
1152 TEST_P(QuicConnectionTest, AckReceiptCausesAckSendBadEntropy) {
1153 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1155 ProcessPacket(1);
1156 // Delay sending, then queue up an ack.
1157 EXPECT_CALL(*send_algorithm_,
1158 TimeUntilSend(_, _, _)).WillOnce(
1159 testing::Return(QuicTime::Delta::FromMicroseconds(1)));
1160 QuicConnectionPeer::SendAck(&connection_);
1162 // Process an ack with a least unacked of the received ack.
1163 // This causes an ack to be sent when TimeUntilSend returns 0.
1164 EXPECT_CALL(*send_algorithm_,
1165 TimeUntilSend(_, _, _)).WillRepeatedly(
1166 testing::Return(QuicTime::Delta::Zero()));
1167 // Skip a packet and then record an ack.
1168 peer_creator_.set_sequence_number(2);
1169 QuicAckFrame frame = InitAckFrame(0);
1170 ProcessAckPacket(&frame);
1173 TEST_P(QuicConnectionTest, OutOfOrderReceiptCausesAckSend) {
1174 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1176 ProcessPacket(3);
1177 // Should ack immediately since we have missing packets.
1178 EXPECT_EQ(1u, writer_->packets_write_attempts());
1180 ProcessPacket(2);
1181 // Should ack immediately since we have missing packets.
1182 EXPECT_EQ(2u, writer_->packets_write_attempts());
1184 ProcessPacket(1);
1185 // Should ack immediately, since this fills the last hole.
1186 EXPECT_EQ(3u, writer_->packets_write_attempts());
1188 ProcessPacket(4);
1189 // Should not cause an ack.
1190 EXPECT_EQ(3u, writer_->packets_write_attempts());
1193 TEST_P(QuicConnectionTest, AckReceiptCausesAckSend) {
1194 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1196 QuicPacketSequenceNumber original;
1197 QuicByteCount packet_size;
1198 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1199 .WillOnce(DoAll(SaveArg<2>(&original), SaveArg<3>(&packet_size),
1200 Return(true)));
1201 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, NULL);
1202 QuicAckFrame frame = InitAckFrame(original);
1203 NackPacket(original, &frame);
1204 // First nack triggers early retransmit.
1205 SequenceNumberSet lost_packets;
1206 lost_packets.insert(1);
1207 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1208 .WillOnce(Return(lost_packets));
1209 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1210 QuicPacketSequenceNumber retransmission;
1211 EXPECT_CALL(*send_algorithm_,
1212 OnPacketSent(_, _, _, packet_size - kQuicVersionSize, _))
1213 .WillOnce(DoAll(SaveArg<2>(&retransmission), Return(true)));
1215 ProcessAckPacket(&frame);
1217 QuicAckFrame frame2 = InitAckFrame(retransmission);
1218 NackPacket(original, &frame2);
1219 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1220 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1221 .WillOnce(Return(SequenceNumberSet()));
1222 ProcessAckPacket(&frame2);
1224 // Now if the peer sends an ack which still reports the retransmitted packet
1225 // as missing, that will bundle an ack with data after two acks in a row
1226 // indicate the high water mark needs to be raised.
1227 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _,
1228 HAS_RETRANSMITTABLE_DATA));
1229 connection_.SendStreamDataWithString(3, "foo", 3, !kFin, NULL);
1230 // No ack sent.
1231 EXPECT_EQ(1u, writer_->frame_count());
1232 EXPECT_EQ(1u, writer_->stream_frames().size());
1234 // No more packet loss for the rest of the test.
1235 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1236 .WillRepeatedly(Return(SequenceNumberSet()));
1237 ProcessAckPacket(&frame2);
1238 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _,
1239 HAS_RETRANSMITTABLE_DATA));
1240 connection_.SendStreamDataWithString(3, "foo", 3, !kFin, NULL);
1241 // Ack bundled.
1242 EXPECT_EQ(3u, writer_->frame_count());
1243 EXPECT_EQ(1u, writer_->stream_frames().size());
1244 EXPECT_FALSE(writer_->ack_frames().empty());
1246 // But an ack with no missing packets will not send an ack.
1247 AckPacket(original, &frame2);
1248 ProcessAckPacket(&frame2);
1249 ProcessAckPacket(&frame2);
1252 TEST_P(QuicConnectionTest, LeastUnackedLower) {
1253 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1255 SendStreamDataToPeer(1, "foo", 0, !kFin, NULL);
1256 SendStreamDataToPeer(1, "bar", 3, !kFin, NULL);
1257 SendStreamDataToPeer(1, "eep", 6, !kFin, NULL);
1259 // Start out saying the least unacked is 2.
1260 peer_creator_.set_sequence_number(5);
1261 QuicStopWaitingFrame frame = InitStopWaitingFrame(2);
1262 ProcessStopWaitingPacket(&frame);
1264 // Change it to 1, but lower the sequence number to fake out-of-order packets.
1265 // This should be fine.
1266 peer_creator_.set_sequence_number(1);
1267 // The scheduler will not process out of order acks, but all packet processing
1268 // causes the connection to try to write.
1269 EXPECT_CALL(visitor_, OnCanWrite());
1270 QuicStopWaitingFrame frame2 = InitStopWaitingFrame(1);
1271 ProcessStopWaitingPacket(&frame2);
1273 // Now claim it's one, but set the ordering so it was sent "after" the first
1274 // one. This should cause a connection error.
1275 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
1276 peer_creator_.set_sequence_number(7);
1277 EXPECT_CALL(visitor_,
1278 OnConnectionClosed(QUIC_INVALID_STOP_WAITING_DATA, false));
1279 QuicStopWaitingFrame frame3 = InitStopWaitingFrame(1);
1280 ProcessStopWaitingPacket(&frame3);
1283 TEST_P(QuicConnectionTest, LargestObservedLower) {
1284 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1286 SendStreamDataToPeer(1, "foo", 0, !kFin, NULL);
1287 SendStreamDataToPeer(1, "bar", 3, !kFin, NULL);
1288 SendStreamDataToPeer(1, "eep", 6, !kFin, NULL);
1289 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1291 // Start out saying the largest observed is 2.
1292 QuicAckFrame frame1 = InitAckFrame(1);
1293 QuicAckFrame frame2 = InitAckFrame(2);
1294 ProcessAckPacket(&frame2);
1296 // Now change it to 1, and it should cause a connection error.
1297 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, false));
1298 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
1299 ProcessAckPacket(&frame1);
1302 TEST_P(QuicConnectionTest, AckUnsentData) {
1303 // Ack a packet which has not been sent.
1304 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, false));
1305 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1306 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
1307 QuicAckFrame frame(MakeAckFrame(1));
1308 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
1309 ProcessAckPacket(&frame);
1312 TEST_P(QuicConnectionTest, AckAll) {
1313 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1314 ProcessPacket(1);
1316 peer_creator_.set_sequence_number(1);
1317 QuicAckFrame frame1 = InitAckFrame(0);
1318 ProcessAckPacket(&frame1);
1321 TEST_P(QuicConnectionTest, SendingDifferentSequenceNumberLengthsBandwidth) {
1322 QuicPacketSequenceNumber last_packet;
1323 QuicPacketCreator* creator =
1324 QuicConnectionPeer::GetPacketCreator(&connection_);
1325 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet);
1326 EXPECT_EQ(1u, last_packet);
1327 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1328 creator->next_sequence_number_length());
1329 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1330 writer_->header().public_header.sequence_number_length);
1332 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
1333 Return(kMaxPacketSize * 256));
1335 SendStreamDataToPeer(1, "bar", 3, !kFin, &last_packet);
1336 EXPECT_EQ(2u, last_packet);
1337 EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER,
1338 creator->next_sequence_number_length());
1339 // The 1 packet lag is due to the sequence number length being recalculated in
1340 // QuicConnection after a packet is sent.
1341 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1342 writer_->header().public_header.sequence_number_length);
1344 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
1345 Return(kMaxPacketSize * 256 * 256));
1347 SendStreamDataToPeer(1, "foo", 6, !kFin, &last_packet);
1348 EXPECT_EQ(3u, last_packet);
1349 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1350 creator->next_sequence_number_length());
1351 EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER,
1352 writer_->header().public_header.sequence_number_length);
1354 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
1355 Return(kMaxPacketSize * 256 * 256 * 256));
1357 SendStreamDataToPeer(1, "bar", 9, !kFin, &last_packet);
1358 EXPECT_EQ(4u, last_packet);
1359 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1360 creator->next_sequence_number_length());
1361 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1362 writer_->header().public_header.sequence_number_length);
1364 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
1365 Return(kMaxPacketSize * 256 * 256 * 256 * 256));
1367 SendStreamDataToPeer(1, "foo", 12, !kFin, &last_packet);
1368 EXPECT_EQ(5u, last_packet);
1369 EXPECT_EQ(PACKET_6BYTE_SEQUENCE_NUMBER,
1370 creator->next_sequence_number_length());
1371 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1372 writer_->header().public_header.sequence_number_length);
1375 TEST_P(QuicConnectionTest, SendingDifferentSequenceNumberLengthsUnackedDelta) {
1376 QuicPacketSequenceNumber last_packet;
1377 QuicPacketCreator* creator =
1378 QuicConnectionPeer::GetPacketCreator(&connection_);
1379 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet);
1380 EXPECT_EQ(1u, last_packet);
1381 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1382 creator->next_sequence_number_length());
1383 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1384 writer_->header().public_header.sequence_number_length);
1386 creator->set_sequence_number(100);
1388 SendStreamDataToPeer(1, "bar", 3, !kFin, &last_packet);
1389 EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER,
1390 creator->next_sequence_number_length());
1391 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1392 writer_->header().public_header.sequence_number_length);
1394 creator->set_sequence_number(100 * 256);
1396 SendStreamDataToPeer(1, "foo", 6, !kFin, &last_packet);
1397 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1398 creator->next_sequence_number_length());
1399 EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER,
1400 writer_->header().public_header.sequence_number_length);
1402 creator->set_sequence_number(100 * 256 * 256);
1404 SendStreamDataToPeer(1, "bar", 9, !kFin, &last_packet);
1405 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1406 creator->next_sequence_number_length());
1407 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1408 writer_->header().public_header.sequence_number_length);
1410 creator->set_sequence_number(100 * 256 * 256 * 256);
1412 SendStreamDataToPeer(1, "foo", 12, !kFin, &last_packet);
1413 EXPECT_EQ(PACKET_6BYTE_SEQUENCE_NUMBER,
1414 creator->next_sequence_number_length());
1415 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1416 writer_->header().public_header.sequence_number_length);
1419 TEST_P(QuicConnectionTest, BasicSending) {
1420 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1421 QuicPacketSequenceNumber last_packet;
1422 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet); // Packet 1
1423 EXPECT_EQ(1u, last_packet);
1424 SendAckPacketToPeer(); // Packet 2
1426 EXPECT_EQ(1u, least_unacked());
1428 SendAckPacketToPeer(); // Packet 3
1429 EXPECT_EQ(1u, least_unacked());
1431 SendStreamDataToPeer(1, "bar", 3, !kFin, &last_packet); // Packet 4
1432 EXPECT_EQ(4u, last_packet);
1433 SendAckPacketToPeer(); // Packet 5
1434 EXPECT_EQ(1u, least_unacked());
1436 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1438 // Peer acks up to packet 3.
1439 QuicAckFrame frame = InitAckFrame(3);
1440 ProcessAckPacket(&frame);
1441 SendAckPacketToPeer(); // Packet 6
1443 // As soon as we've acked one, we skip ack packets 2 and 3 and note lack of
1444 // ack for 4.
1445 EXPECT_EQ(4u, least_unacked());
1447 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1449 // Peer acks up to packet 4, the last packet.
1450 QuicAckFrame frame2 = InitAckFrame(6);
1451 ProcessAckPacket(&frame2); // Acks don't instigate acks.
1453 // Verify that we did not send an ack.
1454 EXPECT_EQ(6u, writer_->header().packet_sequence_number);
1456 // So the last ack has not changed.
1457 EXPECT_EQ(4u, least_unacked());
1459 // If we force an ack, we shouldn't change our retransmit state.
1460 SendAckPacketToPeer(); // Packet 7
1461 EXPECT_EQ(7u, least_unacked());
1463 // But if we send more data it should.
1464 SendStreamDataToPeer(1, "eep", 6, !kFin, &last_packet); // Packet 8
1465 EXPECT_EQ(8u, last_packet);
1466 SendAckPacketToPeer(); // Packet 9
1467 EXPECT_EQ(7u, least_unacked());
1470 TEST_P(QuicConnectionTest, FECSending) {
1471 // All packets carry version info till version is negotiated.
1472 QuicPacketCreator* creator =
1473 QuicConnectionPeer::GetPacketCreator(&connection_);
1474 size_t payload_length;
1475 // GetPacketLengthForOneStream() assumes a stream offset of 0 in determining
1476 // packet length. The size of the offset field in a stream frame is 0 for
1477 // offset 0, and 2 for non-zero offsets up through 64K. Increase
1478 // max_packet_length by 2 so that subsequent packets containing subsequent
1479 // stream frames with non-zero offets will fit within the packet length.
1480 size_t length = 2 + GetPacketLengthForOneStream(
1481 connection_.version(), kIncludeVersion, PACKET_1BYTE_SEQUENCE_NUMBER,
1482 IN_FEC_GROUP, &payload_length);
1483 creator->set_max_packet_length(length);
1485 // Send 4 protected data packets, which should also trigger 1 FEC packet.
1486 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(5);
1487 // The first stream frame will have 2 fewer overhead bytes than the other 3.
1488 const string payload(payload_length * 4 + 2, 'a');
1489 connection_.SendStreamDataWithStringWithFec(1, payload, 0, !kFin, NULL);
1490 // Expect the FEC group to be closed after SendStreamDataWithString.
1491 EXPECT_FALSE(creator->IsFecGroupOpen());
1492 EXPECT_FALSE(creator->IsFecProtected());
1495 TEST_P(QuicConnectionTest, FECQueueing) {
1496 // All packets carry version info till version is negotiated.
1497 size_t payload_length;
1498 QuicPacketCreator* creator =
1499 QuicConnectionPeer::GetPacketCreator(&connection_);
1500 size_t length = GetPacketLengthForOneStream(
1501 connection_.version(), kIncludeVersion, PACKET_1BYTE_SEQUENCE_NUMBER,
1502 IN_FEC_GROUP, &payload_length);
1503 creator->set_max_packet_length(length);
1504 EXPECT_TRUE(creator->IsFecEnabled());
1506 EXPECT_EQ(0u, connection_.NumQueuedPackets());
1507 BlockOnNextWrite();
1508 const string payload(payload_length, 'a');
1509 connection_.SendStreamDataWithStringWithFec(1, payload, 0, !kFin, NULL);
1510 EXPECT_FALSE(creator->IsFecGroupOpen());
1511 EXPECT_FALSE(creator->IsFecProtected());
1512 // Expect the first data packet and the fec packet to be queued.
1513 EXPECT_EQ(2u, connection_.NumQueuedPackets());
1516 TEST_P(QuicConnectionTest, AbandonFECFromCongestionWindow) {
1517 EXPECT_TRUE(QuicConnectionPeer::GetPacketCreator(
1518 &connection_)->IsFecEnabled());
1520 // 1 Data and 1 FEC packet.
1521 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
1522 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, !kFin, NULL);
1524 const QuicTime::Delta retransmission_time =
1525 QuicTime::Delta::FromMilliseconds(5000);
1526 clock_.AdvanceTime(retransmission_time);
1528 // Abandon FEC packet and data packet.
1529 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
1530 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1531 EXPECT_CALL(visitor_, OnCanWrite());
1532 connection_.OnRetransmissionTimeout();
1535 TEST_P(QuicConnectionTest, DontAbandonAckedFEC) {
1536 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1537 EXPECT_TRUE(QuicConnectionPeer::GetPacketCreator(
1538 &connection_)->IsFecEnabled());
1540 // 1 Data and 1 FEC packet.
1541 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(6);
1542 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, !kFin, NULL);
1543 // Send some more data afterwards to ensure early retransmit doesn't trigger.
1544 connection_.SendStreamDataWithStringWithFec(3, "foo", 3, !kFin, NULL);
1545 connection_.SendStreamDataWithStringWithFec(3, "foo", 6, !kFin, NULL);
1547 QuicAckFrame ack_fec = InitAckFrame(2);
1548 // Data packet missing.
1549 // TODO(ianswett): Note that this is not a sensible ack, since if the FEC was
1550 // received, it would cause the covered packet to be acked as well.
1551 NackPacket(1, &ack_fec);
1552 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1553 ProcessAckPacket(&ack_fec);
1554 clock_.AdvanceTime(DefaultRetransmissionTime());
1556 // Don't abandon the acked FEC packet, but it will abandon 2 the subsequent
1557 // FEC packets.
1558 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
1559 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
1560 connection_.GetRetransmissionAlarm()->Fire();
1563 TEST_P(QuicConnectionTest, AbandonAllFEC) {
1564 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1565 EXPECT_TRUE(QuicConnectionPeer::GetPacketCreator(
1566 &connection_)->IsFecEnabled());
1568 // 1 Data and 1 FEC packet.
1569 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(6);
1570 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, !kFin, NULL);
1571 // Send some more data afterwards to ensure early retransmit doesn't trigger.
1572 connection_.SendStreamDataWithStringWithFec(3, "foo", 3, !kFin, NULL);
1573 // Advance the time so not all the FEC packets are abandoned.
1574 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(1));
1575 connection_.SendStreamDataWithStringWithFec(3, "foo", 6, !kFin, NULL);
1577 QuicAckFrame ack_fec = InitAckFrame(5);
1578 // Ack all data packets, but no fec packets.
1579 NackPacket(2, &ack_fec);
1580 NackPacket(4, &ack_fec);
1582 // Lose the first FEC packet and ack the three data packets.
1583 SequenceNumberSet lost_packets;
1584 lost_packets.insert(2);
1585 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1586 .WillOnce(Return(lost_packets));
1587 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1588 ProcessAckPacket(&ack_fec);
1590 clock_.AdvanceTime(DefaultRetransmissionTime().Subtract(
1591 QuicTime::Delta::FromMilliseconds(1)));
1593 // Abandon all packets
1594 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(false));
1595 connection_.GetRetransmissionAlarm()->Fire();
1597 // Ensure the alarm is not set since all packets have been abandoned.
1598 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
1601 TEST_P(QuicConnectionTest, FramePacking) {
1602 CongestionBlockWrites();
1604 // Send an ack and two stream frames in 1 packet by queueing them.
1605 connection_.SendAck();
1606 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
1607 IgnoreResult(InvokeWithoutArgs(&connection_,
1608 &TestConnection::SendStreamData3)),
1609 IgnoreResult(InvokeWithoutArgs(&connection_,
1610 &TestConnection::SendStreamData5))));
1612 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1613 CongestionUnblockWrites();
1614 connection_.GetSendAlarm()->Fire();
1615 EXPECT_EQ(0u, connection_.NumQueuedPackets());
1616 EXPECT_FALSE(connection_.HasQueuedData());
1618 // Parse the last packet and ensure it's an ack and two stream frames from
1619 // two different streams.
1620 EXPECT_EQ(4u, writer_->frame_count());
1621 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
1622 EXPECT_FALSE(writer_->ack_frames().empty());
1623 ASSERT_EQ(2u, writer_->stream_frames().size());
1624 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id);
1625 EXPECT_EQ(kClientDataStreamId2, writer_->stream_frames()[1].stream_id);
1628 TEST_P(QuicConnectionTest, FramePackingNonCryptoThenCrypto) {
1629 CongestionBlockWrites();
1631 // Send an ack and two stream frames (one non-crypto, then one crypto) in 2
1632 // packets by queueing them.
1633 connection_.SendAck();
1634 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
1635 IgnoreResult(InvokeWithoutArgs(&connection_,
1636 &TestConnection::SendStreamData3)),
1637 IgnoreResult(InvokeWithoutArgs(&connection_,
1638 &TestConnection::SendCryptoStreamData))));
1640 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
1641 CongestionUnblockWrites();
1642 connection_.GetSendAlarm()->Fire();
1643 EXPECT_EQ(0u, connection_.NumQueuedPackets());
1644 EXPECT_FALSE(connection_.HasQueuedData());
1646 // Parse the last packet and ensure it's the crypto stream frame.
1647 EXPECT_EQ(1u, writer_->frame_count());
1648 ASSERT_EQ(1u, writer_->stream_frames().size());
1649 EXPECT_EQ(kCryptoStreamId, writer_->stream_frames()[0].stream_id);
1652 TEST_P(QuicConnectionTest, FramePackingCryptoThenNonCrypto) {
1653 CongestionBlockWrites();
1655 // Send an ack and two stream frames (one crypto, then one non-crypto) in 2
1656 // packets by queueing them.
1657 connection_.SendAck();
1658 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
1659 IgnoreResult(InvokeWithoutArgs(&connection_,
1660 &TestConnection::SendCryptoStreamData)),
1661 IgnoreResult(InvokeWithoutArgs(&connection_,
1662 &TestConnection::SendStreamData3))));
1664 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
1665 CongestionUnblockWrites();
1666 connection_.GetSendAlarm()->Fire();
1667 EXPECT_EQ(0u, connection_.NumQueuedPackets());
1668 EXPECT_FALSE(connection_.HasQueuedData());
1670 // Parse the last packet and ensure it's the stream frame from stream 3.
1671 EXPECT_EQ(1u, writer_->frame_count());
1672 ASSERT_EQ(1u, writer_->stream_frames().size());
1673 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id);
1676 TEST_P(QuicConnectionTest, FramePackingFEC) {
1677 EXPECT_TRUE(QuicConnectionPeer::GetPacketCreator(
1678 &connection_)->IsFecEnabled());
1680 CongestionBlockWrites();
1682 // Queue an ack and two stream frames. Ack gets flushed when FEC is turned on
1683 // for sending protected data; two stream frames are packing in 1 packet.
1684 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
1685 IgnoreResult(InvokeWithoutArgs(
1686 &connection_, &TestConnection::SendStreamData3WithFec)),
1687 IgnoreResult(InvokeWithoutArgs(
1688 &connection_, &TestConnection::SendStreamData5WithFec))));
1689 connection_.SendAck();
1691 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
1692 CongestionUnblockWrites();
1693 connection_.GetSendAlarm()->Fire();
1694 EXPECT_EQ(0u, connection_.NumQueuedPackets());
1695 EXPECT_FALSE(connection_.HasQueuedData());
1697 // Parse the last packet and ensure it's in an fec group.
1698 EXPECT_EQ(2u, writer_->header().fec_group);
1699 EXPECT_EQ(0u, writer_->frame_count());
1702 TEST_P(QuicConnectionTest, FramePackingAckResponse) {
1703 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1704 // Process a data packet to queue up a pending ack.
1705 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
1706 ProcessDataPacket(1, 1, kEntropyFlag);
1708 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
1709 IgnoreResult(InvokeWithoutArgs(&connection_,
1710 &TestConnection::SendStreamData3)),
1711 IgnoreResult(InvokeWithoutArgs(&connection_,
1712 &TestConnection::SendStreamData5))));
1714 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1716 // Process an ack to cause the visitor's OnCanWrite to be invoked.
1717 peer_creator_.set_sequence_number(2);
1718 QuicAckFrame ack_one = InitAckFrame(0);
1719 ProcessAckPacket(&ack_one);
1721 EXPECT_EQ(0u, connection_.NumQueuedPackets());
1722 EXPECT_FALSE(connection_.HasQueuedData());
1724 // Parse the last packet and ensure it's an ack and two stream frames from
1725 // two different streams.
1726 EXPECT_EQ(4u, writer_->frame_count());
1727 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
1728 EXPECT_FALSE(writer_->ack_frames().empty());
1729 ASSERT_EQ(2u, writer_->stream_frames().size());
1730 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id);
1731 EXPECT_EQ(kClientDataStreamId2, writer_->stream_frames()[1].stream_id);
1734 TEST_P(QuicConnectionTest, FramePackingSendv) {
1735 // Send data in 1 packet by writing multiple blocks in a single iovector
1736 // using writev.
1737 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
1739 char data[] = "ABCD";
1740 IOVector data_iov;
1741 data_iov.AppendNoCoalesce(data, 2);
1742 data_iov.AppendNoCoalesce(data + 2, 2);
1743 connection_.SendStreamData(1, data_iov, 0, !kFin, MAY_FEC_PROTECT, NULL);
1745 EXPECT_EQ(0u, connection_.NumQueuedPackets());
1746 EXPECT_FALSE(connection_.HasQueuedData());
1748 // Parse the last packet and ensure multiple iovector blocks have
1749 // been packed into a single stream frame from one stream.
1750 EXPECT_EQ(1u, writer_->frame_count());
1751 EXPECT_EQ(1u, writer_->stream_frames().size());
1752 QuicStreamFrame frame = writer_->stream_frames()[0];
1753 EXPECT_EQ(1u, frame.stream_id);
1754 EXPECT_EQ("ABCD", string(static_cast<char*>
1755 (frame.data.iovec()[0].iov_base),
1756 (frame.data.iovec()[0].iov_len)));
1759 TEST_P(QuicConnectionTest, FramePackingSendvQueued) {
1760 // Try to send two stream frames in 1 packet by using writev.
1761 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
1763 BlockOnNextWrite();
1764 char data[] = "ABCD";
1765 IOVector data_iov;
1766 data_iov.AppendNoCoalesce(data, 2);
1767 data_iov.AppendNoCoalesce(data + 2, 2);
1768 connection_.SendStreamData(1, data_iov, 0, !kFin, MAY_FEC_PROTECT, NULL);
1770 EXPECT_EQ(1u, connection_.NumQueuedPackets());
1771 EXPECT_TRUE(connection_.HasQueuedData());
1773 // Unblock the writes and actually send.
1774 writer_->SetWritable();
1775 connection_.OnCanWrite();
1776 EXPECT_EQ(0u, connection_.NumQueuedPackets());
1778 // Parse the last packet and ensure it's one stream frame from one stream.
1779 EXPECT_EQ(1u, writer_->frame_count());
1780 EXPECT_EQ(1u, writer_->stream_frames().size());
1781 EXPECT_EQ(1u, writer_->stream_frames()[0].stream_id);
1784 TEST_P(QuicConnectionTest, SendingZeroBytes) {
1785 // Send a zero byte write with a fin using writev.
1786 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
1787 IOVector empty_iov;
1788 connection_.SendStreamData(1, empty_iov, 0, kFin, MAY_FEC_PROTECT, NULL);
1790 EXPECT_EQ(0u, connection_.NumQueuedPackets());
1791 EXPECT_FALSE(connection_.HasQueuedData());
1793 // Parse the last packet and ensure it's one stream frame from one stream.
1794 EXPECT_EQ(1u, writer_->frame_count());
1795 EXPECT_EQ(1u, writer_->stream_frames().size());
1796 EXPECT_EQ(1u, writer_->stream_frames()[0].stream_id);
1797 EXPECT_TRUE(writer_->stream_frames()[0].fin);
1800 TEST_P(QuicConnectionTest, OnCanWrite) {
1801 // Visitor's OnCanWrite will send data, but will have more pending writes.
1802 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
1803 IgnoreResult(InvokeWithoutArgs(&connection_,
1804 &TestConnection::SendStreamData3)),
1805 IgnoreResult(InvokeWithoutArgs(&connection_,
1806 &TestConnection::SendStreamData5))));
1807 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillOnce(Return(true));
1808 EXPECT_CALL(*send_algorithm_,
1809 TimeUntilSend(_, _, _)).WillRepeatedly(
1810 testing::Return(QuicTime::Delta::Zero()));
1812 connection_.OnCanWrite();
1814 // Parse the last packet and ensure it's the two stream frames from
1815 // two different streams.
1816 EXPECT_EQ(2u, writer_->frame_count());
1817 EXPECT_EQ(2u, writer_->stream_frames().size());
1818 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id);
1819 EXPECT_EQ(kClientDataStreamId2, writer_->stream_frames()[1].stream_id);
1822 TEST_P(QuicConnectionTest, RetransmitOnNack) {
1823 QuicPacketSequenceNumber last_packet;
1824 QuicByteCount second_packet_size;
1825 SendStreamDataToPeer(3, "foo", 0, !kFin, &last_packet); // Packet 1
1826 second_packet_size =
1827 SendStreamDataToPeer(3, "foos", 3, !kFin, &last_packet); // Packet 2
1828 SendStreamDataToPeer(3, "fooos", 7, !kFin, &last_packet); // Packet 3
1830 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1832 // Don't lose a packet on an ack, and nothing is retransmitted.
1833 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1834 QuicAckFrame ack_one = InitAckFrame(1);
1835 ProcessAckPacket(&ack_one);
1837 // Lose a packet and ensure it triggers retransmission.
1838 QuicAckFrame nack_two = InitAckFrame(3);
1839 NackPacket(2, &nack_two);
1840 SequenceNumberSet lost_packets;
1841 lost_packets.insert(2);
1842 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1843 .WillOnce(Return(lost_packets));
1844 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1845 EXPECT_CALL(*send_algorithm_,
1846 OnPacketSent(_, _, _, second_packet_size - kQuicVersionSize, _)).
1847 Times(1);
1848 ProcessAckPacket(&nack_two);
1851 TEST_P(QuicConnectionTest, DiscardRetransmit) {
1852 QuicPacketSequenceNumber last_packet;
1853 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet); // Packet 1
1854 SendStreamDataToPeer(1, "foos", 3, !kFin, &last_packet); // Packet 2
1855 SendStreamDataToPeer(1, "fooos", 7, !kFin, &last_packet); // Packet 3
1857 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1859 // Instigate a loss with an ack.
1860 QuicAckFrame nack_two = InitAckFrame(3);
1861 NackPacket(2, &nack_two);
1862 // The first nack should trigger a fast retransmission, but we'll be
1863 // write blocked, so the packet will be queued.
1864 BlockOnNextWrite();
1865 SequenceNumberSet lost_packets;
1866 lost_packets.insert(2);
1867 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1868 .WillOnce(Return(lost_packets));
1869 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1870 ProcessAckPacket(&nack_two);
1871 EXPECT_EQ(1u, connection_.NumQueuedPackets());
1873 // Now, ack the previous transmission.
1874 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1875 .WillOnce(Return(SequenceNumberSet()));
1876 QuicAckFrame ack_all = InitAckFrame(3);
1877 ProcessAckPacket(&ack_all);
1879 // Unblock the socket and attempt to send the queued packets. However,
1880 // since the previous transmission has been acked, we will not
1881 // send the retransmission.
1882 EXPECT_CALL(*send_algorithm_,
1883 OnPacketSent(_, _, _, _, _)).Times(0);
1885 writer_->SetWritable();
1886 connection_.OnCanWrite();
1888 EXPECT_EQ(0u, connection_.NumQueuedPackets());
1891 TEST_P(QuicConnectionTest, RetransmitNackedLargestObserved) {
1892 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1893 QuicPacketSequenceNumber largest_observed;
1894 QuicByteCount packet_size;
1895 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1896 .WillOnce(DoAll(SaveArg<2>(&largest_observed), SaveArg<3>(&packet_size),
1897 Return(true)));
1898 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, NULL);
1900 QuicAckFrame frame = InitAckFrame(1);
1901 NackPacket(largest_observed, &frame);
1902 // The first nack should retransmit the largest observed packet.
1903 SequenceNumberSet lost_packets;
1904 lost_packets.insert(1);
1905 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1906 .WillOnce(Return(lost_packets));
1907 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1908 EXPECT_CALL(*send_algorithm_,
1909 OnPacketSent(_, _, _, packet_size - kQuicVersionSize, _));
1910 ProcessAckPacket(&frame);
1913 TEST_P(QuicConnectionTest, QueueAfterTwoRTOs) {
1914 for (int i = 0; i < 10; ++i) {
1915 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1916 connection_.SendStreamDataWithString(3, "foo", i * 3, !kFin, NULL);
1919 // Block the congestion window and ensure they're queued.
1920 BlockOnNextWrite();
1921 clock_.AdvanceTime(DefaultRetransmissionTime());
1922 // Only one packet should be retransmitted.
1923 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
1924 connection_.GetRetransmissionAlarm()->Fire();
1925 EXPECT_TRUE(connection_.HasQueuedData());
1927 // Unblock the congestion window.
1928 writer_->SetWritable();
1929 clock_.AdvanceTime(QuicTime::Delta::FromMicroseconds(
1930 2 * DefaultRetransmissionTime().ToMicroseconds()));
1931 // Retransmit already retransmitted packets event though the sequence number
1932 // greater than the largest observed.
1933 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(10);
1934 connection_.GetRetransmissionAlarm()->Fire();
1935 connection_.OnCanWrite();
1938 TEST_P(QuicConnectionTest, WriteBlockedThenSent) {
1939 BlockOnNextWrite();
1940 writer_->set_is_write_blocked_data_buffered(true);
1941 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1942 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, NULL);
1943 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
1945 writer_->SetWritable();
1946 connection_.OnCanWrite();
1947 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
1950 TEST_P(QuicConnectionTest, RetransmitWriteBlockedAckedOriginalThenSent) {
1951 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1952 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, NULL);
1953 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
1955 BlockOnNextWrite();
1956 writer_->set_is_write_blocked_data_buffered(true);
1957 // Simulate the retransmission alarm firing.
1958 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(_));
1959 clock_.AdvanceTime(DefaultRetransmissionTime());
1960 connection_.GetRetransmissionAlarm()->Fire();
1962 // Ack the sent packet before the callback returns, which happens in
1963 // rare circumstances with write blocked sockets.
1964 QuicAckFrame ack = InitAckFrame(1);
1965 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1966 EXPECT_CALL(*send_algorithm_, RevertRetransmissionTimeout());
1967 ProcessAckPacket(&ack);
1969 writer_->SetWritable();
1970 connection_.OnCanWrite();
1971 // There is now a pending packet, but with no retransmittable frames.
1972 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
1973 EXPECT_FALSE(connection_.sent_packet_manager().HasRetransmittableFrames(2));
1976 TEST_P(QuicConnectionTest, AlarmsWhenWriteBlocked) {
1977 // Block the connection.
1978 BlockOnNextWrite();
1979 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, NULL);
1980 EXPECT_EQ(1u, writer_->packets_write_attempts());
1981 EXPECT_TRUE(writer_->IsWriteBlocked());
1983 // Set the send and resumption alarms. Fire the alarms and ensure they don't
1984 // attempt to write.
1985 connection_.GetResumeWritesAlarm()->Set(clock_.ApproximateNow());
1986 connection_.GetSendAlarm()->Set(clock_.ApproximateNow());
1987 connection_.GetResumeWritesAlarm()->Fire();
1988 connection_.GetSendAlarm()->Fire();
1989 EXPECT_TRUE(writer_->IsWriteBlocked());
1990 EXPECT_EQ(1u, writer_->packets_write_attempts());
1993 TEST_P(QuicConnectionTest, NoLimitPacketsPerNack) {
1994 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1995 int offset = 0;
1996 // Send packets 1 to 15.
1997 for (int i = 0; i < 15; ++i) {
1998 SendStreamDataToPeer(1, "foo", offset, !kFin, NULL);
1999 offset += 3;
2002 // Ack 15, nack 1-14.
2003 SequenceNumberSet lost_packets;
2004 QuicAckFrame nack = InitAckFrame(15);
2005 for (int i = 1; i < 15; ++i) {
2006 NackPacket(i, &nack);
2007 lost_packets.insert(i);
2010 // 14 packets have been NACK'd and lost. In TCP cubic, PRR limits
2011 // the retransmission rate in the case of burst losses.
2012 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2013 .WillOnce(Return(lost_packets));
2014 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2015 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(14);
2016 ProcessAckPacket(&nack);
2019 // Test sending multiple acks from the connection to the session.
2020 TEST_P(QuicConnectionTest, MultipleAcks) {
2021 QuicPacketSequenceNumber last_packet;
2022 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet); // Packet 1
2023 EXPECT_EQ(1u, last_packet);
2024 SendStreamDataToPeer(3, "foo", 0, !kFin, &last_packet); // Packet 2
2025 EXPECT_EQ(2u, last_packet);
2026 SendAckPacketToPeer(); // Packet 3
2027 SendStreamDataToPeer(5, "foo", 0, !kFin, &last_packet); // Packet 4
2028 EXPECT_EQ(4u, last_packet);
2029 SendStreamDataToPeer(1, "foo", 3, !kFin, &last_packet); // Packet 5
2030 EXPECT_EQ(5u, last_packet);
2031 SendStreamDataToPeer(3, "foo", 3, !kFin, &last_packet); // Packet 6
2032 EXPECT_EQ(6u, last_packet);
2034 // Client will ack packets 1, 2, [!3], 4, 5.
2035 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2036 QuicAckFrame frame1 = InitAckFrame(5);
2037 NackPacket(3, &frame1);
2038 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2039 ProcessAckPacket(&frame1);
2041 // Now the client implicitly acks 3, and explicitly acks 6.
2042 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2043 QuicAckFrame frame2 = InitAckFrame(6);
2044 ProcessAckPacket(&frame2);
2047 TEST_P(QuicConnectionTest, DontLatchUnackedPacket) {
2048 SendStreamDataToPeer(1, "foo", 0, !kFin, NULL); // Packet 1;
2049 // From now on, we send acks, so the send algorithm won't mark them pending.
2050 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2051 .WillByDefault(Return(false));
2052 SendAckPacketToPeer(); // Packet 2
2054 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2055 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2056 QuicAckFrame frame = InitAckFrame(1);
2057 ProcessAckPacket(&frame);
2059 // Verify that our internal state has least-unacked as 2, because we're still
2060 // waiting for a potential ack for 2.
2062 EXPECT_EQ(2u, stop_waiting()->least_unacked);
2064 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2065 frame = InitAckFrame(2);
2066 ProcessAckPacket(&frame);
2067 EXPECT_EQ(3u, stop_waiting()->least_unacked);
2069 // When we send an ack, we make sure our least-unacked makes sense. In this
2070 // case since we're not waiting on an ack for 2 and all packets are acked, we
2071 // set it to 3.
2072 SendAckPacketToPeer(); // Packet 3
2073 // Least_unacked remains at 3 until another ack is received.
2074 EXPECT_EQ(3u, stop_waiting()->least_unacked);
2075 // Check that the outgoing ack had its sequence number as least_unacked.
2076 EXPECT_EQ(3u, least_unacked());
2078 // Ack the ack, which updates the rtt and raises the least unacked.
2079 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2080 frame = InitAckFrame(3);
2081 ProcessAckPacket(&frame);
2083 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2084 .WillByDefault(Return(true));
2085 SendStreamDataToPeer(1, "bar", 3, false, NULL); // Packet 4
2086 EXPECT_EQ(4u, stop_waiting()->least_unacked);
2087 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2088 .WillByDefault(Return(false));
2089 SendAckPacketToPeer(); // Packet 5
2090 EXPECT_EQ(4u, least_unacked());
2092 // Send two data packets at the end, and ensure if the last one is acked,
2093 // the least unacked is raised above the ack packets.
2094 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2095 .WillByDefault(Return(true));
2096 SendStreamDataToPeer(1, "bar", 6, false, NULL); // Packet 6
2097 SendStreamDataToPeer(1, "bar", 9, false, NULL); // Packet 7
2099 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2100 frame = InitAckFrame(7);
2101 NackPacket(5, &frame);
2102 NackPacket(6, &frame);
2103 ProcessAckPacket(&frame);
2105 EXPECT_EQ(6u, stop_waiting()->least_unacked);
2108 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterFecPacket) {
2109 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2111 // Don't send missing packet 1.
2112 ProcessFecPacket(2, 1, true, !kEntropyFlag, NULL);
2113 // Entropy flag should be false, so entropy should be 0.
2114 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2117 TEST_P(QuicConnectionTest, ReviveMissingPacketWithVaryingSeqNumLengths) {
2118 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2120 // Set up a debug visitor to the connection.
2121 FecQuicConnectionDebugVisitor* fec_visitor =
2122 new FecQuicConnectionDebugVisitor();
2123 connection_.set_debug_visitor(fec_visitor);
2125 QuicPacketSequenceNumber fec_packet = 0;
2126 QuicSequenceNumberLength lengths[] = {PACKET_6BYTE_SEQUENCE_NUMBER,
2127 PACKET_4BYTE_SEQUENCE_NUMBER,
2128 PACKET_2BYTE_SEQUENCE_NUMBER,
2129 PACKET_1BYTE_SEQUENCE_NUMBER};
2130 // For each sequence number length size, revive a packet and check sequence
2131 // number length in the revived packet.
2132 for (size_t i = 0; i < arraysize(lengths); ++i) {
2133 // Set sequence_number_length_ (for data and FEC packets).
2134 sequence_number_length_ = lengths[i];
2135 fec_packet += 2;
2136 // Don't send missing packet, but send fec packet right after it.
2137 ProcessFecPacket(fec_packet, fec_packet - 1, true, !kEntropyFlag, NULL);
2138 // Sequence number length in the revived header should be the same as
2139 // in the original data/fec packet headers.
2140 EXPECT_EQ(sequence_number_length_, fec_visitor->revived_header().
2141 public_header.sequence_number_length);
2145 TEST_P(QuicConnectionTest, ReviveMissingPacketWithVaryingConnectionIdLengths) {
2146 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2148 // Set up a debug visitor to the connection.
2149 FecQuicConnectionDebugVisitor* fec_visitor =
2150 new FecQuicConnectionDebugVisitor();
2151 connection_.set_debug_visitor(fec_visitor);
2153 QuicPacketSequenceNumber fec_packet = 0;
2154 QuicConnectionIdLength lengths[] = {PACKET_8BYTE_CONNECTION_ID,
2155 PACKET_4BYTE_CONNECTION_ID,
2156 PACKET_1BYTE_CONNECTION_ID,
2157 PACKET_0BYTE_CONNECTION_ID};
2158 // For each connection id length size, revive a packet and check connection
2159 // id length in the revived packet.
2160 for (size_t i = 0; i < arraysize(lengths); ++i) {
2161 // Set connection id length (for data and FEC packets).
2162 connection_id_length_ = lengths[i];
2163 fec_packet += 2;
2164 // Don't send missing packet, but send fec packet right after it.
2165 ProcessFecPacket(fec_packet, fec_packet - 1, true, !kEntropyFlag, NULL);
2166 // Connection id length in the revived header should be the same as
2167 // in the original data/fec packet headers.
2168 EXPECT_EQ(connection_id_length_,
2169 fec_visitor->revived_header().public_header.connection_id_length);
2173 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPacketThenFecPacket) {
2174 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2176 ProcessFecProtectedPacket(1, false, kEntropyFlag);
2177 // Don't send missing packet 2.
2178 ProcessFecPacket(3, 1, true, !kEntropyFlag, NULL);
2179 // Entropy flag should be true, so entropy should not be 0.
2180 EXPECT_NE(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2183 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPacketsThenFecPacket) {
2184 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2186 ProcessFecProtectedPacket(1, false, !kEntropyFlag);
2187 // Don't send missing packet 2.
2188 ProcessFecProtectedPacket(3, false, !kEntropyFlag);
2189 ProcessFecPacket(4, 1, true, kEntropyFlag, NULL);
2190 // Ensure QUIC no longer revives entropy for lost packets.
2191 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2192 EXPECT_NE(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 4));
2195 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPacket) {
2196 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2198 // Don't send missing packet 1.
2199 ProcessFecPacket(3, 1, false, !kEntropyFlag, NULL);
2200 // Out of order.
2201 ProcessFecProtectedPacket(2, true, !kEntropyFlag);
2202 // Entropy flag should be false, so entropy should be 0.
2203 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2206 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPackets) {
2207 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2209 ProcessFecProtectedPacket(1, false, !kEntropyFlag);
2210 // Don't send missing packet 2.
2211 ProcessFecPacket(6, 1, false, kEntropyFlag, NULL);
2212 ProcessFecProtectedPacket(3, false, kEntropyFlag);
2213 ProcessFecProtectedPacket(4, false, kEntropyFlag);
2214 ProcessFecProtectedPacket(5, true, !kEntropyFlag);
2215 // Ensure entropy is not revived for the missing packet.
2216 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2217 EXPECT_NE(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 3));
2220 TEST_P(QuicConnectionTest, TLP) {
2221 QuicSentPacketManagerPeer::SetMaxTailLossProbes(
2222 QuicConnectionPeer::GetSentPacketManager(&connection_), 1);
2224 SendStreamDataToPeer(3, "foo", 0, !kFin, NULL);
2225 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2226 QuicTime retransmission_time =
2227 connection_.GetRetransmissionAlarm()->deadline();
2228 EXPECT_NE(QuicTime::Zero(), retransmission_time);
2230 EXPECT_EQ(1u, writer_->header().packet_sequence_number);
2231 // Simulate the retransmission alarm firing and sending a tlp,
2232 // so send algorithm's OnRetransmissionTimeout is not called.
2233 clock_.AdvanceTime(retransmission_time.Subtract(clock_.Now()));
2234 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 2u, _, _));
2235 connection_.GetRetransmissionAlarm()->Fire();
2236 EXPECT_EQ(2u, writer_->header().packet_sequence_number);
2237 // We do not raise the high water mark yet.
2238 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2241 TEST_P(QuicConnectionTest, RTO) {
2242 QuicTime default_retransmission_time = clock_.ApproximateNow().Add(
2243 DefaultRetransmissionTime());
2244 SendStreamDataToPeer(3, "foo", 0, !kFin, NULL);
2245 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2247 EXPECT_EQ(1u, writer_->header().packet_sequence_number);
2248 EXPECT_EQ(default_retransmission_time,
2249 connection_.GetRetransmissionAlarm()->deadline());
2250 // Simulate the retransmission alarm firing.
2251 clock_.AdvanceTime(DefaultRetransmissionTime());
2252 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
2253 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 2u, _, _));
2254 connection_.GetRetransmissionAlarm()->Fire();
2255 EXPECT_EQ(2u, writer_->header().packet_sequence_number);
2256 // We do not raise the high water mark yet.
2257 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2260 TEST_P(QuicConnectionTest, RTOWithSameEncryptionLevel) {
2261 QuicTime default_retransmission_time = clock_.ApproximateNow().Add(
2262 DefaultRetransmissionTime());
2263 use_tagging_decrypter();
2265 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
2266 // the end of the packet. We can test this to check which encrypter was used.
2267 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2268 SendStreamDataToPeer(3, "foo", 0, !kFin, NULL);
2269 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
2271 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2272 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2273 SendStreamDataToPeer(3, "foo", 0, !kFin, NULL);
2274 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2276 EXPECT_EQ(default_retransmission_time,
2277 connection_.GetRetransmissionAlarm()->deadline());
2279 InSequence s;
2280 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
2281 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 3, _, _));
2282 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 4, _, _));
2285 // Simulate the retransmission alarm firing.
2286 clock_.AdvanceTime(DefaultRetransmissionTime());
2287 connection_.GetRetransmissionAlarm()->Fire();
2289 // Packet should have been sent with ENCRYPTION_NONE.
2290 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_previous_packet());
2292 // Packet should have been sent with ENCRYPTION_INITIAL.
2293 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2296 TEST_P(QuicConnectionTest, SendHandshakeMessages) {
2297 use_tagging_decrypter();
2298 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
2299 // the end of the packet. We can test this to check which encrypter was used.
2300 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2302 // Attempt to send a handshake message and have the socket block.
2303 EXPECT_CALL(*send_algorithm_,
2304 TimeUntilSend(_, _, _)).WillRepeatedly(
2305 testing::Return(QuicTime::Delta::Zero()));
2306 BlockOnNextWrite();
2307 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, NULL);
2308 // The packet should be serialized, but not queued.
2309 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2311 // Switch to the new encrypter.
2312 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2313 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2315 // Now become writeable and flush the packets.
2316 writer_->SetWritable();
2317 EXPECT_CALL(visitor_, OnCanWrite());
2318 connection_.OnCanWrite();
2319 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2321 // Verify that the handshake packet went out at the null encryption.
2322 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
2325 TEST_P(QuicConnectionTest,
2326 DropRetransmitsForNullEncryptedPacketAfterForwardSecure) {
2327 use_tagging_decrypter();
2328 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2329 QuicPacketSequenceNumber sequence_number;
2330 SendStreamDataToPeer(3, "foo", 0, !kFin, &sequence_number);
2332 // Simulate the retransmission alarm firing and the socket blocking.
2333 BlockOnNextWrite();
2334 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
2335 clock_.AdvanceTime(DefaultRetransmissionTime());
2336 connection_.GetRetransmissionAlarm()->Fire();
2338 // Go forward secure.
2339 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
2340 new TaggingEncrypter(0x02));
2341 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2342 connection_.NeuterUnencryptedPackets();
2344 EXPECT_EQ(QuicTime::Zero(),
2345 connection_.GetRetransmissionAlarm()->deadline());
2346 // Unblock the socket and ensure that no packets are sent.
2347 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
2348 writer_->SetWritable();
2349 connection_.OnCanWrite();
2352 TEST_P(QuicConnectionTest, RetransmitPacketsWithInitialEncryption) {
2353 use_tagging_decrypter();
2354 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2355 connection_.SetDefaultEncryptionLevel(ENCRYPTION_NONE);
2357 SendStreamDataToPeer(1, "foo", 0, !kFin, NULL);
2359 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2360 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2362 SendStreamDataToPeer(2, "bar", 0, !kFin, NULL);
2363 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2365 connection_.RetransmitUnackedPackets(INITIAL_ENCRYPTION_ONLY);
2368 TEST_P(QuicConnectionTest, BufferNonDecryptablePackets) {
2369 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2370 use_tagging_decrypter();
2372 const uint8 tag = 0x07;
2373 framer_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
2375 // Process an encrypted packet which can not yet be decrypted
2376 // which should result in the packet being buffered.
2377 ProcessDataPacketAtLevel(1, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2379 // Transition to the new encryption state and process another
2380 // encrypted packet which should result in the original packet being
2381 // processed.
2382 connection_.SetDecrypter(new StrictTaggingDecrypter(tag),
2383 ENCRYPTION_INITIAL);
2384 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2385 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
2386 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(2);
2387 ProcessDataPacketAtLevel(2, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2389 // Finally, process a third packet and note that we do not
2390 // reprocess the buffered packet.
2391 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
2392 ProcessDataPacketAtLevel(3, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2395 TEST_P(QuicConnectionTest, TestRetransmitOrder) {
2396 QuicByteCount first_packet_size;
2397 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).WillOnce(
2398 DoAll(SaveArg<3>(&first_packet_size), Return(true)));
2400 connection_.SendStreamDataWithString(3, "first_packet", 0, !kFin, NULL);
2401 QuicByteCount second_packet_size;
2402 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).WillOnce(
2403 DoAll(SaveArg<3>(&second_packet_size), Return(true)));
2404 connection_.SendStreamDataWithString(3, "second_packet", 12, !kFin, NULL);
2405 EXPECT_NE(first_packet_size, second_packet_size);
2406 // Advance the clock by huge time to make sure packets will be retransmitted.
2407 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
2408 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
2410 InSequence s;
2411 EXPECT_CALL(*send_algorithm_,
2412 OnPacketSent(_, _, _, first_packet_size, _));
2413 EXPECT_CALL(*send_algorithm_,
2414 OnPacketSent(_, _, _, second_packet_size, _));
2416 connection_.GetRetransmissionAlarm()->Fire();
2418 // Advance again and expect the packets to be sent again in the same order.
2419 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(20));
2420 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
2422 InSequence s;
2423 EXPECT_CALL(*send_algorithm_,
2424 OnPacketSent(_, _, _, first_packet_size, _));
2425 EXPECT_CALL(*send_algorithm_,
2426 OnPacketSent(_, _, _, second_packet_size, _));
2428 connection_.GetRetransmissionAlarm()->Fire();
2431 TEST_P(QuicConnectionTest, RetransmissionCountCalculation) {
2432 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2433 QuicPacketSequenceNumber original_sequence_number;
2434 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2435 .WillOnce(DoAll(SaveArg<2>(&original_sequence_number), Return(true)));
2436 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, NULL);
2438 EXPECT_TRUE(QuicConnectionPeer::IsSavedForRetransmission(
2439 &connection_, original_sequence_number));
2440 EXPECT_FALSE(QuicConnectionPeer::IsRetransmission(
2441 &connection_, original_sequence_number));
2442 // Force retransmission due to RTO.
2443 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
2444 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
2445 QuicPacketSequenceNumber rto_sequence_number;
2446 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2447 .WillOnce(DoAll(SaveArg<2>(&rto_sequence_number), Return(true)));
2448 connection_.GetRetransmissionAlarm()->Fire();
2449 EXPECT_FALSE(QuicConnectionPeer::IsSavedForRetransmission(
2450 &connection_, original_sequence_number));
2451 ASSERT_TRUE(QuicConnectionPeer::IsSavedForRetransmission(
2452 &connection_, rto_sequence_number));
2453 EXPECT_TRUE(QuicConnectionPeer::IsRetransmission(
2454 &connection_, rto_sequence_number));
2455 // Once by explicit nack.
2456 SequenceNumberSet lost_packets;
2457 lost_packets.insert(rto_sequence_number);
2458 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2459 .WillOnce(Return(lost_packets));
2460 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2461 QuicPacketSequenceNumber nack_sequence_number = 0;
2462 // Ack packets might generate some other packets, which are not
2463 // retransmissions. (More ack packets).
2464 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2465 .Times(AnyNumber());
2466 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2467 .WillOnce(DoAll(SaveArg<2>(&nack_sequence_number), Return(true)));
2468 QuicAckFrame ack = InitAckFrame(rto_sequence_number);
2469 // Nack the retransmitted packet.
2470 NackPacket(original_sequence_number, &ack);
2471 NackPacket(rto_sequence_number, &ack);
2472 ProcessAckPacket(&ack);
2474 ASSERT_NE(0u, nack_sequence_number);
2475 EXPECT_FALSE(QuicConnectionPeer::IsSavedForRetransmission(
2476 &connection_, rto_sequence_number));
2477 ASSERT_TRUE(QuicConnectionPeer::IsSavedForRetransmission(
2478 &connection_, nack_sequence_number));
2479 EXPECT_TRUE(QuicConnectionPeer::IsRetransmission(
2480 &connection_, nack_sequence_number));
2483 TEST_P(QuicConnectionTest, SetRTOAfterWritingToSocket) {
2484 BlockOnNextWrite();
2485 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, NULL);
2486 // Make sure that RTO is not started when the packet is queued.
2487 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
2489 // Test that RTO is started once we write to the socket.
2490 writer_->SetWritable();
2491 connection_.OnCanWrite();
2492 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2495 TEST_P(QuicConnectionTest, DelayRTOWithAckReceipt) {
2496 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2497 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2498 .Times(2);
2499 connection_.SendStreamDataWithString(2, "foo", 0, !kFin, NULL);
2500 connection_.SendStreamDataWithString(3, "bar", 0, !kFin, NULL);
2501 QuicAlarm* retransmission_alarm = connection_.GetRetransmissionAlarm();
2502 EXPECT_TRUE(retransmission_alarm->IsSet());
2503 EXPECT_EQ(clock_.Now().Add(DefaultRetransmissionTime()),
2504 retransmission_alarm->deadline());
2506 // Advance the time right before the RTO, then receive an ack for the first
2507 // packet to delay the RTO.
2508 clock_.AdvanceTime(DefaultRetransmissionTime());
2509 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2510 QuicAckFrame ack = InitAckFrame(1);
2511 ProcessAckPacket(&ack);
2512 EXPECT_TRUE(retransmission_alarm->IsSet());
2513 EXPECT_GT(retransmission_alarm->deadline(), clock_.Now());
2515 // Move forward past the original RTO and ensure the RTO is still pending.
2516 clock_.AdvanceTime(DefaultRetransmissionTime().Multiply(2));
2518 // Ensure the second packet gets retransmitted when it finally fires.
2519 EXPECT_TRUE(retransmission_alarm->IsSet());
2520 EXPECT_LT(retransmission_alarm->deadline(), clock_.ApproximateNow());
2521 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
2522 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2523 // Manually cancel the alarm to simulate a real test.
2524 connection_.GetRetransmissionAlarm()->Fire();
2526 // The new retransmitted sequence number should set the RTO to a larger value
2527 // than previously.
2528 EXPECT_TRUE(retransmission_alarm->IsSet());
2529 QuicTime next_rto_time = retransmission_alarm->deadline();
2530 QuicTime expected_rto_time =
2531 connection_.sent_packet_manager().GetRetransmissionTime();
2532 EXPECT_EQ(next_rto_time, expected_rto_time);
2535 TEST_P(QuicConnectionTest, TestQueued) {
2536 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2537 BlockOnNextWrite();
2538 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, NULL);
2539 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2541 // Unblock the writes and actually send.
2542 writer_->SetWritable();
2543 connection_.OnCanWrite();
2544 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2547 TEST_P(QuicConnectionTest, CloseFecGroup) {
2548 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2549 // Don't send missing packet 1.
2550 // Don't send missing packet 2.
2551 ProcessFecProtectedPacket(3, false, !kEntropyFlag);
2552 // Don't send missing FEC packet 3.
2553 ASSERT_EQ(1u, connection_.NumFecGroups());
2555 // Now send non-fec protected ack packet and close the group.
2556 peer_creator_.set_sequence_number(4);
2557 QuicStopWaitingFrame frame = InitStopWaitingFrame(5);
2558 ProcessStopWaitingPacket(&frame);
2559 ASSERT_EQ(0u, connection_.NumFecGroups());
2562 TEST_P(QuicConnectionTest, NoQuicCongestionFeedbackFrame) {
2563 SendAckPacketToPeer();
2564 EXPECT_TRUE(writer_->feedback_frames().empty());
2567 TEST_P(QuicConnectionTest, WithQuicCongestionFeedbackFrame) {
2568 QuicCongestionFeedbackFrame info;
2569 info.type = kTCP;
2570 info.tcp.receive_window = 0x4030;
2572 // After QUIC_VERSION_22, do not send TCP Congestion Feedback Frames anymore.
2573 if (version() > QUIC_VERSION_22) {
2574 SendAckPacketToPeer();
2575 ASSERT_TRUE(writer_->feedback_frames().empty());
2576 } else {
2577 // Only SetFeedback in this case because SetFeedback will create a receive
2578 // algorithm which is how the received_packet_manager checks if it should be
2579 // creating TCP Congestion Feedback Frames.
2580 SetFeedback(&info);
2581 SendAckPacketToPeer();
2582 ASSERT_FALSE(writer_->feedback_frames().empty());
2583 ASSERT_EQ(kTCP, writer_->feedback_frames()[0].type);
2587 TEST_P(QuicConnectionTest, UpdateQuicCongestionFeedbackFrame) {
2588 SendAckPacketToPeer();
2589 EXPECT_CALL(*receive_algorithm_, RecordIncomingPacket(_, _, _));
2590 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2591 ProcessPacket(1);
2594 TEST_P(QuicConnectionTest, DontUpdateQuicCongestionFeedbackFrameForRevived) {
2595 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2596 SendAckPacketToPeer();
2597 // Process an FEC packet, and revive the missing data packet
2598 // but only contact the receive_algorithm once.
2599 EXPECT_CALL(*receive_algorithm_, RecordIncomingPacket(_, _, _));
2600 ProcessFecPacket(2, 1, true, !kEntropyFlag, NULL);
2603 TEST_P(QuicConnectionTest, InitialTimeout) {
2604 EXPECT_TRUE(connection_.connected());
2605 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_CONNECTION_TIMED_OUT, false));
2606 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2608 QuicTime default_timeout = clock_.ApproximateNow().Add(
2609 QuicTime::Delta::FromSeconds(kDefaultInitialTimeoutSecs));
2610 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
2612 // Simulate the timeout alarm firing.
2613 clock_.AdvanceTime(
2614 QuicTime::Delta::FromSeconds(kDefaultInitialTimeoutSecs));
2615 connection_.GetTimeoutAlarm()->Fire();
2616 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
2617 EXPECT_FALSE(connection_.connected());
2619 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
2620 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
2621 EXPECT_FALSE(connection_.GetResumeWritesAlarm()->IsSet());
2622 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
2623 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
2624 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
2627 TEST_P(QuicConnectionTest, PingAfterSend) {
2628 EXPECT_TRUE(connection_.connected());
2629 EXPECT_CALL(visitor_, HasOpenDataStreams()).WillRepeatedly(Return(true));
2630 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
2632 // Advance to 5ms, and send a packet to the peer, which will set
2633 // the ping alarm.
2634 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
2635 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
2636 SendStreamDataToPeer(1, "GET /", 0, kFin, NULL);
2637 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
2638 EXPECT_EQ(clock_.ApproximateNow().Add(QuicTime::Delta::FromSeconds(15)),
2639 connection_.GetPingAlarm()->deadline());
2641 // Now recevie and ACK of the previous packet, which will move the
2642 // ping alarm forward.
2643 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
2644 QuicAckFrame frame = InitAckFrame(1);
2645 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2646 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2647 ProcessAckPacket(&frame);
2648 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
2649 // The ping timer is set slightly less than 15 seconds in the future, because
2650 // of the 1s ping timer alarm granularity.
2651 EXPECT_EQ(clock_.ApproximateNow().Add(QuicTime::Delta::FromSeconds(15))
2652 .Subtract(QuicTime::Delta::FromMilliseconds(5)),
2653 connection_.GetPingAlarm()->deadline());
2655 writer_->Reset();
2656 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15));
2657 connection_.GetPingAlarm()->Fire();
2658 EXPECT_EQ(1u, writer_->frame_count());
2659 if (version() >= QUIC_VERSION_18) {
2660 ASSERT_EQ(1u, writer_->ping_frames().size());
2661 } else {
2662 ASSERT_EQ(1u, writer_->stream_frames().size());
2663 EXPECT_EQ(kCryptoStreamId, writer_->stream_frames()[0].stream_id);
2664 EXPECT_EQ(0u, writer_->stream_frames()[0].offset);
2666 writer_->Reset();
2668 EXPECT_CALL(visitor_, HasOpenDataStreams()).WillRepeatedly(Return(false));
2669 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
2670 SendAckPacketToPeer();
2672 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
2675 TEST_P(QuicConnectionTest, TimeoutAfterSend) {
2676 EXPECT_TRUE(connection_.connected());
2678 QuicTime default_timeout = clock_.ApproximateNow().Add(
2679 QuicTime::Delta::FromSeconds(kDefaultInitialTimeoutSecs));
2681 // When we send a packet, the timeout will change to 5000 +
2682 // kDefaultInitialTimeoutSecs.
2683 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
2685 // Send an ack so we don't set the retransmission alarm.
2686 SendAckPacketToPeer();
2687 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
2689 // The original alarm will fire. We should not time out because we had a
2690 // network event at t=5000. The alarm will reregister.
2691 clock_.AdvanceTime(QuicTime::Delta::FromMicroseconds(
2692 kDefaultInitialTimeoutSecs * 1000000 - 5000));
2693 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
2694 connection_.GetTimeoutAlarm()->Fire();
2695 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
2696 EXPECT_TRUE(connection_.connected());
2697 EXPECT_EQ(default_timeout.Add(QuicTime::Delta::FromMilliseconds(5)),
2698 connection_.GetTimeoutAlarm()->deadline());
2700 // This time, we should time out.
2701 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_CONNECTION_TIMED_OUT, false));
2702 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2703 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
2704 EXPECT_EQ(default_timeout.Add(QuicTime::Delta::FromMilliseconds(5)),
2705 clock_.ApproximateNow());
2706 connection_.GetTimeoutAlarm()->Fire();
2707 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
2708 EXPECT_FALSE(connection_.connected());
2711 TEST_P(QuicConnectionTest, SendScheduler) {
2712 // Test that if we send a packet without delay, it is not queued.
2713 QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
2714 EXPECT_CALL(*send_algorithm_,
2715 TimeUntilSend(_, _, _)).WillOnce(
2716 testing::Return(QuicTime::Delta::Zero()));
2717 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2718 connection_.SendPacket(
2719 ENCRYPTION_NONE, 1, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA);
2720 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2723 TEST_P(QuicConnectionTest, SendSchedulerDelay) {
2724 // Test that if we send a packet with a delay, it ends up queued.
2725 QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
2726 EXPECT_CALL(*send_algorithm_,
2727 TimeUntilSend(_, _, _)).WillOnce(
2728 testing::Return(QuicTime::Delta::FromMicroseconds(1)));
2729 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 1, _, _)).Times(0);
2730 connection_.SendPacket(
2731 ENCRYPTION_NONE, 1, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA);
2732 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2735 TEST_P(QuicConnectionTest, SendSchedulerEAGAIN) {
2736 QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
2737 BlockOnNextWrite();
2738 EXPECT_CALL(*send_algorithm_,
2739 TimeUntilSend(_, _, _)).WillOnce(
2740 testing::Return(QuicTime::Delta::Zero()));
2741 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 1, _, _)).Times(0);
2742 connection_.SendPacket(
2743 ENCRYPTION_NONE, 1, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA);
2744 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2747 TEST_P(QuicConnectionTest, SendSchedulerDelayThenSend) {
2748 // Test that if we send a packet with a delay, it ends up queued.
2749 QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
2750 EXPECT_CALL(*send_algorithm_,
2751 TimeUntilSend(_, _, _)).WillOnce(
2752 testing::Return(QuicTime::Delta::FromMicroseconds(1)));
2753 connection_.SendPacket(
2754 ENCRYPTION_NONE, 1, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA);
2755 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2757 // Advance the clock to fire the alarm, and configure the scheduler
2758 // to permit the packet to be sent.
2759 EXPECT_CALL(*send_algorithm_,
2760 TimeUntilSend(_, _, _)).WillRepeatedly(
2761 testing::Return(QuicTime::Delta::Zero()));
2762 clock_.AdvanceTime(QuicTime::Delta::FromMicroseconds(1));
2763 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2764 connection_.GetSendAlarm()->Fire();
2765 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2768 TEST_P(QuicConnectionTest, SendSchedulerDelayThenRetransmit) {
2769 CongestionUnblockWrites();
2770 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 1, _, _));
2771 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, NULL);
2772 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2773 // Advance the time for retransmission of lost packet.
2774 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(501));
2775 // Test that if we send a retransmit with a delay, it ends up queued in the
2776 // sent packet manager, but not yet serialized.
2777 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
2778 CongestionBlockWrites();
2779 connection_.GetRetransmissionAlarm()->Fire();
2780 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2782 // Advance the clock to fire the alarm, and configure the scheduler
2783 // to permit the packet to be sent.
2784 CongestionUnblockWrites();
2786 // Ensure the scheduler is notified this is a retransmit.
2787 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2788 clock_.AdvanceTime(QuicTime::Delta::FromMicroseconds(1));
2789 connection_.GetSendAlarm()->Fire();
2790 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2793 TEST_P(QuicConnectionTest, SendSchedulerDelayAndQueue) {
2794 QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
2795 EXPECT_CALL(*send_algorithm_,
2796 TimeUntilSend(_, _, _)).WillOnce(
2797 testing::Return(QuicTime::Delta::FromMicroseconds(1)));
2798 connection_.SendPacket(
2799 ENCRYPTION_NONE, 1, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA);
2800 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2802 // Attempt to send another packet and make sure that it gets queued.
2803 packet = ConstructDataPacket(2, 0, !kEntropyFlag);
2804 connection_.SendPacket(
2805 ENCRYPTION_NONE, 2, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA);
2806 EXPECT_EQ(2u, connection_.NumQueuedPackets());
2809 TEST_P(QuicConnectionTest, SendSchedulerDelayThenAckAndSend) {
2810 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2811 QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
2812 EXPECT_CALL(*send_algorithm_,
2813 TimeUntilSend(_, _, _)).WillOnce(
2814 testing::Return(QuicTime::Delta::FromMicroseconds(10)));
2815 connection_.SendPacket(
2816 ENCRYPTION_NONE, 1, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA);
2817 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2819 // Now send non-retransmitting information, that we're not going to
2820 // retransmit 3. The far end should stop waiting for it.
2821 QuicAckFrame frame = InitAckFrame(0);
2822 EXPECT_CALL(*send_algorithm_,
2823 TimeUntilSend(_, _, _)).WillRepeatedly(
2824 testing::Return(QuicTime::Delta::Zero()));
2825 EXPECT_CALL(*send_algorithm_,
2826 OnPacketSent(_, _, _, _, _));
2827 ProcessAckPacket(&frame);
2829 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2830 // Ensure alarm is not set
2831 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
2834 TEST_P(QuicConnectionTest, SendSchedulerDelayThenAckAndHold) {
2835 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2836 QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
2837 EXPECT_CALL(*send_algorithm_,
2838 TimeUntilSend(_, _, _)).WillOnce(
2839 testing::Return(QuicTime::Delta::FromMicroseconds(10)));
2840 connection_.SendPacket(
2841 ENCRYPTION_NONE, 1, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA);
2842 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2844 // Now send non-retransmitting information, that we're not going to
2845 // retransmit 3. The far end should stop waiting for it.
2846 QuicAckFrame frame = InitAckFrame(0);
2847 EXPECT_CALL(*send_algorithm_,
2848 TimeUntilSend(_, _, _)).WillOnce(
2849 testing::Return(QuicTime::Delta::FromMicroseconds(1)));
2850 ProcessAckPacket(&frame);
2852 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2855 TEST_P(QuicConnectionTest, SendSchedulerDelayThenOnCanWrite) {
2856 // TODO(ianswett): This test is unrealistic, because we would not serialize
2857 // new data if the send algorithm said not to.
2858 QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
2859 CongestionBlockWrites();
2860 connection_.SendPacket(
2861 ENCRYPTION_NONE, 1, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA);
2862 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2864 // OnCanWrite should send the packet, because it won't consult the send
2865 // algorithm for queued packets.
2866 connection_.OnCanWrite();
2867 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2870 TEST_P(QuicConnectionTest, TestQueueLimitsOnSendStreamData) {
2871 // All packets carry version info till version is negotiated.
2872 size_t payload_length;
2873 size_t length = GetPacketLengthForOneStream(
2874 connection_.version(), kIncludeVersion, PACKET_1BYTE_SEQUENCE_NUMBER,
2875 NOT_IN_FEC_GROUP, &payload_length);
2876 QuicConnectionPeer::GetPacketCreator(&connection_)->set_max_packet_length(
2877 length);
2879 // Queue the first packet.
2880 EXPECT_CALL(*send_algorithm_,
2881 TimeUntilSend(_, _, _)).WillOnce(
2882 testing::Return(QuicTime::Delta::FromMicroseconds(10)));
2883 const string payload(payload_length, 'a');
2884 EXPECT_EQ(0u,
2885 connection_.SendStreamDataWithString(3, payload, 0,
2886 !kFin, NULL).bytes_consumed);
2887 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2890 TEST_P(QuicConnectionTest, LoopThroughSendingPackets) {
2891 // All packets carry version info till version is negotiated.
2892 size_t payload_length;
2893 // GetPacketLengthForOneStream() assumes a stream offset of 0 in determining
2894 // packet length. The size of the offset field in a stream frame is 0 for
2895 // offset 0, and 2 for non-zero offsets up through 16K. Increase
2896 // max_packet_length by 2 so that subsequent packets containing subsequent
2897 // stream frames with non-zero offets will fit within the packet length.
2898 size_t length = 2 + GetPacketLengthForOneStream(
2899 connection_.version(), kIncludeVersion, PACKET_1BYTE_SEQUENCE_NUMBER,
2900 NOT_IN_FEC_GROUP, &payload_length);
2901 QuicConnectionPeer::GetPacketCreator(&connection_)->set_max_packet_length(
2902 length);
2904 // Queue the first packet.
2905 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(7);
2906 // The first stream frame will have 2 fewer overhead bytes than the other six.
2907 const string payload(payload_length * 7 + 2, 'a');
2908 EXPECT_EQ(payload.size(),
2909 connection_.SendStreamDataWithString(1, payload, 0,
2910 !kFin, NULL).bytes_consumed);
2913 TEST_P(QuicConnectionTest, SendDelayedAck) {
2914 QuicTime ack_time = clock_.ApproximateNow().Add(DefaultDelayedAckTime());
2915 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2916 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
2917 const uint8 tag = 0x07;
2918 connection_.SetDecrypter(new StrictTaggingDecrypter(tag),
2919 ENCRYPTION_INITIAL);
2920 framer_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
2921 // Process a packet from the non-crypto stream.
2922 frame1_.stream_id = 3;
2924 // The same as ProcessPacket(1) except that ENCRYPTION_INITIAL is used
2925 // instead of ENCRYPTION_NONE.
2926 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
2927 ProcessDataPacketAtLevel(1, 0, !kEntropyFlag, ENCRYPTION_INITIAL);
2929 // Check if delayed ack timer is running for the expected interval.
2930 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
2931 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
2932 // Simulate delayed ack alarm firing.
2933 connection_.GetAckAlarm()->Fire();
2934 // Check that ack is sent and that delayed ack alarm is reset.
2935 EXPECT_EQ(2u, writer_->frame_count());
2936 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
2937 EXPECT_FALSE(writer_->ack_frames().empty());
2938 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
2941 TEST_P(QuicConnectionTest, SendEarlyDelayedAckForCrypto) {
2942 QuicTime ack_time = clock_.ApproximateNow();
2943 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2944 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
2945 // Process a packet from the crypto stream, which is frame1_'s default.
2946 ProcessPacket(1);
2947 // Check if delayed ack timer is running for the expected interval.
2948 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
2949 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
2950 // Simulate delayed ack alarm firing.
2951 connection_.GetAckAlarm()->Fire();
2952 // Check that ack is sent and that delayed ack alarm is reset.
2953 EXPECT_EQ(2u, writer_->frame_count());
2954 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
2955 EXPECT_FALSE(writer_->ack_frames().empty());
2956 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
2959 TEST_P(QuicConnectionTest, SendDelayedAckOnSecondPacket) {
2960 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2961 ProcessPacket(1);
2962 ProcessPacket(2);
2963 // Check that ack is sent and that delayed ack alarm is reset.
2964 EXPECT_EQ(2u, writer_->frame_count());
2965 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
2966 EXPECT_FALSE(writer_->ack_frames().empty());
2967 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
2970 TEST_P(QuicConnectionTest, NoAckOnOldNacks) {
2971 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2972 // Drop one packet, triggering a sequence of acks.
2973 ProcessPacket(2);
2974 size_t frames_per_ack = 2;
2975 EXPECT_EQ(frames_per_ack, writer_->frame_count());
2976 EXPECT_FALSE(writer_->ack_frames().empty());
2977 writer_->Reset();
2978 ProcessPacket(3);
2979 EXPECT_EQ(frames_per_ack, writer_->frame_count());
2980 EXPECT_FALSE(writer_->ack_frames().empty());
2981 writer_->Reset();
2982 ProcessPacket(4);
2983 EXPECT_EQ(frames_per_ack, writer_->frame_count());
2984 EXPECT_FALSE(writer_->ack_frames().empty());
2985 writer_->Reset();
2986 ProcessPacket(5);
2987 EXPECT_EQ(frames_per_ack, writer_->frame_count());
2988 EXPECT_FALSE(writer_->ack_frames().empty());
2989 writer_->Reset();
2990 // Now only set the timer on the 6th packet, instead of sending another ack.
2991 ProcessPacket(6);
2992 EXPECT_EQ(0u, writer_->frame_count());
2993 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
2996 TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingPacket) {
2997 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2998 ProcessPacket(1);
2999 connection_.SendStreamDataWithString(kClientDataStreamId1, "foo", 0,
3000 !kFin, NULL);
3001 // Check that ack is bundled with outgoing data and that delayed ack
3002 // alarm is reset.
3003 EXPECT_EQ(3u, writer_->frame_count());
3004 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3005 EXPECT_FALSE(writer_->ack_frames().empty());
3006 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3009 TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingCryptoPacket) {
3010 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3011 ProcessPacket(1);
3012 connection_.SendStreamDataWithString(kCryptoStreamId, "foo", 0, !kFin, NULL);
3013 // Check that ack is bundled with outgoing crypto data.
3014 EXPECT_EQ(3u, writer_->frame_count());
3015 EXPECT_FALSE(writer_->ack_frames().empty());
3016 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3019 TEST_P(QuicConnectionTest, BundleAckForSecondCHLO) {
3020 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3021 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3022 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(
3023 IgnoreResult(InvokeWithoutArgs(&connection_,
3024 &TestConnection::SendCryptoStreamData)));
3025 // Process a packet from the crypto stream, which is frame1_'s default.
3026 // Receiving the CHLO as packet 2 first will cause the connection to
3027 // immediately send an ack, due to the packet gap.
3028 ProcessPacket(2);
3029 // Check that ack is sent and that delayed ack alarm is reset.
3030 EXPECT_EQ(3u, writer_->frame_count());
3031 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3032 EXPECT_EQ(1u, writer_->stream_frames().size());
3033 EXPECT_FALSE(writer_->ack_frames().empty());
3034 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3037 TEST_P(QuicConnectionTest, BundleAckWithDataOnIncomingAck) {
3038 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3039 connection_.SendStreamDataWithString(kClientDataStreamId1, "foo", 0,
3040 !kFin, NULL);
3041 connection_.SendStreamDataWithString(kClientDataStreamId1, "foo", 3,
3042 !kFin, NULL);
3043 // Ack the second packet, which will retransmit the first packet.
3044 QuicAckFrame ack = InitAckFrame(2);
3045 NackPacket(1, &ack);
3046 SequenceNumberSet lost_packets;
3047 lost_packets.insert(1);
3048 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3049 .WillOnce(Return(lost_packets));
3050 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3051 ProcessAckPacket(&ack);
3052 EXPECT_EQ(1u, writer_->frame_count());
3053 EXPECT_EQ(1u, writer_->stream_frames().size());
3054 writer_->Reset();
3056 // Now ack the retransmission, which will both raise the high water mark
3057 // and see if there is more data to send.
3058 ack = InitAckFrame(3);
3059 NackPacket(1, &ack);
3060 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3061 .WillOnce(Return(SequenceNumberSet()));
3062 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3063 ProcessAckPacket(&ack);
3065 // Check that no packet is sent and the ack alarm isn't set.
3066 EXPECT_EQ(0u, writer_->frame_count());
3067 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3068 writer_->Reset();
3070 // Send the same ack, but send both data and an ack together.
3071 ack = InitAckFrame(3);
3072 NackPacket(1, &ack);
3073 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3074 .WillOnce(Return(SequenceNumberSet()));
3075 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(
3076 IgnoreResult(InvokeWithoutArgs(
3077 &connection_,
3078 &TestConnection::EnsureWritableAndSendStreamData5)));
3079 ProcessAckPacket(&ack);
3081 // Check that ack is bundled with outgoing data and the delayed ack
3082 // alarm is reset.
3083 EXPECT_EQ(3u, writer_->frame_count());
3084 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3085 EXPECT_FALSE(writer_->ack_frames().empty());
3086 EXPECT_EQ(1u, writer_->stream_frames().size());
3087 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3090 TEST_P(QuicConnectionTest, NoAckSentForClose) {
3091 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3092 ProcessPacket(1);
3093 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, true));
3094 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3095 ProcessClosePacket(2, 0);
3098 TEST_P(QuicConnectionTest, SendWhenDisconnected) {
3099 EXPECT_TRUE(connection_.connected());
3100 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, false));
3101 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, false);
3102 EXPECT_FALSE(connection_.connected());
3103 QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
3104 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 1, _, _)).Times(0);
3105 connection_.SendPacket(
3106 ENCRYPTION_NONE, 1, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA);
3109 TEST_P(QuicConnectionTest, PublicReset) {
3110 QuicPublicResetPacket header;
3111 header.public_header.connection_id = connection_id_;
3112 header.public_header.reset_flag = true;
3113 header.public_header.version_flag = false;
3114 header.rejected_sequence_number = 10101;
3115 scoped_ptr<QuicEncryptedPacket> packet(
3116 framer_.BuildPublicResetPacket(header));
3117 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PUBLIC_RESET, true));
3118 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *packet);
3121 TEST_P(QuicConnectionTest, GoAway) {
3122 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3124 QuicGoAwayFrame goaway;
3125 goaway.last_good_stream_id = 1;
3126 goaway.error_code = QUIC_PEER_GOING_AWAY;
3127 goaway.reason_phrase = "Going away.";
3128 EXPECT_CALL(visitor_, OnGoAway(_));
3129 ProcessGoAwayPacket(&goaway);
3132 TEST_P(QuicConnectionTest, WindowUpdate) {
3133 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3135 QuicWindowUpdateFrame window_update;
3136 window_update.stream_id = 3;
3137 window_update.byte_offset = 1234;
3138 EXPECT_CALL(visitor_, OnWindowUpdateFrames(_));
3139 ProcessFramePacket(QuicFrame(&window_update));
3142 TEST_P(QuicConnectionTest, Blocked) {
3143 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3145 QuicBlockedFrame blocked;
3146 blocked.stream_id = 3;
3147 EXPECT_CALL(visitor_, OnBlockedFrames(_));
3148 ProcessFramePacket(QuicFrame(&blocked));
3151 TEST_P(QuicConnectionTest, InvalidPacket) {
3152 EXPECT_CALL(visitor_,
3153 OnConnectionClosed(QUIC_INVALID_PACKET_HEADER, false));
3154 QuicEncryptedPacket encrypted(NULL, 0);
3155 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), encrypted);
3156 // The connection close packet should have error details.
3157 ASSERT_FALSE(writer_->connection_close_frames().empty());
3158 EXPECT_EQ("Unable to read public flags.",
3159 writer_->connection_close_frames()[0].error_details);
3162 TEST_P(QuicConnectionTest, MissingPacketsBeforeLeastUnacked) {
3163 // Set the sequence number of the ack packet to be least unacked (4).
3164 peer_creator_.set_sequence_number(3);
3165 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3166 QuicStopWaitingFrame frame = InitStopWaitingFrame(4);
3167 ProcessStopWaitingPacket(&frame);
3168 EXPECT_TRUE(outgoing_ack()->missing_packets.empty());
3171 TEST_P(QuicConnectionTest, ReceivedEntropyHashCalculation) {
3172 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(AtLeast(1));
3173 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3174 ProcessDataPacket(1, 1, kEntropyFlag);
3175 ProcessDataPacket(4, 1, kEntropyFlag);
3176 ProcessDataPacket(3, 1, !kEntropyFlag);
3177 ProcessDataPacket(7, 1, kEntropyFlag);
3178 EXPECT_EQ(146u, outgoing_ack()->entropy_hash);
3181 TEST_P(QuicConnectionTest, ReceivedEntropyHashCalculationHalfFEC) {
3182 // FEC packets should not change the entropy hash calculation.
3183 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(AtLeast(1));
3184 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3185 ProcessDataPacket(1, 1, kEntropyFlag);
3186 ProcessFecPacket(4, 1, false, kEntropyFlag, NULL);
3187 ProcessDataPacket(3, 3, !kEntropyFlag);
3188 ProcessFecPacket(7, 3, false, kEntropyFlag, NULL);
3189 EXPECT_EQ(146u, outgoing_ack()->entropy_hash);
3192 TEST_P(QuicConnectionTest, UpdateEntropyForReceivedPackets) {
3193 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(AtLeast(1));
3194 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3195 ProcessDataPacket(1, 1, kEntropyFlag);
3196 ProcessDataPacket(5, 1, kEntropyFlag);
3197 ProcessDataPacket(4, 1, !kEntropyFlag);
3198 EXPECT_EQ(34u, outgoing_ack()->entropy_hash);
3199 // Make 4th packet my least unacked, and update entropy for 2, 3 packets.
3200 peer_creator_.set_sequence_number(5);
3201 QuicPacketEntropyHash six_packet_entropy_hash = 0;
3202 QuicPacketEntropyHash kRandomEntropyHash = 129u;
3203 QuicStopWaitingFrame frame = InitStopWaitingFrame(4);
3204 frame.entropy_hash = kRandomEntropyHash;
3205 if (ProcessStopWaitingPacket(&frame)) {
3206 six_packet_entropy_hash = 1 << 6;
3209 EXPECT_EQ((kRandomEntropyHash + (1 << 5) + six_packet_entropy_hash),
3210 outgoing_ack()->entropy_hash);
3213 TEST_P(QuicConnectionTest, UpdateEntropyHashUptoCurrentPacket) {
3214 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(AtLeast(1));
3215 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3216 ProcessDataPacket(1, 1, kEntropyFlag);
3217 ProcessDataPacket(5, 1, !kEntropyFlag);
3218 ProcessDataPacket(22, 1, kEntropyFlag);
3219 EXPECT_EQ(66u, outgoing_ack()->entropy_hash);
3220 peer_creator_.set_sequence_number(22);
3221 QuicPacketEntropyHash kRandomEntropyHash = 85u;
3222 // Current packet is the least unacked packet.
3223 QuicPacketEntropyHash ack_entropy_hash;
3224 QuicStopWaitingFrame frame = InitStopWaitingFrame(23);
3225 frame.entropy_hash = kRandomEntropyHash;
3226 ack_entropy_hash = ProcessStopWaitingPacket(&frame);
3227 EXPECT_EQ((kRandomEntropyHash + ack_entropy_hash),
3228 outgoing_ack()->entropy_hash);
3229 ProcessDataPacket(25, 1, kEntropyFlag);
3230 EXPECT_EQ((kRandomEntropyHash + ack_entropy_hash + (1 << (25 % 8))),
3231 outgoing_ack()->entropy_hash);
3234 TEST_P(QuicConnectionTest, EntropyCalculationForTruncatedAck) {
3235 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(AtLeast(1));
3236 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3237 QuicPacketEntropyHash entropy[51];
3238 entropy[0] = 0;
3239 for (int i = 1; i < 51; ++i) {
3240 bool should_send = i % 10 != 1;
3241 bool entropy_flag = (i & (i - 1)) != 0;
3242 if (!should_send) {
3243 entropy[i] = entropy[i - 1];
3244 continue;
3246 if (entropy_flag) {
3247 entropy[i] = entropy[i - 1] ^ (1 << (i % 8));
3248 } else {
3249 entropy[i] = entropy[i - 1];
3251 ProcessDataPacket(i, 1, entropy_flag);
3253 for (int i = 1; i < 50; ++i) {
3254 EXPECT_EQ(entropy[i], QuicConnectionPeer::ReceivedEntropyHash(
3255 &connection_, i));
3259 TEST_P(QuicConnectionTest, ServerSendsVersionNegotiationPacket) {
3260 connection_.SetSupportedVersions(QuicSupportedVersions());
3261 framer_.set_version_for_tests(QUIC_VERSION_UNSUPPORTED);
3263 QuicPacketHeader header;
3264 header.public_header.connection_id = connection_id_;
3265 header.public_header.reset_flag = false;
3266 header.public_header.version_flag = true;
3267 header.entropy_flag = false;
3268 header.fec_flag = false;
3269 header.packet_sequence_number = 12;
3270 header.fec_group = 0;
3272 QuicFrames frames;
3273 QuicFrame frame(&frame1_);
3274 frames.push_back(frame);
3275 scoped_ptr<QuicPacket> packet(
3276 BuildUnsizedDataPacket(&framer_, header, frames).packet);
3277 scoped_ptr<QuicEncryptedPacket> encrypted(
3278 framer_.EncryptPacket(ENCRYPTION_NONE, 12, *packet));
3280 framer_.set_version(version());
3281 connection_.set_is_server(true);
3282 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3283 EXPECT_TRUE(writer_->version_negotiation_packet() != NULL);
3285 size_t num_versions = arraysize(kSupportedQuicVersions);
3286 ASSERT_EQ(num_versions,
3287 writer_->version_negotiation_packet()->versions.size());
3289 // We expect all versions in kSupportedQuicVersions to be
3290 // included in the packet.
3291 for (size_t i = 0; i < num_versions; ++i) {
3292 EXPECT_EQ(kSupportedQuicVersions[i],
3293 writer_->version_negotiation_packet()->versions[i]);
3297 TEST_P(QuicConnectionTest, ServerSendsVersionNegotiationPacketSocketBlocked) {
3298 connection_.SetSupportedVersions(QuicSupportedVersions());
3299 framer_.set_version_for_tests(QUIC_VERSION_UNSUPPORTED);
3301 QuicPacketHeader header;
3302 header.public_header.connection_id = connection_id_;
3303 header.public_header.reset_flag = false;
3304 header.public_header.version_flag = true;
3305 header.entropy_flag = false;
3306 header.fec_flag = false;
3307 header.packet_sequence_number = 12;
3308 header.fec_group = 0;
3310 QuicFrames frames;
3311 QuicFrame frame(&frame1_);
3312 frames.push_back(frame);
3313 scoped_ptr<QuicPacket> packet(
3314 BuildUnsizedDataPacket(&framer_, header, frames).packet);
3315 scoped_ptr<QuicEncryptedPacket> encrypted(
3316 framer_.EncryptPacket(ENCRYPTION_NONE, 12, *packet));
3318 framer_.set_version(version());
3319 connection_.set_is_server(true);
3320 BlockOnNextWrite();
3321 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3322 EXPECT_EQ(0u, writer_->last_packet_size());
3323 EXPECT_TRUE(connection_.HasQueuedData());
3325 writer_->SetWritable();
3326 connection_.OnCanWrite();
3327 EXPECT_TRUE(writer_->version_negotiation_packet() != NULL);
3329 size_t num_versions = arraysize(kSupportedQuicVersions);
3330 ASSERT_EQ(num_versions,
3331 writer_->version_negotiation_packet()->versions.size());
3333 // We expect all versions in kSupportedQuicVersions to be
3334 // included in the packet.
3335 for (size_t i = 0; i < num_versions; ++i) {
3336 EXPECT_EQ(kSupportedQuicVersions[i],
3337 writer_->version_negotiation_packet()->versions[i]);
3341 TEST_P(QuicConnectionTest,
3342 ServerSendsVersionNegotiationPacketSocketBlockedDataBuffered) {
3343 connection_.SetSupportedVersions(QuicSupportedVersions());
3344 framer_.set_version_for_tests(QUIC_VERSION_UNSUPPORTED);
3346 QuicPacketHeader header;
3347 header.public_header.connection_id = connection_id_;
3348 header.public_header.reset_flag = false;
3349 header.public_header.version_flag = true;
3350 header.entropy_flag = false;
3351 header.fec_flag = false;
3352 header.packet_sequence_number = 12;
3353 header.fec_group = 0;
3355 QuicFrames frames;
3356 QuicFrame frame(&frame1_);
3357 frames.push_back(frame);
3358 scoped_ptr<QuicPacket> packet(
3359 BuildUnsizedDataPacket(&framer_, header, frames).packet);
3360 scoped_ptr<QuicEncryptedPacket> encrypted(
3361 framer_.EncryptPacket(ENCRYPTION_NONE, 12, *packet));
3363 framer_.set_version(version());
3364 connection_.set_is_server(true);
3365 BlockOnNextWrite();
3366 writer_->set_is_write_blocked_data_buffered(true);
3367 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3368 EXPECT_EQ(0u, writer_->last_packet_size());
3369 EXPECT_FALSE(connection_.HasQueuedData());
3372 TEST_P(QuicConnectionTest, ClientHandlesVersionNegotiation) {
3373 // Start out with some unsupported version.
3374 QuicConnectionPeer::GetFramer(&connection_)->set_version_for_tests(
3375 QUIC_VERSION_UNSUPPORTED);
3377 QuicPacketHeader header;
3378 header.public_header.connection_id = connection_id_;
3379 header.public_header.reset_flag = false;
3380 header.public_header.version_flag = true;
3381 header.entropy_flag = false;
3382 header.fec_flag = false;
3383 header.packet_sequence_number = 12;
3384 header.fec_group = 0;
3386 QuicVersionVector supported_versions;
3387 for (size_t i = 0; i < arraysize(kSupportedQuicVersions); ++i) {
3388 supported_versions.push_back(kSupportedQuicVersions[i]);
3391 // Send a version negotiation packet.
3392 scoped_ptr<QuicEncryptedPacket> encrypted(
3393 framer_.BuildVersionNegotiationPacket(
3394 header.public_header, supported_versions));
3395 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3397 // Now force another packet. The connection should transition into
3398 // NEGOTIATED_VERSION state and tell the packet creator to StopSendingVersion.
3399 header.public_header.version_flag = false;
3400 QuicFrames frames;
3401 QuicFrame frame(&frame1_);
3402 frames.push_back(frame);
3403 scoped_ptr<QuicPacket> packet(
3404 BuildUnsizedDataPacket(&framer_, header, frames).packet);
3405 encrypted.reset(framer_.EncryptPacket(ENCRYPTION_NONE, 12, *packet));
3406 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
3407 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3408 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3410 ASSERT_FALSE(QuicPacketCreatorPeer::SendVersionInPacket(
3411 QuicConnectionPeer::GetPacketCreator(&connection_)));
3414 TEST_P(QuicConnectionTest, BadVersionNegotiation) {
3415 QuicPacketHeader header;
3416 header.public_header.connection_id = connection_id_;
3417 header.public_header.reset_flag = false;
3418 header.public_header.version_flag = true;
3419 header.entropy_flag = false;
3420 header.fec_flag = false;
3421 header.packet_sequence_number = 12;
3422 header.fec_group = 0;
3424 QuicVersionVector supported_versions;
3425 for (size_t i = 0; i < arraysize(kSupportedQuicVersions); ++i) {
3426 supported_versions.push_back(kSupportedQuicVersions[i]);
3429 // Send a version negotiation packet with the version the client started with.
3430 // It should be rejected.
3431 EXPECT_CALL(visitor_,
3432 OnConnectionClosed(QUIC_INVALID_VERSION_NEGOTIATION_PACKET,
3433 false));
3434 scoped_ptr<QuicEncryptedPacket> encrypted(
3435 framer_.BuildVersionNegotiationPacket(
3436 header.public_header, supported_versions));
3437 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3440 TEST_P(QuicConnectionTest, CheckSendStats) {
3441 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3442 connection_.SendStreamDataWithString(3, "first", 0, !kFin, NULL);
3443 size_t first_packet_size = writer_->last_packet_size();
3445 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3446 connection_.SendStreamDataWithString(5, "second", 0, !kFin, NULL);
3447 size_t second_packet_size = writer_->last_packet_size();
3449 // 2 retransmissions due to rto, 1 due to explicit nack.
3450 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
3451 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
3453 // Retransmit due to RTO.
3454 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
3455 connection_.GetRetransmissionAlarm()->Fire();
3457 // Retransmit due to explicit nacks.
3458 QuicAckFrame nack_three = InitAckFrame(4);
3459 NackPacket(3, &nack_three);
3460 NackPacket(1, &nack_three);
3461 SequenceNumberSet lost_packets;
3462 lost_packets.insert(1);
3463 lost_packets.insert(3);
3464 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3465 .WillOnce(Return(lost_packets));
3466 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3467 EXPECT_CALL(visitor_, OnCanWrite()).Times(2);
3468 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3469 EXPECT_CALL(*send_algorithm_, RevertRetransmissionTimeout());
3470 ProcessAckPacket(&nack_three);
3472 EXPECT_CALL(*send_algorithm_, BandwidthEstimate()).WillOnce(
3473 Return(QuicBandwidth::Zero()));
3475 const uint32 kSlowStartThreshold = 23u;
3476 EXPECT_CALL(*send_algorithm_, GetSlowStartThreshold()).WillOnce(
3477 Return(kSlowStartThreshold));
3479 const QuicConnectionStats& stats = connection_.GetStats();
3480 EXPECT_EQ(3 * first_packet_size + 2 * second_packet_size - kQuicVersionSize,
3481 stats.bytes_sent);
3482 EXPECT_EQ(5u, stats.packets_sent);
3483 EXPECT_EQ(2 * first_packet_size + second_packet_size - kQuicVersionSize,
3484 stats.bytes_retransmitted);
3485 EXPECT_EQ(3u, stats.packets_retransmitted);
3486 EXPECT_EQ(1u, stats.rto_count);
3487 EXPECT_EQ(kMaxPacketSize, stats.congestion_window);
3488 EXPECT_EQ(kSlowStartThreshold, stats.slow_start_threshold);
3489 EXPECT_EQ(kDefaultMaxPacketSize, stats.max_packet_size);
3492 TEST_P(QuicConnectionTest, CheckReceiveStats) {
3493 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3495 size_t received_bytes = 0;
3496 received_bytes += ProcessFecProtectedPacket(1, false, !kEntropyFlag);
3497 received_bytes += ProcessFecProtectedPacket(3, false, !kEntropyFlag);
3498 // Should be counted against dropped packets.
3499 received_bytes += ProcessDataPacket(3, 1, !kEntropyFlag);
3500 received_bytes += ProcessFecPacket(4, 1, true, !kEntropyFlag, NULL);
3502 EXPECT_CALL(*send_algorithm_, BandwidthEstimate()).WillOnce(
3503 Return(QuicBandwidth::Zero()));
3504 const uint32 kSlowStartThreshold = 23u;
3505 EXPECT_CALL(*send_algorithm_, GetSlowStartThreshold()).WillOnce(
3506 Return(kSlowStartThreshold));
3508 const QuicConnectionStats& stats = connection_.GetStats();
3509 EXPECT_EQ(received_bytes, stats.bytes_received);
3510 EXPECT_EQ(4u, stats.packets_received);
3512 EXPECT_EQ(1u, stats.packets_revived);
3513 EXPECT_EQ(1u, stats.packets_dropped);
3515 EXPECT_EQ(kSlowStartThreshold, stats.slow_start_threshold);
3518 TEST_P(QuicConnectionTest, TestFecGroupLimits) {
3519 // Create and return a group for 1.
3520 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 1) != NULL);
3522 // Create and return a group for 2.
3523 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 2) != NULL);
3525 // Create and return a group for 4. This should remove 1 but not 2.
3526 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 4) != NULL);
3527 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 1) == NULL);
3528 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 2) != NULL);
3530 // Create and return a group for 3. This will kill off 2.
3531 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 3) != NULL);
3532 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 2) == NULL);
3534 // Verify that adding 5 kills off 3, despite 4 being created before 3.
3535 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 5) != NULL);
3536 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 4) != NULL);
3537 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 3) == NULL);
3540 TEST_P(QuicConnectionTest, ProcessFramesIfPacketClosedConnection) {
3541 // Construct a packet with stream frame and connection close frame.
3542 header_.public_header.connection_id = connection_id_;
3543 header_.packet_sequence_number = 1;
3544 header_.public_header.reset_flag = false;
3545 header_.public_header.version_flag = false;
3546 header_.entropy_flag = false;
3547 header_.fec_flag = false;
3548 header_.fec_group = 0;
3550 QuicConnectionCloseFrame qccf;
3551 qccf.error_code = QUIC_PEER_GOING_AWAY;
3552 QuicFrame close_frame(&qccf);
3553 QuicFrame stream_frame(&frame1_);
3555 QuicFrames frames;
3556 frames.push_back(stream_frame);
3557 frames.push_back(close_frame);
3558 scoped_ptr<QuicPacket> packet(
3559 BuildUnsizedDataPacket(&framer_, header_, frames).packet);
3560 EXPECT_TRUE(NULL != packet.get());
3561 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPacket(
3562 ENCRYPTION_NONE, 1, *packet));
3564 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, true));
3565 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
3566 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3568 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3571 TEST_P(QuicConnectionTest, SelectMutualVersion) {
3572 connection_.SetSupportedVersions(QuicSupportedVersions());
3573 // Set the connection to speak the lowest quic version.
3574 connection_.set_version(QuicVersionMin());
3575 EXPECT_EQ(QuicVersionMin(), connection_.version());
3577 // Pass in available versions which includes a higher mutually supported
3578 // version. The higher mutually supported version should be selected.
3579 QuicVersionVector supported_versions;
3580 for (size_t i = 0; i < arraysize(kSupportedQuicVersions); ++i) {
3581 supported_versions.push_back(kSupportedQuicVersions[i]);
3583 EXPECT_TRUE(connection_.SelectMutualVersion(supported_versions));
3584 EXPECT_EQ(QuicVersionMax(), connection_.version());
3586 // Expect that the lowest version is selected.
3587 // Ensure the lowest supported version is less than the max, unless they're
3588 // the same.
3589 EXPECT_LE(QuicVersionMin(), QuicVersionMax());
3590 QuicVersionVector lowest_version_vector;
3591 lowest_version_vector.push_back(QuicVersionMin());
3592 EXPECT_TRUE(connection_.SelectMutualVersion(lowest_version_vector));
3593 EXPECT_EQ(QuicVersionMin(), connection_.version());
3595 // Shouldn't be able to find a mutually supported version.
3596 QuicVersionVector unsupported_version;
3597 unsupported_version.push_back(QUIC_VERSION_UNSUPPORTED);
3598 EXPECT_FALSE(connection_.SelectMutualVersion(unsupported_version));
3601 TEST_P(QuicConnectionTest, ConnectionCloseWhenWritable) {
3602 EXPECT_FALSE(writer_->IsWriteBlocked());
3604 // Send a packet.
3605 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, NULL);
3606 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3607 EXPECT_EQ(1u, writer_->packets_write_attempts());
3609 TriggerConnectionClose();
3610 EXPECT_EQ(2u, writer_->packets_write_attempts());
3613 TEST_P(QuicConnectionTest, ConnectionCloseGettingWriteBlocked) {
3614 BlockOnNextWrite();
3615 TriggerConnectionClose();
3616 EXPECT_EQ(1u, writer_->packets_write_attempts());
3617 EXPECT_TRUE(writer_->IsWriteBlocked());
3620 TEST_P(QuicConnectionTest, ConnectionCloseWhenWriteBlocked) {
3621 BlockOnNextWrite();
3622 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, NULL);
3623 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3624 EXPECT_EQ(1u, writer_->packets_write_attempts());
3625 EXPECT_TRUE(writer_->IsWriteBlocked());
3626 TriggerConnectionClose();
3627 EXPECT_EQ(1u, writer_->packets_write_attempts());
3630 TEST_P(QuicConnectionTest, AckNotifierTriggerCallback) {
3631 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3633 // Create a delegate which we expect to be called.
3634 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
3635 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _, _, _)).Times(1);
3637 // Send some data, which will register the delegate to be notified.
3638 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
3640 // Process an ACK from the server which should trigger the callback.
3641 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3642 QuicAckFrame frame = InitAckFrame(1);
3643 ProcessAckPacket(&frame);
3646 TEST_P(QuicConnectionTest, AckNotifierFailToTriggerCallback) {
3647 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3649 // Create a delegate which we don't expect to be called.
3650 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
3651 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _, _, _)).Times(0);
3653 // Send some data, which will register the delegate to be notified. This will
3654 // not be ACKed and so the delegate should never be called.
3655 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
3657 // Send some other data which we will ACK.
3658 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, NULL);
3659 connection_.SendStreamDataWithString(1, "bar", 0, !kFin, NULL);
3661 // Now we receive ACK for packets 2 and 3, but importantly missing packet 1
3662 // which we registered to be notified about.
3663 QuicAckFrame frame = InitAckFrame(3);
3664 NackPacket(1, &frame);
3665 SequenceNumberSet lost_packets;
3666 lost_packets.insert(1);
3667 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3668 .WillOnce(Return(lost_packets));
3669 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3670 ProcessAckPacket(&frame);
3673 TEST_P(QuicConnectionTest, AckNotifierCallbackAfterRetransmission) {
3674 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3676 // Create a delegate which we expect to be called.
3677 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
3678 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _, _, _)).Times(1);
3680 // Send four packets, and register to be notified on ACK of packet 2.
3681 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, NULL);
3682 connection_.SendStreamDataWithString(3, "bar", 0, !kFin, delegate.get());
3683 connection_.SendStreamDataWithString(3, "baz", 0, !kFin, NULL);
3684 connection_.SendStreamDataWithString(3, "qux", 0, !kFin, NULL);
3686 // Now we receive ACK for packets 1, 3, and 4 and lose 2.
3687 QuicAckFrame frame = InitAckFrame(4);
3688 NackPacket(2, &frame);
3689 SequenceNumberSet lost_packets;
3690 lost_packets.insert(2);
3691 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3692 .WillOnce(Return(lost_packets));
3693 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3694 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3695 ProcessAckPacket(&frame);
3697 // Now we get an ACK for packet 5 (retransmitted packet 2), which should
3698 // trigger the callback.
3699 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3700 .WillRepeatedly(Return(SequenceNumberSet()));
3701 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3702 QuicAckFrame second_ack_frame = InitAckFrame(5);
3703 ProcessAckPacket(&second_ack_frame);
3706 // AckNotifierCallback is triggered by the ack of a packet that timed
3707 // out and was retransmitted, even though the retransmission has a
3708 // different sequence number.
3709 TEST_P(QuicConnectionTest, AckNotifierCallbackForAckAfterRTO) {
3710 InSequence s;
3712 // Create a delegate which we expect to be called.
3713 scoped_refptr<MockAckNotifierDelegate> delegate(
3714 new StrictMock<MockAckNotifierDelegate>);
3716 QuicTime default_retransmission_time = clock_.ApproximateNow().Add(
3717 DefaultRetransmissionTime());
3718 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, delegate.get());
3719 EXPECT_EQ(1u, stop_waiting()->least_unacked);
3721 EXPECT_EQ(1u, writer_->header().packet_sequence_number);
3722 EXPECT_EQ(default_retransmission_time,
3723 connection_.GetRetransmissionAlarm()->deadline());
3724 // Simulate the retransmission alarm firing.
3725 clock_.AdvanceTime(DefaultRetransmissionTime());
3726 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
3727 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 2u, _, _));
3728 connection_.GetRetransmissionAlarm()->Fire();
3729 EXPECT_EQ(2u, writer_->header().packet_sequence_number);
3730 // We do not raise the high water mark yet.
3731 EXPECT_EQ(1u, stop_waiting()->least_unacked);
3733 // Ack the original packet, which will revert the RTO.
3734 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3735 EXPECT_CALL(*delegate.get(), OnAckNotification(1, _, 1, _, _));
3736 EXPECT_CALL(*send_algorithm_, RevertRetransmissionTimeout());
3737 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3738 QuicAckFrame ack_frame = InitAckFrame(1);
3739 ProcessAckPacket(&ack_frame);
3741 // Delegate is not notified again when the retransmit is acked.
3742 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3743 QuicAckFrame second_ack_frame = InitAckFrame(2);
3744 ProcessAckPacket(&second_ack_frame);
3747 // AckNotifierCallback is triggered by the ack of a packet that was
3748 // previously nacked, even though the retransmission has a different
3749 // sequence number.
3750 TEST_P(QuicConnectionTest, AckNotifierCallbackForAckOfNackedPacket) {
3751 InSequence s;
3753 // Create a delegate which we expect to be called.
3754 scoped_refptr<MockAckNotifierDelegate> delegate(
3755 new StrictMock<MockAckNotifierDelegate>);
3757 // Send four packets, and register to be notified on ACK of packet 2.
3758 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, NULL);
3759 connection_.SendStreamDataWithString(3, "bar", 0, !kFin, delegate.get());
3760 connection_.SendStreamDataWithString(3, "baz", 0, !kFin, NULL);
3761 connection_.SendStreamDataWithString(3, "qux", 0, !kFin, NULL);
3763 // Now we receive ACK for packets 1, 3, and 4 and lose 2.
3764 QuicAckFrame frame = InitAckFrame(4);
3765 NackPacket(2, &frame);
3766 SequenceNumberSet lost_packets;
3767 lost_packets.insert(2);
3768 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3769 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3770 .WillOnce(Return(lost_packets));
3771 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3772 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3773 ProcessAckPacket(&frame);
3775 // Now we get an ACK for packet 2, which was previously nacked.
3776 SequenceNumberSet no_lost_packets;
3777 EXPECT_CALL(*delegate.get(), OnAckNotification(1, _, 1, _, _));
3778 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3779 .WillOnce(Return(no_lost_packets));
3780 QuicAckFrame second_ack_frame = InitAckFrame(4);
3781 ProcessAckPacket(&second_ack_frame);
3783 // Verify that the delegate is not notified again when the
3784 // retransmit is acked.
3785 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3786 .WillOnce(Return(no_lost_packets));
3787 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3788 QuicAckFrame third_ack_frame = InitAckFrame(5);
3789 ProcessAckPacket(&third_ack_frame);
3792 TEST_P(QuicConnectionTest, AckNotifierFECTriggerCallback) {
3793 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3795 // Create a delegate which we expect to be called.
3796 scoped_refptr<MockAckNotifierDelegate> delegate(
3797 new MockAckNotifierDelegate);
3798 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _, _, _)).Times(1);
3800 // Send some data, which will register the delegate to be notified.
3801 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
3802 connection_.SendStreamDataWithString(2, "bar", 0, !kFin, NULL);
3804 // Process an ACK from the server with a revived packet, which should trigger
3805 // the callback.
3806 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3807 QuicAckFrame frame = InitAckFrame(2);
3808 NackPacket(1, &frame);
3809 frame.revived_packets.insert(1);
3810 ProcessAckPacket(&frame);
3811 // If the ack is processed again, the notifier should not be called again.
3812 ProcessAckPacket(&frame);
3815 TEST_P(QuicConnectionTest, AckNotifierCallbackAfterFECRecovery) {
3816 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3817 EXPECT_CALL(visitor_, OnCanWrite());
3819 // Create a delegate which we expect to be called.
3820 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
3821 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _, _, _)).Times(1);
3823 // Expect ACKs for 1 packet.
3824 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3826 // Send one packet, and register to be notified on ACK.
3827 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
3829 // Ack packet gets dropped, but we receive an FEC packet that covers it.
3830 // Should recover the Ack packet and trigger the notification callback.
3831 QuicFrames frames;
3833 QuicAckFrame ack_frame = InitAckFrame(1);
3834 frames.push_back(QuicFrame(&ack_frame));
3836 // Dummy stream frame to satisfy expectations set elsewhere.
3837 frames.push_back(QuicFrame(&frame1_));
3839 QuicPacketHeader ack_header;
3840 ack_header.public_header.connection_id = connection_id_;
3841 ack_header.public_header.reset_flag = false;
3842 ack_header.public_header.version_flag = false;
3843 ack_header.entropy_flag = !kEntropyFlag;
3844 ack_header.fec_flag = true;
3845 ack_header.packet_sequence_number = 1;
3846 ack_header.is_in_fec_group = IN_FEC_GROUP;
3847 ack_header.fec_group = 1;
3849 QuicPacket* packet =
3850 BuildUnsizedDataPacket(&framer_, ack_header, frames).packet;
3852 // Take the packet which contains the ACK frame, and construct and deliver an
3853 // FEC packet which allows the ACK packet to be recovered.
3854 ProcessFecPacket(2, 1, true, !kEntropyFlag, packet);
3857 TEST_P(QuicConnectionTest, NetworkChangeVisitorCallbacksChangeFecState) {
3858 QuicPacketCreator* creator =
3859 QuicConnectionPeer::GetPacketCreator(&connection_);
3860 size_t max_packets_per_fec_group = creator->max_packets_per_fec_group();
3862 QuicSentPacketManager::NetworkChangeVisitor* visitor =
3863 QuicSentPacketManagerPeer::GetNetworkChangeVisitor(
3864 QuicConnectionPeer::GetSentPacketManager(&connection_));
3865 EXPECT_TRUE(visitor);
3867 // Increase FEC group size by increasing congestion window to a large number.
3868 visitor->OnCongestionWindowChange(1000 * kDefaultTCPMSS);
3869 EXPECT_LT(max_packets_per_fec_group, creator->max_packets_per_fec_group());
3872 class MockQuicConnectionDebugVisitor
3873 : public QuicConnectionDebugVisitor {
3874 public:
3875 MOCK_METHOD1(OnFrameAddedToPacket,
3876 void(const QuicFrame&));
3878 MOCK_METHOD5(OnPacketSent,
3879 void(QuicPacketSequenceNumber,
3880 EncryptionLevel,
3881 TransmissionType,
3882 const QuicEncryptedPacket&,
3883 WriteResult));
3885 MOCK_METHOD2(OnPacketRetransmitted,
3886 void(QuicPacketSequenceNumber,
3887 QuicPacketSequenceNumber));
3889 MOCK_METHOD3(OnPacketReceived,
3890 void(const IPEndPoint&,
3891 const IPEndPoint&,
3892 const QuicEncryptedPacket&));
3894 MOCK_METHOD1(OnProtocolVersionMismatch,
3895 void(QuicVersion));
3897 MOCK_METHOD1(OnPacketHeader,
3898 void(const QuicPacketHeader& header));
3900 MOCK_METHOD1(OnStreamFrame,
3901 void(const QuicStreamFrame&));
3903 MOCK_METHOD1(OnAckFrame,
3904 void(const QuicAckFrame& frame));
3906 MOCK_METHOD1(OnCongestionFeedbackFrame,
3907 void(const QuicCongestionFeedbackFrame&));
3909 MOCK_METHOD1(OnStopWaitingFrame,
3910 void(const QuicStopWaitingFrame&));
3912 MOCK_METHOD1(OnRstStreamFrame,
3913 void(const QuicRstStreamFrame&));
3915 MOCK_METHOD1(OnConnectionCloseFrame,
3916 void(const QuicConnectionCloseFrame&));
3918 MOCK_METHOD1(OnPublicResetPacket,
3919 void(const QuicPublicResetPacket&));
3921 MOCK_METHOD1(OnVersionNegotiationPacket,
3922 void(const QuicVersionNegotiationPacket&));
3924 MOCK_METHOD2(OnRevivedPacket,
3925 void(const QuicPacketHeader&, StringPiece payload));
3928 TEST_P(QuicConnectionTest, OnPacketHeaderDebugVisitor) {
3929 QuicPacketHeader header;
3931 MockQuicConnectionDebugVisitor* debug_visitor =
3932 new MockQuicConnectionDebugVisitor();
3933 connection_.set_debug_visitor(debug_visitor);
3934 EXPECT_CALL(*debug_visitor, OnPacketHeader(Ref(header))).Times(1);
3935 connection_.OnPacketHeader(header);
3938 TEST_P(QuicConnectionTest, Pacing) {
3939 TestConnection server(connection_id_, IPEndPoint(), helper_.get(),
3940 factory_, /* is_server= */ true, version());
3941 TestConnection client(connection_id_, IPEndPoint(), helper_.get(),
3942 factory_, /* is_server= */ false, version());
3943 EXPECT_FALSE(client.sent_packet_manager().using_pacing());
3944 EXPECT_FALSE(server.sent_packet_manager().using_pacing());
3947 TEST_P(QuicConnectionTest, ControlFramesInstigateAcks) {
3948 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3950 // Send a WINDOW_UPDATE frame.
3951 QuicWindowUpdateFrame window_update;
3952 window_update.stream_id = 3;
3953 window_update.byte_offset = 1234;
3954 EXPECT_CALL(visitor_, OnWindowUpdateFrames(_));
3955 ProcessFramePacket(QuicFrame(&window_update));
3957 // Ensure that this has caused the ACK alarm to be set.
3958 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
3959 EXPECT_TRUE(ack_alarm->IsSet());
3961 // Cancel alarm, and try again with BLOCKED frame.
3962 ack_alarm->Cancel();
3963 QuicBlockedFrame blocked;
3964 blocked.stream_id = 3;
3965 EXPECT_CALL(visitor_, OnBlockedFrames(_));
3966 ProcessFramePacket(QuicFrame(&blocked));
3967 EXPECT_TRUE(ack_alarm->IsSet());
3970 } // namespace
3971 } // namespace test
3972 } // namespace net