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. 4 5 #include "net/quic/quic_connection.h" 6 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" 30 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::_; 47 48 namespace net { 49 namespace test { 50 namespace { 51 52 const char data1[] = "foo"; 53 const char data2[] = "bar"; 54 55 const bool kFin = true; 56 const bool kEntropyFlag = true; 57 58 const QuicPacketEntropyHash kTestEntropyHash = 76; 59 60 const int kDefaultRetransmissionTimeMs = 500; 61 62 class TestReceiveAlgorithm : public ReceiveAlgorithmInterface { 63 public: 64 explicit TestReceiveAlgorithm(QuicCongestionFeedbackFrame* feedback) 65 : feedback_(feedback) { 66 } 67 68 bool GenerateCongestionFeedback( 69 QuicCongestionFeedbackFrame* congestion_feedback) { 70 if (feedback_ == NULL) { 71 return false; 72 } 73 *congestion_feedback = *feedback_; 74 return true; 75 } 76 77 MOCK_METHOD3(RecordIncomingPacket, 78 void(QuicByteCount, QuicPacketSequenceNumber, QuicTime)); 79 80 private: 81 QuicCongestionFeedbackFrame* feedback_; 82 83 DISALLOW_COPY_AND_ASSIGN(TestReceiveAlgorithm); 84 }; 85 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) { 91 } 92 93 virtual ~TaggingEncrypter() {} 94 95 // QuicEncrypter interface. 96 virtual bool SetKey(StringPiece key) OVERRIDE { return true; } 97 virtual bool SetNoncePrefix(StringPiece nonce_prefix) OVERRIDE { 98 return true; 99 } 100 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; 109 } 110 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); 118 } 119 120 virtual size_t GetKeySize() const OVERRIDE { return 0; } 121 virtual size_t GetNoncePrefixSize() const OVERRIDE { return 0; } 122 123 virtual size_t GetMaxPlaintextSize(size_t ciphertext_size) const OVERRIDE { 124 return ciphertext_size - kTagSize; 125 } 126 127 virtual size_t GetCiphertextSize(size_t plaintext_size) const OVERRIDE { 128 return plaintext_size + kTagSize; 129 } 130 131 virtual StringPiece GetKey() const OVERRIDE { 132 return StringPiece(); 133 } 134 135 virtual StringPiece GetNoncePrefix() const OVERRIDE { 136 return StringPiece(); 137 } 138 139 private: 140 enum { 141 kTagSize = 12, 142 }; 143 144 const uint8 tag_; 145 146 DISALLOW_COPY_AND_ASSIGN(TaggingEncrypter); 147 }; 148 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() {} 154 155 // QuicDecrypter interface 156 virtual bool SetKey(StringPiece key) OVERRIDE { return true; } 157 virtual bool SetNoncePrefix(StringPiece nonce_prefix) OVERRIDE { 158 return true; 159 } 160 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; 168 } 169 if (!CheckTag(ciphertext, GetTag(ciphertext))) { 170 return false; 171 } 172 *output_length = ciphertext.size() - kTagSize; 173 memcpy(output, ciphertext.data(), *output_length); 174 return true; 175 } 176 177 virtual QuicData* DecryptPacket(QuicPacketSequenceNumber sequence_number, 178 StringPiece associated_data, 179 StringPiece ciphertext) OVERRIDE { 180 if (ciphertext.size() < kTagSize) { 181 return NULL; 182 } 183 if (!CheckTag(ciphertext, GetTag(ciphertext))) { 184 return NULL; 185 } 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 */); 191 } 192 193 virtual StringPiece GetKey() const OVERRIDE { return StringPiece(); } 194 virtual StringPiece GetNoncePrefix() const OVERRIDE { return StringPiece(); } 195 196 protected: 197 virtual uint8 GetTag(StringPiece ciphertext) { 198 return ciphertext.data()[ciphertext.size()-1]; 199 } 200 201 private: 202 enum { 203 kTagSize = 12, 204 }; 205 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; 210 } 211 } 212 213 return true; 214 } 215 }; 216 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() {} 223 224 // TaggingQuicDecrypter 225 virtual uint8 GetTag(StringPiece ciphertext) OVERRIDE { 226 return tag_; 227 } 228 229 private: 230 const uint8 tag_; 231 }; 232 233 class TestConnectionHelper : public QuicConnectionHelperInterface { 234 public: 235 class TestAlarm : public QuicAlarm { 236 public: 237 explicit TestAlarm(QuicAlarm::Delegate* delegate) 238 : QuicAlarm(delegate) { 239 } 240 241 virtual void SetImpl() OVERRIDE {} 242 virtual void CancelImpl() OVERRIDE {} 243 using QuicAlarm::Fire; 244 }; 245 246 TestConnectionHelper(MockClock* clock, MockRandom* random_generator) 247 : clock_(clock), 248 random_generator_(random_generator) { 249 clock_->AdvanceTime(QuicTime::Delta::FromSeconds(1)); 250 } 251 252 // QuicConnectionHelperInterface 253 virtual const QuicClock* GetClock() const OVERRIDE { 254 return clock_; 255 } 256 257 virtual QuicRandom* GetRandomGenerator() OVERRIDE { 258 return random_generator_; 259 } 260 261 virtual QuicAlarm* CreateAlarm(QuicAlarm::Delegate* delegate) OVERRIDE { 262 return new TestAlarm(delegate); 263 } 264 265 private: 266 MockClock* clock_; 267 MockRandom* random_generator_; 268 269 DISALLOW_COPY_AND_ASSIGN(TestConnectionHelper); 270 }; 271 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) { 285 } 286 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_; 294 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_)); 299 } 300 301 if (use_tagging_decrypter_) { 302 framer_.framer()->SetDecrypter(new TaggingDecrypter, ENCRYPTION_NONE); 303 } 304 EXPECT_TRUE(framer_.ProcessPacket(packet)); 305 if (block_on_next_write_) { 306 write_blocked_ = true; 307 block_on_next_write_ = false; 308 } 309 if (IsWriteBlocked()) { 310 return WriteResult(WRITE_STATUS_BLOCKED, -1); 311 } 312 last_packet_size_ = packet.length(); 313 return WriteResult(WRITE_STATUS_OK, last_packet_size_); 314 } 315 316 virtual bool IsWriteBlockedDataBuffered() const OVERRIDE { 317 return is_write_blocked_data_buffered_; 318 } 319 320 virtual bool IsWriteBlocked() const OVERRIDE { return write_blocked_; } 321 322 virtual void SetWritable() OVERRIDE { write_blocked_ = false; } 323 324 void BlockOnNextWrite() { block_on_next_write_ = true; } 325 326 const QuicPacketHeader& header() { return framer_.header(); } 327 328 size_t frame_count() const { return framer_.num_frames(); } 329 330 const vector<QuicAckFrame>& ack_frames() const { 331 return framer_.ack_frames(); 332 } 333 334 const vector<QuicCongestionFeedbackFrame>& feedback_frames() const { 335 return framer_.feedback_frames(); 336 } 337 338 const vector<QuicStopWaitingFrame>& stop_waiting_frames() const { 339 return framer_.stop_waiting_frames(); 340 } 341 342 const vector<QuicConnectionCloseFrame>& connection_close_frames() const { 343 return framer_.connection_close_frames(); 344 } 345 346 const vector<QuicStreamFrame>& stream_frames() const { 347 return framer_.stream_frames(); 348 } 349 350 const vector<QuicPingFrame>& ping_frames() const { 351 return framer_.ping_frames(); 352 } 353 354 size_t last_packet_size() { 355 return last_packet_size_; 356 } 357 358 const QuicVersionNegotiationPacket* version_negotiation_packet() { 359 return framer_.version_negotiation_packet(); 360 } 361 362 void set_is_write_blocked_data_buffered(bool buffered) { 363 is_write_blocked_data_buffered_ = buffered; 364 } 365 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); 370 } 371 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_; } 377 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_; 381 } 382 383 void use_tagging_decrypter() { 384 use_tagging_decrypter_ = true; 385 } 386 387 uint32 packets_write_attempts() { return packets_write_attempts_; } 388 389 void Reset() { framer_.Reset(); } 390 391 void SetSupportedVersions(const QuicVersionVector& versions) { 392 framer_.SetSupportedVersions(versions); 393 } 394 395 private: 396 QuicVersion version_; 397 SimpleQuicFramer framer_; 398 size_t last_packet_size_; 399 bool write_blocked_; 400 bool block_on_next_write_; 401 bool is_write_blocked_data_buffered_; 402 uint32 final_bytes_of_last_packet_; 403 uint32 final_bytes_of_previous_packet_; 404 bool use_tagging_decrypter_; 405 uint32 packets_write_attempts_; 406 407 DISALLOW_COPY_AND_ASSIGN(TestPacketWriter); 408 }; 409 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); 429 } 430 431 void SendAck() { 432 QuicConnectionPeer::SendAck(this); 433 } 434 435 void SetReceiveAlgorithm(TestReceiveAlgorithm* receive_algorithm) { 436 QuicConnectionPeer::SetReceiveAlgorithm(this, receive_algorithm); 437 } 438 439 void SetSendAlgorithm(SendAlgorithmInterface* send_algorithm) { 440 QuicConnectionPeer::SetSendAlgorithm(this, send_algorithm); 441 } 442 443 void SetLossAlgorithm(LossDetectionInterface* loss_algorithm) { 444 QuicSentPacketManagerPeer::SetLossAlgorithm( 445 QuicConnectionPeer::GetSentPacketManager(this), loss_algorithm); 446 } 447 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)); 459 } 460 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); 469 } 470 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); 479 } 480 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()); 491 } 492 return QuicConnection::SendStreamData(id, data_iov, offset, fin, 493 fec_protection, delegate); 494 } 495 496 QuicConsumedData SendStreamData3() { 497 return SendStreamDataWithString(kClientDataStreamId1, "food", 0, !kFin, 498 NULL); 499 } 500 501 QuicConsumedData SendStreamData3WithFec() { 502 return SendStreamDataWithStringWithFec(kClientDataStreamId1, "food", 0, 503 !kFin, NULL); 504 } 505 506 QuicConsumedData SendStreamData5() { 507 return SendStreamDataWithString(kClientDataStreamId2, "food2", 0, 508 !kFin, NULL); 509 } 510 511 QuicConsumedData SendStreamData5WithFec() { 512 return SendStreamDataWithStringWithFec(kClientDataStreamId2, "food2", 0, 513 !kFin, NULL); 514 } 515 // Ensures the connection can write stream data before writing. 516 QuicConsumedData EnsureWritableAndSendStreamData5() { 517 EXPECT_TRUE(CanWriteStreamData()); 518 return SendStreamData5(); 519 } 520 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); 528 } 529 530 bool is_server() { 531 return QuicConnectionPeer::IsServer(this); 532 } 533 534 void set_version(QuicVersion version) { 535 QuicConnectionPeer::GetFramer(this)->set_version(version); 536 } 537 538 void SetSupportedVersions(const QuicVersionVector& versions) { 539 QuicConnectionPeer::GetFramer(this)->SetSupportedVersions(versions); 540 writer()->SetSupportedVersions(versions); 541 } 542 543 void set_is_server(bool is_server) { 544 writer()->set_is_server(is_server); 545 QuicConnectionPeer::SetIsServer(this, is_server); 546 } 547 548 TestConnectionHelper::TestAlarm* GetAckAlarm() { 549 return reinterpret_cast<TestConnectionHelper::TestAlarm*>( 550 QuicConnectionPeer::GetAckAlarm(this)); 551 } 552 553 TestConnectionHelper::TestAlarm* GetPingAlarm() { 554 return reinterpret_cast<TestConnectionHelper::TestAlarm*>( 555 QuicConnectionPeer::GetPingAlarm(this)); 556 } 557 558 TestConnectionHelper::TestAlarm* GetResumeWritesAlarm() { 559 return reinterpret_cast<TestConnectionHelper::TestAlarm*>( 560 QuicConnectionPeer::GetResumeWritesAlarm(this)); 561 } 562 563 TestConnectionHelper::TestAlarm* GetRetransmissionAlarm() { 564 return reinterpret_cast<TestConnectionHelper::TestAlarm*>( 565 QuicConnectionPeer::GetRetransmissionAlarm(this)); 566 } 567 568 TestConnectionHelper::TestAlarm* GetSendAlarm() { 569 return reinterpret_cast<TestConnectionHelper::TestAlarm*>( 570 QuicConnectionPeer::GetSendAlarm(this)); 571 } 572 573 TestConnectionHelper::TestAlarm* GetTimeoutAlarm() { 574 return reinterpret_cast<TestConnectionHelper::TestAlarm*>( 575 QuicConnectionPeer::GetTimeoutAlarm(this)); 576 } 577 578 using QuicConnection::SelectMutualVersion; 579 580 private: 581 TestPacketWriter* writer() { 582 return static_cast<TestPacketWriter*>(QuicConnection::writer()); 583 } 584 585 DISALLOW_COPY_AND_ASSIGN(TestConnection); 586 }; 587 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; 595 } 596 597 // Public accessor method. 598 QuicPacketHeader revived_header() const { 599 return revived_header_; 600 } 601 602 private: 603 QuicPacketHeader revived_header_; 604 }; 605 606 class MockPacketWriterFactory : public QuicConnection::PacketWriterFactory { 607 public: 608 MockPacketWriterFactory(QuicPacketWriter* writer) { 609 ON_CALL(*this, Create(_)).WillByDefault(Return(writer)); 610 } 611 virtual ~MockPacketWriterFactory() {} 612 613 MOCK_CONST_METHOD1(Create, QuicPacketWriter*(QuicConnection* connection)); 614 }; 615 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()); 664 665 EXPECT_CALL(*loss_algorithm_, GetLossTimeout()) 666 .WillRepeatedly(Return(QuicTime::Zero())); 667 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _)) 668 .WillRepeatedly(Return(SequenceNumberSet())); 669 } 670 671 QuicVersion version() { 672 return GetParam(); 673 } 674 675 QuicAckFrame* outgoing_ack() { 676 outgoing_ack_.reset(QuicConnectionPeer::CreateAckFrame(&connection_)); 677 return outgoing_ack_.get(); 678 } 679 680 QuicStopWaitingFrame* stop_waiting() { 681 stop_waiting_.reset( 682 QuicConnectionPeer::CreateStopWaitingFrame(&connection_)); 683 return stop_waiting_.get(); 684 } 685 686 QuicPacketSequenceNumber least_unacked() { 687 if (writer_->stop_waiting_frames().empty()) { 688 return 0; 689 } 690 return writer_->stop_waiting_frames()[0].least_unacked; 691 } 692 693 void use_tagging_decrypter() { 694 writer_->use_tagging_decrypter(); 695 } 696 697 void ProcessPacket(QuicPacketSequenceNumber number) { 698 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1); 699 ProcessDataPacket(number, 0, !kEntropyFlag); 700 } 701 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; 715 } 716 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); 722 } 723 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(); 734 } 735 736 void ProcessPingPacket(QuicPacketSequenceNumber number) { 737 scoped_ptr<QuicPacket> packet(ConstructPingPacket(number)); 738 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPacket( 739 ENCRYPTION_NONE, number, *packet)); 740 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted); 741 } 742 743 void ProcessClosePacket(QuicPacketSequenceNumber number, 744 QuicFecGroupNumber fec_group) { 745 scoped_ptr<QuicPacket> packet(ConstructClosePacket(number, fec_group)); 746 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPacket( 747 ENCRYPTION_NONE, number, *packet)); 748 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted); 749 } 750 751 size_t ProcessFecProtectedPacket(QuicPacketSequenceNumber number, 752 bool expect_revival, bool entropy_flag) { 753 if (expect_revival) { 754 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1); 755 } 756 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1). 757 RetiresOnSaturation(); 758 return ProcessDataPacket(number, 1, entropy_flag); 759 } 760 761 // Processes an FEC packet that covers the packets that would have been 762 // received. 763 size_t ProcessFecPacket(QuicPacketSequenceNumber number, 764 QuicPacketSequenceNumber min_protected_packet, 765 bool expect_revival, 766 bool entropy_flag, 767 QuicPacket* packet) { 768 if (expect_revival) { 769 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1); 770 } 771 772 // Construct the decrypted data packet so we can compute the correct 773 // redundancy. If |packet| has been provided then use that, otherwise 774 // construct a default data packet. 775 scoped_ptr<QuicPacket> data_packet; 776 if (packet) { 777 data_packet.reset(packet); 778 } else { 779 data_packet.reset(ConstructDataPacket(number, 1, !kEntropyFlag)); 780 } 781 782 header_.public_header.connection_id = connection_id_; 783 header_.public_header.reset_flag = false; 784 header_.public_header.version_flag = false; 785 header_.public_header.sequence_number_length = sequence_number_length_; 786 header_.public_header.connection_id_length = connection_id_length_; 787 header_.packet_sequence_number = number; 788 header_.entropy_flag = entropy_flag; 789 header_.fec_flag = true; 790 header_.is_in_fec_group = IN_FEC_GROUP; 791 header_.fec_group = min_protected_packet; 792 QuicFecData fec_data; 793 fec_data.fec_group = header_.fec_group; 794 795 // Since all data packets in this test have the same payload, the 796 // redundancy is either equal to that payload or the xor of that payload 797 // with itself, depending on the number of packets. 798 if (((number - min_protected_packet) % 2) == 0) { 799 for (size_t i = GetStartOfFecProtectedData( 800 header_.public_header.connection_id_length, 801 header_.public_header.version_flag, 802 header_.public_header.sequence_number_length); 803 i < data_packet->length(); ++i) { 804 data_packet->mutable_data()[i] ^= data_packet->data()[i]; 805 } 806 } 807 fec_data.redundancy = data_packet->FecProtectedData(); 808 809 scoped_ptr<QuicPacket> fec_packet( 810 framer_.BuildFecPacket(header_, fec_data).packet); 811 scoped_ptr<QuicEncryptedPacket> encrypted( 812 framer_.EncryptPacket(ENCRYPTION_NONE, number, *fec_packet)); 813 814 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted); 815 return encrypted->length(); 816 } 817 818 QuicByteCount SendStreamDataToPeer(QuicStreamId id, 819 StringPiece data, 820 QuicStreamOffset offset, 821 bool fin, 822 QuicPacketSequenceNumber* last_packet) { 823 QuicByteCount packet_size; 824 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) 825 .WillOnce(DoAll(SaveArg<3>(&packet_size), Return(true))); 826 connection_.SendStreamDataWithString(id, data, offset, fin, NULL); 827 if (last_packet != NULL) { 828 *last_packet = 829 QuicConnectionPeer::GetPacketCreator(&connection_)->sequence_number(); 830 } 831 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) 832 .Times(AnyNumber()); 833 return packet_size; 834 } 835 836 void SendAckPacketToPeer() { 837 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); 838 connection_.SendAck(); 839 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) 840 .Times(AnyNumber()); 841 } 842 843 QuicPacketEntropyHash ProcessAckPacket(QuicAckFrame* frame) { 844 return ProcessFramePacket(QuicFrame(frame)); 845 } 846 847 QuicPacketEntropyHash ProcessStopWaitingPacket(QuicStopWaitingFrame* frame) { 848 return ProcessFramePacket(QuicFrame(frame)); 849 } 850 851 QuicPacketEntropyHash ProcessGoAwayPacket(QuicGoAwayFrame* frame) { 852 return ProcessFramePacket(QuicFrame(frame)); 853 } 854 855 bool IsMissing(QuicPacketSequenceNumber number) { 856 return IsAwaitingPacket(*outgoing_ack(), number); 857 } 858 859 QuicPacket* ConstructDataPacket(QuicPacketSequenceNumber number, 860 QuicFecGroupNumber fec_group, 861 bool entropy_flag) { 862 header_.public_header.connection_id = connection_id_; 863 header_.public_header.reset_flag = false; 864 header_.public_header.version_flag = false; 865 header_.public_header.sequence_number_length = sequence_number_length_; 866 header_.public_header.connection_id_length = connection_id_length_; 867 header_.entropy_flag = entropy_flag; 868 header_.fec_flag = false; 869 header_.packet_sequence_number = number; 870 header_.is_in_fec_group = fec_group == 0u ? NOT_IN_FEC_GROUP : IN_FEC_GROUP; 871 header_.fec_group = fec_group; 872 873 QuicFrames frames; 874 QuicFrame frame(&frame1_); 875 frames.push_back(frame); 876 QuicPacket* packet = 877 BuildUnsizedDataPacket(&framer_, header_, frames).packet; 878 EXPECT_TRUE(packet != NULL); 879 return packet; 880 } 881 882 QuicPacket* ConstructPingPacket(QuicPacketSequenceNumber number) { 883 header_.public_header.connection_id = connection_id_; 884 header_.packet_sequence_number = number; 885 header_.public_header.reset_flag = false; 886 header_.public_header.version_flag = false; 887 header_.entropy_flag = false; 888 header_.fec_flag = false; 889 header_.is_in_fec_group = NOT_IN_FEC_GROUP; 890 header_.fec_group = 0; 891 892 QuicPingFrame ping; 893 894 QuicFrames frames; 895 QuicFrame frame(&ping); 896 frames.push_back(frame); 897 QuicPacket* packet = 898 BuildUnsizedDataPacket(&framer_, header_, frames).packet; 899 EXPECT_TRUE(packet != NULL); 900 return packet; 901 } 902 903 QuicPacket* ConstructClosePacket(QuicPacketSequenceNumber number, 904 QuicFecGroupNumber fec_group) { 905 header_.public_header.connection_id = connection_id_; 906 header_.packet_sequence_number = number; 907 header_.public_header.reset_flag = false; 908 header_.public_header.version_flag = false; 909 header_.entropy_flag = false; 910 header_.fec_flag = false; 911 header_.is_in_fec_group = fec_group == 0u ? NOT_IN_FEC_GROUP : IN_FEC_GROUP; 912 header_.fec_group = fec_group; 913 914 QuicConnectionCloseFrame qccf; 915 qccf.error_code = QUIC_PEER_GOING_AWAY; 916 917 QuicFrames frames; 918 QuicFrame frame(&qccf); 919 frames.push_back(frame); 920 QuicPacket* packet = 921 BuildUnsizedDataPacket(&framer_, header_, frames).packet; 922 EXPECT_TRUE(packet != NULL); 923 return packet; 924 } 925 926 void SetFeedback(QuicCongestionFeedbackFrame* feedback) { 927 receive_algorithm_ = new TestReceiveAlgorithm(feedback); 928 connection_.SetReceiveAlgorithm(receive_algorithm_); 929 } 930 931 QuicTime::Delta DefaultRetransmissionTime() { 932 return QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs); 933 } 934 935 QuicTime::Delta DefaultDelayedAckTime() { 936 return QuicTime::Delta::FromMilliseconds(kMaxDelayedAckTimeMs); 937 } 938 939 // Initialize a frame acknowledging all packets up to largest_observed. 940 const QuicAckFrame InitAckFrame(QuicPacketSequenceNumber largest_observed) { 941 QuicAckFrame frame(MakeAckFrame(largest_observed)); 942 if (largest_observed > 0) { 943 frame.entropy_hash = 944 QuicConnectionPeer::GetSentEntropyHash(&connection_, 945 largest_observed); 946 } 947 return frame; 948 } 949 950 const QuicStopWaitingFrame InitStopWaitingFrame( 951 QuicPacketSequenceNumber least_unacked) { 952 QuicStopWaitingFrame frame; 953 frame.least_unacked = least_unacked; 954 return frame; 955 } 956 957 // Explicitly nack a packet. 958 void NackPacket(QuicPacketSequenceNumber missing, QuicAckFrame* frame) { 959 frame->missing_packets.insert(missing); 960 frame->entropy_hash ^= 961 QuicConnectionPeer::PacketEntropy(&connection_, missing); 962 } 963 964 // Undo nacking a packet within the frame. 965 void AckPacket(QuicPacketSequenceNumber arrived, QuicAckFrame* frame) { 966 EXPECT_THAT(frame->missing_packets, Contains(arrived)); 967 frame->missing_packets.erase(arrived); 968 frame->entropy_hash ^= 969 QuicConnectionPeer::PacketEntropy(&connection_, arrived); 970 } 971 972 void TriggerConnectionClose() { 973 // Send an erroneous packet to close the connection. 974 EXPECT_CALL(visitor_, 975 OnConnectionClosed(QUIC_INVALID_PACKET_HEADER, false)); 976 // Call ProcessDataPacket rather than ProcessPacket, as we should not get a 977 // packet call to the visitor. 978 ProcessDataPacket(6000, 0, !kEntropyFlag); 979 EXPECT_FALSE( 980 QuicConnectionPeer::GetConnectionClosePacket(&connection_) == NULL); 981 } 982 983 void BlockOnNextWrite() { 984 writer_->BlockOnNextWrite(); 985 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1)); 986 } 987 988 void CongestionBlockWrites() { 989 EXPECT_CALL(*send_algorithm_, 990 TimeUntilSend(_, _, _)).WillRepeatedly( 991 testing::Return(QuicTime::Delta::FromSeconds(1))); 992 } 993 994 void CongestionUnblockWrites() { 995 EXPECT_CALL(*send_algorithm_, 996 TimeUntilSend(_, _, _)).WillRepeatedly( 997 testing::Return(QuicTime::Delta::Zero())); 998 } 999 1000 QuicConnectionId connection_id_; 1001 QuicFramer framer_; 1002 QuicPacketCreator peer_creator_; 1003 MockEntropyCalculator entropy_calculator_; 1004 1005 MockSendAlgorithm* send_algorithm_; 1006 MockLossAlgorithm* loss_algorithm_; 1007 TestReceiveAlgorithm* receive_algorithm_; 1008 MockClock clock_; 1009 MockRandom random_generator_; 1010 scoped_ptr<TestConnectionHelper> helper_; 1011 scoped_ptr<TestPacketWriter> writer_; 1012 NiceMock<MockPacketWriterFactory> factory_; 1013 TestConnection connection_; 1014 StrictMock<MockConnectionVisitor> visitor_; 1015 1016 QuicPacketHeader header_; 1017 QuicStreamFrame frame1_; 1018 QuicStreamFrame frame2_; 1019 scoped_ptr<QuicAckFrame> outgoing_ack_; 1020 scoped_ptr<QuicStopWaitingFrame> stop_waiting_; 1021 QuicSequenceNumberLength sequence_number_length_; 1022 QuicConnectionIdLength connection_id_length_; 1023 1024 private: 1025 DISALLOW_COPY_AND_ASSIGN(QuicConnectionTest); 1026 }; 1027 1028 // Run all end to end tests with all supported versions. 1029 INSTANTIATE_TEST_CASE_P(SupportedVersion, 1030 QuicConnectionTest, 1031 ::testing::ValuesIn(QuicSupportedVersions())); 1032 1033 TEST_P(QuicConnectionTest, PacketsInOrder) { 1034 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 1035 1036 ProcessPacket(1); 1037 EXPECT_EQ(1u, outgoing_ack()->largest_observed); 1038 EXPECT_EQ(0u, outgoing_ack()->missing_packets.size()); 1039 1040 ProcessPacket(2); 1041 EXPECT_EQ(2u, outgoing_ack()->largest_observed); 1042 EXPECT_EQ(0u, outgoing_ack()->missing_packets.size()); 1043 1044 ProcessPacket(3); 1045 EXPECT_EQ(3u, outgoing_ack()->largest_observed); 1046 EXPECT_EQ(0u, outgoing_ack()->missing_packets.size()); 1047 } 1048 1049 TEST_P(QuicConnectionTest, PacketsOutOfOrder) { 1050 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 1051 1052 ProcessPacket(3); 1053 EXPECT_EQ(3u, outgoing_ack()->largest_observed); 1054 EXPECT_TRUE(IsMissing(2)); 1055 EXPECT_TRUE(IsMissing(1)); 1056 1057 ProcessPacket(2); 1058 EXPECT_EQ(3u, outgoing_ack()->largest_observed); 1059 EXPECT_FALSE(IsMissing(2)); 1060 EXPECT_TRUE(IsMissing(1)); 1061 1062 ProcessPacket(1); 1063 EXPECT_EQ(3u, outgoing_ack()->largest_observed); 1064 EXPECT_FALSE(IsMissing(2)); 1065 EXPECT_FALSE(IsMissing(1)); 1066 } 1067 1068 TEST_P(QuicConnectionTest, DuplicatePacket) { 1069 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 1070 1071 ProcessPacket(3); 1072 EXPECT_EQ(3u, outgoing_ack()->largest_observed); 1073 EXPECT_TRUE(IsMissing(2)); 1074 EXPECT_TRUE(IsMissing(1)); 1075 1076 // Send packet 3 again, but do not set the expectation that 1077 // the visitor OnStreamFrames() will be called. 1078 ProcessDataPacket(3, 0, !kEntropyFlag); 1079 EXPECT_EQ(3u, outgoing_ack()->largest_observed); 1080 EXPECT_TRUE(IsMissing(2)); 1081 EXPECT_TRUE(IsMissing(1)); 1082 } 1083 1084 TEST_P(QuicConnectionTest, PacketsOutOfOrderWithAdditionsAndLeastAwaiting) { 1085 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 1086 1087 ProcessPacket(3); 1088 EXPECT_EQ(3u, outgoing_ack()->largest_observed); 1089 EXPECT_TRUE(IsMissing(2)); 1090 EXPECT_TRUE(IsMissing(1)); 1091 1092 ProcessPacket(2); 1093 EXPECT_EQ(3u, outgoing_ack()->largest_observed); 1094 EXPECT_TRUE(IsMissing(1)); 1095 1096 ProcessPacket(5); 1097 EXPECT_EQ(5u, outgoing_ack()->largest_observed); 1098 EXPECT_TRUE(IsMissing(1)); 1099 EXPECT_TRUE(IsMissing(4)); 1100 1101 // Pretend at this point the client has gotten acks for 2 and 3 and 1 is a 1102 // packet the peer will not retransmit. It indicates this by sending 'least 1103 // awaiting' is 4. The connection should then realize 1 will not be 1104 // retransmitted, and will remove it from the missing list. 1105 peer_creator_.set_sequence_number(5); 1106 QuicAckFrame frame = InitAckFrame(1); 1107 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _)); 1108 ProcessAckPacket(&frame); 1109 1110 // Force an ack to be sent. 1111 SendAckPacketToPeer(); 1112 EXPECT_TRUE(IsMissing(4)); 1113 } 1114 1115 TEST_P(QuicConnectionTest, RejectPacketTooFarOut) { 1116 EXPECT_CALL(visitor_, 1117 OnConnectionClosed(QUIC_INVALID_PACKET_HEADER, false)); 1118 // Call ProcessDataPacket rather than ProcessPacket, as we should not get a 1119 // packet call to the visitor. 1120 ProcessDataPacket(6000, 0, !kEntropyFlag); 1121 EXPECT_FALSE( 1122 QuicConnectionPeer::GetConnectionClosePacket(&connection_) == NULL); 1123 } 1124 1125 TEST_P(QuicConnectionTest, RejectUnencryptedStreamData) { 1126 // Process an unencrypted packet from the non-crypto stream. 1127 frame1_.stream_id = 3; 1128 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 1129 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_UNENCRYPTED_STREAM_DATA, 1130 false)); 1131 ProcessDataPacket(1, 0, !kEntropyFlag); 1132 EXPECT_FALSE( 1133 QuicConnectionPeer::GetConnectionClosePacket(&connection_) == NULL); 1134 const vector<QuicConnectionCloseFrame>& connection_close_frames = 1135 writer_->connection_close_frames(); 1136 EXPECT_EQ(1u, connection_close_frames.size()); 1137 EXPECT_EQ(QUIC_UNENCRYPTED_STREAM_DATA, 1138 connection_close_frames[0].error_code); 1139 } 1140 1141 TEST_P(QuicConnectionTest, TruncatedAck) { 1142 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 1143 QuicPacketSequenceNumber num_packets = 256 * 2 + 1; 1144 for (QuicPacketSequenceNumber i = 0; i < num_packets; ++i) { 1145 SendStreamDataToPeer(3, "foo", i * 3, !kFin, NULL); 1146 } 1147 1148 QuicAckFrame frame = InitAckFrame(num_packets); 1149 SequenceNumberSet lost_packets; 1150 // Create an ack with 256 nacks, none adjacent to one another. 1151 for (QuicPacketSequenceNumber i = 1; i <= 256; ++i) { 1152 NackPacket(i * 2, &frame); 1153 if (i < 256) { // Last packet is nacked, but not lost. 1154 lost_packets.insert(i * 2); 1155 } 1156 } 1157 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _)) 1158 .WillOnce(Return(lost_packets)); 1159 EXPECT_CALL(entropy_calculator_, 1160 EntropyHash(511)).WillOnce(testing::Return(0)); 1161 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _)); 1162 ProcessAckPacket(&frame); 1163 1164 const QuicSentPacketManager& sent_packet_manager = 1165 connection_.sent_packet_manager(); 1166 // A truncated ack will not have the true largest observed. 1167 EXPECT_GT(num_packets, sent_packet_manager.largest_observed()); 1168 1169 AckPacket(192, &frame); 1170 1171 // Removing one missing packet allows us to ack 192 and one more range, but 1172 // 192 has already been declared lost, so it doesn't register as an ack. 1173 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _)) 1174 .WillOnce(Return(SequenceNumberSet())); 1175 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _)); 1176 ProcessAckPacket(&frame); 1177 EXPECT_EQ(num_packets, sent_packet_manager.largest_observed()); 1178 } 1179 1180 TEST_P(QuicConnectionTest, AckReceiptCausesAckSendBadEntropy) { 1181 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 1182 1183 ProcessPacket(1); 1184 // Delay sending, then queue up an ack. 1185 EXPECT_CALL(*send_algorithm_, 1186 TimeUntilSend(_, _, _)).WillOnce( 1187 testing::Return(QuicTime::Delta::FromMicroseconds(1))); 1188 QuicConnectionPeer::SendAck(&connection_); 1189 1190 // Process an ack with a least unacked of the received ack. 1191 // This causes an ack to be sent when TimeUntilSend returns 0. 1192 EXPECT_CALL(*send_algorithm_, 1193 TimeUntilSend(_, _, _)).WillRepeatedly( 1194 testing::Return(QuicTime::Delta::Zero())); 1195 // Skip a packet and then record an ack. 1196 peer_creator_.set_sequence_number(2); 1197 QuicAckFrame frame = InitAckFrame(0); 1198 ProcessAckPacket(&frame); 1199 } 1200 1201 TEST_P(QuicConnectionTest, OutOfOrderReceiptCausesAckSend) { 1202 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 1203 1204 ProcessPacket(3); 1205 // Should ack immediately since we have missing packets. 1206 EXPECT_EQ(1u, writer_->packets_write_attempts()); 1207 1208 ProcessPacket(2); 1209 // Should ack immediately since we have missing packets. 1210 EXPECT_EQ(2u, writer_->packets_write_attempts()); 1211 1212 ProcessPacket(1); 1213 // Should ack immediately, since this fills the last hole. 1214 EXPECT_EQ(3u, writer_->packets_write_attempts()); 1215 1216 ProcessPacket(4); 1217 // Should not cause an ack. 1218 EXPECT_EQ(3u, writer_->packets_write_attempts()); 1219 } 1220 1221 TEST_P(QuicConnectionTest, AckReceiptCausesAckSend) { 1222 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 1223 1224 QuicPacketSequenceNumber original; 1225 QuicByteCount packet_size; 1226 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) 1227 .WillOnce(DoAll(SaveArg<2>(&original), SaveArg<3>(&packet_size), 1228 Return(true))); 1229 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, NULL); 1230 QuicAckFrame frame = InitAckFrame(original); 1231 NackPacket(original, &frame); 1232 // First nack triggers early retransmit. 1233 SequenceNumberSet lost_packets; 1234 lost_packets.insert(1); 1235 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _)) 1236 .WillOnce(Return(lost_packets)); 1237 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _)); 1238 QuicPacketSequenceNumber retransmission; 1239 EXPECT_CALL(*send_algorithm_, 1240 OnPacketSent(_, _, _, packet_size - kQuicVersionSize, _)) 1241 .WillOnce(DoAll(SaveArg<2>(&retransmission), Return(true))); 1242 1243 ProcessAckPacket(&frame); 1244 1245 QuicAckFrame frame2 = InitAckFrame(retransmission); 1246 NackPacket(original, &frame2); 1247 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _)); 1248 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _)) 1249 .WillOnce(Return(SequenceNumberSet())); 1250 ProcessAckPacket(&frame2); 1251 1252 // Now if the peer sends an ack which still reports the retransmitted packet 1253 // as missing, that will bundle an ack with data after two acks in a row 1254 // indicate the high water mark needs to be raised. 1255 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, 1256 HAS_RETRANSMITTABLE_DATA)); 1257 connection_.SendStreamDataWithString(3, "foo", 3, !kFin, NULL); 1258 // No ack sent. 1259 EXPECT_EQ(1u, writer_->frame_count()); 1260 EXPECT_EQ(1u, writer_->stream_frames().size()); 1261 1262 // No more packet loss for the rest of the test. 1263 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _)) 1264 .WillRepeatedly(Return(SequenceNumberSet())); 1265 ProcessAckPacket(&frame2); 1266 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, 1267 HAS_RETRANSMITTABLE_DATA)); 1268 connection_.SendStreamDataWithString(3, "foo", 3, !kFin, NULL); 1269 // Ack bundled. 1270 EXPECT_EQ(3u, writer_->frame_count()); 1271 EXPECT_EQ(1u, writer_->stream_frames().size()); 1272 EXPECT_FALSE(writer_->ack_frames().empty()); 1273 1274 // But an ack with no missing packets will not send an ack. 1275 AckPacket(original, &frame2); 1276 ProcessAckPacket(&frame2); 1277 ProcessAckPacket(&frame2); 1278 } 1279 1280 TEST_P(QuicConnectionTest, 20AcksCausesAckSend) { 1281 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 1282 1283 SendStreamDataToPeer(1, "foo", 0, !kFin, NULL); 1284 1285 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_); 1286 // But an ack with no missing packets will not send an ack. 1287 QuicAckFrame frame = InitAckFrame(1); 1288 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _)); 1289 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _)) 1290 .WillRepeatedly(Return(SequenceNumberSet())); 1291 for (int i = 0; i < 20; ++i) { 1292 EXPECT_FALSE(ack_alarm->IsSet()); 1293 ProcessAckPacket(&frame); 1294 } 1295 EXPECT_TRUE(ack_alarm->IsSet()); 1296 } 1297 1298 TEST_P(QuicConnectionTest, LeastUnackedLower) { 1299 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 1300 1301 SendStreamDataToPeer(1, "foo", 0, !kFin, NULL); 1302 SendStreamDataToPeer(1, "bar", 3, !kFin, NULL); 1303 SendStreamDataToPeer(1, "eep", 6, !kFin, NULL); 1304 1305 // Start out saying the least unacked is 2. 1306 peer_creator_.set_sequence_number(5); 1307 QuicStopWaitingFrame frame = InitStopWaitingFrame(2); 1308 ProcessStopWaitingPacket(&frame); 1309 1310 // Change it to 1, but lower the sequence number to fake out-of-order packets. 1311 // This should be fine. 1312 peer_creator_.set_sequence_number(1); 1313 // The scheduler will not process out of order acks, but all packet processing 1314 // causes the connection to try to write. 1315 EXPECT_CALL(visitor_, OnCanWrite()); 1316 QuicStopWaitingFrame frame2 = InitStopWaitingFrame(1); 1317 ProcessStopWaitingPacket(&frame2); 1318 1319 // Now claim it's one, but set the ordering so it was sent "after" the first 1320 // one. This should cause a connection error. 1321 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)); 1322 peer_creator_.set_sequence_number(7); 1323 EXPECT_CALL(visitor_, 1324 OnConnectionClosed(QUIC_INVALID_STOP_WAITING_DATA, false)); 1325 QuicStopWaitingFrame frame3 = InitStopWaitingFrame(1); 1326 ProcessStopWaitingPacket(&frame3); 1327 } 1328 1329 TEST_P(QuicConnectionTest, LargestObservedLower) { 1330 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 1331 1332 SendStreamDataToPeer(1, "foo", 0, !kFin, NULL); 1333 SendStreamDataToPeer(1, "bar", 3, !kFin, NULL); 1334 SendStreamDataToPeer(1, "eep", 6, !kFin, NULL); 1335 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _)); 1336 1337 // Start out saying the largest observed is 2. 1338 QuicAckFrame frame1 = InitAckFrame(1); 1339 QuicAckFrame frame2 = InitAckFrame(2); 1340 ProcessAckPacket(&frame2); 1341 1342 // Now change it to 1, and it should cause a connection error. 1343 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, false)); 1344 EXPECT_CALL(visitor_, OnCanWrite()).Times(0); 1345 ProcessAckPacket(&frame1); 1346 } 1347 1348 TEST_P(QuicConnectionTest, AckUnsentData) { 1349 // Ack a packet which has not been sent. 1350 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, false)); 1351 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 1352 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)); 1353 QuicAckFrame frame(MakeAckFrame(1)); 1354 EXPECT_CALL(visitor_, OnCanWrite()).Times(0); 1355 ProcessAckPacket(&frame); 1356 } 1357 1358 TEST_P(QuicConnectionTest, AckAll) { 1359 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 1360 ProcessPacket(1); 1361 1362 peer_creator_.set_sequence_number(1); 1363 QuicAckFrame frame1 = InitAckFrame(0); 1364 ProcessAckPacket(&frame1); 1365 } 1366 1367 TEST_P(QuicConnectionTest, SendingDifferentSequenceNumberLengthsBandwidth) { 1368 QuicPacketSequenceNumber last_packet; 1369 QuicPacketCreator* creator = 1370 QuicConnectionPeer::GetPacketCreator(&connection_); 1371 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet); 1372 EXPECT_EQ(1u, last_packet); 1373 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER, 1374 creator->next_sequence_number_length()); 1375 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER, 1376 writer_->header().public_header.sequence_number_length); 1377 1378 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly( 1379 Return(kMaxPacketSize * 256)); 1380 1381 SendStreamDataToPeer(1, "bar", 3, !kFin, &last_packet); 1382 EXPECT_EQ(2u, last_packet); 1383 EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER, 1384 creator->next_sequence_number_length()); 1385 // The 1 packet lag is due to the sequence number length being recalculated in 1386 // QuicConnection after a packet is sent. 1387 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER, 1388 writer_->header().public_header.sequence_number_length); 1389 1390 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly( 1391 Return(kMaxPacketSize * 256 * 256)); 1392 1393 SendStreamDataToPeer(1, "foo", 6, !kFin, &last_packet); 1394 EXPECT_EQ(3u, last_packet); 1395 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER, 1396 creator->next_sequence_number_length()); 1397 EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER, 1398 writer_->header().public_header.sequence_number_length); 1399 1400 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly( 1401 Return(kMaxPacketSize * 256 * 256 * 256)); 1402 1403 SendStreamDataToPeer(1, "bar", 9, !kFin, &last_packet); 1404 EXPECT_EQ(4u, 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); 1409 1410 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly( 1411 Return(kMaxPacketSize * 256 * 256 * 256 * 256)); 1412 1413 SendStreamDataToPeer(1, "foo", 12, !kFin, &last_packet); 1414 EXPECT_EQ(5u, last_packet); 1415 EXPECT_EQ(PACKET_6BYTE_SEQUENCE_NUMBER, 1416 creator->next_sequence_number_length()); 1417 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER, 1418 writer_->header().public_header.sequence_number_length); 1419 } 1420 1421 // TODO(ianswett): Re-enable this test by finding a good way to test different 1422 // sequence number lengths without sending packets with giant gaps. 1423 TEST_P(QuicConnectionTest, 1424 DISABLED_SendingDifferentSequenceNumberLengthsUnackedDelta) { 1425 QuicPacketSequenceNumber last_packet; 1426 QuicPacketCreator* creator = 1427 QuicConnectionPeer::GetPacketCreator(&connection_); 1428 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet); 1429 EXPECT_EQ(1u, last_packet); 1430 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER, 1431 creator->next_sequence_number_length()); 1432 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER, 1433 writer_->header().public_header.sequence_number_length); 1434 1435 creator->set_sequence_number(100); 1436 1437 SendStreamDataToPeer(1, "bar", 3, !kFin, &last_packet); 1438 EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER, 1439 creator->next_sequence_number_length()); 1440 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER, 1441 writer_->header().public_header.sequence_number_length); 1442 1443 creator->set_sequence_number(100 * 256); 1444 1445 SendStreamDataToPeer(1, "foo", 6, !kFin, &last_packet); 1446 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER, 1447 creator->next_sequence_number_length()); 1448 EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER, 1449 writer_->header().public_header.sequence_number_length); 1450 1451 creator->set_sequence_number(100 * 256 * 256); 1452 1453 SendStreamDataToPeer(1, "bar", 9, !kFin, &last_packet); 1454 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER, 1455 creator->next_sequence_number_length()); 1456 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER, 1457 writer_->header().public_header.sequence_number_length); 1458 1459 creator->set_sequence_number(100 * 256 * 256 * 256); 1460 1461 SendStreamDataToPeer(1, "foo", 12, !kFin, &last_packet); 1462 EXPECT_EQ(PACKET_6BYTE_SEQUENCE_NUMBER, 1463 creator->next_sequence_number_length()); 1464 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER, 1465 writer_->header().public_header.sequence_number_length); 1466 } 1467 1468 TEST_P(QuicConnectionTest, BasicSending) { 1469 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 1470 QuicPacketSequenceNumber last_packet; 1471 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet); // Packet 1 1472 EXPECT_EQ(1u, last_packet); 1473 SendAckPacketToPeer(); // Packet 2 1474 1475 EXPECT_EQ(1u, least_unacked()); 1476 1477 SendAckPacketToPeer(); // Packet 3 1478 EXPECT_EQ(1u, least_unacked()); 1479 1480 SendStreamDataToPeer(1, "bar", 3, !kFin, &last_packet); // Packet 4 1481 EXPECT_EQ(4u, last_packet); 1482 SendAckPacketToPeer(); // Packet 5 1483 EXPECT_EQ(1u, least_unacked()); 1484 1485 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _)); 1486 1487 // Peer acks up to packet 3. 1488 QuicAckFrame frame = InitAckFrame(3); 1489 ProcessAckPacket(&frame); 1490 SendAckPacketToPeer(); // Packet 6 1491 1492 // As soon as we've acked one, we skip ack packets 2 and 3 and note lack of 1493 // ack for 4. 1494 EXPECT_EQ(4u, least_unacked()); 1495 1496 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _)); 1497 1498 // Peer acks up to packet 4, the last packet. 1499 QuicAckFrame frame2 = InitAckFrame(6); 1500 ProcessAckPacket(&frame2); // Acks don't instigate acks. 1501 1502 // Verify that we did not send an ack. 1503 EXPECT_EQ(6u, writer_->header().packet_sequence_number); 1504 1505 // So the last ack has not changed. 1506 EXPECT_EQ(4u, least_unacked()); 1507 1508 // If we force an ack, we shouldn't change our retransmit state. 1509 SendAckPacketToPeer(); // Packet 7 1510 EXPECT_EQ(7u, least_unacked()); 1511 1512 // But if we send more data it should. 1513 SendStreamDataToPeer(1, "eep", 6, !kFin, &last_packet); // Packet 8 1514 EXPECT_EQ(8u, last_packet); 1515 SendAckPacketToPeer(); // Packet 9 1516 EXPECT_EQ(7u, least_unacked()); 1517 } 1518 1519 TEST_P(QuicConnectionTest, FECSending) { 1520 // All packets carry version info till version is negotiated. 1521 QuicPacketCreator* creator = 1522 QuicConnectionPeer::GetPacketCreator(&connection_); 1523 size_t payload_length; 1524 // GetPacketLengthForOneStream() assumes a stream offset of 0 in determining 1525 // packet length. The size of the offset field in a stream frame is 0 for 1526 // offset 0, and 2 for non-zero offsets up through 64K. Increase 1527 // max_packet_length by 2 so that subsequent packets containing subsequent 1528 // stream frames with non-zero offets will fit within the packet length. 1529 size_t length = 2 + GetPacketLengthForOneStream( 1530 connection_.version(), kIncludeVersion, PACKET_1BYTE_SEQUENCE_NUMBER, 1531 IN_FEC_GROUP, &payload_length); 1532 creator->set_max_packet_length(length); 1533 1534 // Send 4 protected data packets, which should also trigger 1 FEC packet. 1535 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(5); 1536 // The first stream frame will have 2 fewer overhead bytes than the other 3. 1537 const string payload(payload_length * 4 + 2, 'a'); 1538 connection_.SendStreamDataWithStringWithFec(1, payload, 0, !kFin, NULL); 1539 // Expect the FEC group to be closed after SendStreamDataWithString. 1540 EXPECT_FALSE(creator->IsFecGroupOpen()); 1541 EXPECT_FALSE(creator->IsFecProtected()); 1542 } 1543 1544 TEST_P(QuicConnectionTest, FECQueueing) { 1545 // All packets carry version info till version is negotiated. 1546 size_t payload_length; 1547 QuicPacketCreator* creator = 1548 QuicConnectionPeer::GetPacketCreator(&connection_); 1549 size_t length = GetPacketLengthForOneStream( 1550 connection_.version(), kIncludeVersion, PACKET_1BYTE_SEQUENCE_NUMBER, 1551 IN_FEC_GROUP, &payload_length); 1552 creator->set_max_packet_length(length); 1553 EXPECT_TRUE(creator->IsFecEnabled()); 1554 1555 EXPECT_EQ(0u, connection_.NumQueuedPackets()); 1556 BlockOnNextWrite(); 1557 const string payload(payload_length, 'a'); 1558 connection_.SendStreamDataWithStringWithFec(1, payload, 0, !kFin, NULL); 1559 EXPECT_FALSE(creator->IsFecGroupOpen()); 1560 EXPECT_FALSE(creator->IsFecProtected()); 1561 // Expect the first data packet and the fec packet to be queued. 1562 EXPECT_EQ(2u, connection_.NumQueuedPackets()); 1563 } 1564 1565 TEST_P(QuicConnectionTest, AbandonFECFromCongestionWindow) { 1566 EXPECT_TRUE(QuicConnectionPeer::GetPacketCreator( 1567 &connection_)->IsFecEnabled()); 1568 1569 // 1 Data and 1 FEC packet. 1570 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2); 1571 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, !kFin, NULL); 1572 1573 const QuicTime::Delta retransmission_time = 1574 QuicTime::Delta::FromMilliseconds(5000); 1575 clock_.AdvanceTime(retransmission_time); 1576 1577 // Abandon FEC packet and data packet. 1578 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true)); 1579 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); 1580 EXPECT_CALL(visitor_, OnCanWrite()); 1581 connection_.OnRetransmissionTimeout(); 1582 } 1583 1584 TEST_P(QuicConnectionTest, DontAbandonAckedFEC) { 1585 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 1586 EXPECT_TRUE(QuicConnectionPeer::GetPacketCreator( 1587 &connection_)->IsFecEnabled()); 1588 1589 // 1 Data and 1 FEC packet. 1590 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(6); 1591 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, !kFin, NULL); 1592 // Send some more data afterwards to ensure early retransmit doesn't trigger. 1593 connection_.SendStreamDataWithStringWithFec(3, "foo", 3, !kFin, NULL); 1594 connection_.SendStreamDataWithStringWithFec(3, "foo", 6, !kFin, NULL); 1595 1596 QuicAckFrame ack_fec = InitAckFrame(2); 1597 // Data packet missing. 1598 // TODO(ianswett): Note that this is not a sensible ack, since if the FEC was 1599 // received, it would cause the covered packet to be acked as well. 1600 NackPacket(1, &ack_fec); 1601 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _)); 1602 ProcessAckPacket(&ack_fec); 1603 clock_.AdvanceTime(DefaultRetransmissionTime()); 1604 1605 // Don't abandon the acked FEC packet, but it will abandon 2 the subsequent 1606 // FEC packets. 1607 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true)); 1608 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3); 1609 connection_.GetRetransmissionAlarm()->Fire(); 1610 } 1611 1612 TEST_P(QuicConnectionTest, AbandonAllFEC) { 1613 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 1614 EXPECT_TRUE(QuicConnectionPeer::GetPacketCreator( 1615 &connection_)->IsFecEnabled()); 1616 1617 // 1 Data and 1 FEC packet. 1618 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(6); 1619 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, !kFin, NULL); 1620 // Send some more data afterwards to ensure early retransmit doesn't trigger. 1621 connection_.SendStreamDataWithStringWithFec(3, "foo", 3, !kFin, NULL); 1622 // Advance the time so not all the FEC packets are abandoned. 1623 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(1)); 1624 connection_.SendStreamDataWithStringWithFec(3, "foo", 6, !kFin, NULL); 1625 1626 QuicAckFrame ack_fec = InitAckFrame(5); 1627 // Ack all data packets, but no fec packets. 1628 NackPacket(2, &ack_fec); 1629 NackPacket(4, &ack_fec); 1630 1631 // Lose the first FEC packet and ack the three data packets. 1632 SequenceNumberSet lost_packets; 1633 lost_packets.insert(2); 1634 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _)) 1635 .WillOnce(Return(lost_packets)); 1636 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _)); 1637 ProcessAckPacket(&ack_fec); 1638 1639 clock_.AdvanceTime(DefaultRetransmissionTime().Subtract( 1640 QuicTime::Delta::FromMilliseconds(1))); 1641 1642 // Abandon all packets 1643 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(false)); 1644 connection_.GetRetransmissionAlarm()->Fire(); 1645 1646 // Ensure the alarm is not set since all packets have been abandoned. 1647 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet()); 1648 } 1649 1650 TEST_P(QuicConnectionTest, FramePacking) { 1651 CongestionBlockWrites(); 1652 1653 // Send an ack and two stream frames in 1 packet by queueing them. 1654 connection_.SendAck(); 1655 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll( 1656 IgnoreResult(InvokeWithoutArgs(&connection_, 1657 &TestConnection::SendStreamData3)), 1658 IgnoreResult(InvokeWithoutArgs(&connection_, 1659 &TestConnection::SendStreamData5)))); 1660 1661 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); 1662 CongestionUnblockWrites(); 1663 connection_.GetSendAlarm()->Fire(); 1664 EXPECT_EQ(0u, connection_.NumQueuedPackets()); 1665 EXPECT_FALSE(connection_.HasQueuedData()); 1666 1667 // Parse the last packet and ensure it's an ack and two stream frames from 1668 // two different streams. 1669 EXPECT_EQ(4u, writer_->frame_count()); 1670 EXPECT_FALSE(writer_->stop_waiting_frames().empty()); 1671 EXPECT_FALSE(writer_->ack_frames().empty()); 1672 ASSERT_EQ(2u, writer_->stream_frames().size()); 1673 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id); 1674 EXPECT_EQ(kClientDataStreamId2, writer_->stream_frames()[1].stream_id); 1675 } 1676 1677 TEST_P(QuicConnectionTest, FramePackingNonCryptoThenCrypto) { 1678 CongestionBlockWrites(); 1679 1680 // Send an ack and two stream frames (one non-crypto, then one crypto) in 2 1681 // packets by queueing them. 1682 connection_.SendAck(); 1683 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll( 1684 IgnoreResult(InvokeWithoutArgs(&connection_, 1685 &TestConnection::SendStreamData3)), 1686 IgnoreResult(InvokeWithoutArgs(&connection_, 1687 &TestConnection::SendCryptoStreamData)))); 1688 1689 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2); 1690 CongestionUnblockWrites(); 1691 connection_.GetSendAlarm()->Fire(); 1692 EXPECT_EQ(0u, connection_.NumQueuedPackets()); 1693 EXPECT_FALSE(connection_.HasQueuedData()); 1694 1695 // Parse the last packet and ensure it's the crypto stream frame. 1696 EXPECT_EQ(1u, writer_->frame_count()); 1697 ASSERT_EQ(1u, writer_->stream_frames().size()); 1698 EXPECT_EQ(kCryptoStreamId, writer_->stream_frames()[0].stream_id); 1699 } 1700 1701 TEST_P(QuicConnectionTest, FramePackingCryptoThenNonCrypto) { 1702 CongestionBlockWrites(); 1703 1704 // Send an ack and two stream frames (one crypto, then one non-crypto) in 2 1705 // packets by queueing them. 1706 connection_.SendAck(); 1707 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll( 1708 IgnoreResult(InvokeWithoutArgs(&connection_, 1709 &TestConnection::SendCryptoStreamData)), 1710 IgnoreResult(InvokeWithoutArgs(&connection_, 1711 &TestConnection::SendStreamData3)))); 1712 1713 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2); 1714 CongestionUnblockWrites(); 1715 connection_.GetSendAlarm()->Fire(); 1716 EXPECT_EQ(0u, connection_.NumQueuedPackets()); 1717 EXPECT_FALSE(connection_.HasQueuedData()); 1718 1719 // Parse the last packet and ensure it's the stream frame from stream 3. 1720 EXPECT_EQ(1u, writer_->frame_count()); 1721 ASSERT_EQ(1u, writer_->stream_frames().size()); 1722 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id); 1723 } 1724 1725 TEST_P(QuicConnectionTest, FramePackingFEC) { 1726 EXPECT_TRUE(QuicConnectionPeer::GetPacketCreator( 1727 &connection_)->IsFecEnabled()); 1728 1729 CongestionBlockWrites(); 1730 1731 // Queue an ack and two stream frames. Ack gets flushed when FEC is turned on 1732 // for sending protected data; two stream frames are packing in 1 packet. 1733 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll( 1734 IgnoreResult(InvokeWithoutArgs( 1735 &connection_, &TestConnection::SendStreamData3WithFec)), 1736 IgnoreResult(InvokeWithoutArgs( 1737 &connection_, &TestConnection::SendStreamData5WithFec)))); 1738 connection_.SendAck(); 1739 1740 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3); 1741 CongestionUnblockWrites(); 1742 connection_.GetSendAlarm()->Fire(); 1743 EXPECT_EQ(0u, connection_.NumQueuedPackets()); 1744 EXPECT_FALSE(connection_.HasQueuedData()); 1745 1746 // Parse the last packet and ensure it's in an fec group. 1747 EXPECT_EQ(2u, writer_->header().fec_group); 1748 EXPECT_EQ(0u, writer_->frame_count()); 1749 } 1750 1751 TEST_P(QuicConnectionTest, FramePackingAckResponse) { 1752 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 1753 // Process a data packet to queue up a pending ack. 1754 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1); 1755 ProcessDataPacket(1, 1, kEntropyFlag); 1756 1757 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll( 1758 IgnoreResult(InvokeWithoutArgs(&connection_, 1759 &TestConnection::SendStreamData3)), 1760 IgnoreResult(InvokeWithoutArgs(&connection_, 1761 &TestConnection::SendStreamData5)))); 1762 1763 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); 1764 1765 // Process an ack to cause the visitor's OnCanWrite to be invoked. 1766 peer_creator_.set_sequence_number(2); 1767 QuicAckFrame ack_one = InitAckFrame(0); 1768 ProcessAckPacket(&ack_one); 1769 1770 EXPECT_EQ(0u, connection_.NumQueuedPackets()); 1771 EXPECT_FALSE(connection_.HasQueuedData()); 1772 1773 // Parse the last packet and ensure it's an ack and two stream frames from 1774 // two different streams. 1775 EXPECT_EQ(4u, writer_->frame_count()); 1776 EXPECT_FALSE(writer_->stop_waiting_frames().empty()); 1777 EXPECT_FALSE(writer_->ack_frames().empty()); 1778 ASSERT_EQ(2u, writer_->stream_frames().size()); 1779 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id); 1780 EXPECT_EQ(kClientDataStreamId2, writer_->stream_frames()[1].stream_id); 1781 } 1782 1783 TEST_P(QuicConnectionTest, FramePackingSendv) { 1784 // Send data in 1 packet by writing multiple blocks in a single iovector 1785 // using writev. 1786 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)); 1787 1788 char data[] = "ABCD"; 1789 IOVector data_iov; 1790 data_iov.AppendNoCoalesce(data, 2); 1791 data_iov.AppendNoCoalesce(data + 2, 2); 1792 connection_.SendStreamData(1, data_iov, 0, !kFin, MAY_FEC_PROTECT, NULL); 1793 1794 EXPECT_EQ(0u, connection_.NumQueuedPackets()); 1795 EXPECT_FALSE(connection_.HasQueuedData()); 1796 1797 // Parse the last packet and ensure multiple iovector blocks have 1798 // been packed into a single stream frame from one stream. 1799 EXPECT_EQ(1u, writer_->frame_count()); 1800 EXPECT_EQ(1u, writer_->stream_frames().size()); 1801 QuicStreamFrame frame = writer_->stream_frames()[0]; 1802 EXPECT_EQ(1u, frame.stream_id); 1803 EXPECT_EQ("ABCD", string(static_cast<char*> 1804 (frame.data.iovec()[0].iov_base), 1805 (frame.data.iovec()[0].iov_len))); 1806 } 1807 1808 TEST_P(QuicConnectionTest, FramePackingSendvQueued) { 1809 // Try to send two stream frames in 1 packet by using writev. 1810 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)); 1811 1812 BlockOnNextWrite(); 1813 char data[] = "ABCD"; 1814 IOVector data_iov; 1815 data_iov.AppendNoCoalesce(data, 2); 1816 data_iov.AppendNoCoalesce(data + 2, 2); 1817 connection_.SendStreamData(1, data_iov, 0, !kFin, MAY_FEC_PROTECT, NULL); 1818 1819 EXPECT_EQ(1u, connection_.NumQueuedPackets()); 1820 EXPECT_TRUE(connection_.HasQueuedData()); 1821 1822 // Unblock the writes and actually send. 1823 writer_->SetWritable(); 1824 connection_.OnCanWrite(); 1825 EXPECT_EQ(0u, connection_.NumQueuedPackets()); 1826 1827 // Parse the last packet and ensure it's one stream frame from one stream. 1828 EXPECT_EQ(1u, writer_->frame_count()); 1829 EXPECT_EQ(1u, writer_->stream_frames().size()); 1830 EXPECT_EQ(1u, writer_->stream_frames()[0].stream_id); 1831 } 1832 1833 TEST_P(QuicConnectionTest, SendingZeroBytes) { 1834 // Send a zero byte write with a fin using writev. 1835 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)); 1836 IOVector empty_iov; 1837 connection_.SendStreamData(1, empty_iov, 0, kFin, MAY_FEC_PROTECT, NULL); 1838 1839 EXPECT_EQ(0u, connection_.NumQueuedPackets()); 1840 EXPECT_FALSE(connection_.HasQueuedData()); 1841 1842 // Parse the last packet and ensure it's one stream frame from one stream. 1843 EXPECT_EQ(1u, writer_->frame_count()); 1844 EXPECT_EQ(1u, writer_->stream_frames().size()); 1845 EXPECT_EQ(1u, writer_->stream_frames()[0].stream_id); 1846 EXPECT_TRUE(writer_->stream_frames()[0].fin); 1847 } 1848 1849 TEST_P(QuicConnectionTest, OnCanWrite) { 1850 // Visitor's OnCanWrite will send data, but will have more pending writes. 1851 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll( 1852 IgnoreResult(InvokeWithoutArgs(&connection_, 1853 &TestConnection::SendStreamData3)), 1854 IgnoreResult(InvokeWithoutArgs(&connection_, 1855 &TestConnection::SendStreamData5)))); 1856 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillOnce(Return(true)); 1857 EXPECT_CALL(*send_algorithm_, 1858 TimeUntilSend(_, _, _)).WillRepeatedly( 1859 testing::Return(QuicTime::Delta::Zero())); 1860 1861 connection_.OnCanWrite(); 1862 1863 // Parse the last packet and ensure it's the two stream frames from 1864 // two different streams. 1865 EXPECT_EQ(2u, writer_->frame_count()); 1866 EXPECT_EQ(2u, writer_->stream_frames().size()); 1867 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id); 1868 EXPECT_EQ(kClientDataStreamId2, writer_->stream_frames()[1].stream_id); 1869 } 1870 1871 TEST_P(QuicConnectionTest, RetransmitOnNack) { 1872 QuicPacketSequenceNumber last_packet; 1873 QuicByteCount second_packet_size; 1874 SendStreamDataToPeer(3, "foo", 0, !kFin, &last_packet); // Packet 1 1875 second_packet_size = 1876 SendStreamDataToPeer(3, "foos", 3, !kFin, &last_packet); // Packet 2 1877 SendStreamDataToPeer(3, "fooos", 7, !kFin, &last_packet); // Packet 3 1878 1879 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 1880 1881 // Don't lose a packet on an ack, and nothing is retransmitted. 1882 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _)); 1883 QuicAckFrame ack_one = InitAckFrame(1); 1884 ProcessAckPacket(&ack_one); 1885 1886 // Lose a packet and ensure it triggers retransmission. 1887 QuicAckFrame nack_two = InitAckFrame(3); 1888 NackPacket(2, &nack_two); 1889 SequenceNumberSet lost_packets; 1890 lost_packets.insert(2); 1891 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _)) 1892 .WillOnce(Return(lost_packets)); 1893 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _)); 1894 EXPECT_CALL(*send_algorithm_, 1895 OnPacketSent(_, _, _, second_packet_size - kQuicVersionSize, _)). 1896 Times(1); 1897 ProcessAckPacket(&nack_two); 1898 } 1899 1900 TEST_P(QuicConnectionTest, DiscardRetransmit) { 1901 QuicPacketSequenceNumber last_packet; 1902 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet); // Packet 1 1903 SendStreamDataToPeer(1, "foos", 3, !kFin, &last_packet); // Packet 2 1904 SendStreamDataToPeer(1, "fooos", 7, !kFin, &last_packet); // Packet 3 1905 1906 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 1907 1908 // Instigate a loss with an ack. 1909 QuicAckFrame nack_two = InitAckFrame(3); 1910 NackPacket(2, &nack_two); 1911 // The first nack should trigger a fast retransmission, but we'll be 1912 // write blocked, so the packet will be queued. 1913 BlockOnNextWrite(); 1914 SequenceNumberSet lost_packets; 1915 lost_packets.insert(2); 1916 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _)) 1917 .WillOnce(Return(lost_packets)); 1918 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _)); 1919 ProcessAckPacket(&nack_two); 1920 EXPECT_EQ(1u, connection_.NumQueuedPackets()); 1921 1922 // Now, ack the previous transmission. 1923 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _)) 1924 .WillOnce(Return(SequenceNumberSet())); 1925 QuicAckFrame ack_all = InitAckFrame(3); 1926 ProcessAckPacket(&ack_all); 1927 1928 // Unblock the socket and attempt to send the queued packets. However, 1929 // since the previous transmission has been acked, we will not 1930 // send the retransmission. 1931 EXPECT_CALL(*send_algorithm_, 1932 OnPacketSent(_, _, _, _, _)).Times(0); 1933 1934 writer_->SetWritable(); 1935 connection_.OnCanWrite(); 1936 1937 EXPECT_EQ(0u, connection_.NumQueuedPackets()); 1938 } 1939 1940 TEST_P(QuicConnectionTest, RetransmitNackedLargestObserved) { 1941 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 1942 QuicPacketSequenceNumber largest_observed; 1943 QuicByteCount packet_size; 1944 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) 1945 .WillOnce(DoAll(SaveArg<2>(&largest_observed), SaveArg<3>(&packet_size), 1946 Return(true))); 1947 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, NULL); 1948 1949 QuicAckFrame frame = InitAckFrame(1); 1950 NackPacket(largest_observed, &frame); 1951 // The first nack should retransmit the largest observed packet. 1952 SequenceNumberSet lost_packets; 1953 lost_packets.insert(1); 1954 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _)) 1955 .WillOnce(Return(lost_packets)); 1956 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _)); 1957 EXPECT_CALL(*send_algorithm_, 1958 OnPacketSent(_, _, _, packet_size - kQuicVersionSize, _)); 1959 ProcessAckPacket(&frame); 1960 } 1961 1962 TEST_P(QuicConnectionTest, QueueAfterTwoRTOs) { 1963 for (int i = 0; i < 10; ++i) { 1964 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); 1965 connection_.SendStreamDataWithString(3, "foo", i * 3, !kFin, NULL); 1966 } 1967 1968 // Block the congestion window and ensure they're queued. 1969 BlockOnNextWrite(); 1970 clock_.AdvanceTime(DefaultRetransmissionTime()); 1971 // Only one packet should be retransmitted. 1972 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true)); 1973 connection_.GetRetransmissionAlarm()->Fire(); 1974 EXPECT_TRUE(connection_.HasQueuedData()); 1975 1976 // Unblock the congestion window. 1977 writer_->SetWritable(); 1978 clock_.AdvanceTime(QuicTime::Delta::FromMicroseconds( 1979 2 * DefaultRetransmissionTime().ToMicroseconds())); 1980 // Retransmit already retransmitted packets event though the sequence number 1981 // greater than the largest observed. 1982 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(10); 1983 connection_.GetRetransmissionAlarm()->Fire(); 1984 connection_.OnCanWrite(); 1985 } 1986 1987 TEST_P(QuicConnectionTest, WriteBlockedThenSent) { 1988 BlockOnNextWrite(); 1989 writer_->set_is_write_blocked_data_buffered(true); 1990 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); 1991 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, NULL); 1992 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet()); 1993 1994 writer_->SetWritable(); 1995 connection_.OnCanWrite(); 1996 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet()); 1997 } 1998 1999 TEST_P(QuicConnectionTest, RetransmitWriteBlockedAckedOriginalThenSent) { 2000 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 2001 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, NULL); 2002 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet()); 2003 2004 BlockOnNextWrite(); 2005 writer_->set_is_write_blocked_data_buffered(true); 2006 // Simulate the retransmission alarm firing. 2007 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(_)); 2008 clock_.AdvanceTime(DefaultRetransmissionTime()); 2009 connection_.GetRetransmissionAlarm()->Fire(); 2010 2011 // Ack the sent packet before the callback returns, which happens in 2012 // rare circumstances with write blocked sockets. 2013 QuicAckFrame ack = InitAckFrame(1); 2014 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _)); 2015 EXPECT_CALL(*send_algorithm_, RevertRetransmissionTimeout()); 2016 ProcessAckPacket(&ack); 2017 2018 writer_->SetWritable(); 2019 connection_.OnCanWrite(); 2020 // There is now a pending packet, but with no retransmittable frames. 2021 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet()); 2022 EXPECT_FALSE(connection_.sent_packet_manager().HasRetransmittableFrames(2)); 2023 } 2024 2025 TEST_P(QuicConnectionTest, AlarmsWhenWriteBlocked) { 2026 // Block the connection. 2027 BlockOnNextWrite(); 2028 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, NULL); 2029 EXPECT_EQ(1u, writer_->packets_write_attempts()); 2030 EXPECT_TRUE(writer_->IsWriteBlocked()); 2031 2032 // Set the send and resumption alarms. Fire the alarms and ensure they don't 2033 // attempt to write. 2034 connection_.GetResumeWritesAlarm()->Set(clock_.ApproximateNow()); 2035 connection_.GetSendAlarm()->Set(clock_.ApproximateNow()); 2036 connection_.GetResumeWritesAlarm()->Fire(); 2037 connection_.GetSendAlarm()->Fire(); 2038 EXPECT_TRUE(writer_->IsWriteBlocked()); 2039 EXPECT_EQ(1u, writer_->packets_write_attempts()); 2040 } 2041 2042 TEST_P(QuicConnectionTest, NoLimitPacketsPerNack) { 2043 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 2044 int offset = 0; 2045 // Send packets 1 to 15. 2046 for (int i = 0; i < 15; ++i) { 2047 SendStreamDataToPeer(1, "foo", offset, !kFin, NULL); 2048 offset += 3; 2049 } 2050 2051 // Ack 15, nack 1-14. 2052 SequenceNumberSet lost_packets; 2053 QuicAckFrame nack = InitAckFrame(15); 2054 for (int i = 1; i < 15; ++i) { 2055 NackPacket(i, &nack); 2056 lost_packets.insert(i); 2057 } 2058 2059 // 14 packets have been NACK'd and lost. In TCP cubic, PRR limits 2060 // the retransmission rate in the case of burst losses. 2061 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _)) 2062 .WillOnce(Return(lost_packets)); 2063 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _)); 2064 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(14); 2065 ProcessAckPacket(&nack); 2066 } 2067 2068 // Test sending multiple acks from the connection to the session. 2069 TEST_P(QuicConnectionTest, MultipleAcks) { 2070 QuicPacketSequenceNumber last_packet; 2071 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet); // Packet 1 2072 EXPECT_EQ(1u, last_packet); 2073 SendStreamDataToPeer(3, "foo", 0, !kFin, &last_packet); // Packet 2 2074 EXPECT_EQ(2u, last_packet); 2075 SendAckPacketToPeer(); // Packet 3 2076 SendStreamDataToPeer(5, "foo", 0, !kFin, &last_packet); // Packet 4 2077 EXPECT_EQ(4u, last_packet); 2078 SendStreamDataToPeer(1, "foo", 3, !kFin, &last_packet); // Packet 5 2079 EXPECT_EQ(5u, last_packet); 2080 SendStreamDataToPeer(3, "foo", 3, !kFin, &last_packet); // Packet 6 2081 EXPECT_EQ(6u, last_packet); 2082 2083 // Client will ack packets 1, 2, [!3], 4, 5. 2084 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _)); 2085 QuicAckFrame frame1 = InitAckFrame(5); 2086 NackPacket(3, &frame1); 2087 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 2088 ProcessAckPacket(&frame1); 2089 2090 // Now the client implicitly acks 3, and explicitly acks 6. 2091 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _)); 2092 QuicAckFrame frame2 = InitAckFrame(6); 2093 ProcessAckPacket(&frame2); 2094 } 2095 2096 TEST_P(QuicConnectionTest, DontLatchUnackedPacket) { 2097 SendStreamDataToPeer(1, "foo", 0, !kFin, NULL); // Packet 1; 2098 // From now on, we send acks, so the send algorithm won't mark them pending. 2099 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) 2100 .WillByDefault(Return(false)); 2101 SendAckPacketToPeer(); // Packet 2 2102 2103 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 2104 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _)); 2105 QuicAckFrame frame = InitAckFrame(1); 2106 ProcessAckPacket(&frame); 2107 2108 // Verify that our internal state has least-unacked as 2, because we're still 2109 // waiting for a potential ack for 2. 2110 2111 EXPECT_EQ(2u, stop_waiting()->least_unacked); 2112 2113 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _)); 2114 frame = InitAckFrame(2); 2115 ProcessAckPacket(&frame); 2116 EXPECT_EQ(3u, stop_waiting()->least_unacked); 2117 2118 // When we send an ack, we make sure our least-unacked makes sense. In this 2119 // case since we're not waiting on an ack for 2 and all packets are acked, we 2120 // set it to 3. 2121 SendAckPacketToPeer(); // Packet 3 2122 // Least_unacked remains at 3 until another ack is received. 2123 EXPECT_EQ(3u, stop_waiting()->least_unacked); 2124 // Check that the outgoing ack had its sequence number as least_unacked. 2125 EXPECT_EQ(3u, least_unacked()); 2126 2127 // Ack the ack, which updates the rtt and raises the least unacked. 2128 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _)); 2129 frame = InitAckFrame(3); 2130 ProcessAckPacket(&frame); 2131 2132 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) 2133 .WillByDefault(Return(true)); 2134 SendStreamDataToPeer(1, "bar", 3, false, NULL); // Packet 4 2135 EXPECT_EQ(4u, stop_waiting()->least_unacked); 2136 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) 2137 .WillByDefault(Return(false)); 2138 SendAckPacketToPeer(); // Packet 5 2139 EXPECT_EQ(4u, least_unacked()); 2140 2141 // Send two data packets at the end, and ensure if the last one is acked, 2142 // the least unacked is raised above the ack packets. 2143 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) 2144 .WillByDefault(Return(true)); 2145 SendStreamDataToPeer(1, "bar", 6, false, NULL); // Packet 6 2146 SendStreamDataToPeer(1, "bar", 9, false, NULL); // Packet 7 2147 2148 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _)); 2149 frame = InitAckFrame(7); 2150 NackPacket(5, &frame); 2151 NackPacket(6, &frame); 2152 ProcessAckPacket(&frame); 2153 2154 EXPECT_EQ(6u, stop_waiting()->least_unacked); 2155 } 2156 2157 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterFecPacket) { 2158 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 2159 2160 // Don't send missing packet 1. 2161 ProcessFecPacket(2, 1, true, !kEntropyFlag, NULL); 2162 // Entropy flag should be false, so entropy should be 0. 2163 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2)); 2164 } 2165 2166 TEST_P(QuicConnectionTest, ReviveMissingPacketWithVaryingSeqNumLengths) { 2167 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 2168 2169 // Set up a debug visitor to the connection. 2170 FecQuicConnectionDebugVisitor* fec_visitor = 2171 new FecQuicConnectionDebugVisitor(); 2172 connection_.set_debug_visitor(fec_visitor); 2173 2174 QuicPacketSequenceNumber fec_packet = 0; 2175 QuicSequenceNumberLength lengths[] = {PACKET_6BYTE_SEQUENCE_NUMBER, 2176 PACKET_4BYTE_SEQUENCE_NUMBER, 2177 PACKET_2BYTE_SEQUENCE_NUMBER, 2178 PACKET_1BYTE_SEQUENCE_NUMBER}; 2179 // For each sequence number length size, revive a packet and check sequence 2180 // number length in the revived packet. 2181 for (size_t i = 0; i < arraysize(lengths); ++i) { 2182 // Set sequence_number_length_ (for data and FEC packets). 2183 sequence_number_length_ = lengths[i]; 2184 fec_packet += 2; 2185 // Don't send missing packet, but send fec packet right after it. 2186 ProcessFecPacket(fec_packet, fec_packet - 1, true, !kEntropyFlag, NULL); 2187 // Sequence number length in the revived header should be the same as 2188 // in the original data/fec packet headers. 2189 EXPECT_EQ(sequence_number_length_, fec_visitor->revived_header(). 2190 public_header.sequence_number_length); 2191 } 2192 } 2193 2194 TEST_P(QuicConnectionTest, ReviveMissingPacketWithVaryingConnectionIdLengths) { 2195 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 2196 2197 // Set up a debug visitor to the connection. 2198 FecQuicConnectionDebugVisitor* fec_visitor = 2199 new FecQuicConnectionDebugVisitor(); 2200 connection_.set_debug_visitor(fec_visitor); 2201 2202 QuicPacketSequenceNumber fec_packet = 0; 2203 QuicConnectionIdLength lengths[] = {PACKET_8BYTE_CONNECTION_ID, 2204 PACKET_4BYTE_CONNECTION_ID, 2205 PACKET_1BYTE_CONNECTION_ID, 2206 PACKET_0BYTE_CONNECTION_ID}; 2207 // For each connection id length size, revive a packet and check connection 2208 // id length in the revived packet. 2209 for (size_t i = 0; i < arraysize(lengths); ++i) { 2210 // Set connection id length (for data and FEC packets). 2211 connection_id_length_ = lengths[i]; 2212 fec_packet += 2; 2213 // Don't send missing packet, but send fec packet right after it. 2214 ProcessFecPacket(fec_packet, fec_packet - 1, true, !kEntropyFlag, NULL); 2215 // Connection id length in the revived header should be the same as 2216 // in the original data/fec packet headers. 2217 EXPECT_EQ(connection_id_length_, 2218 fec_visitor->revived_header().public_header.connection_id_length); 2219 } 2220 } 2221 2222 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPacketThenFecPacket) { 2223 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 2224 2225 ProcessFecProtectedPacket(1, false, kEntropyFlag); 2226 // Don't send missing packet 2. 2227 ProcessFecPacket(3, 1, true, !kEntropyFlag, NULL); 2228 // Entropy flag should be true, so entropy should not be 0. 2229 EXPECT_NE(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2)); 2230 } 2231 2232 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPacketsThenFecPacket) { 2233 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 2234 2235 ProcessFecProtectedPacket(1, false, !kEntropyFlag); 2236 // Don't send missing packet 2. 2237 ProcessFecProtectedPacket(3, false, !kEntropyFlag); 2238 ProcessFecPacket(4, 1, true, kEntropyFlag, NULL); 2239 // Ensure QUIC no longer revives entropy for lost packets. 2240 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2)); 2241 EXPECT_NE(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 4)); 2242 } 2243 2244 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPacket) { 2245 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 2246 2247 // Don't send missing packet 1. 2248 ProcessFecPacket(3, 1, false, !kEntropyFlag, NULL); 2249 // Out of order. 2250 ProcessFecProtectedPacket(2, true, !kEntropyFlag); 2251 // Entropy flag should be false, so entropy should be 0. 2252 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2)); 2253 } 2254 2255 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPackets) { 2256 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 2257 2258 ProcessFecProtectedPacket(1, false, !kEntropyFlag); 2259 // Don't send missing packet 2. 2260 ProcessFecPacket(6, 1, false, kEntropyFlag, NULL); 2261 ProcessFecProtectedPacket(3, false, kEntropyFlag); 2262 ProcessFecProtectedPacket(4, false, kEntropyFlag); 2263 ProcessFecProtectedPacket(5, true, !kEntropyFlag); 2264 // Ensure entropy is not revived for the missing packet. 2265 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2)); 2266 EXPECT_NE(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 3)); 2267 } 2268 2269 TEST_P(QuicConnectionTest, TLP) { 2270 QuicSentPacketManagerPeer::SetMaxTailLossProbes( 2271 QuicConnectionPeer::GetSentPacketManager(&connection_), 1); 2272 2273 SendStreamDataToPeer(3, "foo", 0, !kFin, NULL); 2274 EXPECT_EQ(1u, stop_waiting()->least_unacked); 2275 QuicTime retransmission_time = 2276 connection_.GetRetransmissionAlarm()->deadline(); 2277 EXPECT_NE(QuicTime::Zero(), retransmission_time); 2278 2279 EXPECT_EQ(1u, writer_->header().packet_sequence_number); 2280 // Simulate the retransmission alarm firing and sending a tlp, 2281 // so send algorithm's OnRetransmissionTimeout is not called. 2282 clock_.AdvanceTime(retransmission_time.Subtract(clock_.Now())); 2283 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 2u, _, _)); 2284 connection_.GetRetransmissionAlarm()->Fire(); 2285 EXPECT_EQ(2u, writer_->header().packet_sequence_number); 2286 // We do not raise the high water mark yet. 2287 EXPECT_EQ(1u, stop_waiting()->least_unacked); 2288 } 2289 2290 TEST_P(QuicConnectionTest, RTO) { 2291 QuicTime default_retransmission_time = clock_.ApproximateNow().Add( 2292 DefaultRetransmissionTime()); 2293 SendStreamDataToPeer(3, "foo", 0, !kFin, NULL); 2294 EXPECT_EQ(1u, stop_waiting()->least_unacked); 2295 2296 EXPECT_EQ(1u, writer_->header().packet_sequence_number); 2297 EXPECT_EQ(default_retransmission_time, 2298 connection_.GetRetransmissionAlarm()->deadline()); 2299 // Simulate the retransmission alarm firing. 2300 clock_.AdvanceTime(DefaultRetransmissionTime()); 2301 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true)); 2302 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 2u, _, _)); 2303 connection_.GetRetransmissionAlarm()->Fire(); 2304 EXPECT_EQ(2u, writer_->header().packet_sequence_number); 2305 // We do not raise the high water mark yet. 2306 EXPECT_EQ(1u, stop_waiting()->least_unacked); 2307 } 2308 2309 TEST_P(QuicConnectionTest, RTOWithSameEncryptionLevel) { 2310 QuicTime default_retransmission_time = clock_.ApproximateNow().Add( 2311 DefaultRetransmissionTime()); 2312 use_tagging_decrypter(); 2313 2314 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at 2315 // the end of the packet. We can test this to check which encrypter was used. 2316 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01)); 2317 SendStreamDataToPeer(3, "foo", 0, !kFin, NULL); 2318 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet()); 2319 2320 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02)); 2321 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL); 2322 SendStreamDataToPeer(3, "foo", 0, !kFin, NULL); 2323 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet()); 2324 2325 EXPECT_EQ(default_retransmission_time, 2326 connection_.GetRetransmissionAlarm()->deadline()); 2327 { 2328 InSequence s; 2329 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true)); 2330 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 3, _, _)); 2331 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 4, _, _)); 2332 } 2333 2334 // Simulate the retransmission alarm firing. 2335 clock_.AdvanceTime(DefaultRetransmissionTime()); 2336 connection_.GetRetransmissionAlarm()->Fire(); 2337 2338 // Packet should have been sent with ENCRYPTION_NONE. 2339 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_previous_packet()); 2340 2341 // Packet should have been sent with ENCRYPTION_INITIAL. 2342 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet()); 2343 } 2344 2345 TEST_P(QuicConnectionTest, SendHandshakeMessages) { 2346 use_tagging_decrypter(); 2347 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at 2348 // the end of the packet. We can test this to check which encrypter was used. 2349 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01)); 2350 2351 // Attempt to send a handshake message and have the socket block. 2352 EXPECT_CALL(*send_algorithm_, 2353 TimeUntilSend(_, _, _)).WillRepeatedly( 2354 testing::Return(QuicTime::Delta::Zero())); 2355 BlockOnNextWrite(); 2356 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, NULL); 2357 // The packet should be serialized, but not queued. 2358 EXPECT_EQ(1u, connection_.NumQueuedPackets()); 2359 2360 // Switch to the new encrypter. 2361 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02)); 2362 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL); 2363 2364 // Now become writeable and flush the packets. 2365 writer_->SetWritable(); 2366 EXPECT_CALL(visitor_, OnCanWrite()); 2367 connection_.OnCanWrite(); 2368 EXPECT_EQ(0u, connection_.NumQueuedPackets()); 2369 2370 // Verify that the handshake packet went out at the null encryption. 2371 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet()); 2372 } 2373 2374 TEST_P(QuicConnectionTest, 2375 DropRetransmitsForNullEncryptedPacketAfterForwardSecure) { 2376 use_tagging_decrypter(); 2377 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01)); 2378 QuicPacketSequenceNumber sequence_number; 2379 SendStreamDataToPeer(3, "foo", 0, !kFin, &sequence_number); 2380 2381 // Simulate the retransmission alarm firing and the socket blocking. 2382 BlockOnNextWrite(); 2383 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true)); 2384 clock_.AdvanceTime(DefaultRetransmissionTime()); 2385 connection_.GetRetransmissionAlarm()->Fire(); 2386 2387 // Go forward secure. 2388 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE, 2389 new TaggingEncrypter(0x02)); 2390 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); 2391 connection_.NeuterUnencryptedPackets(); 2392 2393 EXPECT_EQ(QuicTime::Zero(), 2394 connection_.GetRetransmissionAlarm()->deadline()); 2395 // Unblock the socket and ensure that no packets are sent. 2396 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0); 2397 writer_->SetWritable(); 2398 connection_.OnCanWrite(); 2399 } 2400 2401 TEST_P(QuicConnectionTest, RetransmitPacketsWithInitialEncryption) { 2402 use_tagging_decrypter(); 2403 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01)); 2404 connection_.SetDefaultEncryptionLevel(ENCRYPTION_NONE); 2405 2406 SendStreamDataToPeer(1, "foo", 0, !kFin, NULL); 2407 2408 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02)); 2409 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL); 2410 2411 SendStreamDataToPeer(2, "bar", 0, !kFin, NULL); 2412 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); 2413 2414 connection_.RetransmitUnackedPackets(ALL_INITIAL_RETRANSMISSION); 2415 } 2416 2417 TEST_P(QuicConnectionTest, BufferNonDecryptablePackets) { 2418 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 2419 use_tagging_decrypter(); 2420 2421 const uint8 tag = 0x07; 2422 framer_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag)); 2423 2424 // Process an encrypted packet which can not yet be decrypted 2425 // which should result in the packet being buffered. 2426 ProcessDataPacketAtLevel(1, 0, kEntropyFlag, ENCRYPTION_INITIAL); 2427 2428 // Transition to the new encryption state and process another 2429 // encrypted packet which should result in the original packet being 2430 // processed. 2431 connection_.SetDecrypter(new StrictTaggingDecrypter(tag), 2432 ENCRYPTION_INITIAL); 2433 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL); 2434 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag)); 2435 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(2); 2436 ProcessDataPacketAtLevel(2, 0, kEntropyFlag, ENCRYPTION_INITIAL); 2437 2438 // Finally, process a third packet and note that we do not 2439 // reprocess the buffered packet. 2440 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1); 2441 ProcessDataPacketAtLevel(3, 0, kEntropyFlag, ENCRYPTION_INITIAL); 2442 } 2443 2444 TEST_P(QuicConnectionTest, TestRetransmitOrder) { 2445 QuicByteCount first_packet_size; 2446 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).WillOnce( 2447 DoAll(SaveArg<3>(&first_packet_size), Return(true))); 2448 2449 connection_.SendStreamDataWithString(3, "first_packet", 0, !kFin, NULL); 2450 QuicByteCount second_packet_size; 2451 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).WillOnce( 2452 DoAll(SaveArg<3>(&second_packet_size), Return(true))); 2453 connection_.SendStreamDataWithString(3, "second_packet", 12, !kFin, NULL); 2454 EXPECT_NE(first_packet_size, second_packet_size); 2455 // Advance the clock by huge time to make sure packets will be retransmitted. 2456 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10)); 2457 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true)); 2458 { 2459 InSequence s; 2460 EXPECT_CALL(*send_algorithm_, 2461 OnPacketSent(_, _, _, first_packet_size, _)); 2462 EXPECT_CALL(*send_algorithm_, 2463 OnPacketSent(_, _, _, second_packet_size, _)); 2464 } 2465 connection_.GetRetransmissionAlarm()->Fire(); 2466 2467 // Advance again and expect the packets to be sent again in the same order. 2468 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(20)); 2469 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true)); 2470 { 2471 InSequence s; 2472 EXPECT_CALL(*send_algorithm_, 2473 OnPacketSent(_, _, _, first_packet_size, _)); 2474 EXPECT_CALL(*send_algorithm_, 2475 OnPacketSent(_, _, _, second_packet_size, _)); 2476 } 2477 connection_.GetRetransmissionAlarm()->Fire(); 2478 } 2479 2480 TEST_P(QuicConnectionTest, RetransmissionCountCalculation) { 2481 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 2482 QuicPacketSequenceNumber original_sequence_number; 2483 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) 2484 .WillOnce(DoAll(SaveArg<2>(&original_sequence_number), Return(true))); 2485 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, NULL); 2486 2487 EXPECT_TRUE(QuicConnectionPeer::IsSavedForRetransmission( 2488 &connection_, original_sequence_number)); 2489 EXPECT_FALSE(QuicConnectionPeer::IsRetransmission( 2490 &connection_, original_sequence_number)); 2491 // Force retransmission due to RTO. 2492 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10)); 2493 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true)); 2494 QuicPacketSequenceNumber rto_sequence_number; 2495 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) 2496 .WillOnce(DoAll(SaveArg<2>(&rto_sequence_number), Return(true))); 2497 connection_.GetRetransmissionAlarm()->Fire(); 2498 EXPECT_FALSE(QuicConnectionPeer::IsSavedForRetransmission( 2499 &connection_, original_sequence_number)); 2500 ASSERT_TRUE(QuicConnectionPeer::IsSavedForRetransmission( 2501 &connection_, rto_sequence_number)); 2502 EXPECT_TRUE(QuicConnectionPeer::IsRetransmission( 2503 &connection_, rto_sequence_number)); 2504 // Once by explicit nack. 2505 SequenceNumberSet lost_packets; 2506 lost_packets.insert(rto_sequence_number); 2507 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _)) 2508 .WillOnce(Return(lost_packets)); 2509 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _)); 2510 QuicPacketSequenceNumber nack_sequence_number = 0; 2511 // Ack packets might generate some other packets, which are not 2512 // retransmissions. (More ack packets). 2513 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) 2514 .Times(AnyNumber()); 2515 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) 2516 .WillOnce(DoAll(SaveArg<2>(&nack_sequence_number), Return(true))); 2517 QuicAckFrame ack = InitAckFrame(rto_sequence_number); 2518 // Nack the retransmitted packet. 2519 NackPacket(original_sequence_number, &ack); 2520 NackPacket(rto_sequence_number, &ack); 2521 ProcessAckPacket(&ack); 2522 2523 ASSERT_NE(0u, nack_sequence_number); 2524 EXPECT_FALSE(QuicConnectionPeer::IsSavedForRetransmission( 2525 &connection_, rto_sequence_number)); 2526 ASSERT_TRUE(QuicConnectionPeer::IsSavedForRetransmission( 2527 &connection_, nack_sequence_number)); 2528 EXPECT_TRUE(QuicConnectionPeer::IsRetransmission( 2529 &connection_, nack_sequence_number)); 2530 } 2531 2532 TEST_P(QuicConnectionTest, SetRTOAfterWritingToSocket) { 2533 BlockOnNextWrite(); 2534 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, NULL); 2535 // Make sure that RTO is not started when the packet is queued. 2536 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet()); 2537 2538 // Test that RTO is started once we write to the socket. 2539 writer_->SetWritable(); 2540 connection_.OnCanWrite(); 2541 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet()); 2542 } 2543 2544 TEST_P(QuicConnectionTest, DelayRTOWithAckReceipt) { 2545 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 2546 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) 2547 .Times(2); 2548 connection_.SendStreamDataWithString(2, "foo", 0, !kFin, NULL); 2549 connection_.SendStreamDataWithString(3, "bar", 0, !kFin, NULL); 2550 QuicAlarm* retransmission_alarm = connection_.GetRetransmissionAlarm(); 2551 EXPECT_TRUE(retransmission_alarm->IsSet()); 2552 EXPECT_EQ(clock_.Now().Add(DefaultRetransmissionTime()), 2553 retransmission_alarm->deadline()); 2554 2555 // Advance the time right before the RTO, then receive an ack for the first 2556 // packet to delay the RTO. 2557 clock_.AdvanceTime(DefaultRetransmissionTime()); 2558 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _)); 2559 QuicAckFrame ack = InitAckFrame(1); 2560 ProcessAckPacket(&ack); 2561 EXPECT_TRUE(retransmission_alarm->IsSet()); 2562 EXPECT_GT(retransmission_alarm->deadline(), clock_.Now()); 2563 2564 // Move forward past the original RTO and ensure the RTO is still pending. 2565 clock_.AdvanceTime(DefaultRetransmissionTime().Multiply(2)); 2566 2567 // Ensure the second packet gets retransmitted when it finally fires. 2568 EXPECT_TRUE(retransmission_alarm->IsSet()); 2569 EXPECT_LT(retransmission_alarm->deadline(), clock_.ApproximateNow()); 2570 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true)); 2571 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)); 2572 // Manually cancel the alarm to simulate a real test. 2573 connection_.GetRetransmissionAlarm()->Fire(); 2574 2575 // The new retransmitted sequence number should set the RTO to a larger value 2576 // than previously. 2577 EXPECT_TRUE(retransmission_alarm->IsSet()); 2578 QuicTime next_rto_time = retransmission_alarm->deadline(); 2579 QuicTime expected_rto_time = 2580 connection_.sent_packet_manager().GetRetransmissionTime(); 2581 EXPECT_EQ(next_rto_time, expected_rto_time); 2582 } 2583 2584 TEST_P(QuicConnectionTest, TestQueued) { 2585 EXPECT_EQ(0u, connection_.NumQueuedPackets()); 2586 BlockOnNextWrite(); 2587 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, NULL); 2588 EXPECT_EQ(1u, connection_.NumQueuedPackets()); 2589 2590 // Unblock the writes and actually send. 2591 writer_->SetWritable(); 2592 connection_.OnCanWrite(); 2593 EXPECT_EQ(0u, connection_.NumQueuedPackets()); 2594 } 2595 2596 TEST_P(QuicConnectionTest, CloseFecGroup) { 2597 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 2598 // Don't send missing packet 1. 2599 // Don't send missing packet 2. 2600 ProcessFecProtectedPacket(3, false, !kEntropyFlag); 2601 // Don't send missing FEC packet 3. 2602 ASSERT_EQ(1u, connection_.NumFecGroups()); 2603 2604 // Now send non-fec protected ack packet and close the group. 2605 peer_creator_.set_sequence_number(4); 2606 QuicStopWaitingFrame frame = InitStopWaitingFrame(5); 2607 ProcessStopWaitingPacket(&frame); 2608 ASSERT_EQ(0u, connection_.NumFecGroups()); 2609 } 2610 2611 TEST_P(QuicConnectionTest, NoQuicCongestionFeedbackFrame) { 2612 SendAckPacketToPeer(); 2613 EXPECT_TRUE(writer_->feedback_frames().empty()); 2614 } 2615 2616 TEST_P(QuicConnectionTest, WithQuicCongestionFeedbackFrame) { 2617 QuicCongestionFeedbackFrame info; 2618 info.type = kTCP; 2619 info.tcp.receive_window = 0x4030; 2620 2621 // After QUIC_VERSION_22, do not send TCP Congestion Feedback Frames anymore. 2622 if (version() > QUIC_VERSION_22) { 2623 SendAckPacketToPeer(); 2624 ASSERT_TRUE(writer_->feedback_frames().empty()); 2625 } else { 2626 // Only SetFeedback in this case because SetFeedback will create a receive 2627 // algorithm which is how the received_packet_manager checks if it should be 2628 // creating TCP Congestion Feedback Frames. 2629 SetFeedback(&info); 2630 SendAckPacketToPeer(); 2631 ASSERT_FALSE(writer_->feedback_frames().empty()); 2632 ASSERT_EQ(kTCP, writer_->feedback_frames()[0].type); 2633 } 2634 } 2635 2636 TEST_P(QuicConnectionTest, UpdateQuicCongestionFeedbackFrame) { 2637 SendAckPacketToPeer(); 2638 EXPECT_CALL(*receive_algorithm_, RecordIncomingPacket(_, _, _)); 2639 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 2640 ProcessPacket(1); 2641 } 2642 2643 TEST_P(QuicConnectionTest, DontUpdateQuicCongestionFeedbackFrameForRevived) { 2644 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 2645 SendAckPacketToPeer(); 2646 // Process an FEC packet, and revive the missing data packet 2647 // but only contact the receive_algorithm once. 2648 EXPECT_CALL(*receive_algorithm_, RecordIncomingPacket(_, _, _)); 2649 ProcessFecPacket(2, 1, true, !kEntropyFlag, NULL); 2650 } 2651 2652 TEST_P(QuicConnectionTest, InitialTimeout) { 2653 EXPECT_TRUE(connection_.connected()); 2654 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_CONNECTION_TIMED_OUT, false)); 2655 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber()); 2656 2657 QuicTime default_timeout = clock_.ApproximateNow().Add( 2658 QuicTime::Delta::FromSeconds(kDefaultInitialTimeoutSecs)); 2659 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline()); 2660 2661 if (FLAGS_quic_timeouts_require_activity) { 2662 // Simulate the timeout alarm firing. 2663 clock_.AdvanceTime( 2664 QuicTime::Delta::FromSeconds(kDefaultInitialTimeoutSecs)); 2665 connection_.GetTimeoutAlarm()->Fire(); 2666 // We should not actually timeout until a packet is sent. 2667 EXPECT_TRUE(connection_.connected()); 2668 SendStreamDataToPeer(1, "GET /", 0, kFin, NULL); 2669 } 2670 2671 // Simulate the timeout alarm firing. 2672 clock_.AdvanceTime( 2673 QuicTime::Delta::FromSeconds(kDefaultInitialTimeoutSecs)); 2674 connection_.GetTimeoutAlarm()->Fire(); 2675 2676 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet()); 2677 EXPECT_FALSE(connection_.connected()); 2678 2679 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet()); 2680 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet()); 2681 EXPECT_FALSE(connection_.GetResumeWritesAlarm()->IsSet()); 2682 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet()); 2683 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet()); 2684 } 2685 2686 TEST_P(QuicConnectionTest, OverallTimeout) { 2687 connection_.SetOverallConnectionTimeout( 2688 QuicTime::Delta::FromSeconds(kDefaultMaxTimeForCryptoHandshakeSecs)); 2689 EXPECT_TRUE(connection_.connected()); 2690 EXPECT_CALL(visitor_, 2691 OnConnectionClosed(QUIC_CONNECTION_OVERALL_TIMED_OUT, false)); 2692 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber()); 2693 2694 QuicTime overall_timeout = clock_.ApproximateNow().Add( 2695 QuicTime::Delta::FromSeconds(kDefaultMaxTimeForCryptoHandshakeSecs)); 2696 EXPECT_EQ(overall_timeout, connection_.GetTimeoutAlarm()->deadline()); 2697 2698 EXPECT_TRUE(connection_.connected()); 2699 SendStreamDataToPeer(1, "GET /", 0, kFin, NULL); 2700 2701 clock_.AdvanceTime( 2702 QuicTime::Delta::FromSeconds(2 * kDefaultInitialTimeoutSecs)); 2703 2704 // Process an ack and see that the connection still times out. 2705 QuicAckFrame frame = InitAckFrame(1); 2706 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 2707 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _)); 2708 ProcessAckPacket(&frame); 2709 2710 // Simulate the timeout alarm firing. 2711 connection_.GetTimeoutAlarm()->Fire(); 2712 2713 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet()); 2714 EXPECT_FALSE(connection_.connected()); 2715 2716 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet()); 2717 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet()); 2718 EXPECT_FALSE(connection_.GetResumeWritesAlarm()->IsSet()); 2719 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet()); 2720 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet()); 2721 } 2722 2723 TEST_P(QuicConnectionTest, PingAfterSend) { 2724 EXPECT_TRUE(connection_.connected()); 2725 EXPECT_CALL(visitor_, HasOpenDataStreams()).WillRepeatedly(Return(true)); 2726 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet()); 2727 2728 // Advance to 5ms, and send a packet to the peer, which will set 2729 // the ping alarm. 2730 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); 2731 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet()); 2732 SendStreamDataToPeer(1, "GET /", 0, kFin, NULL); 2733 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet()); 2734 EXPECT_EQ(clock_.ApproximateNow().Add(QuicTime::Delta::FromSeconds(15)), 2735 connection_.GetPingAlarm()->deadline()); 2736 2737 // Now recevie and ACK of the previous packet, which will move the 2738 // ping alarm forward. 2739 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); 2740 QuicAckFrame frame = InitAckFrame(1); 2741 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 2742 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _)); 2743 ProcessAckPacket(&frame); 2744 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet()); 2745 // The ping timer is set slightly less than 15 seconds in the future, because 2746 // of the 1s ping timer alarm granularity. 2747 EXPECT_EQ(clock_.ApproximateNow().Add(QuicTime::Delta::FromSeconds(15)) 2748 .Subtract(QuicTime::Delta::FromMilliseconds(5)), 2749 connection_.GetPingAlarm()->deadline()); 2750 2751 writer_->Reset(); 2752 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15)); 2753 connection_.GetPingAlarm()->Fire(); 2754 EXPECT_EQ(1u, writer_->frame_count()); 2755 if (version() >= QUIC_VERSION_18) { 2756 ASSERT_EQ(1u, writer_->ping_frames().size()); 2757 } else { 2758 ASSERT_EQ(1u, writer_->stream_frames().size()); 2759 EXPECT_EQ(kCryptoStreamId, writer_->stream_frames()[0].stream_id); 2760 EXPECT_EQ(0u, writer_->stream_frames()[0].offset); 2761 } 2762 writer_->Reset(); 2763 2764 EXPECT_CALL(visitor_, HasOpenDataStreams()).WillRepeatedly(Return(false)); 2765 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); 2766 SendAckPacketToPeer(); 2767 2768 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet()); 2769 } 2770 2771 TEST_P(QuicConnectionTest, TimeoutAfterSend) { 2772 EXPECT_TRUE(connection_.connected()); 2773 2774 QuicTime default_timeout = clock_.ApproximateNow().Add( 2775 QuicTime::Delta::FromSeconds(kDefaultInitialTimeoutSecs)); 2776 2777 // When we send a packet, the timeout will change to 5000 + 2778 // kDefaultInitialTimeoutSecs. 2779 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); 2780 2781 // Send an ack so we don't set the retransmission alarm. 2782 SendAckPacketToPeer(); 2783 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline()); 2784 2785 // The original alarm will fire. We should not time out because we had a 2786 // network event at t=5000. The alarm will reregister. 2787 clock_.AdvanceTime(QuicTime::Delta::FromMicroseconds( 2788 kDefaultInitialTimeoutSecs * 1000000 - 5000)); 2789 EXPECT_EQ(default_timeout, clock_.ApproximateNow()); 2790 connection_.GetTimeoutAlarm()->Fire(); 2791 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet()); 2792 EXPECT_TRUE(connection_.connected()); 2793 EXPECT_EQ(default_timeout.Add(QuicTime::Delta::FromMilliseconds(5)), 2794 connection_.GetTimeoutAlarm()->deadline()); 2795 2796 // This time, we should time out. 2797 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_CONNECTION_TIMED_OUT, false)); 2798 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)); 2799 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); 2800 EXPECT_EQ(default_timeout.Add(QuicTime::Delta::FromMilliseconds(5)), 2801 clock_.ApproximateNow()); 2802 connection_.GetTimeoutAlarm()->Fire(); 2803 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet()); 2804 EXPECT_FALSE(connection_.connected()); 2805 } 2806 2807 TEST_P(QuicConnectionTest, SendScheduler) { 2808 // Test that if we send a packet without delay, it is not queued. 2809 QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag); 2810 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)); 2811 connection_.SendPacket( 2812 ENCRYPTION_NONE, 1, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA); 2813 EXPECT_EQ(0u, connection_.NumQueuedPackets()); 2814 } 2815 2816 TEST_P(QuicConnectionTest, SendSchedulerEAGAIN) { 2817 QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag); 2818 BlockOnNextWrite(); 2819 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 1, _, _)).Times(0); 2820 connection_.SendPacket( 2821 ENCRYPTION_NONE, 1, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA); 2822 EXPECT_EQ(1u, connection_.NumQueuedPackets()); 2823 } 2824 2825 TEST_P(QuicConnectionTest, TestQueueLimitsOnSendStreamData) { 2826 // All packets carry version info till version is negotiated. 2827 size_t payload_length; 2828 size_t length = GetPacketLengthForOneStream( 2829 connection_.version(), kIncludeVersion, PACKET_1BYTE_SEQUENCE_NUMBER, 2830 NOT_IN_FEC_GROUP, &payload_length); 2831 QuicConnectionPeer::GetPacketCreator(&connection_)->set_max_packet_length( 2832 length); 2833 2834 // Queue the first packet. 2835 EXPECT_CALL(*send_algorithm_, 2836 TimeUntilSend(_, _, _)).WillOnce( 2837 testing::Return(QuicTime::Delta::FromMicroseconds(10))); 2838 const string payload(payload_length, 'a'); 2839 EXPECT_EQ(0u, 2840 connection_.SendStreamDataWithString(3, payload, 0, 2841 !kFin, NULL).bytes_consumed); 2842 EXPECT_EQ(0u, connection_.NumQueuedPackets()); 2843 } 2844 2845 TEST_P(QuicConnectionTest, LoopThroughSendingPackets) { 2846 // All packets carry version info till version is negotiated. 2847 size_t payload_length; 2848 // GetPacketLengthForOneStream() assumes a stream offset of 0 in determining 2849 // packet length. The size of the offset field in a stream frame is 0 for 2850 // offset 0, and 2 for non-zero offsets up through 16K. Increase 2851 // max_packet_length by 2 so that subsequent packets containing subsequent 2852 // stream frames with non-zero offets will fit within the packet length. 2853 size_t length = 2 + GetPacketLengthForOneStream( 2854 connection_.version(), kIncludeVersion, PACKET_1BYTE_SEQUENCE_NUMBER, 2855 NOT_IN_FEC_GROUP, &payload_length); 2856 QuicConnectionPeer::GetPacketCreator(&connection_)->set_max_packet_length( 2857 length); 2858 2859 // Queue the first packet. 2860 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(7); 2861 // The first stream frame will have 2 fewer overhead bytes than the other six. 2862 const string payload(payload_length * 7 + 2, 'a'); 2863 EXPECT_EQ(payload.size(), 2864 connection_.SendStreamDataWithString(1, payload, 0, 2865 !kFin, NULL).bytes_consumed); 2866 } 2867 2868 TEST_P(QuicConnectionTest, SendDelayedAck) { 2869 QuicTime ack_time = clock_.ApproximateNow().Add(DefaultDelayedAckTime()); 2870 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 2871 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet()); 2872 const uint8 tag = 0x07; 2873 connection_.SetDecrypter(new StrictTaggingDecrypter(tag), 2874 ENCRYPTION_INITIAL); 2875 framer_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag)); 2876 // Process a packet from the non-crypto stream. 2877 frame1_.stream_id = 3; 2878 2879 // The same as ProcessPacket(1) except that ENCRYPTION_INITIAL is used 2880 // instead of ENCRYPTION_NONE. 2881 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1); 2882 ProcessDataPacketAtLevel(1, 0, !kEntropyFlag, ENCRYPTION_INITIAL); 2883 2884 // Check if delayed ack timer is running for the expected interval. 2885 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet()); 2886 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline()); 2887 // Simulate delayed ack alarm firing. 2888 connection_.GetAckAlarm()->Fire(); 2889 // Check that ack is sent and that delayed ack alarm is reset. 2890 EXPECT_EQ(2u, writer_->frame_count()); 2891 EXPECT_FALSE(writer_->stop_waiting_frames().empty()); 2892 EXPECT_FALSE(writer_->ack_frames().empty()); 2893 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet()); 2894 } 2895 2896 TEST_P(QuicConnectionTest, SendEarlyDelayedAckForCrypto) { 2897 QuicTime ack_time = clock_.ApproximateNow(); 2898 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 2899 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet()); 2900 // Process a packet from the crypto stream, which is frame1_'s default. 2901 ProcessPacket(1); 2902 // Check if delayed ack timer is running for the expected interval. 2903 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet()); 2904 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline()); 2905 // Simulate delayed ack alarm firing. 2906 connection_.GetAckAlarm()->Fire(); 2907 // Check that ack is sent and that delayed ack alarm is reset. 2908 EXPECT_EQ(2u, writer_->frame_count()); 2909 EXPECT_FALSE(writer_->stop_waiting_frames().empty()); 2910 EXPECT_FALSE(writer_->ack_frames().empty()); 2911 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet()); 2912 } 2913 2914 TEST_P(QuicConnectionTest, SendDelayedAckOnSecondPacket) { 2915 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 2916 ProcessPacket(1); 2917 ProcessPacket(2); 2918 // Check that ack is sent and that delayed ack alarm is reset. 2919 EXPECT_EQ(2u, writer_->frame_count()); 2920 EXPECT_FALSE(writer_->stop_waiting_frames().empty()); 2921 EXPECT_FALSE(writer_->ack_frames().empty()); 2922 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet()); 2923 } 2924 2925 TEST_P(QuicConnectionTest, SendDelayedAckForPing) { 2926 if (version() < QUIC_VERSION_18) { 2927 return; 2928 } 2929 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 2930 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet()); 2931 ProcessPingPacket(1); 2932 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet()); 2933 } 2934 2935 TEST_P(QuicConnectionTest, NoAckOnOldNacks) { 2936 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 2937 // Drop one packet, triggering a sequence of acks. 2938 ProcessPacket(2); 2939 size_t frames_per_ack = 2; 2940 EXPECT_EQ(frames_per_ack, writer_->frame_count()); 2941 EXPECT_FALSE(writer_->ack_frames().empty()); 2942 writer_->Reset(); 2943 ProcessPacket(3); 2944 EXPECT_EQ(frames_per_ack, writer_->frame_count()); 2945 EXPECT_FALSE(writer_->ack_frames().empty()); 2946 writer_->Reset(); 2947 ProcessPacket(4); 2948 EXPECT_EQ(frames_per_ack, writer_->frame_count()); 2949 EXPECT_FALSE(writer_->ack_frames().empty()); 2950 writer_->Reset(); 2951 ProcessPacket(5); 2952 EXPECT_EQ(frames_per_ack, writer_->frame_count()); 2953 EXPECT_FALSE(writer_->ack_frames().empty()); 2954 writer_->Reset(); 2955 // Now only set the timer on the 6th packet, instead of sending another ack. 2956 ProcessPacket(6); 2957 EXPECT_EQ(0u, writer_->frame_count()); 2958 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet()); 2959 } 2960 2961 TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingPacket) { 2962 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 2963 ProcessPacket(1); 2964 connection_.SendStreamDataWithString(kClientDataStreamId1, "foo", 0, 2965 !kFin, NULL); 2966 // Check that ack is bundled with outgoing data and that delayed ack 2967 // alarm is reset. 2968 EXPECT_EQ(3u, writer_->frame_count()); 2969 EXPECT_FALSE(writer_->stop_waiting_frames().empty()); 2970 EXPECT_FALSE(writer_->ack_frames().empty()); 2971 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet()); 2972 } 2973 2974 TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingCryptoPacket) { 2975 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 2976 ProcessPacket(1); 2977 connection_.SendStreamDataWithString(kCryptoStreamId, "foo", 0, !kFin, NULL); 2978 // Check that ack is bundled with outgoing crypto data. 2979 EXPECT_EQ(3u, writer_->frame_count()); 2980 EXPECT_FALSE(writer_->ack_frames().empty()); 2981 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet()); 2982 } 2983 2984 TEST_P(QuicConnectionTest, BlockAndBufferOnFirstCHLOPacketOfTwo) { 2985 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 2986 ProcessPacket(1); 2987 BlockOnNextWrite(); 2988 writer_->set_is_write_blocked_data_buffered(true); 2989 connection_.SendStreamDataWithString(kCryptoStreamId, "foo", 0, !kFin, NULL); 2990 EXPECT_TRUE(writer_->IsWriteBlocked()); 2991 EXPECT_FALSE(connection_.HasQueuedData()); 2992 connection_.SendStreamDataWithString(kCryptoStreamId, "bar", 3, !kFin, NULL); 2993 EXPECT_TRUE(writer_->IsWriteBlocked()); 2994 EXPECT_TRUE(connection_.HasQueuedData()); 2995 } 2996 2997 TEST_P(QuicConnectionTest, BundleAckForSecondCHLO) { 2998 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 2999 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet()); 3000 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce( 3001 IgnoreResult(InvokeWithoutArgs(&connection_, 3002 &TestConnection::SendCryptoStreamData))); 3003 // Process a packet from the crypto stream, which is frame1_'s default. 3004 // Receiving the CHLO as packet 2 first will cause the connection to 3005 // immediately send an ack, due to the packet gap. 3006 ProcessPacket(2); 3007 // Check that ack is sent and that delayed ack alarm is reset. 3008 EXPECT_EQ(3u, writer_->frame_count()); 3009 EXPECT_FALSE(writer_->stop_waiting_frames().empty()); 3010 EXPECT_EQ(1u, writer_->stream_frames().size()); 3011 EXPECT_FALSE(writer_->ack_frames().empty()); 3012 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet()); 3013 } 3014 3015 TEST_P(QuicConnectionTest, BundleAckWithDataOnIncomingAck) { 3016 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 3017 connection_.SendStreamDataWithString(kClientDataStreamId1, "foo", 0, 3018 !kFin, NULL); 3019 connection_.SendStreamDataWithString(kClientDataStreamId1, "foo", 3, 3020 !kFin, NULL); 3021 // Ack the second packet, which will retransmit the first packet. 3022 QuicAckFrame ack = InitAckFrame(2); 3023 NackPacket(1, &ack); 3024 SequenceNumberSet lost_packets; 3025 lost_packets.insert(1); 3026 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _)) 3027 .WillOnce(Return(lost_packets)); 3028 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _)); 3029 ProcessAckPacket(&ack); 3030 EXPECT_EQ(1u, writer_->frame_count()); 3031 EXPECT_EQ(1u, writer_->stream_frames().size()); 3032 writer_->Reset(); 3033 3034 // Now ack the retransmission, which will both raise the high water mark 3035 // and see if there is more data to send. 3036 ack = InitAckFrame(3); 3037 NackPacket(1, &ack); 3038 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _)) 3039 .WillOnce(Return(SequenceNumberSet())); 3040 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _)); 3041 ProcessAckPacket(&ack); 3042 3043 // Check that no packet is sent and the ack alarm isn't set. 3044 EXPECT_EQ(0u, writer_->frame_count()); 3045 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet()); 3046 writer_->Reset(); 3047 3048 // Send the same ack, but send both data and an ack together. 3049 ack = InitAckFrame(3); 3050 NackPacket(1, &ack); 3051 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _)) 3052 .WillOnce(Return(SequenceNumberSet())); 3053 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce( 3054 IgnoreResult(InvokeWithoutArgs( 3055 &connection_, 3056 &TestConnection::EnsureWritableAndSendStreamData5))); 3057 ProcessAckPacket(&ack); 3058 3059 // Check that ack is bundled with outgoing data and the delayed ack 3060 // alarm is reset. 3061 EXPECT_EQ(3u, writer_->frame_count()); 3062 EXPECT_FALSE(writer_->stop_waiting_frames().empty()); 3063 EXPECT_FALSE(writer_->ack_frames().empty()); 3064 EXPECT_EQ(1u, writer_->stream_frames().size()); 3065 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet()); 3066 } 3067 3068 TEST_P(QuicConnectionTest, NoAckSentForClose) { 3069 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 3070 ProcessPacket(1); 3071 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, true)); 3072 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0); 3073 ProcessClosePacket(2, 0); 3074 } 3075 3076 TEST_P(QuicConnectionTest, SendWhenDisconnected) { 3077 EXPECT_TRUE(connection_.connected()); 3078 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, false)); 3079 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, false); 3080 EXPECT_FALSE(connection_.connected()); 3081 EXPECT_FALSE(connection_.CanWriteStreamData()); 3082 QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag); 3083 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 1, _, _)).Times(0); 3084 connection_.SendPacket( 3085 ENCRYPTION_NONE, 1, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA); 3086 } 3087 3088 TEST_P(QuicConnectionTest, PublicReset) { 3089 QuicPublicResetPacket header; 3090 header.public_header.connection_id = connection_id_; 3091 header.public_header.reset_flag = true; 3092 header.public_header.version_flag = false; 3093 header.rejected_sequence_number = 10101; 3094 scoped_ptr<QuicEncryptedPacket> packet( 3095 framer_.BuildPublicResetPacket(header)); 3096 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PUBLIC_RESET, true)); 3097 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *packet); 3098 } 3099 3100 TEST_P(QuicConnectionTest, GoAway) { 3101 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 3102 3103 QuicGoAwayFrame goaway; 3104 goaway.last_good_stream_id = 1; 3105 goaway.error_code = QUIC_PEER_GOING_AWAY; 3106 goaway.reason_phrase = "Going away."; 3107 EXPECT_CALL(visitor_, OnGoAway(_)); 3108 ProcessGoAwayPacket(&goaway); 3109 } 3110 3111 TEST_P(QuicConnectionTest, WindowUpdate) { 3112 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 3113 3114 QuicWindowUpdateFrame window_update; 3115 window_update.stream_id = 3; 3116 window_update.byte_offset = 1234; 3117 EXPECT_CALL(visitor_, OnWindowUpdateFrames(_)); 3118 ProcessFramePacket(QuicFrame(&window_update)); 3119 } 3120 3121 TEST_P(QuicConnectionTest, Blocked) { 3122 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 3123 3124 QuicBlockedFrame blocked; 3125 blocked.stream_id = 3; 3126 EXPECT_CALL(visitor_, OnBlockedFrames(_)); 3127 ProcessFramePacket(QuicFrame(&blocked)); 3128 } 3129 3130 TEST_P(QuicConnectionTest, InvalidPacket) { 3131 EXPECT_CALL(visitor_, 3132 OnConnectionClosed(QUIC_INVALID_PACKET_HEADER, false)); 3133 QuicEncryptedPacket encrypted(NULL, 0); 3134 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), encrypted); 3135 // The connection close packet should have error details. 3136 ASSERT_FALSE(writer_->connection_close_frames().empty()); 3137 EXPECT_EQ("Unable to read public flags.", 3138 writer_->connection_close_frames()[0].error_details); 3139 } 3140 3141 TEST_P(QuicConnectionTest, MissingPacketsBeforeLeastUnacked) { 3142 // Set the sequence number of the ack packet to be least unacked (4). 3143 peer_creator_.set_sequence_number(3); 3144 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 3145 QuicStopWaitingFrame frame = InitStopWaitingFrame(4); 3146 ProcessStopWaitingPacket(&frame); 3147 EXPECT_TRUE(outgoing_ack()->missing_packets.empty()); 3148 } 3149 3150 TEST_P(QuicConnectionTest, ReceivedEntropyHashCalculation) { 3151 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(AtLeast(1)); 3152 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 3153 ProcessDataPacket(1, 1, kEntropyFlag); 3154 ProcessDataPacket(4, 1, kEntropyFlag); 3155 ProcessDataPacket(3, 1, !kEntropyFlag); 3156 ProcessDataPacket(7, 1, kEntropyFlag); 3157 EXPECT_EQ(146u, outgoing_ack()->entropy_hash); 3158 } 3159 3160 TEST_P(QuicConnectionTest, ReceivedEntropyHashCalculationHalfFEC) { 3161 // FEC packets should not change the entropy hash calculation. 3162 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(AtLeast(1)); 3163 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 3164 ProcessDataPacket(1, 1, kEntropyFlag); 3165 ProcessFecPacket(4, 1, false, kEntropyFlag, NULL); 3166 ProcessDataPacket(3, 3, !kEntropyFlag); 3167 ProcessFecPacket(7, 3, false, kEntropyFlag, NULL); 3168 EXPECT_EQ(146u, outgoing_ack()->entropy_hash); 3169 } 3170 3171 TEST_P(QuicConnectionTest, UpdateEntropyForReceivedPackets) { 3172 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(AtLeast(1)); 3173 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 3174 ProcessDataPacket(1, 1, kEntropyFlag); 3175 ProcessDataPacket(5, 1, kEntropyFlag); 3176 ProcessDataPacket(4, 1, !kEntropyFlag); 3177 EXPECT_EQ(34u, outgoing_ack()->entropy_hash); 3178 // Make 4th packet my least unacked, and update entropy for 2, 3 packets. 3179 peer_creator_.set_sequence_number(5); 3180 QuicPacketEntropyHash six_packet_entropy_hash = 0; 3181 QuicPacketEntropyHash kRandomEntropyHash = 129u; 3182 QuicStopWaitingFrame frame = InitStopWaitingFrame(4); 3183 frame.entropy_hash = kRandomEntropyHash; 3184 if (ProcessStopWaitingPacket(&frame)) { 3185 six_packet_entropy_hash = 1 << 6; 3186 } 3187 3188 EXPECT_EQ((kRandomEntropyHash + (1 << 5) + six_packet_entropy_hash), 3189 outgoing_ack()->entropy_hash); 3190 } 3191 3192 TEST_P(QuicConnectionTest, UpdateEntropyHashUptoCurrentPacket) { 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(22, 1, kEntropyFlag); 3198 EXPECT_EQ(66u, outgoing_ack()->entropy_hash); 3199 peer_creator_.set_sequence_number(22); 3200 QuicPacketEntropyHash kRandomEntropyHash = 85u; 3201 // Current packet is the least unacked packet. 3202 QuicPacketEntropyHash ack_entropy_hash; 3203 QuicStopWaitingFrame frame = InitStopWaitingFrame(23); 3204 frame.entropy_hash = kRandomEntropyHash; 3205 ack_entropy_hash = ProcessStopWaitingPacket(&frame); 3206 EXPECT_EQ((kRandomEntropyHash + ack_entropy_hash), 3207 outgoing_ack()->entropy_hash); 3208 ProcessDataPacket(25, 1, kEntropyFlag); 3209 EXPECT_EQ((kRandomEntropyHash + ack_entropy_hash + (1 << (25 % 8))), 3210 outgoing_ack()->entropy_hash); 3211 } 3212 3213 TEST_P(QuicConnectionTest, EntropyCalculationForTruncatedAck) { 3214 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(AtLeast(1)); 3215 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 3216 QuicPacketEntropyHash entropy[51]; 3217 entropy[0] = 0; 3218 for (int i = 1; i < 51; ++i) { 3219 bool should_send = i % 10 != 1; 3220 bool entropy_flag = (i & (i - 1)) != 0; 3221 if (!should_send) { 3222 entropy[i] = entropy[i - 1]; 3223 continue; 3224 } 3225 if (entropy_flag) { 3226 entropy[i] = entropy[i - 1] ^ (1 << (i % 8)); 3227 } else { 3228 entropy[i] = entropy[i - 1]; 3229 } 3230 ProcessDataPacket(i, 1, entropy_flag); 3231 } 3232 for (int i = 1; i < 50; ++i) { 3233 EXPECT_EQ(entropy[i], QuicConnectionPeer::ReceivedEntropyHash( 3234 &connection_, i)); 3235 } 3236 } 3237 3238 TEST_P(QuicConnectionTest, ServerSendsVersionNegotiationPacket) { 3239 connection_.SetSupportedVersions(QuicSupportedVersions()); 3240 framer_.set_version_for_tests(QUIC_VERSION_UNSUPPORTED); 3241 3242 QuicPacketHeader header; 3243 header.public_header.connection_id = connection_id_; 3244 header.public_header.reset_flag = false; 3245 header.public_header.version_flag = true; 3246 header.entropy_flag = false; 3247 header.fec_flag = false; 3248 header.packet_sequence_number = 12; 3249 header.fec_group = 0; 3250 3251 QuicFrames frames; 3252 QuicFrame frame(&frame1_); 3253 frames.push_back(frame); 3254 scoped_ptr<QuicPacket> packet( 3255 BuildUnsizedDataPacket(&framer_, header, frames).packet); 3256 scoped_ptr<QuicEncryptedPacket> encrypted( 3257 framer_.EncryptPacket(ENCRYPTION_NONE, 12, *packet)); 3258 3259 framer_.set_version(version()); 3260 connection_.set_is_server(true); 3261 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted); 3262 EXPECT_TRUE(writer_->version_negotiation_packet() != NULL); 3263 3264 size_t num_versions = arraysize(kSupportedQuicVersions); 3265 ASSERT_EQ(num_versions, 3266 writer_->version_negotiation_packet()->versions.size()); 3267 3268 // We expect all versions in kSupportedQuicVersions to be 3269 // included in the packet. 3270 for (size_t i = 0; i < num_versions; ++i) { 3271 EXPECT_EQ(kSupportedQuicVersions[i], 3272 writer_->version_negotiation_packet()->versions[i]); 3273 } 3274 } 3275 3276 TEST_P(QuicConnectionTest, ServerSendsVersionNegotiationPacketSocketBlocked) { 3277 connection_.SetSupportedVersions(QuicSupportedVersions()); 3278 framer_.set_version_for_tests(QUIC_VERSION_UNSUPPORTED); 3279 3280 QuicPacketHeader header; 3281 header.public_header.connection_id = connection_id_; 3282 header.public_header.reset_flag = false; 3283 header.public_header.version_flag = true; 3284 header.entropy_flag = false; 3285 header.fec_flag = false; 3286 header.packet_sequence_number = 12; 3287 header.fec_group = 0; 3288 3289 QuicFrames frames; 3290 QuicFrame frame(&frame1_); 3291 frames.push_back(frame); 3292 scoped_ptr<QuicPacket> packet( 3293 BuildUnsizedDataPacket(&framer_, header, frames).packet); 3294 scoped_ptr<QuicEncryptedPacket> encrypted( 3295 framer_.EncryptPacket(ENCRYPTION_NONE, 12, *packet)); 3296 3297 framer_.set_version(version()); 3298 connection_.set_is_server(true); 3299 BlockOnNextWrite(); 3300 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted); 3301 EXPECT_EQ(0u, writer_->last_packet_size()); 3302 EXPECT_TRUE(connection_.HasQueuedData()); 3303 3304 writer_->SetWritable(); 3305 connection_.OnCanWrite(); 3306 EXPECT_TRUE(writer_->version_negotiation_packet() != NULL); 3307 3308 size_t num_versions = arraysize(kSupportedQuicVersions); 3309 ASSERT_EQ(num_versions, 3310 writer_->version_negotiation_packet()->versions.size()); 3311 3312 // We expect all versions in kSupportedQuicVersions to be 3313 // included in the packet. 3314 for (size_t i = 0; i < num_versions; ++i) { 3315 EXPECT_EQ(kSupportedQuicVersions[i], 3316 writer_->version_negotiation_packet()->versions[i]); 3317 } 3318 } 3319 3320 TEST_P(QuicConnectionTest, 3321 ServerSendsVersionNegotiationPacketSocketBlockedDataBuffered) { 3322 connection_.SetSupportedVersions(QuicSupportedVersions()); 3323 framer_.set_version_for_tests(QUIC_VERSION_UNSUPPORTED); 3324 3325 QuicPacketHeader header; 3326 header.public_header.connection_id = connection_id_; 3327 header.public_header.reset_flag = false; 3328 header.public_header.version_flag = true; 3329 header.entropy_flag = false; 3330 header.fec_flag = false; 3331 header.packet_sequence_number = 12; 3332 header.fec_group = 0; 3333 3334 QuicFrames frames; 3335 QuicFrame frame(&frame1_); 3336 frames.push_back(frame); 3337 scoped_ptr<QuicPacket> packet( 3338 BuildUnsizedDataPacket(&framer_, header, frames).packet); 3339 scoped_ptr<QuicEncryptedPacket> encrypted( 3340 framer_.EncryptPacket(ENCRYPTION_NONE, 12, *packet)); 3341 3342 framer_.set_version(version()); 3343 connection_.set_is_server(true); 3344 BlockOnNextWrite(); 3345 writer_->set_is_write_blocked_data_buffered(true); 3346 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted); 3347 EXPECT_EQ(0u, writer_->last_packet_size()); 3348 EXPECT_FALSE(connection_.HasQueuedData()); 3349 } 3350 3351 TEST_P(QuicConnectionTest, ClientHandlesVersionNegotiation) { 3352 // Start out with some unsupported version. 3353 QuicConnectionPeer::GetFramer(&connection_)->set_version_for_tests( 3354 QUIC_VERSION_UNSUPPORTED); 3355 3356 QuicPacketHeader header; 3357 header.public_header.connection_id = connection_id_; 3358 header.public_header.reset_flag = false; 3359 header.public_header.version_flag = true; 3360 header.entropy_flag = false; 3361 header.fec_flag = false; 3362 header.packet_sequence_number = 12; 3363 header.fec_group = 0; 3364 3365 QuicVersionVector supported_versions; 3366 for (size_t i = 0; i < arraysize(kSupportedQuicVersions); ++i) { 3367 supported_versions.push_back(kSupportedQuicVersions[i]); 3368 } 3369 3370 // Send a version negotiation packet. 3371 scoped_ptr<QuicEncryptedPacket> encrypted( 3372 framer_.BuildVersionNegotiationPacket( 3373 header.public_header, supported_versions)); 3374 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted); 3375 3376 // Now force another packet. The connection should transition into 3377 // NEGOTIATED_VERSION state and tell the packet creator to StopSendingVersion. 3378 header.public_header.version_flag = false; 3379 QuicFrames frames; 3380 QuicFrame frame(&frame1_); 3381 frames.push_back(frame); 3382 scoped_ptr<QuicPacket> packet( 3383 BuildUnsizedDataPacket(&framer_, header, frames).packet); 3384 encrypted.reset(framer_.EncryptPacket(ENCRYPTION_NONE, 12, *packet)); 3385 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1); 3386 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 3387 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted); 3388 3389 ASSERT_FALSE(QuicPacketCreatorPeer::SendVersionInPacket( 3390 QuicConnectionPeer::GetPacketCreator(&connection_))); 3391 } 3392 3393 TEST_P(QuicConnectionTest, BadVersionNegotiation) { 3394 QuicPacketHeader header; 3395 header.public_header.connection_id = connection_id_; 3396 header.public_header.reset_flag = false; 3397 header.public_header.version_flag = true; 3398 header.entropy_flag = false; 3399 header.fec_flag = false; 3400 header.packet_sequence_number = 12; 3401 header.fec_group = 0; 3402 3403 QuicVersionVector supported_versions; 3404 for (size_t i = 0; i < arraysize(kSupportedQuicVersions); ++i) { 3405 supported_versions.push_back(kSupportedQuicVersions[i]); 3406 } 3407 3408 // Send a version negotiation packet with the version the client started with. 3409 // It should be rejected. 3410 EXPECT_CALL(visitor_, 3411 OnConnectionClosed(QUIC_INVALID_VERSION_NEGOTIATION_PACKET, 3412 false)); 3413 scoped_ptr<QuicEncryptedPacket> encrypted( 3414 framer_.BuildVersionNegotiationPacket( 3415 header.public_header, supported_versions)); 3416 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted); 3417 } 3418 3419 TEST_P(QuicConnectionTest, CheckSendStats) { 3420 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)); 3421 connection_.SendStreamDataWithString(3, "first", 0, !kFin, NULL); 3422 size_t first_packet_size = writer_->last_packet_size(); 3423 3424 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)); 3425 connection_.SendStreamDataWithString(5, "second", 0, !kFin, NULL); 3426 size_t second_packet_size = writer_->last_packet_size(); 3427 3428 // 2 retransmissions due to rto, 1 due to explicit nack. 3429 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true)); 3430 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3); 3431 3432 // Retransmit due to RTO. 3433 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10)); 3434 connection_.GetRetransmissionAlarm()->Fire(); 3435 3436 // Retransmit due to explicit nacks. 3437 QuicAckFrame nack_three = InitAckFrame(4); 3438 NackPacket(3, &nack_three); 3439 NackPacket(1, &nack_three); 3440 SequenceNumberSet lost_packets; 3441 lost_packets.insert(1); 3442 lost_packets.insert(3); 3443 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _)) 3444 .WillOnce(Return(lost_packets)); 3445 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _)); 3446 EXPECT_CALL(visitor_, OnCanWrite()).Times(2); 3447 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 3448 EXPECT_CALL(*send_algorithm_, RevertRetransmissionTimeout()); 3449 ProcessAckPacket(&nack_three); 3450 3451 EXPECT_CALL(*send_algorithm_, BandwidthEstimate()).WillOnce( 3452 Return(QuicBandwidth::Zero())); 3453 3454 const uint32 kSlowStartThreshold = 23u; 3455 EXPECT_CALL(*send_algorithm_, GetSlowStartThreshold()).WillOnce( 3456 Return(kSlowStartThreshold)); 3457 3458 const QuicConnectionStats& stats = connection_.GetStats(); 3459 EXPECT_EQ(3 * first_packet_size + 2 * second_packet_size - kQuicVersionSize, 3460 stats.bytes_sent); 3461 EXPECT_EQ(5u, stats.packets_sent); 3462 EXPECT_EQ(2 * first_packet_size + second_packet_size - kQuicVersionSize, 3463 stats.bytes_retransmitted); 3464 EXPECT_EQ(3u, stats.packets_retransmitted); 3465 EXPECT_EQ(1u, stats.rto_count); 3466 EXPECT_EQ(kMaxPacketSize, stats.congestion_window); 3467 EXPECT_EQ(kSlowStartThreshold, stats.slow_start_threshold); 3468 EXPECT_EQ(kDefaultMaxPacketSize, stats.max_packet_size); 3469 } 3470 3471 TEST_P(QuicConnectionTest, CheckReceiveStats) { 3472 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 3473 3474 size_t received_bytes = 0; 3475 received_bytes += ProcessFecProtectedPacket(1, false, !kEntropyFlag); 3476 received_bytes += ProcessFecProtectedPacket(3, false, !kEntropyFlag); 3477 // Should be counted against dropped packets. 3478 received_bytes += ProcessDataPacket(3, 1, !kEntropyFlag); 3479 received_bytes += ProcessFecPacket(4, 1, true, !kEntropyFlag, NULL); 3480 3481 EXPECT_CALL(*send_algorithm_, BandwidthEstimate()).WillOnce( 3482 Return(QuicBandwidth::Zero())); 3483 const uint32 kSlowStartThreshold = 23u; 3484 EXPECT_CALL(*send_algorithm_, GetSlowStartThreshold()).WillOnce( 3485 Return(kSlowStartThreshold)); 3486 3487 const QuicConnectionStats& stats = connection_.GetStats(); 3488 EXPECT_EQ(received_bytes, stats.bytes_received); 3489 EXPECT_EQ(4u, stats.packets_received); 3490 3491 EXPECT_EQ(1u, stats.packets_revived); 3492 EXPECT_EQ(1u, stats.packets_dropped); 3493 3494 EXPECT_EQ(kSlowStartThreshold, stats.slow_start_threshold); 3495 } 3496 3497 TEST_P(QuicConnectionTest, TestFecGroupLimits) { 3498 // Create and return a group for 1. 3499 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 1) != NULL); 3500 3501 // Create and return a group for 2. 3502 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 2) != NULL); 3503 3504 // Create and return a group for 4. This should remove 1 but not 2. 3505 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 4) != NULL); 3506 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 1) == NULL); 3507 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 2) != NULL); 3508 3509 // Create and return a group for 3. This will kill off 2. 3510 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 3) != NULL); 3511 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 2) == NULL); 3512 3513 // Verify that adding 5 kills off 3, despite 4 being created before 3. 3514 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 5) != NULL); 3515 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 4) != NULL); 3516 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 3) == NULL); 3517 } 3518 3519 TEST_P(QuicConnectionTest, ProcessFramesIfPacketClosedConnection) { 3520 // Construct a packet with stream frame and connection close frame. 3521 header_.public_header.connection_id = connection_id_; 3522 header_.packet_sequence_number = 1; 3523 header_.public_header.reset_flag = false; 3524 header_.public_header.version_flag = false; 3525 header_.entropy_flag = false; 3526 header_.fec_flag = false; 3527 header_.fec_group = 0; 3528 3529 QuicConnectionCloseFrame qccf; 3530 qccf.error_code = QUIC_PEER_GOING_AWAY; 3531 QuicFrame close_frame(&qccf); 3532 QuicFrame stream_frame(&frame1_); 3533 3534 QuicFrames frames; 3535 frames.push_back(stream_frame); 3536 frames.push_back(close_frame); 3537 scoped_ptr<QuicPacket> packet( 3538 BuildUnsizedDataPacket(&framer_, header_, frames).packet); 3539 EXPECT_TRUE(NULL != packet.get()); 3540 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPacket( 3541 ENCRYPTION_NONE, 1, *packet)); 3542 3543 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, true)); 3544 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1); 3545 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 3546 3547 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted); 3548 } 3549 3550 TEST_P(QuicConnectionTest, SelectMutualVersion) { 3551 connection_.SetSupportedVersions(QuicSupportedVersions()); 3552 // Set the connection to speak the lowest quic version. 3553 connection_.set_version(QuicVersionMin()); 3554 EXPECT_EQ(QuicVersionMin(), connection_.version()); 3555 3556 // Pass in available versions which includes a higher mutually supported 3557 // version. The higher mutually supported version should be selected. 3558 QuicVersionVector supported_versions; 3559 for (size_t i = 0; i < arraysize(kSupportedQuicVersions); ++i) { 3560 supported_versions.push_back(kSupportedQuicVersions[i]); 3561 } 3562 EXPECT_TRUE(connection_.SelectMutualVersion(supported_versions)); 3563 EXPECT_EQ(QuicVersionMax(), connection_.version()); 3564 3565 // Expect that the lowest version is selected. 3566 // Ensure the lowest supported version is less than the max, unless they're 3567 // the same. 3568 EXPECT_LE(QuicVersionMin(), QuicVersionMax()); 3569 QuicVersionVector lowest_version_vector; 3570 lowest_version_vector.push_back(QuicVersionMin()); 3571 EXPECT_TRUE(connection_.SelectMutualVersion(lowest_version_vector)); 3572 EXPECT_EQ(QuicVersionMin(), connection_.version()); 3573 3574 // Shouldn't be able to find a mutually supported version. 3575 QuicVersionVector unsupported_version; 3576 unsupported_version.push_back(QUIC_VERSION_UNSUPPORTED); 3577 EXPECT_FALSE(connection_.SelectMutualVersion(unsupported_version)); 3578 } 3579 3580 TEST_P(QuicConnectionTest, ConnectionCloseWhenWritable) { 3581 EXPECT_FALSE(writer_->IsWriteBlocked()); 3582 3583 // Send a packet. 3584 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, NULL); 3585 EXPECT_EQ(0u, connection_.NumQueuedPackets()); 3586 EXPECT_EQ(1u, writer_->packets_write_attempts()); 3587 3588 TriggerConnectionClose(); 3589 EXPECT_EQ(2u, writer_->packets_write_attempts()); 3590 } 3591 3592 TEST_P(QuicConnectionTest, ConnectionCloseGettingWriteBlocked) { 3593 BlockOnNextWrite(); 3594 TriggerConnectionClose(); 3595 EXPECT_EQ(1u, writer_->packets_write_attempts()); 3596 EXPECT_TRUE(writer_->IsWriteBlocked()); 3597 } 3598 3599 TEST_P(QuicConnectionTest, ConnectionCloseWhenWriteBlocked) { 3600 BlockOnNextWrite(); 3601 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, NULL); 3602 EXPECT_EQ(1u, connection_.NumQueuedPackets()); 3603 EXPECT_EQ(1u, writer_->packets_write_attempts()); 3604 EXPECT_TRUE(writer_->IsWriteBlocked()); 3605 TriggerConnectionClose(); 3606 EXPECT_EQ(1u, writer_->packets_write_attempts()); 3607 } 3608 3609 TEST_P(QuicConnectionTest, AckNotifierTriggerCallback) { 3610 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 3611 3612 // Create a delegate which we expect to be called. 3613 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate); 3614 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _, _, _)).Times(1); 3615 3616 // Send some data, which will register the delegate to be notified. 3617 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get()); 3618 3619 // Process an ACK from the server which should trigger the callback. 3620 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _)); 3621 QuicAckFrame frame = InitAckFrame(1); 3622 ProcessAckPacket(&frame); 3623 } 3624 3625 TEST_P(QuicConnectionTest, AckNotifierFailToTriggerCallback) { 3626 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 3627 3628 // Create a delegate which we don't expect to be called. 3629 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate); 3630 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _, _, _)).Times(0); 3631 3632 // Send some data, which will register the delegate to be notified. This will 3633 // not be ACKed and so the delegate should never be called. 3634 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get()); 3635 3636 // Send some other data which we will ACK. 3637 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, NULL); 3638 connection_.SendStreamDataWithString(1, "bar", 0, !kFin, NULL); 3639 3640 // Now we receive ACK for packets 2 and 3, but importantly missing packet 1 3641 // which we registered to be notified about. 3642 QuicAckFrame frame = InitAckFrame(3); 3643 NackPacket(1, &frame); 3644 SequenceNumberSet lost_packets; 3645 lost_packets.insert(1); 3646 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _)) 3647 .WillOnce(Return(lost_packets)); 3648 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _)); 3649 ProcessAckPacket(&frame); 3650 } 3651 3652 TEST_P(QuicConnectionTest, AckNotifierCallbackAfterRetransmission) { 3653 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 3654 3655 // Create a delegate which we expect to be called. 3656 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate); 3657 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _, _, _)).Times(1); 3658 3659 // Send four packets, and register to be notified on ACK of packet 2. 3660 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, NULL); 3661 connection_.SendStreamDataWithString(3, "bar", 0, !kFin, delegate.get()); 3662 connection_.SendStreamDataWithString(3, "baz", 0, !kFin, NULL); 3663 connection_.SendStreamDataWithString(3, "qux", 0, !kFin, NULL); 3664 3665 // Now we receive ACK for packets 1, 3, and 4 and lose 2. 3666 QuicAckFrame frame = InitAckFrame(4); 3667 NackPacket(2, &frame); 3668 SequenceNumberSet lost_packets; 3669 lost_packets.insert(2); 3670 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _)) 3671 .WillOnce(Return(lost_packets)); 3672 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _)); 3673 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)); 3674 ProcessAckPacket(&frame); 3675 3676 // Now we get an ACK for packet 5 (retransmitted packet 2), which should 3677 // trigger the callback. 3678 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _)) 3679 .WillRepeatedly(Return(SequenceNumberSet())); 3680 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _)); 3681 QuicAckFrame second_ack_frame = InitAckFrame(5); 3682 ProcessAckPacket(&second_ack_frame); 3683 } 3684 3685 // AckNotifierCallback is triggered by the ack of a packet that timed 3686 // out and was retransmitted, even though the retransmission has a 3687 // different sequence number. 3688 TEST_P(QuicConnectionTest, AckNotifierCallbackForAckAfterRTO) { 3689 InSequence s; 3690 3691 // Create a delegate which we expect to be called. 3692 scoped_refptr<MockAckNotifierDelegate> delegate( 3693 new StrictMock<MockAckNotifierDelegate>); 3694 3695 QuicTime default_retransmission_time = clock_.ApproximateNow().Add( 3696 DefaultRetransmissionTime()); 3697 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, delegate.get()); 3698 EXPECT_EQ(1u, stop_waiting()->least_unacked); 3699 3700 EXPECT_EQ(1u, writer_->header().packet_sequence_number); 3701 EXPECT_EQ(default_retransmission_time, 3702 connection_.GetRetransmissionAlarm()->deadline()); 3703 // Simulate the retransmission alarm firing. 3704 clock_.AdvanceTime(DefaultRetransmissionTime()); 3705 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true)); 3706 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 2u, _, _)); 3707 connection_.GetRetransmissionAlarm()->Fire(); 3708 EXPECT_EQ(2u, writer_->header().packet_sequence_number); 3709 // We do not raise the high water mark yet. 3710 EXPECT_EQ(1u, stop_waiting()->least_unacked); 3711 3712 // Ack the original packet, which will revert the RTO. 3713 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 3714 EXPECT_CALL(*delegate.get(), OnAckNotification(1, _, 1, _, _)); 3715 EXPECT_CALL(*send_algorithm_, RevertRetransmissionTimeout()); 3716 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _)); 3717 QuicAckFrame ack_frame = InitAckFrame(1); 3718 ProcessAckPacket(&ack_frame); 3719 3720 // Delegate is not notified again when the retransmit is acked. 3721 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _)); 3722 QuicAckFrame second_ack_frame = InitAckFrame(2); 3723 ProcessAckPacket(&second_ack_frame); 3724 } 3725 3726 // AckNotifierCallback is triggered by the ack of a packet that was 3727 // previously nacked, even though the retransmission has a different 3728 // sequence number. 3729 TEST_P(QuicConnectionTest, AckNotifierCallbackForAckOfNackedPacket) { 3730 InSequence s; 3731 3732 // Create a delegate which we expect to be called. 3733 scoped_refptr<MockAckNotifierDelegate> delegate( 3734 new StrictMock<MockAckNotifierDelegate>); 3735 3736 // Send four packets, and register to be notified on ACK of packet 2. 3737 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, NULL); 3738 connection_.SendStreamDataWithString(3, "bar", 0, !kFin, delegate.get()); 3739 connection_.SendStreamDataWithString(3, "baz", 0, !kFin, NULL); 3740 connection_.SendStreamDataWithString(3, "qux", 0, !kFin, NULL); 3741 3742 // Now we receive ACK for packets 1, 3, and 4 and lose 2. 3743 QuicAckFrame frame = InitAckFrame(4); 3744 NackPacket(2, &frame); 3745 SequenceNumberSet lost_packets; 3746 lost_packets.insert(2); 3747 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 3748 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _)) 3749 .WillOnce(Return(lost_packets)); 3750 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _)); 3751 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)); 3752 ProcessAckPacket(&frame); 3753 3754 // Now we get an ACK for packet 2, which was previously nacked. 3755 SequenceNumberSet no_lost_packets; 3756 EXPECT_CALL(*delegate.get(), OnAckNotification(1, _, 1, _, _)); 3757 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _)) 3758 .WillOnce(Return(no_lost_packets)); 3759 QuicAckFrame second_ack_frame = InitAckFrame(4); 3760 ProcessAckPacket(&second_ack_frame); 3761 3762 // Verify that the delegate is not notified again when the 3763 // retransmit is acked. 3764 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _)) 3765 .WillOnce(Return(no_lost_packets)); 3766 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _)); 3767 QuicAckFrame third_ack_frame = InitAckFrame(5); 3768 ProcessAckPacket(&third_ack_frame); 3769 } 3770 3771 TEST_P(QuicConnectionTest, AckNotifierFECTriggerCallback) { 3772 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 3773 3774 // Create a delegate which we expect to be called. 3775 scoped_refptr<MockAckNotifierDelegate> delegate( 3776 new MockAckNotifierDelegate); 3777 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _, _, _)).Times(1); 3778 3779 // Send some data, which will register the delegate to be notified. 3780 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get()); 3781 connection_.SendStreamDataWithString(2, "bar", 0, !kFin, NULL); 3782 3783 // Process an ACK from the server with a revived packet, which should trigger 3784 // the callback. 3785 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _)); 3786 QuicAckFrame frame = InitAckFrame(2); 3787 NackPacket(1, &frame); 3788 frame.revived_packets.insert(1); 3789 ProcessAckPacket(&frame); 3790 // If the ack is processed again, the notifier should not be called again. 3791 ProcessAckPacket(&frame); 3792 } 3793 3794 TEST_P(QuicConnectionTest, AckNotifierCallbackAfterFECRecovery) { 3795 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 3796 EXPECT_CALL(visitor_, OnCanWrite()); 3797 3798 // Create a delegate which we expect to be called. 3799 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate); 3800 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _, _, _)).Times(1); 3801 3802 // Expect ACKs for 1 packet. 3803 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _)); 3804 3805 // Send one packet, and register to be notified on ACK. 3806 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get()); 3807 3808 // Ack packet gets dropped, but we receive an FEC packet that covers it. 3809 // Should recover the Ack packet and trigger the notification callback. 3810 QuicFrames frames; 3811 3812 QuicAckFrame ack_frame = InitAckFrame(1); 3813 frames.push_back(QuicFrame(&ack_frame)); 3814 3815 // Dummy stream frame to satisfy expectations set elsewhere. 3816 frames.push_back(QuicFrame(&frame1_)); 3817 3818 QuicPacketHeader ack_header; 3819 ack_header.public_header.connection_id = connection_id_; 3820 ack_header.public_header.reset_flag = false; 3821 ack_header.public_header.version_flag = false; 3822 ack_header.entropy_flag = !kEntropyFlag; 3823 ack_header.fec_flag = true; 3824 ack_header.packet_sequence_number = 1; 3825 ack_header.is_in_fec_group = IN_FEC_GROUP; 3826 ack_header.fec_group = 1; 3827 3828 QuicPacket* packet = 3829 BuildUnsizedDataPacket(&framer_, ack_header, frames).packet; 3830 3831 // Take the packet which contains the ACK frame, and construct and deliver an 3832 // FEC packet which allows the ACK packet to be recovered. 3833 ProcessFecPacket(2, 1, true, !kEntropyFlag, packet); 3834 } 3835 3836 TEST_P(QuicConnectionTest, NetworkChangeVisitorCallbacksChangeFecState) { 3837 QuicPacketCreator* creator = 3838 QuicConnectionPeer::GetPacketCreator(&connection_); 3839 size_t max_packets_per_fec_group = creator->max_packets_per_fec_group(); 3840 3841 QuicSentPacketManager::NetworkChangeVisitor* visitor = 3842 QuicSentPacketManagerPeer::GetNetworkChangeVisitor( 3843 QuicConnectionPeer::GetSentPacketManager(&connection_)); 3844 EXPECT_TRUE(visitor); 3845 3846 // Increase FEC group size by increasing congestion window to a large number. 3847 visitor->OnCongestionWindowChange(1000 * kDefaultTCPMSS); 3848 EXPECT_LT(max_packets_per_fec_group, creator->max_packets_per_fec_group()); 3849 } 3850 3851 class MockQuicConnectionDebugVisitor 3852 : public QuicConnectionDebugVisitor { 3853 public: 3854 MOCK_METHOD1(OnFrameAddedToPacket, 3855 void(const QuicFrame&)); 3856 3857 MOCK_METHOD5(OnPacketSent, 3858 void(QuicPacketSequenceNumber, 3859 EncryptionLevel, 3860 TransmissionType, 3861 const QuicEncryptedPacket&, 3862 WriteResult)); 3863 3864 MOCK_METHOD2(OnPacketRetransmitted, 3865 void(QuicPacketSequenceNumber, 3866 QuicPacketSequenceNumber)); 3867 3868 MOCK_METHOD3(OnPacketReceived, 3869 void(const IPEndPoint&, 3870 const IPEndPoint&, 3871 const QuicEncryptedPacket&)); 3872 3873 MOCK_METHOD1(OnProtocolVersionMismatch, 3874 void(QuicVersion)); 3875 3876 MOCK_METHOD1(OnPacketHeader, 3877 void(const QuicPacketHeader& header)); 3878 3879 MOCK_METHOD1(OnStreamFrame, 3880 void(const QuicStreamFrame&)); 3881 3882 MOCK_METHOD1(OnAckFrame, 3883 void(const QuicAckFrame& frame)); 3884 3885 MOCK_METHOD1(OnCongestionFeedbackFrame, 3886 void(const QuicCongestionFeedbackFrame&)); 3887 3888 MOCK_METHOD1(OnStopWaitingFrame, 3889 void(const QuicStopWaitingFrame&)); 3890 3891 MOCK_METHOD1(OnRstStreamFrame, 3892 void(const QuicRstStreamFrame&)); 3893 3894 MOCK_METHOD1(OnConnectionCloseFrame, 3895 void(const QuicConnectionCloseFrame&)); 3896 3897 MOCK_METHOD1(OnPublicResetPacket, 3898 void(const QuicPublicResetPacket&)); 3899 3900 MOCK_METHOD1(OnVersionNegotiationPacket, 3901 void(const QuicVersionNegotiationPacket&)); 3902 3903 MOCK_METHOD2(OnRevivedPacket, 3904 void(const QuicPacketHeader&, StringPiece payload)); 3905 }; 3906 3907 TEST_P(QuicConnectionTest, OnPacketHeaderDebugVisitor) { 3908 QuicPacketHeader header; 3909 3910 MockQuicConnectionDebugVisitor* debug_visitor = 3911 new MockQuicConnectionDebugVisitor(); 3912 connection_.set_debug_visitor(debug_visitor); 3913 EXPECT_CALL(*debug_visitor, OnPacketHeader(Ref(header))).Times(1); 3914 connection_.OnPacketHeader(header); 3915 } 3916 3917 TEST_P(QuicConnectionTest, Pacing) { 3918 TestConnection server(connection_id_, IPEndPoint(), helper_.get(), 3919 factory_, /* is_server= */ true, version()); 3920 TestConnection client(connection_id_, IPEndPoint(), helper_.get(), 3921 factory_, /* is_server= */ false, version()); 3922 EXPECT_FALSE(client.sent_packet_manager().using_pacing()); 3923 EXPECT_FALSE(server.sent_packet_manager().using_pacing()); 3924 } 3925 3926 TEST_P(QuicConnectionTest, ControlFramesInstigateAcks) { 3927 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); 3928 3929 // Send a WINDOW_UPDATE frame. 3930 QuicWindowUpdateFrame window_update; 3931 window_update.stream_id = 3; 3932 window_update.byte_offset = 1234; 3933 EXPECT_CALL(visitor_, OnWindowUpdateFrames(_)); 3934 ProcessFramePacket(QuicFrame(&window_update)); 3935 3936 // Ensure that this has caused the ACK alarm to be set. 3937 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_); 3938 EXPECT_TRUE(ack_alarm->IsSet()); 3939 3940 // Cancel alarm, and try again with BLOCKED frame. 3941 ack_alarm->Cancel(); 3942 QuicBlockedFrame blocked; 3943 blocked.stream_id = 3; 3944 EXPECT_CALL(visitor_, OnBlockedFrames(_)); 3945 ProcessFramePacket(QuicFrame(&blocked)); 3946 EXPECT_TRUE(ack_alarm->IsSet()); 3947 } 3948 3949 } // namespace 3950 } // namespace test 3951 } // namespace net 3952