blob: e62e2a503a139834c731043d596c4b65e91be773 [file] [log] [blame]
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/quic/quic_connection.h"
#include <errno.h>
#include <memory>
#include <ostream>
#include <utility>
#include "base/bind.h"
#include "base/macros.h"
#include "base/stl_util.h"
#include "net/base/ip_address.h"
#include "net/base/net_errors.h"
#include "net/quic/congestion_control/loss_detection_interface.h"
#include "net/quic/congestion_control/send_algorithm_interface.h"
#include "net/quic/crypto/null_encrypter.h"
#include "net/quic/crypto/quic_decrypter.h"
#include "net/quic/crypto/quic_encrypter.h"
#include "net/quic/quic_flags.h"
#include "net/quic/quic_protocol.h"
#include "net/quic/quic_simple_buffer_allocator.h"
#include "net/quic/quic_utils.h"
#include "net/quic/test_tools/mock_clock.h"
#include "net/quic/test_tools/mock_random.h"
#include "net/quic/test_tools/quic_config_peer.h"
#include "net/quic/test_tools/quic_connection_peer.h"
#include "net/quic/test_tools/quic_framer_peer.h"
#include "net/quic/test_tools/quic_packet_creator_peer.h"
#include "net/quic/test_tools/quic_packet_generator_peer.h"
#include "net/quic/test_tools/quic_sent_packet_manager_peer.h"
#include "net/quic/test_tools/quic_test_utils.h"
#include "net/quic/test_tools/simple_quic_framer.h"
#include "net/test/gtest_util.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using base::StringPiece;
using std::map;
using std::ostream;
using std::string;
using std::vector;
using testing::AnyNumber;
using testing::AtLeast;
using testing::Contains;
using testing::DoAll;
using testing::InSequence;
using testing::InvokeWithoutArgs;
using testing::NiceMock;
using testing::Ref;
using testing::Return;
using testing::SaveArg;
using testing::SetArgPointee;
using testing::StrictMock;
using testing::_;
namespace net {
namespace test {
namespace {
const char data1[] = "foo";
const char data2[] = "bar";
const bool kFin = true;
const bool kEntropyFlag = true;
const bool kHasStopWaiting = true;
const QuicPacketEntropyHash kTestEntropyHash = 76;
const int kDefaultRetransmissionTimeMs = 500;
const IPEndPoint kPeerAddress = IPEndPoint(Loopback6(), /*port=*/12345);
const IPEndPoint kSelfAddress = IPEndPoint(Loopback6(), /*port=*/443);
Perspective InvertPerspective(Perspective perspective) {
return perspective == Perspective::IS_CLIENT ? Perspective::IS_SERVER
: Perspective::IS_CLIENT;
}
// TaggingEncrypter appends kTagSize bytes of |tag| to the end of each message.
class TaggingEncrypter : public QuicEncrypter {
public:
explicit TaggingEncrypter(uint8_t tag) : tag_(tag) {}
~TaggingEncrypter() override {}
// QuicEncrypter interface.
bool SetKey(StringPiece key) override { return true; }
bool SetNoncePrefix(StringPiece nonce_prefix) override { return true; }
bool EncryptPacket(QuicPathId path_id,
QuicPacketNumber packet_number,
StringPiece associated_data,
StringPiece plaintext,
char* output,
size_t* output_length,
size_t max_output_length) override {
const size_t len = plaintext.size() + kTagSize;
if (max_output_length < len) {
return false;
}
// Memmove is safe for inplace encryption.
memmove(output, plaintext.data(), plaintext.size());
output += plaintext.size();
memset(output, tag_, kTagSize);
*output_length = len;
return true;
}
size_t GetKeySize() const override { return 0; }
size_t GetNoncePrefixSize() const override { return 0; }
size_t GetMaxPlaintextSize(size_t ciphertext_size) const override {
return ciphertext_size - kTagSize;
}
size_t GetCiphertextSize(size_t plaintext_size) const override {
return plaintext_size + kTagSize;
}
StringPiece GetKey() const override { return StringPiece(); }
StringPiece GetNoncePrefix() const override { return StringPiece(); }
private:
enum {
kTagSize = 12,
};
const uint8_t tag_;
DISALLOW_COPY_AND_ASSIGN(TaggingEncrypter);
};
// TaggingDecrypter ensures that the final kTagSize bytes of the message all
// have the same value and then removes them.
class TaggingDecrypter : public QuicDecrypter {
public:
~TaggingDecrypter() override {}
// QuicDecrypter interface
bool SetKey(StringPiece key) override { return true; }
bool SetNoncePrefix(StringPiece nonce_prefix) override { return true; }
bool SetPreliminaryKey(StringPiece key) override {
QUIC_BUG << "should not be called";
return false;
}
bool SetDiversificationNonce(DiversificationNonce key) override {
return true;
}
bool DecryptPacket(QuicPathId path_id,
QuicPacketNumber packet_number,
StringPiece associated_data,
StringPiece ciphertext,
char* output,
size_t* output_length,
size_t max_output_length) override {
if (ciphertext.size() < kTagSize) {
return false;
}
if (!CheckTag(ciphertext, GetTag(ciphertext))) {
return false;
}
*output_length = ciphertext.size() - kTagSize;
memcpy(output, ciphertext.data(), *output_length);
return true;
}
StringPiece GetKey() const override { return StringPiece(); }
StringPiece GetNoncePrefix() const override { return StringPiece(); }
const char* cipher_name() const override { return "Tagging"; }
// Use a distinct value starting with 0xFFFFFF, which is never used by TLS.
uint32_t cipher_id() const override { return 0xFFFFFFF0; }
protected:
virtual uint8_t GetTag(StringPiece ciphertext) {
return ciphertext.data()[ciphertext.size() - 1];
}
private:
enum {
kTagSize = 12,
};
bool CheckTag(StringPiece ciphertext, uint8_t tag) {
for (size_t i = ciphertext.size() - kTagSize; i < ciphertext.size(); i++) {
if (ciphertext.data()[i] != tag) {
return false;
}
}
return true;
}
};
// StringTaggingDecrypter ensures that the final kTagSize bytes of the message
// match the expected value.
class StrictTaggingDecrypter : public TaggingDecrypter {
public:
explicit StrictTaggingDecrypter(uint8_t tag) : tag_(tag) {}
~StrictTaggingDecrypter() override {}
// TaggingQuicDecrypter
uint8_t GetTag(StringPiece ciphertext) override { return tag_; }
const char* cipher_name() const override { return "StrictTagging"; }
// Use a distinct value starting with 0xFFFFFF, which is never used by TLS.
uint32_t cipher_id() const override { return 0xFFFFFFF1; }
private:
const uint8_t tag_;
};
class TestConnectionHelper : public QuicConnectionHelperInterface {
public:
TestConnectionHelper(MockClock* clock, MockRandom* random_generator)
: clock_(clock), random_generator_(random_generator) {
clock_->AdvanceTime(QuicTime::Delta::FromSeconds(1));
}
// QuicConnectionHelperInterface
const QuicClock* GetClock() const override { return clock_; }
QuicRandom* GetRandomGenerator() override { return random_generator_; }
QuicBufferAllocator* GetBufferAllocator() override {
return &buffer_allocator_;
}
private:
MockClock* clock_;
MockRandom* random_generator_;
SimpleBufferAllocator buffer_allocator_;
DISALLOW_COPY_AND_ASSIGN(TestConnectionHelper);
};
class TestAlarmFactory : public QuicAlarmFactory {
public:
class TestAlarm : public QuicAlarm {
public:
explicit TestAlarm(QuicArenaScopedPtr<QuicAlarm::Delegate> delegate)
: QuicAlarm(std::move(delegate)) {}
void SetImpl() override {}
void CancelImpl() override {}
using QuicAlarm::Fire;
};
TestAlarmFactory() {}
QuicAlarm* CreateAlarm(QuicAlarm::Delegate* delegate) override {
return new TestAlarm(QuicArenaScopedPtr<QuicAlarm::Delegate>(delegate));
}
QuicArenaScopedPtr<QuicAlarm> CreateAlarm(
QuicArenaScopedPtr<QuicAlarm::Delegate> delegate,
QuicConnectionArena* arena) override {
return arena->New<TestAlarm>(std::move(delegate));
}
private:
DISALLOW_COPY_AND_ASSIGN(TestAlarmFactory);
};
class TestPacketWriter : public QuicPacketWriter {
public:
TestPacketWriter(QuicVersion version, MockClock* clock)
: version_(version),
framer_(SupportedVersions(version_)),
last_packet_size_(0),
write_blocked_(false),
write_should_fail_(false),
block_on_next_write_(false),
is_write_blocked_data_buffered_(false),
final_bytes_of_last_packet_(0),
final_bytes_of_previous_packet_(0),
use_tagging_decrypter_(false),
packets_write_attempts_(0),
clock_(clock),
write_pause_time_delta_(QuicTime::Delta::Zero()),
max_packet_size_(kMaxPacketSize) {}
// QuicPacketWriter interface
WriteResult WritePacket(const char* buffer,
size_t buf_len,
const IPAddress& self_address,
const IPEndPoint& peer_address,
PerPacketOptions* options) override {
QuicEncryptedPacket packet(buffer, buf_len);
++packets_write_attempts_;
if (packet.length() >= sizeof(final_bytes_of_last_packet_)) {
final_bytes_of_previous_packet_ = final_bytes_of_last_packet_;
memcpy(&final_bytes_of_last_packet_, packet.data() + packet.length() - 4,
sizeof(final_bytes_of_last_packet_));
}
if (use_tagging_decrypter_) {
framer_.framer()->SetDecrypter(ENCRYPTION_NONE, new TaggingDecrypter);
}
EXPECT_TRUE(framer_.ProcessPacket(packet));
if (block_on_next_write_) {
write_blocked_ = true;
block_on_next_write_ = false;
}
if (IsWriteBlocked()) {
return WriteResult(WRITE_STATUS_BLOCKED, -1);
}
if (ShouldWriteFail()) {
return WriteResult(WRITE_STATUS_ERROR, 0);
}
last_packet_size_ = packet.length();
if (!write_pause_time_delta_.IsZero()) {
clock_->AdvanceTime(write_pause_time_delta_);
}
return WriteResult(WRITE_STATUS_OK, last_packet_size_);
}
bool IsWriteBlockedDataBuffered() const override {
return is_write_blocked_data_buffered_;
}
bool ShouldWriteFail() { return write_should_fail_; }
bool IsWriteBlocked() const override { return write_blocked_; }
void SetWritable() override { write_blocked_ = false; }
void SetShouldWriteFail() { write_should_fail_ = true; }
QuicByteCount GetMaxPacketSize(
const IPEndPoint& /*peer_address*/) const override {
return max_packet_size_;
}
void BlockOnNextWrite() { block_on_next_write_ = true; }
// Sets the amount of time that the writer should before the actual write.
void SetWritePauseTimeDelta(QuicTime::Delta delta) {
write_pause_time_delta_ = delta;
}
const QuicPacketHeader& header() { return framer_.header(); }
size_t frame_count() const { return framer_.num_frames(); }
const vector<QuicAckFrame>& ack_frames() const {
return framer_.ack_frames();
}
const vector<QuicStopWaitingFrame>& stop_waiting_frames() const {
return framer_.stop_waiting_frames();
}
const vector<QuicConnectionCloseFrame>& connection_close_frames() const {
return framer_.connection_close_frames();
}
const vector<QuicRstStreamFrame>& rst_stream_frames() const {
return framer_.rst_stream_frames();
}
const vector<QuicStreamFrame*>& stream_frames() const {
return framer_.stream_frames();
}
const vector<QuicPingFrame>& ping_frames() const {
return framer_.ping_frames();
}
size_t last_packet_size() { return last_packet_size_; }
const QuicVersionNegotiationPacket* version_negotiation_packet() {
return framer_.version_negotiation_packet();
}
void set_is_write_blocked_data_buffered(bool buffered) {
is_write_blocked_data_buffered_ = buffered;
}
void set_perspective(Perspective perspective) {
// We invert perspective here, because the framer needs to parse packets
// we send.
QuicFramerPeer::SetPerspective(framer_.framer(),
InvertPerspective(perspective));
}
// final_bytes_of_last_packet_ returns the last four bytes of the previous
// packet as a little-endian, uint32_t. This is intended to be used with a
// TaggingEncrypter so that tests can determine which encrypter was used for
// a given packet.
uint32_t final_bytes_of_last_packet() { return final_bytes_of_last_packet_; }
// Returns the final bytes of the second to last packet.
uint32_t final_bytes_of_previous_packet() {
return final_bytes_of_previous_packet_;
}
void use_tagging_decrypter() { use_tagging_decrypter_ = true; }
uint32_t packets_write_attempts() { return packets_write_attempts_; }
void Reset() { framer_.Reset(); }
void SetSupportedVersions(const QuicVersionVector& versions) {
framer_.SetSupportedVersions(versions);
}
void set_max_packet_size(QuicByteCount max_packet_size) {
max_packet_size_ = max_packet_size;
}
private:
QuicVersion version_;
SimpleQuicFramer framer_;
size_t last_packet_size_;
bool write_blocked_;
bool write_should_fail_;
bool block_on_next_write_;
bool is_write_blocked_data_buffered_;
uint32_t final_bytes_of_last_packet_;
uint32_t final_bytes_of_previous_packet_;
bool use_tagging_decrypter_;
uint32_t packets_write_attempts_;
MockClock* clock_;
// If non-zero, the clock will pause during WritePacket for this amount of
// time.
QuicTime::Delta write_pause_time_delta_;
QuicByteCount max_packet_size_;
DISALLOW_COPY_AND_ASSIGN(TestPacketWriter);
};
class TestConnection : public QuicConnection {
public:
TestConnection(QuicConnectionId connection_id,
IPEndPoint address,
TestConnectionHelper* helper,
TestAlarmFactory* alarm_factory,
TestPacketWriter* writer,
Perspective perspective,
QuicVersion version)
: QuicConnection(connection_id,
address,
helper,
alarm_factory,
writer,
/* owns_writer= */ false,
perspective,
SupportedVersions(version)) {
writer->set_perspective(perspective);
}
void SendAck() { QuicConnectionPeer::SendAck(this); }
void SetSendAlgorithm(SendAlgorithmInterface* send_algorithm) {
QuicConnectionPeer::SetSendAlgorithm(this, send_algorithm);
}
void SetLossAlgorithm(LossDetectionInterface* loss_algorithm) {
// TODO(fayang): connection tests should use MockSentPacketManager.
QuicSentPacketManagerPeer::SetLossAlgorithm(
static_cast<QuicSentPacketManager*>(
QuicConnectionPeer::GetSentPacketManager(this)),
loss_algorithm);
}
void SendPacket(EncryptionLevel level,
QuicPathId path_id,
QuicPacketNumber packet_number,
QuicPacket* packet,
QuicPacketEntropyHash entropy_hash,
HasRetransmittableData retransmittable,
bool has_ack,
bool has_pending_frames) {
char buffer[kMaxPacketSize];
size_t encrypted_length =
QuicConnectionPeer::GetFramer(this)->EncryptPayload(
ENCRYPTION_NONE, path_id, packet_number, *packet, buffer,
kMaxPacketSize);
delete packet;
SerializedPacket serialized_packet(
kDefaultPathId, packet_number, PACKET_6BYTE_PACKET_NUMBER, buffer,
encrypted_length, entropy_hash, has_ack, has_pending_frames);
if (retransmittable == HAS_RETRANSMITTABLE_DATA) {
serialized_packet.retransmittable_frames.push_back(
QuicFrame(new QuicStreamFrame()));
}
OnSerializedPacket(&serialized_packet);
}
QuicConsumedData SendStreamDataWithString(
QuicStreamId id,
StringPiece data,
QuicStreamOffset offset,
bool fin,
QuicAckListenerInterface* listener) {
struct iovec iov;
QuicIOVector data_iov(MakeIOVector(data, &iov));
return QuicConnection::SendStreamData(id, data_iov, offset, fin, listener);
}
QuicConsumedData SendStreamData3() {
return SendStreamDataWithString(kClientDataStreamId1, "food", 0, !kFin,
nullptr);
}
QuicConsumedData SendStreamData5() {
return SendStreamDataWithString(kClientDataStreamId2, "food2", 0, !kFin,
nullptr);
}
// Ensures the connection can write stream data before writing.
QuicConsumedData EnsureWritableAndSendStreamData5() {
EXPECT_TRUE(CanWriteStreamData());
return SendStreamData5();
}
// The crypto stream has special semantics so that it is not blocked by a
// congestion window limitation, and also so that it gets put into a separate
// packet (so that it is easier to reason about a crypto frame not being
// split needlessly across packet boundaries). As a result, we have separate
// tests for some cases for this stream.
QuicConsumedData SendCryptoStreamData() {
return SendStreamDataWithString(kCryptoStreamId, "chlo", 0, !kFin, nullptr);
}
void set_version(QuicVersion version) {
QuicConnectionPeer::GetFramer(this)->set_version(version);
}
void SetSupportedVersions(const QuicVersionVector& versions) {
QuicConnectionPeer::GetFramer(this)->SetSupportedVersions(versions);
writer()->SetSupportedVersions(versions);
}
void set_perspective(Perspective perspective) {
writer()->set_perspective(perspective);
QuicConnectionPeer::SetPerspective(this, perspective);
}
// Enable path MTU discovery. Assumes that the test is performed from the
// client perspective and the higher value of MTU target is used.
void EnablePathMtuDiscovery(MockSendAlgorithm* send_algorithm) {
ASSERT_EQ(Perspective::IS_CLIENT, perspective());
QuicConfig config;
QuicTagVector connection_options;
connection_options.push_back(kMTUH);
config.SetConnectionOptionsToSend(connection_options);
EXPECT_CALL(*send_algorithm, SetFromConfig(_, _));
SetFromConfig(config);
// Normally, the pacing would be disabled in the test, but calling
// SetFromConfig enables it. Set nearly-infinite bandwidth to make the
// pacing algorithm work.
EXPECT_CALL(*send_algorithm, PacingRate())
.WillRepeatedly(Return(QuicBandwidth::FromKBytesPerSecond(10000)));
}
TestAlarmFactory::TestAlarm* GetAckAlarm() {
return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
QuicConnectionPeer::GetAckAlarm(this));
}
TestAlarmFactory::TestAlarm* GetPingAlarm() {
return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
QuicConnectionPeer::GetPingAlarm(this));
}
TestAlarmFactory::TestAlarm* GetResumeWritesAlarm() {
return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
QuicConnectionPeer::GetResumeWritesAlarm(this));
}
TestAlarmFactory::TestAlarm* GetRetransmissionAlarm() {
return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
QuicConnectionPeer::GetRetransmissionAlarm(this));
}
TestAlarmFactory::TestAlarm* GetSendAlarm() {
return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
QuicConnectionPeer::GetSendAlarm(this));
}
TestAlarmFactory::TestAlarm* GetTimeoutAlarm() {
return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
QuicConnectionPeer::GetTimeoutAlarm(this));
}
TestAlarmFactory::TestAlarm* GetMtuDiscoveryAlarm() {
return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
QuicConnectionPeer::GetMtuDiscoveryAlarm(this));
}
void DisableTailLossProbe() {
QuicSentPacketManagerPeer::SetMaxTailLossProbes(
QuicConnectionPeer::GetSentPacketManager(this), 0);
}
using QuicConnection::SelectMutualVersion;
using QuicConnection::set_defer_send_in_response_to_packets;
private:
TestPacketWriter* writer() {
return static_cast<TestPacketWriter*>(QuicConnection::writer());
}
DISALLOW_COPY_AND_ASSIGN(TestConnection);
};
enum class AckResponse { kDefer, kImmediate };
// Run tests with combinations of {QuicVersion, AckResponse}.
struct TestParams {
TestParams(QuicVersion version, AckResponse ack_response)
: version(version), ack_response(ack_response) {}
friend ostream& operator<<(ostream& os, const TestParams& p) {
os << "{ client_version: " << QuicVersionToString(p.version)
<< " ack_response: "
<< (p.ack_response == AckResponse::kDefer ? "defer" : "immediate")
<< " }";
return os;
}
QuicVersion version;
AckResponse ack_response;
};
// Constructs various test permutations.
vector<TestParams> GetTestParams() {
vector<TestParams> params;
QuicVersionVector all_supported_versions = QuicSupportedVersions();
for (size_t i = 0; i < all_supported_versions.size(); ++i) {
for (AckResponse ack_response :
{AckResponse::kDefer, AckResponse::kImmediate}) {
params.push_back(TestParams(all_supported_versions[i], ack_response));
}
}
return params;
}
class QuicConnectionTest : public ::testing::TestWithParam<TestParams> {
protected:
QuicConnectionTest()
: connection_id_(42),
framer_(SupportedVersions(version()),
QuicTime::Zero(),
Perspective::IS_CLIENT),
send_algorithm_(new StrictMock<MockSendAlgorithm>),
loss_algorithm_(new MockLossAlgorithm()),
helper_(new TestConnectionHelper(&clock_, &random_generator_)),
alarm_factory_(new TestAlarmFactory()),
peer_framer_(SupportedVersions(version()),
QuicTime::Zero(),
Perspective::IS_SERVER),
peer_creator_(connection_id_,
&peer_framer_,
&random_generator_,
&buffer_allocator_,
/*delegate=*/nullptr),
writer_(new TestPacketWriter(version(), &clock_)),
connection_(connection_id_,
kPeerAddress,
helper_.get(),
alarm_factory_.get(),
writer_.get(),
Perspective::IS_CLIENT,
version()),
creator_(QuicConnectionPeer::GetPacketCreator(&connection_)),
generator_(QuicConnectionPeer::GetPacketGenerator(&connection_)),
manager_(QuicConnectionPeer::GetSentPacketManager(&connection_)),
frame1_(1, false, 0, StringPiece(data1)),
frame2_(1, false, 3, StringPiece(data2)),
packet_number_length_(PACKET_6BYTE_PACKET_NUMBER),
connection_id_length_(PACKET_8BYTE_CONNECTION_ID) {
connection_.set_defer_send_in_response_to_packets(GetParam().ack_response ==
AckResponse::kDefer);
FLAGS_quic_always_log_bugs_for_tests = true;
connection_.set_visitor(&visitor_);
connection_.SetSendAlgorithm(send_algorithm_);
connection_.SetLossAlgorithm(loss_algorithm_);
framer_.set_received_entropy_calculator(&entropy_calculator_);
peer_framer_.set_received_entropy_calculator(&peer_entropy_calculator_);
EXPECT_CALL(*send_algorithm_, TimeUntilSend(_, _))
.WillRepeatedly(Return(QuicTime::Delta::Zero()));
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
.Times(AnyNumber());
EXPECT_CALL(*send_algorithm_, RetransmissionDelay())
.WillRepeatedly(Return(QuicTime::Delta::Zero()));
EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
.WillRepeatedly(Return(kDefaultTCPMSS));
EXPECT_CALL(*send_algorithm_, PacingRate())
.WillRepeatedly(Return(QuicBandwidth::Zero()));
ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
.WillByDefault(Return(true));
EXPECT_CALL(*send_algorithm_, HasReliableBandwidthEstimate())
.Times(AnyNumber());
EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
.Times(AnyNumber())
.WillRepeatedly(Return(QuicBandwidth::Zero()));
EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
EXPECT_CALL(visitor_, WillingAndAbleToWrite()).Times(AnyNumber());
EXPECT_CALL(visitor_, HasPendingHandshake()).Times(AnyNumber());
EXPECT_CALL(visitor_, OnCanWrite()).Times(AnyNumber());
EXPECT_CALL(visitor_, PostProcessAfterData()).Times(AnyNumber());
EXPECT_CALL(visitor_, HasOpenDynamicStreams())
.WillRepeatedly(Return(false));
EXPECT_CALL(visitor_, OnCongestionWindowChange(_)).Times(AnyNumber());
EXPECT_CALL(*loss_algorithm_, GetLossTimeout())
.WillRepeatedly(Return(QuicTime::Zero()));
EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _))
.Times(AnyNumber());
// TODO(ianswett): Fix QuicConnectionTests so they don't attempt to write
// non-crypto stream data at ENCRYPTION_NONE.
FLAGS_quic_never_write_unencrypted_data = false;
}
QuicVersion version() { return GetParam().version; }
QuicAckFrame* outgoing_ack() {
QuicFrame ack_frame = QuicConnectionPeer::GetUpdatedAckFrame(&connection_);
ack_ = *ack_frame.ack_frame;
return &ack_;
}
QuicStopWaitingFrame* stop_waiting() {
QuicConnectionPeer::PopulateStopWaitingFrame(&connection_, &stop_waiting_);
return &stop_waiting_;
}
QuicPacketNumber least_unacked() {
if (writer_->stop_waiting_frames().empty()) {
return 0;
}
return writer_->stop_waiting_frames()[0].least_unacked;
}
void use_tagging_decrypter() { writer_->use_tagging_decrypter(); }
void ProcessPacket(QuicPathId path_id, QuicPacketNumber number) {
EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
ProcessDataPacket(path_id, number, !kEntropyFlag);
if (connection_.GetSendAlarm()->IsSet()) {
connection_.GetSendAlarm()->Fire();
}
}
QuicPacketEntropyHash ProcessFramePacket(QuicFrame frame) {
return ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
}
QuicPacketEntropyHash ProcessFramePacketWithAddresses(
QuicFrame frame,
IPEndPoint self_address,
IPEndPoint peer_address) {
QuicFrames frames;
frames.push_back(QuicFrame(frame));
QuicPacketCreatorPeer::SetSendVersionInPacket(
&peer_creator_, connection_.perspective() == Perspective::IS_SERVER);
char buffer[kMaxPacketSize];
SerializedPacket serialized_packet =
QuicPacketCreatorPeer::SerializeAllFrames(&peer_creator_, frames,
buffer, kMaxPacketSize);
connection_.ProcessUdpPacket(
self_address, peer_address,
QuicReceivedPacket(serialized_packet.encrypted_buffer,
serialized_packet.encrypted_length, clock_.Now()));
if (connection_.GetSendAlarm()->IsSet()) {
connection_.GetSendAlarm()->Fire();
}
return serialized_packet.entropy_hash;
}
QuicPacketEntropyHash ProcessFramePacketAtLevel(QuicPathId path_id,
QuicPacketNumber number,
QuicFrame frame,
EncryptionLevel level) {
QuicPacketHeader header;
header.public_header.connection_id = connection_id_;
header.public_header.packet_number_length = packet_number_length_;
header.public_header.connection_id_length = connection_id_length_;
header.public_header.multipath_flag = path_id != kDefaultPathId;
header.path_id = path_id;
header.packet_number = number;
QuicFrames frames;
frames.push_back(frame);
std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
char buffer[kMaxPacketSize];
size_t encrypted_length = framer_.EncryptPayload(
level, path_id, number, *packet, buffer, kMaxPacketSize);
connection_.ProcessUdpPacket(
kSelfAddress, kPeerAddress,
QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
return base::checked_cast<QuicPacketEntropyHash>(encrypted_length);
}
size_t ProcessDataPacket(QuicPathId path_id,
QuicPacketNumber number,
bool entropy_flag) {
return ProcessDataPacketAtLevel(path_id, number, entropy_flag, false,
ENCRYPTION_NONE);
}
size_t ProcessDataPacketAtLevel(QuicPathId path_id,
QuicPacketNumber number,
bool entropy_flag,
bool has_stop_waiting,
EncryptionLevel level) {
std::unique_ptr<QuicPacket> packet(
ConstructDataPacket(path_id, number, entropy_flag, has_stop_waiting));
char buffer[kMaxPacketSize];
size_t encrypted_length = framer_.EncryptPayload(
level, path_id, number, *packet, buffer, kMaxPacketSize);
connection_.ProcessUdpPacket(
kSelfAddress, kPeerAddress,
QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
if (connection_.GetSendAlarm()->IsSet()) {
connection_.GetSendAlarm()->Fire();
}
return encrypted_length;
}
void ProcessClosePacket(QuicPathId path_id, QuicPacketNumber number) {
std::unique_ptr<QuicPacket> packet(ConstructClosePacket(number));
char buffer[kMaxPacketSize];
size_t encrypted_length = framer_.EncryptPayload(
ENCRYPTION_NONE, path_id, number, *packet, buffer, kMaxPacketSize);
connection_.ProcessUdpPacket(
kSelfAddress, kPeerAddress,
QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
}
QuicByteCount SendStreamDataToPeer(QuicStreamId id,
StringPiece data,
QuicStreamOffset offset,
bool fin,
QuicPacketNumber* last_packet) {
QuicByteCount packet_size;
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
.WillOnce(DoAll(SaveArg<3>(&packet_size), Return(true)));
connection_.SendStreamDataWithString(id, data, offset, fin, nullptr);
if (last_packet != nullptr) {
*last_packet = creator_->packet_number();
}
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
.Times(AnyNumber());
return packet_size;
}
void SendAckPacketToPeer() {
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
connection_.SendAck();
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
.Times(AnyNumber());
}
void ProcessAckPacket(QuicPacketNumber packet_number, QuicAckFrame* frame) {
QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, packet_number - 1);
ProcessFramePacket(QuicFrame(frame));
}
QuicPacketEntropyHash ProcessAckPacket(QuicAckFrame* frame) {
return ProcessFramePacket(QuicFrame(frame));
}
QuicPacketEntropyHash ProcessStopWaitingPacket(QuicStopWaitingFrame* frame) {
return ProcessFramePacket(QuicFrame(frame));
}
QuicPacketEntropyHash ProcessStopWaitingPacketAtLevel(
QuicPathId path_id,
QuicPacketNumber number,
QuicStopWaitingFrame* frame,
EncryptionLevel level) {
return ProcessFramePacketAtLevel(path_id, number, QuicFrame(frame),
ENCRYPTION_INITIAL);
}
QuicPacketEntropyHash ProcessGoAwayPacket(QuicGoAwayFrame* frame) {
return ProcessFramePacket(QuicFrame(frame));
}
QuicPacketEntropyHash ProcessPathClosePacket(QuicPathCloseFrame* frame) {
return ProcessFramePacket(QuicFrame(frame));
}
bool IsMissing(QuicPacketNumber number) {
return IsAwaitingPacket(*outgoing_ack(), number, 0);
}
QuicPacket* ConstructPacket(QuicPacketHeader header, QuicFrames frames) {
QuicPacket* packet = BuildUnsizedDataPacket(&peer_framer_, header, frames);
EXPECT_NE(nullptr, packet);
return packet;
}
QuicPacket* ConstructDataPacket(QuicPathId path_id,
QuicPacketNumber number,
bool entropy_flag,
bool has_stop_waiting) {
QuicPacketHeader header;
header.public_header.connection_id = connection_id_;
header.public_header.packet_number_length = packet_number_length_;
header.public_header.connection_id_length = connection_id_length_;
header.public_header.multipath_flag = path_id != kDefaultPathId;
header.entropy_flag = entropy_flag;
header.path_id = path_id;
header.packet_number = number;
QuicFrames frames;
frames.push_back(QuicFrame(&frame1_));
if (has_stop_waiting) {
frames.push_back(QuicFrame(&stop_waiting_));
}
return ConstructPacket(header, frames);
}
QuicPacket* ConstructClosePacket(QuicPacketNumber number) {
QuicPacketHeader header;
header.public_header.connection_id = connection_id_;
header.packet_number = number;
QuicConnectionCloseFrame qccf;
qccf.error_code = QUIC_PEER_GOING_AWAY;
QuicFrames frames;
frames.push_back(QuicFrame(&qccf));
return ConstructPacket(header, frames);
}
QuicTime::Delta DefaultRetransmissionTime() {
return QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
}
QuicTime::Delta DefaultDelayedAckTime() {
return QuicTime::Delta::FromMilliseconds(kMaxDelayedAckTimeMs);
}
// Initialize a frame acknowledging all packets up to largest_observed.
const QuicAckFrame InitAckFrame(QuicPacketNumber largest_observed) {
QuicAckFrame frame(MakeAckFrame(largest_observed));
if (GetParam().version <= QUIC_VERSION_33) {
if (largest_observed > 0) {
frame.entropy_hash = QuicConnectionPeer::GetSentEntropyHash(
&connection_, largest_observed);
}
} else {
frame.missing = false;
if (largest_observed > 0) {
frame.packets.Add(1, largest_observed + 1);
}
}
return frame;
}
const QuicStopWaitingFrame InitStopWaitingFrame(
QuicPacketNumber least_unacked) {
QuicStopWaitingFrame frame;
frame.least_unacked = least_unacked;
return frame;
}
// Explicitly nack a packet.
void NackPacket(QuicPacketNumber missing, QuicAckFrame* frame) {
if (frame->missing) {
frame->packets.Add(missing);
frame->entropy_hash ^=
QuicConnectionPeer::PacketEntropy(&connection_, missing);
} else {
frame->packets.Remove(missing);
}
}
// Undo nacking a packet within the frame.
void AckPacket(QuicPacketNumber arrived, QuicAckFrame* frame) {
if (frame->missing) {
EXPECT_TRUE(frame->packets.Contains(arrived));
frame->packets.Remove(arrived);
frame->entropy_hash ^=
QuicConnectionPeer::PacketEntropy(&connection_, arrived);
} else {
EXPECT_FALSE(frame->packets.Contains(arrived));
frame->packets.Add(arrived);
}
}
void TriggerConnectionClose() {
// Send an erroneous packet to close the connection.
EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_PACKET_HEADER, _,
ConnectionCloseSource::FROM_SELF));
// Call ProcessDataPacket rather than ProcessPacket, as we should not get a
// packet call to the visitor.
ProcessDataPacket(kDefaultPathId, 6000, !kEntropyFlag);
EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
nullptr);
}
void BlockOnNextWrite() {
writer_->BlockOnNextWrite();
EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
}
void SetWritePauseTimeDelta(QuicTime::Delta delta) {
writer_->SetWritePauseTimeDelta(delta);
}
void CongestionBlockWrites() {
EXPECT_CALL(*send_algorithm_, TimeUntilSend(_, _))
.WillRepeatedly(testing::Return(QuicTime::Delta::FromSeconds(1)));
}
void CongestionUnblockWrites() {
EXPECT_CALL(*send_algorithm_, TimeUntilSend(_, _))
.WillRepeatedly(testing::Return(QuicTime::Delta::Zero()));
}
void set_perspective(Perspective perspective) {
connection_.set_perspective(perspective);
QuicFramerPeer::SetPerspective(&peer_framer_,
InvertPerspective(perspective));
}
QuicConnectionId connection_id_;
QuicFramer framer_;
MockEntropyCalculator entropy_calculator_;
MockEntropyCalculator peer_entropy_calculator_;
MockSendAlgorithm* send_algorithm_;
MockLossAlgorithm* loss_algorithm_;
MockClock clock_;
MockRandom random_generator_;
SimpleBufferAllocator buffer_allocator_;
std::unique_ptr<TestConnectionHelper> helper_;
std::unique_ptr<TestAlarmFactory> alarm_factory_;
QuicFramer peer_framer_;
QuicPacketCreator peer_creator_;
std::unique_ptr<TestPacketWriter> writer_;
TestConnection connection_;
QuicPacketCreator* creator_;
QuicPacketGenerator* generator_;
QuicSentPacketManager* manager_;
StrictMock<MockQuicConnectionVisitor> visitor_;
QuicStreamFrame frame1_;
QuicStreamFrame frame2_;
QuicAckFrame ack_;
QuicStopWaitingFrame stop_waiting_;
QuicPacketNumberLength packet_number_length_;
QuicConnectionIdLength connection_id_length_;
private:
DISALLOW_COPY_AND_ASSIGN(QuicConnectionTest);
};
// Run all end to end tests with all supported versions.
INSTANTIATE_TEST_CASE_P(SupportedVersion,
QuicConnectionTest,
::testing::ValuesIn(GetTestParams()));
TEST_P(QuicConnectionTest, SelfAddressChangeAtClient) {
EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
EXPECT_TRUE(connection_.connected());
QuicStreamFrame stream_frame(1u, false, 0u, StringPiece());
EXPECT_CALL(visitor_, OnStreamFrame(_));
ProcessFramePacketWithAddresses(QuicFrame(&stream_frame), kSelfAddress,
kPeerAddress);
// Cause change in self_address.
IPEndPoint self_address(IPAddress(1, 1, 1, 1), 123);
EXPECT_CALL(visitor_, OnStreamFrame(_));
ProcessFramePacketWithAddresses(QuicFrame(&stream_frame), self_address,
kPeerAddress);
EXPECT_TRUE(connection_.connected());
}
TEST_P(QuicConnectionTest, SelfAddressChangeAtServer) {
EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
set_perspective(Perspective::IS_SERVER);
QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
EXPECT_TRUE(connection_.connected());
QuicStreamFrame stream_frame(1u, false, 0u, StringPiece());
EXPECT_CALL(visitor_, OnStreamFrame(_));
ProcessFramePacketWithAddresses(QuicFrame(&stream_frame), kSelfAddress,
kPeerAddress);
// Cause change in self_address.
IPEndPoint self_address(IPAddress(1, 1, 1, 1), 123);
EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_ERROR_MIGRATING_ADDRESS, _, _));
ProcessFramePacketWithAddresses(QuicFrame(&stream_frame), self_address,
kPeerAddress);
EXPECT_FALSE(connection_.connected());
}
TEST_P(QuicConnectionTest, MaxPacketSize) {
EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
EXPECT_EQ(1350u, connection_.max_packet_length());
}
TEST_P(QuicConnectionTest, SmallerServerMaxPacketSize) {
QuicConnectionId connection_id = 42;
TestConnection connection(connection_id, kPeerAddress, helper_.get(),
alarm_factory_.get(), writer_.get(),
Perspective::IS_SERVER, version());
EXPECT_EQ(Perspective::IS_SERVER, connection.perspective());
EXPECT_EQ(1000u, connection.max_packet_length());
}
TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSize) {
EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
set_perspective(Perspective::IS_SERVER);
connection_.SetMaxPacketLength(1000);
QuicPacketHeader header;
header.public_header.connection_id = connection_id_;
header.public_header.version_flag = true;
header.path_id = kDefaultPathId;
header.packet_number = 1;
QuicFrames frames;
QuicPaddingFrame padding;
frames.push_back(QuicFrame(&frame1_));
frames.push_back(QuicFrame(padding));
std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
char buffer[kMaxPacketSize];
size_t encrypted_length = framer_.EncryptPayload(
ENCRYPTION_NONE, kDefaultPathId, 12, *packet, buffer, kMaxPacketSize);
EXPECT_EQ(kMaxPacketSize, encrypted_length);
framer_.set_version(version());
EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
connection_.ProcessUdpPacket(
kSelfAddress, kPeerAddress,
QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
EXPECT_EQ(kMaxPacketSize, connection_.max_packet_length());
}
TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSizeWhileWriterLimited) {
EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
const QuicByteCount lower_max_packet_size = 1240;
writer_->set_max_packet_size(lower_max_packet_size);
set_perspective(Perspective::IS_SERVER);
connection_.SetMaxPacketLength(1000);
EXPECT_EQ(1000u, connection_.max_packet_length());
QuicPacketHeader header;
header.public_header.connection_id = connection_id_;
header.public_header.version_flag = true;
header.path_id = kDefaultPathId;
header.packet_number = 1;
QuicFrames frames;
QuicPaddingFrame padding;
frames.push_back(QuicFrame(&frame1_));
frames.push_back(QuicFrame(padding));
std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
char buffer[kMaxPacketSize];
size_t encrypted_length = framer_.EncryptPayload(
ENCRYPTION_NONE, kDefaultPathId, 12, *packet, buffer, kMaxPacketSize);
EXPECT_EQ(kMaxPacketSize, encrypted_length);
framer_.set_version(version());
EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
connection_.ProcessUdpPacket(
kSelfAddress, kPeerAddress,
QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
// Here, the limit imposed by the writer is lower than the size of the packet
// received, so the writer max packet size is used.
EXPECT_EQ(lower_max_packet_size, connection_.max_packet_length());
}
TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriter) {
const QuicByteCount lower_max_packet_size = 1240;
writer_->set_max_packet_size(lower_max_packet_size);
static_assert(lower_max_packet_size < kDefaultMaxPacketSize,
"Default maximum packet size is too low");
connection_.SetMaxPacketLength(kDefaultMaxPacketSize);
EXPECT_EQ(lower_max_packet_size, connection_.max_packet_length());
}
TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriterForNewConnection) {
const QuicConnectionId connection_id = 17;
const QuicByteCount lower_max_packet_size = 1240;
writer_->set_max_packet_size(lower_max_packet_size);
TestConnection connection(connection_id, kPeerAddress, helper_.get(),
alarm_factory_.get(), writer_.get(),
Perspective::IS_CLIENT, version());
EXPECT_EQ(Perspective::IS_CLIENT, connection.perspective());
EXPECT_EQ(lower_max_packet_size, connection.max_packet_length());
}
TEST_P(QuicConnectionTest, PacketsInOrder) {
EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
ProcessPacket(kDefaultPathId, 1);
EXPECT_EQ(1u, outgoing_ack()->largest_observed);
if (outgoing_ack()->missing) {
EXPECT_TRUE(outgoing_ack()->packets.Empty());
} else {
EXPECT_EQ(1u, outgoing_ack()->packets.NumIntervals());
}
ProcessPacket(kDefaultPathId, 2);
EXPECT_EQ(2u, outgoing_ack()->largest_observed);
if (outgoing_ack()->missing) {
EXPECT_TRUE(outgoing_ack()->packets.Empty());
} else {
EXPECT_EQ(1u, outgoing_ack()->packets.NumIntervals());
}
ProcessPacket(kDefaultPathId, 3);
EXPECT_EQ(3u, outgoing_ack()->largest_observed);
if (outgoing_ack()->missing) {
EXPECT_TRUE(outgoing_ack()->packets.Empty());
} else {
EXPECT_EQ(1u, outgoing_ack()->packets.NumIntervals());
}
}
TEST_P(QuicConnectionTest, PacketsOutOfOrder) {
EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
ProcessPacket(kDefaultPathId, 3);
EXPECT_EQ(3u, outgoing_ack()->largest_observed);
EXPECT_TRUE(IsMissing(2));
EXPECT_TRUE(IsMissing(1));
ProcessPacket(kDefaultPathId, 2);
EXPECT_EQ(3u, outgoing_ack()->largest_observed);
EXPECT_FALSE(IsMissing(2));
EXPECT_TRUE(IsMissing(1));
ProcessPacket(kDefaultPathId, 1);
EXPECT_EQ(3u, outgoing_ack()->largest_observed);
EXPECT_FALSE(IsMissing(2));
EXPECT_FALSE(IsMissing(1));
}
TEST_P(QuicConnectionTest, DuplicatePacket) {
EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
ProcessPacket(kDefaultPathId, 3);
EXPECT_EQ(3u, outgoing_ack()->largest_observed);
EXPECT_TRUE(IsMissing(2));
EXPECT_TRUE(IsMissing(1));
// Send packet 3 again, but do not set the expectation that
// the visitor OnStreamFrame() will be called.
ProcessDataPacket(kDefaultPathId, 3, !kEntropyFlag);
EXPECT_EQ(3u, outgoing_ack()->largest_observed);
EXPECT_TRUE(IsMissing(2));
EXPECT_TRUE(IsMissing(1));
}
TEST_P(QuicConnectionTest, PacketsOutOfOrderWithAdditionsAndLeastAwaiting) {
EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
ProcessPacket(kDefaultPathId, 3);
EXPECT_EQ(3u, outgoing_ack()->largest_observed);
EXPECT_TRUE(IsMissing(2));
EXPECT_TRUE(IsMissing(1));
ProcessPacket(kDefaultPathId, 2);
EXPECT_EQ(3u, outgoing_ack()->largest_observed);
EXPECT_TRUE(IsMissing(1));
ProcessPacket(kDefaultPathId, 5);
EXPECT_EQ(5u, outgoing_ack()->largest_observed);
EXPECT_TRUE(IsMissing(1));
EXPECT_TRUE(IsMissing(4));
// Pretend at this point the client has gotten acks for 2 and 3 and 1 is a
// packet the peer will not retransmit. It indicates this by sending 'least
// awaiting' is 4. The connection should then realize 1 will not be
// retransmitted, and will remove it from the missing list.
QuicAckFrame frame = InitAckFrame(1);
EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _));
ProcessAckPacket(6, &frame);
// Force an ack to be sent.
SendAckPacketToPeer();
EXPECT_TRUE(IsMissing(4));
}
TEST_P(QuicConnectionTest, RejectPacketTooFarOut) {
EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_PACKET_HEADER, _,
ConnectionCloseSource::FROM_SELF));
// Call ProcessDataPacket rather than ProcessPacket, as we should not get a
// packet call to the visitor.
ProcessDataPacket(kDefaultPathId, 6000, !kEntropyFlag);
EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
nullptr);
}
TEST_P(QuicConnectionTest, RejectUnencryptedStreamData) {
// Process an unencrypted packet from the non-crypto stream.
frame1_.stream_id = 3;
EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_UNENCRYPTED_STREAM_DATA, _,
ConnectionCloseSource::FROM_SELF));
EXPECT_DFATAL(ProcessDataPacket(kDefaultPathId, 1, !kEntropyFlag), "");
EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
nullptr);
const vector<QuicConnectionCloseFrame>& connection_close_frames =
writer_->connection_close_frames();
EXPECT_EQ(1u, connection_close_frames.size());
EXPECT_EQ(QUIC_UNENCRYPTED_STREAM_DATA,
connection_close_frames[0].error_code);
}
TEST_P(QuicConnectionTest, TruncatedAck) {
if (GetParam().version > QUIC_VERSION_33) {
return;
}
EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
QuicPacketNumber num_packets = 256 * 2 + 1;
for (QuicPacketNumber i = 0; i < num_packets; ++i) {
SendStreamDataToPeer(3, "foo", i * 3, !kFin, nullptr);
}
QuicAckFrame frame = InitAckFrame(num_packets);
PacketNumberSet lost_packets;
// Create an ack with 256 nacks, none adjacent to one another.
for (QuicPacketNumber i = 1; i <= 256; ++i) {
NackPacket(i * 2, &frame);
if (i < 256) { // Last packet is nacked, but not lost.
lost_packets.insert(i * 2);
}
}
EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _));
EXPECT_CALL(peer_entropy_calculator_, EntropyHash(511))
.WillOnce(Return(static_cast<QuicPacketEntropyHash>(0)));
EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
ProcessAckPacket(&frame);
// A truncated ack will not have the true largest observed.
EXPECT_GT(num_packets, manager_->GetLargestObserved(frame.path_id));
AckPacket(192, &frame);
// Removing one missing packet allows us to ack 192 and one more range, but
// 192 has already been declared lost, so it doesn't register as an ack.
EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _));
EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
ProcessAckPacket(&frame);
EXPECT_EQ(num_packets, manager_->GetLargestObserved(frame.path_id));
}
TEST_P(QuicConnectionTest, AckReceiptCausesAckSendBadEntropy) {
EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
ProcessPacket(kDefaultPathId, 1);
// Delay sending, then queue up an ack.
QuicConnectionPeer::SendAck(&connection_);
// Process an ack with a least unacked of the received ack.
// This causes an ack to be sent when TimeUntilSend returns 0.
EXPECT_CALL(*send_algorithm_, TimeUntilSend(_, _))
.WillRepeatedly(testing::Return(QuicTime::Delta::Zero()));
// Skip a packet and then record an ack.
QuicAckFrame frame = InitAckFrame(0);
ProcessAckPacket(3, &frame);
}
TEST_P(QuicConnectionTest, OutOfOrderReceiptCausesAckSend) {
EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
ProcessPacket(kDefaultPathId, 3);
// Should ack immediately since we have missing packets.
EXPECT_EQ(1u, writer_->packets_write_attempts());
ProcessPacket(kDefaultPathId, 2);
// Should ack immediately since we have missing packets.
EXPECT_EQ(2u, writer_->packets_write_attempts());
ProcessPacket(kDefaultPathId, 1);
// Should ack immediately, since this fills the last hole.
EXPECT_EQ(3u, writer_->packets_write_attempts());
ProcessPacket(kDefaultPathId, 4);
// Should not cause an ack.
EXPECT_EQ(3u, writer_->packets_write_attempts());
}
TEST_P(QuicConnectionTest, OutOfOrderAckReceiptCausesNoAck) {
EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr);
SendStreamDataToPeer(1, "bar", 3, !kFin, nullptr);
EXPECT_EQ(2u, writer_->packets_write_attempts());
QuicAckFrame ack1 = InitAckFrame(1);
QuicAckFrame ack2 = InitAckFrame(2);
EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
ProcessAckPacket(2, &ack2);
// Should ack immediately since we have missing packets.
EXPECT_EQ(2u, writer_->packets_write_attempts());
ProcessAckPacket(1, &ack1);
// Should not ack an ack filling a missing packet.
EXPECT_EQ(2u, writer_->packets_write_attempts());
}
TEST_P(QuicConnectionTest, AckReceiptCausesAckSend) {
EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
QuicPacketNumber original;
QuicByteCount packet_size;
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
.WillOnce(
DoAll(SaveArg<2>(&original), SaveArg<3>(&packet_size), Return(true)));
connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
QuicAckFrame frame = InitAckFrame(original);
NackPacket(original, &frame);
// First nack triggers early retransmit.
SendAlgorithmInterface::CongestionVector lost_packets;
lost_packets.push_back(std::make_pair(1, kMaxPacketSize));
EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _))
.WillOnce(SetArgPointee<4>(lost_packets));
EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
QuicPacketNumber retransmission;
EXPECT_CALL(*send_algorithm_,
OnPacketSent(_, _, _, packet_size - kQuicVersionSize, _))
.WillOnce(DoAll(SaveArg<2>(&retransmission), Return(true)));
ProcessAckPacket(&frame);
QuicAckFrame frame2 = InitAckFrame(retransmission);
NackPacket(original, &frame2);
EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _));
ProcessAckPacket(&frame2);
// Now if the peer sends an ack which still reports the retransmitted packet
// as missing, that will bundle an ack with data after two acks in a row
// indicate the high water mark needs to be raised.
EXPECT_CALL(*send_algorithm_,
OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA));
connection_.SendStreamDataWithString(3, "foo", 3, !kFin, nullptr);
// No ack sent.
EXPECT_EQ(1u, writer_->frame_count());
EXPECT_EQ(1u, writer_->stream_frames().size());
// No more packet loss for the rest of the test.
EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _)).Times(AnyNumber());
ProcessAckPacket(&frame2);
EXPECT_CALL(*send_algorithm_,
OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA));
connection_.SendStreamDataWithString(3, "foo", 3, !kFin, nullptr);
// Ack bundled.
EXPECT_EQ(3u, writer_->frame_count());
EXPECT_EQ(1u, writer_->stream_frames().size());
EXPECT_FALSE(writer_->ack_frames().empty());
// But an ack with no missing packets will not send an ack.
AckPacket(original, &frame2);
ProcessAckPacket(&frame2);
ProcessAckPacket(&frame2);
}
TEST_P(QuicConnectionTest, 20AcksCausesAckSend) {
EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr);
QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
// But an ack with no missing packets will not send an ack.
QuicAckFrame frame = InitAckFrame(1);
EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
for (int i = 0; i < 19; ++i) {
ProcessAckPacket(&frame);
EXPECT_FALSE(ack_alarm->IsSet());
}
EXPECT_EQ(1u, writer_->packets_write_attempts());
// The 20th ack packet will cause an ack to be sent.
ProcessAckPacket(&frame);
EXPECT_EQ(2u, writer_->packets_write_attempts());
}
TEST_P(QuicConnectionTest, LeastUnackedLower) {
EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr);
SendStreamDataToPeer(1, "bar", 3, !kFin, nullptr);
SendStreamDataToPeer(1, "eep", 6, !kFin, nullptr);
// Start out saying the least unacked is 2.
QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
QuicStopWaitingFrame frame = InitStopWaitingFrame(2);
ProcessStopWaitingPacket(&frame);
// Change it to 1, but lower the packet number to fake out-of-order packets.
// This should be fine.
QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 1);
// The scheduler will not process out of order acks, but all packet processing
// causes the connection to try to write.
EXPECT_CALL(visitor_, OnCanWrite());
QuicStopWaitingFrame frame2 = InitStopWaitingFrame(1);
ProcessStopWaitingPacket(&frame2);
// Now claim it's one, but set the ordering so it was sent "after" the first
// one. This should cause a connection error.
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 7);
EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_STOP_WAITING_DATA, _,
ConnectionCloseSource::FROM_SELF));
QuicStopWaitingFrame frame3 = InitStopWaitingFrame(1);
ProcessStopWaitingPacket(&frame3);
}
TEST_P(QuicConnectionTest, TooManySentPackets) {
EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
const int num_packets = kMaxTrackedPackets + 100;
for (int i = 0; i < num_packets; ++i) {
SendStreamDataToPeer(1, "foo", 3 * i, !kFin, nullptr);
}
// Ack packet 1, which leaves more than the limit outstanding.
EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
if (GetParam().version <= QUIC_VERSION_33) {
EXPECT_CALL(visitor_,
OnConnectionClosed(QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS, _,
ConnectionCloseSource::FROM_SELF));
// We're receive buffer limited, so the connection won't try to write more.
EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
}
// Nack the first packet and ack the rest, leaving a huge gap.
QuicAckFrame frame1 = InitAckFrame(num_packets);
NackPacket(1, &frame1);
ProcessAckPacket(&frame1);
}
TEST_P(QuicConnectionTest, TooManyReceivedPackets) {
EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
if (GetParam().version <= QUIC_VERSION_33) {
EXPECT_CALL(visitor_,
OnConnectionClosed(QUIC_TOO_MANY_OUTSTANDING_RECEIVED_PACKETS,
_, ConnectionCloseSource::FROM_SELF));
}
// Miss 99 of every 100 packets for 5500 packets.
for (QuicPacketNumber i = 1; i < kMaxTrackedPackets + 500; i += 100) {
ProcessPacket(kDefaultPathId, i);
if (!connection_.connected()) {
break;
}
}
}
TEST_P(QuicConnectionTest, LargestObservedLower) {
EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr);
SendStreamDataToPeer(1, "bar", 3, !kFin, nullptr);
SendStreamDataToPeer(1, "eep", 6, !kFin, nullptr);
EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
// Start out saying the largest observed is 2.
QuicAckFrame frame1 = InitAckFrame(1);
QuicAckFrame frame2 = InitAckFrame(2);
ProcessAckPacket(&frame2);
// Now change it to 1, and it should cause a connection error.
EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, _,
ConnectionCloseSource::FROM_SELF));
EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
ProcessAckPacket(&frame1);
}
TEST_P(QuicConnectionTest, AckUnsentData) {
// Ack a packet which has not been sent.
EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, _,
ConnectionCloseSource::FROM_SELF));
EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
QuicAckFrame frame(MakeAckFrame(1));
EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
ProcessAckPacket(&frame);
}
TEST_P(QuicConnectionTest, AckAll) {
EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
ProcessPacket(kDefaultPathId, 1);
QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 1);
QuicAckFrame frame1 = InitAckFrame(0);
ProcessAckPacket(&frame1);
}
TEST_P(QuicConnectionTest, SendingDifferentSequenceNumberLengthsBandwidth) {
QuicPacketNumber last_packet;
SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet);
EXPECT_EQ(1u, last_packet);
EXPECT_EQ(PACKET_1BYTE_PACKET_NUMBER,
QuicPacketCreatorPeer::NextPacketNumberLength(creator_));
EXPECT_EQ(PACKET_1BYTE_PACKET_NUMBER,
writer_->header().public_header.packet_number_length);
EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
.WillRepeatedly(Return(kMaxPacketSize * 256));
SendStreamDataToPeer(1, "bar", 3, !kFin, &last_packet);
EXPECT_EQ(2u, last_packet);
EXPECT_EQ(PACKET_2BYTE_PACKET_NUMBER,
QuicPacketCreatorPeer::NextPacketNumberLength(creator_));
// The 1 packet lag is due to the packet number length being recalculated in
// QuicConnection after a packet is sent.
EXPECT_EQ(PACKET_1BYTE_PACKET_NUMBER,
writer_->header().public_header.packet_number_length);
EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
.WillRepeatedly(Return(kMaxPacketSize * 256 * 256));
SendStreamDataToPeer(1, "foo", 6, !kFin, &last_packet);
EXPECT_EQ(3u, last_packet);
EXPECT_EQ(PACKET_4BYTE_PACKET_NUMBER,
QuicPacketCreatorPeer::NextPacketNumberLength(creator_));
EXPECT_EQ(PACKET_2BYTE_PACKET_NUMBER,
writer_->header().public_header.packet_number_length);
EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
.WillRepeatedly(Return(kMaxPacketSize * 256 * 256 * 256));
SendStreamDataToPeer(1, "bar", 9, !kFin, &last_packet);
EXPECT_EQ(4u, last_packet);
EXPECT_EQ(PACKET_4BYTE_PACKET_NUMBER,
QuicPacketCreatorPeer::NextPacketNumberLength(creator_));
EXPECT_EQ(PACKET_4BYTE_PACKET_NUMBER,
writer_->header().public_header.packet_number_length);
EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
.WillRepeatedly(Return(kMaxPacketSize * 256 * 256 * 256 * 256));
SendStreamDataToPeer(1, "foo", 12, !kFin, &last_packet);
EXPECT_EQ(5u, last_packet);
EXPECT_EQ(PACKET_6BYTE_PACKET_NUMBER,
QuicPacketCreatorPeer::NextPacketNumberLength(creator_));
EXPECT_EQ(PACKET_4BYTE_PACKET_NUMBER,
writer_->header().public_header.packet_number_length);
}
// TODO(ianswett): Re-enable this test by finding a good way to test different
// packet number lengths without sending packets with giant gaps.
TEST_P(QuicConnectionTest,
DISABLED_SendingDifferentSequenceNumberLengthsUnackedDelta) {
QuicPacketNumber last_packet;
SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet);
EXPECT_EQ(1u, last_packet);
EXPECT_EQ(PACKET_1BYTE_PACKET_NUMBER,
QuicPacketCreatorPeer::NextPacketNumberLength(creator_));
EXPECT_EQ(PACKET_1BYTE_PACKET_NUMBER,
writer_->header().public_header.packet_number_length);
QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 100);
SendStreamDataToPeer(1, "bar", 3, !kFin, &last_packet);
EXPECT_EQ(PACKET_2BYTE_PACKET_NUMBER,
QuicPacketCreatorPeer::NextPacketNumberLength(creator_));
EXPECT_EQ(PACKET_1BYTE_PACKET_NUMBER,
writer_->header().public_header.packet_number_length);
QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 100 * 256);
SendStreamDataToPeer(1, "foo", 6, !kFin, &last_packet);
EXPECT_EQ(PACKET_4BYTE_PACKET_NUMBER,
QuicPacketCreatorPeer::NextPacketNumberLength(creator_));
EXPECT_EQ(PACKET_2BYTE_PACKET_NUMBER,
writer_->header().public_header.packet_number_length);
QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 100 * 256 * 256);
SendStreamDataToPeer(1, "bar", 9, !kFin, &last_packet);
EXPECT_EQ(PACKET_4BYTE_PACKET_NUMBER,
QuicPacketCreatorPeer::NextPacketNumberLength(creator_));
EXPECT_EQ(PACKET_4BYTE_PACKET_NUMBER,
writer_->header().public_header.packet_number_length);
QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 100 * 256 * 256 * 256);
SendStreamDataToPeer(1, "foo", 12, !kFin, &last_packet);
EXPECT_EQ(PACKET_6BYTE_PACKET_NUMBER,
QuicPacketCreatorPeer::NextPacketNumberLength(creator_));
EXPECT_EQ(PACKET_4BYTE_PACKET_NUMBER,
writer_->header().public_header.packet_number_length);
}
TEST_P(QuicConnectionTest, BasicSending) {
EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
QuicPacketNumber last_packet;
SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet); // Packet 1
EXPECT_EQ(1u, last_packet);
SendAckPacketToPeer(); // Packet 2
EXPECT_EQ(1u, least_unacked());
SendAckPacketToPeer(); // Packet 3
EXPECT_EQ(1u, least_unacked());
SendStreamDataToPeer(1, "bar", 3, !kFin, &last_packet); // Packet 4
EXPECT_EQ(4u, last_packet);
SendAckPacketToPeer(); // Packet 5
EXPECT_EQ(1u, least_unacked());
EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
// Peer acks up to packet 3.
QuicAckFrame frame = InitAckFrame(3);
ProcessAckPacket(&frame);
SendAckPacketToPeer(); // Packet 6
// As soon as we've acked one, we skip ack packets 2 and 3 and note lack of
// ack for 4.
EXPECT_EQ(4u, least_unacked());
EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
// Peer acks up to packet 4, the last packet.
QuicAckFrame frame2 = InitAckFrame(6);
ProcessAckPacket(&frame2); // Acks don't instigate acks.
// Verify that we did not send an ack.
EXPECT_EQ(6u, writer_->header().packet_number);
// So the last ack has not changed.
EXPECT_EQ(4u, least_unacked());
// If we force an ack, we shouldn't change our retransmit state.
SendAckPacketToPeer(); // Packet 7
EXPECT_EQ(7u, least_unacked());
// But if we send more data it should.
SendStreamDataToPeer(1, "eep", 6, !kFin, &last_packet); // Packet 8
EXPECT_EQ(8u, last_packet);
SendAckPacketToPeer(); // Packet 9
EXPECT_EQ(7u, least_unacked());
}
// QuicConnection should record the the packet sent-time prior to sending the
// packet.
TEST_P(QuicConnectionTest, RecordSentTimeBeforePacketSent) {
// We're using a MockClock for the tests, so we have complete control over the
// time.
// Our recorded timestamp for the last packet sent time will be passed in to
// the send_algorithm. Make sure that it is set to the correct value.
QuicTime actual_recorded_send_time = QuicTime::Zero();
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
.WillOnce(DoAll(SaveArg<0>(&actual_recorded_send_time), Return(true)));
// First send without any pause and check the result.
QuicTime expected_recorded_send_time = clock_.Now();
connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
<< "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
<< ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
// Now pause during the write, and check the results.
actual_recorded_send_time = QuicTime::Zero();
const QuicTime::Delta write_pause_time_delta =
QuicTime::Delta::FromMilliseconds(5000);
SetWritePauseTimeDelta(write_pause_time_delta);
expected_recorded_send_time = clock_.Now();
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
.WillOnce(DoAll(SaveArg<0>(&actual_recorded_send_time), Return(true)));
connection_.SendStreamDataWithString(2, "baz", 0, !kFin, nullptr);
EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
<< "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
<< ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
}
TEST_P(QuicConnectionTest, FramePacking) {
// Send an ack and two stream frames in 1 packet by queueing them.
{
QuicConnection::ScopedPacketBundler bundler(&connection_,
QuicConnection::SEND_ACK);
connection_.SendStreamData3();
connection_.SendStreamData5();
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
}
EXPECT_EQ(0u, connection_.NumQueuedPackets());
EXPECT_FALSE(connection_.HasQueuedData());
// Parse the last packet and ensure it's an ack and two stream frames from
// two different streams.
EXPECT_EQ(4u, writer_->frame_count());
EXPECT_FALSE(writer_->stop_waiting_frames().empty());
EXPECT_FALSE(writer_->ack_frames().empty());
ASSERT_EQ(2u, writer_->stream_frames().size());
EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0]->stream_id);
EXPECT_EQ(kClientDataStreamId2, writer_->stream_frames()[1]->stream_id);
}
TEST_P(QuicConnectionTest, FramePackingNonCryptoThenCrypto) {
// Send an ack and two stream frames (one non-crypto, then one crypto) in 2
// packets by queueing them.
{
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
QuicConnection::ScopedPacketBundler bundler(&connection_,
QuicConnection::SEND_ACK);
connection_.SendStreamData3();
connection_.SendCryptoStreamData();
}
EXPECT_EQ(0u, connection_.NumQueuedPackets());
EXPECT_FALSE(connection_.HasQueuedData());
// Parse the last packet and ensure it's the crypto stream frame.
EXPECT_EQ(1u, writer_->frame_count());
ASSERT_EQ(1u, writer_->stream_frames().size());
EXPECT_EQ(kCryptoStreamId, writer_->stream_frames()[0]->stream_id);
}
TEST_P(QuicConnectionTest, FramePackingCryptoThenNonCrypto) {
// Send an ack and two stream frames (one crypto, then one non-crypto) in 2
// packets by queueing them.
{
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
QuicConnection::ScopedPacketBundler bundler(&connection_,
QuicConnection::SEND_ACK);
connection_.SendCryptoStreamData();
connection_.SendStreamData3();
}
EXPECT_EQ(0u, connection_.NumQueuedPackets());
EXPECT_FALSE(connection_.HasQueuedData());
// Parse the last packet and ensure it's the stream frame from stream 3.
EXPECT_EQ(1u, writer_->frame_count());
ASSERT_EQ(1u, writer_->stream_frames().size());
EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0]->stream_id);
}
TEST_P(QuicConnectionTest, FramePackingAckResponse) {
EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
// Process a data packet to queue up a pending ack.
EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
ProcessDataPacket(kDefaultPathId, 1, kEntropyFlag);
EXPECT_CALL(visitor_, OnCanWrite())
.WillOnce(DoAll(IgnoreResult(InvokeWithoutArgs(
&connection_, &TestConnection::SendStreamData3)),
IgnoreResult(InvokeWithoutArgs(
&connection_, &TestConnection::SendStreamData5))));
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
// Process an ack to cause the visitor's OnCanWrite to be invoked.
QuicAckFrame ack_one = InitAckFrame(0);
ProcessAckPacket(3, &ack_one);
EXPECT_EQ(0u, connection_.NumQueuedPackets());
EXPECT_FALSE(connection_.HasQueuedData());
// Parse the last packet and ensure it's an ack and two stream frames from
// two different streams.
EXPECT_EQ(4u, writer_->frame_count());
EXPECT_FALSE(writer_->stop_waiting_frames().empty());
EXPECT_FALSE(writer_->ack_frames().empty());
ASSERT_EQ(2u, writer_->stream_frames().size());
EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0]->stream_id);
EXPECT_EQ(kClientDataStreamId2, writer_->stream_frames()[1]->stream_id);
}
TEST_P(QuicConnectionTest, FramePackingSendv) {
// Send data in 1 packet by writing multiple blocks in a single iovector
// using writev.
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
char data[] = "ABCD";
struct iovec iov[2];
iov[0].iov_base = data;
iov[0].iov_len = 2;
iov[1].iov_base = data + 2;
iov[1].iov_len = 2;
connection_.SendStreamData(1, QuicIOVector(iov, 2, 4), 0, !kFin, nullptr);
EXPECT_EQ(0u, connection_.NumQueuedPackets());
EXPECT_FALSE(connection_.HasQueuedData());
// Parse the last packet and ensure multiple iovector blocks have
// been packed into a single stream frame from one stream.
EXPECT_EQ(1u, writer_->frame_count());
EXPECT_EQ(1u, writer_->stream_frames().size());
QuicStreamFrame* frame = writer_->stream_frames()[0];
EXPECT_EQ(1u, frame->stream_id);
EXPECT_EQ("ABCD", StringPiece(frame->data_buffer, frame->data_length));
}
TEST_P(QuicConnectionTest, FramePackingSendvQueued) {
// Try to send two stream frames in 1 packet by using writev.
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
BlockOnNextWrite();
char data[] = "ABCD";
struct iovec iov[2];
iov[0].iov_base = data;
iov[0].iov_len = 2;
iov[1].iov_base = data + 2;
iov[1].iov_len = 2;
connection_.SendStreamData(1, QuicIOVector(iov, 2, 4), 0, !kFin, nullptr);
EXPECT_EQ(1u, connection_.NumQueuedPackets());
EXPECT_TRUE(connection_.HasQueuedData());
// Unblock the writes and actually send.
writer_->SetWritable();
connection_.OnCanWrite();
EXPECT_EQ(0u, connection_.NumQueuedPackets());
// Parse the last packet and ensure it's one stream frame from one stream.
EXPECT_EQ(1u, writer_->frame_count());
EXPECT_EQ(1u, writer_->stream_frames().size());
EXPECT_EQ(1u, writer_->stream_frames()[0]->stream_id);
}
TEST_P(QuicConnectionTest, SendingZeroBytes) {
// Send a zero byte write with a fin using writev.
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
QuicIOVector empty_iov(nullptr, 0, 0);
connection_.SendStreamData(kHeadersStreamId, empty_iov, 0, kFin, nullptr);
EXPECT_EQ(0u, connection_.NumQueuedPackets());
EXPECT_FALSE(connection_.HasQueuedData());
// Parse the last packet and ensure it's one stream frame from one stream.
EXPECT_EQ(1u, writer_->frame_count());
EXPECT_EQ(1u, writer_->stream_frames().size());
EXPECT_EQ(kHeadersStreamId, writer_->stream_frames()[0]->stream_id);
EXPECT_TRUE(writer_->stream_frames()[0]->fin);
}
TEST_P(QuicConnectionTest, OnCanWrite) {
// Visitor's OnCanWrite will send data, but will have more pending writes.
EXPECT_CALL(visitor_, OnCanWrite())
.WillOnce(DoAll(IgnoreResult(InvokeWithoutArgs(
&connection_, &TestConnection::SendStreamData3)),
IgnoreResult(InvokeWithoutArgs(
&connection_, &TestConnection::SendStreamData5))));
EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillOnce(Return(true));
EXPECT_CALL(*send_algorithm_, TimeUntilSend(_, _))
.WillRepeatedly(testing::Return(QuicTime::Delta::Zero()));
connection_.OnCanWrite();
// Parse the last packet and ensure it's the two stream frames from
// two different streams.
EXPECT_EQ(2u, writer_->frame_count());
EXPECT_EQ(2u, writer_->stream_frames().size());
EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0]->stream_id);
EXPECT_EQ(kClientDataStreamId2, writer_->stream_frames()[1]->stream_id);
}
TEST_P(QuicConnectionTest, RetransmitOnNack) {
QuicPacketNumber last_packet;
QuicByteCount second_packet_size;
SendStreamDataToPeer(3, "foo", 0, !kFin, &last_packet); // Packet 1
second_packet_size =
SendStreamDataToPeer(3, "foos", 3, !kFin, &last_packet); // Packet 2
SendStreamDataToPeer(3, "fooos", 7, !kFin, &last_packet); // Packet 3
EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
// Don't lose a packet on an ack, and nothing is retransmitted.
EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
QuicAckFrame ack_one = InitAckFrame(1);
ProcessAckPacket(&ack_one);
// Lose a packet and ensure it triggers retransmission.
QuicAckFrame nack_two = InitAckFrame(3);
NackPacket(2, &nack_two);
SendAlgorithmInterface::CongestionVector lost_packets;
lost_packets.push_back(std::make_pair(2, kMaxPacketSize));
EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _))
.WillOnce(SetArgPointee<4>(lost_packets));
EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
EXPECT_CALL(*send_algorithm_,
OnPacketSent(_, _, _, second_packet_size - kQuicVersionSize, _))
.Times(1);
ProcessAckPacket(&nack_two);
}
TEST_P(QuicConnectionTest, DoNotSendQueuedPacketForResetStream) {
// Block the connection to queue the packet.
BlockOnNextWrite();
QuicStreamId stream_id = 2;
connection_.SendStreamDataWithString(stream_id, "foo", 0, !kFin, nullptr);
// Now that there is a queued packet, reset the stream.
connection_.SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 14);
// Unblock the connection and verify that only the RST_STREAM is sent.
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
writer_->SetWritable();
connection_.OnCanWrite();
EXPECT_EQ(1u, writer_->frame_count());
EXPECT_EQ(1u, writer_->rst_stream_frames().size());
}
TEST_P(QuicConnectionTest, SendQueuedPacketForQuicRstStreamNoError) {
// Block the connection to queue the packet.
BlockOnNextWrite();
QuicStreamId stream_id = 2;
connection_.SendStreamDataWithString(stream_id, "foo", 0, !kFin, nullptr);
// Now that there is a queued packet, reset the stream.
connection_.SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 14);
// Unblock the connection and verify that the RST_STREAM is sent and the data
// packet is sent on QUIC_VERSION_29 or later versions.
if (version() > QUIC_VERSION_28) {
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
.Times(AtLeast(2));
} else {
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
}
writer_->SetWritable();
connection_.OnCanWrite();
EXPECT_EQ(1u, writer_->frame_count());
EXPECT_EQ(1u, writer_->rst_stream_frames().size());
}
TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnNack) {
QuicStreamId stream_id = 2;
QuicPacketNumber last_packet;
SendStreamDataToPeer(stream_id, "foo", 0, !kFin, &last_packet);
SendStreamDataToPeer(stream_id, "foos", 3, !kFin, &last_packet);
SendStreamDataToPeer(stream_id, "fooos", 7, !kFin, &last_packet);
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
connection_.SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 14);
// Lose a packet and ensure it does not trigger retransmission.
QuicAckFrame nack_two = InitAckFrame(last_packet);
NackPacket(last_packet - 1, &nack_two);
EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _));
EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
ProcessAckPacket(&nack_two);
}
TEST_P(QuicConnectionTest, RetransmitForQuicRstStreamNoErrorOnNack) {
QuicStreamId stream_id = 2;
QuicPacketNumber last_packet;
SendStreamDataToPeer(stream_id, "foo", 0, !kFin, &last_packet);
SendStreamDataToPeer(stream_id, "foos", 3, !kFin, &last_packet);
SendStreamDataToPeer(stream_id, "fooos", 7, !kFin, &last_packet);
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
connection_.SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 14);
// Lose a packet, ensure it triggers retransmission on QUIC_VERSION_29
// or later versions.
QuicAckFrame nack_two = InitAckFrame(last_packet);
NackPacket(last_packet - 1, &nack_two);
EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
SendAlgorithmInterface::CongestionVector lost_packets;
lost_packets.push_back(std::make_pair(last_packet - 1, kMaxPacketSize));
EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _))
.WillOnce(SetArgPointee<4>(lost_packets));
EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
if (version() > QUIC_VERSION_28) {
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
.Times(AtLeast(1));
} else {
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
}
ProcessAckPacket(&nack_two);
}
TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnRTO) {
QuicStreamId stream_id = 2;
QuicPacketNumber last_packet;
SendStreamDataToPeer(stream_id, "foo", 0, !kFin, &last_packet);
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
connection_.SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 14);
// Fire the RTO and verify that the RST_STREAM is resent, not stream data.
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
clock_.AdvanceTime(DefaultRetransmissionTime());
connection_.GetRetransmissionAlarm()->Fire();
EXPECT_EQ(1u, writer_->frame_count());
EXPECT_EQ(1u, writer_->rst_stream_frames().size());
EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
}
TEST_P(QuicConnectionTest, RetransmitForQuicRstStreamNoErrorOnRTO) {
connection_.DisableTailLossProbe();
QuicStreamId stream_id = 2;
QuicPacketNumber last_packet;
SendStreamDataToPeer(stream_id, "foo", 0, !kFin, &last_packet);
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
connection_.SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 14);
// Fire the RTO and verify that the RST_STREAM is resent, the stream data
// is only sent on QUIC_VERSION_29 or later versions.
if (version() > QUIC_VERSION_28) {
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
.Times(AtLeast(2));
} else {
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
}
clock_.AdvanceTime(DefaultRetransmissionTime());
connection_.GetRetransmissionAlarm()->Fire();
EXPECT_EQ(1u, writer_->frame_count());
ASSERT_EQ(1u, writer_->rst_stream_frames().size());
EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
}
TEST_P(QuicConnectionTest, DoNotSendPendingRetransmissionForResetStream) {
QuicStreamId stream_id = 2;
QuicPacketNumber last_packet;
SendStreamDataToPeer(stream_id, "foo", 0, !kFin, &last_packet);
SendStreamDataToPeer(stream_id, "foos", 3, !kFin, &last_packet);
BlockOnNextWrite();
connection_.SendStreamDataWithString(stream_id, "fooos", 7, !kFin, nullptr);
// Lose a packet which will trigger a pending retransmission.
QuicAckFrame ack = InitAckFrame(last_packet);
NackPacket(last_packet - 1, &ack);
PacketNumberSet lost_packets;
lost_packets.insert(last_packet - 1);
EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _));
EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
ProcessAckPacket(&ack);
connection_.SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 14);
// Unblock the connection and verify that the RST_STREAM is sent but not the
// second data packet nor a retransmit.
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
writer_->SetWritable();
connection_.OnCanWrite();
EXPECT_EQ(1u, writer_->frame_count());
EXPECT_EQ(1u, writer_->rst_stream_frames().size());
EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
}
TEST_P(QuicConnectionTest, SendPendingRetransmissionForQuicRstStreamNoError) {
QuicStreamId stream_id = 2;
QuicPacketNumber last_packet;
SendStreamDataToPeer(stream_id, "foo", 0, !kFin, &last_packet);
SendStreamDataToPeer(stream_id, "foos", 3, !kFin, &last_packet);
BlockOnNextWrite();
connection_.SendStreamDataWithString(stream_id, "fooos", 7, !kFin, nullptr);
// Lose a packet which will trigger a pending retransmission.
QuicAckFrame ack = InitAckFrame(last_packet);
NackPacket(last_packet - 1, &ack);
EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
SendAlgorithmInterface::CongestionVector lost_packets;
lost_packets.push_back(std::make_pair(last_packet - 1, kMaxPacketSize));
EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _))
.WillOnce(SetArgPointee<4>(lost_packets));
EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
ProcessAckPacket(&ack);
connection_.SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 14);
// Unblock the connection and verify that the RST_STREAM is sent and the
// second data packet or a retransmit is only sent on QUIC_VERSION_29 or
// later versions.
if (version() > QUIC_VERSION_28) {
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
.Times(AtLeast(2));
} else {
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
}
writer_->SetWritable();
connection_.OnCanWrite();
EXPECT_EQ(1u, writer_->frame_count());
if (version() > QUIC_VERSION_28) {
EXPECT_EQ(0u, writer_->rst_stream_frames().size());
} else {
EXPECT_EQ(1u, writer_->rst_stream_frames().size());
EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
}
}
TEST_P(QuicConnectionTest, DiscardRetransmit) {
QuicPacketNumber last_packet;
SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet); // Packet 1
SendStreamDataToPeer(1, "foos", 3, !kFin, &last_packet); // Packet 2
SendStreamDataToPeer(1, "fooos", 7, !kFin, &last_packet); // Packet 3
EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
// Instigate a loss with an ack.
QuicAckFrame nack_two = InitAckFrame(3);
NackPacket(2, &nack_two);
// The first nack should trigger a fast retransmission, but we'll be
// write blocked, so the packet will be queued.
BlockOnNextWrite();
SendAlgorithmInterface::CongestionVector lost_packets;
lost_packets.push_back(std::make_pair(2, kMaxPacketSize));
EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _))
.WillOnce(SetArgPointee<4>(lost_packets));
EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
ProcessAckPacket(&nack_two);
EXPECT_EQ(1u, connection_.NumQueuedPackets());
// Now, ack the previous transmission.
EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _));
QuicAckFrame ack_all = InitAckFrame(3);
ProcessAckPacket(&ack_all);
// Unblock the socket and attempt to send the queued packets. However,
// since the previous transmission has been acked, we will not
// send the retransmission.
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
writer_->SetWritable();
connection_.OnCanWrite();
EXPECT_EQ(0u, connection_.NumQueuedPackets());
}
TEST_P(QuicConnectionTest, RetransmitNackedLargestObserved) {
EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
QuicPacketNumber largest_observed;
QuicByteCount packet_size;
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
.WillOnce(DoAll(SaveArg<2>(&largest_observed), SaveArg<3>(&packet_size),
Return(true)));
connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
QuicAckFrame frame = InitAckFrame(1);
NackPacket(largest_observed, &frame);
// The first nack should retransmit the largest observed packet.
SendAlgorithmInterface::CongestionVector lost_packets;
lost_packets.push_back(std::make_pair(1, kMaxPacketSize));
EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _))
.WillOnce(SetArgPointee<4>(lost_packets));
EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
EXPECT_CALL(*send_algorithm_,
OnPacketSent(_, _, _, packet_size - kQuicVersionSize, _));
ProcessAckPacket(&frame);
}
TEST_P(QuicConnectionTest, QueueAfterTwoRTOs) {
connection_.DisableTailLossProbe();
for (int i = 0; i < 10; ++i) {
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
connection_.SendStreamDataWithString(3, "foo", i * 3, !kFin, nullptr);
}
// Block the writer and ensure they're queued.
BlockOnNextWrite();
clock_.AdvanceTime(DefaultRetransmissionTime());
// Only one packet should be retransmitted.
connection_.GetRetransmissionAlarm()->Fire();
EXPECT_TRUE(connection_.HasQueuedData());
// Unblock the writer.
writer_->SetWritable();
clock_.AdvanceTime(QuicTime::Delta::FromMicroseconds(
2 * DefaultRetransmissionTime().ToMicroseconds()));
// Retransmit already retransmitted packets event though the packet number
// greater than the largest observed.
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
connection_.GetRetransmissionAlarm()->Fire();
connection_.OnCanWrite();
}
TEST_P(QuicConnectionTest, WriteBlockedBufferedThenSent) {
BlockOnNextWrite();
writer_->set_is_write_blocked_data_buffered(true);
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
writer_->SetWritable();
connection_.OnCanWrite();
EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
}
TEST_P(QuicConnectionTest, WriteBlockedThenSent) {
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
BlockOnNextWrite();
connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
EXPECT_EQ(1u, connection_.NumQueuedPackets());
// The second packet should also be queued, in order to ensure packets are
// never sent out of order.
writer_->SetWritable();
connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
EXPECT_EQ(2u, connection_.NumQueuedPackets());
// Now both are sent in order when we unblock.
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
connection_.OnCanWrite();
EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
}
TEST_P(QuicConnectionTest, RetransmitWriteBlockedAckedOriginalThenSent) {
EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
BlockOnNextWrite();
writer_->set_is_write_blocked_data_buffered(true);
// Simulate the retransmission alarm firing.
clock_.AdvanceTime(DefaultRetransmissionTime());
connection_.GetRetransmissionAlarm()->Fire();
// Ack the sent packet before the callback returns, which happens in
// rare circumstances with write blocked sockets.
QuicAckFrame ack = InitAckFrame(1);
EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
ProcessAckPacket(&ack);
writer_->SetWritable();
connection_.OnCanWrite();
// There is now a pending packet, but with no retransmittable frames.
EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
EXPECT_FALSE(connection_.sent_packet_manager().HasRetransmittableFrames(
ack.path_id, 2));
}
TEST_P(QuicConnectionTest, AlarmsWhenWriteBlocked) {
// Block the connection.
BlockOnNextWrite();
connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
EXPECT_EQ(1u, writer_->packets_write_attempts());
EXPECT_TRUE(writer_->IsWriteBlocked());
// Set the send and resumption alarms. Fire the alarms and ensure they don't
// attempt to write.
connection_.GetResumeWritesAlarm()->Set(clock_.ApproximateNow());
connection_.GetSendAlarm()->Set(clock_.ApproximateNow());
connection_.GetResumeWritesAlarm()->Fire();
connection_.GetSendAlarm()->Fire();
EXPECT_TRUE(writer_->IsWriteBlocked());
EXPECT_EQ(1u, writer_->packets_write_attempts());
}
TEST_P(QuicConnectionTest, NoLimitPacketsPerNack) {
EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
int offset = 0;
// Send packets 1 to 15.
for (int i = 0; i < 15; ++i) {
SendStreamDataToPeer(1, "foo", offset, !kFin, nullptr);
offset += 3;
}
// Ack 15, nack 1-14.
QuicAckFrame nack = InitAckFrame(15);
for (int i = 1; i < 15; ++i) {
NackPacket(i, &nack);
}
// 14 packets have been NACK'd and lost.
SendAlgorithmInterface::CongestionVector lost_packets;
for (int i = 1; i < 15; ++i) {
lost_packets.push_back(std::make_pair(i, kMaxPacketSize));
}
EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _))
.WillOnce(SetArgPointee<4>(lost_packets));
EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(14);
ProcessAckPacket(&nack);
}
// Test sending multiple acks from the connection to the session.
TEST_P(QuicConnectionTest, MultipleAcks) {
QuicPacketNumber last_packet;
SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet); // Packet 1
EXPECT_EQ(1u, last_packet);
SendStreamDataToPeer(3, "foo", 0, !kFin, &last_packet); // Packet 2
EXPECT_EQ(2u, last_packet);
SendAckPacketToPeer(); // Packet 3
SendStreamDataToPeer(5, "foo", 0, !kFin, &last_packet); // Packet 4
EXPECT_EQ(4u, last_packet);
SendStreamDataToPeer(1, "foo", 3, !kFin, &last_packet); // Packet 5
EXPECT_EQ(5u, last_packet);
SendStreamDataToPeer(3, "foo", 3, !kFin, &last_packet); // Packet 6
EXPECT_EQ(6u, last_packet);
// Client will ack packets 1, 2, [!3], 4, 5.
EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
QuicAckFrame frame1 = InitAckFrame(5);
NackPacket(3, &frame1);
EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
ProcessAckPacket(&frame1);
// Now the client implicitly acks 3, and explicitly acks 6.
EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
QuicAckFrame frame2 = InitAckFrame(6);
ProcessAckPacket(&frame2);
}
TEST_P(QuicConnectionTest, DontLatchUnackedPacket) {
SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr); // Packet 1;
// From now on, we send acks, so the send algorithm won't mark them pending.
ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
.WillByDefault(Return(false));
SendAckPacketToPeer(); // Packet 2
EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
QuicAckFrame frame = InitAckFrame(1);
ProcessAckPacket(&frame);
// Verify that our internal state has least-unacked as 2, because we're still
// waiting for a potential ack for 2.
EXPECT_EQ(2u, stop_waiting()->least_unacked);
EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
frame = InitAckFrame(2);
ProcessAckPacket(&frame);
EXPECT_EQ(3u, stop_waiting()->least_unacked);
// When we send an ack, we make sure our least-unacked makes sense. In this
// case since we're not waiting on an ack for 2 and all packets are acked, we
// set it to 3.
SendAckPacketToPeer(); // Packet 3
// Least_unacked remains at 3 until another ack is received.
EXPECT_EQ(3u, stop_waiting()->least_unacked);
// Check that the outgoing ack had its packet number as least_unacked.
EXPECT_EQ(3u, least_unacked());
// Ack the ack, which updates the rtt and raises the least unacked.
EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
frame = InitAckFrame(3);
ProcessAckPacket(&frame);
ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
.WillByDefault(Return(true));
SendStreamDataToPeer(1, "bar", 3, false, nullptr); // Packet 4
EXPECT_EQ(4u, stop_waiting()->least_unacked);
ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
.WillByDefault(Return(false));
SendAckPacketToPeer(); // Packet 5
EXPECT_EQ(4u, least_unacked());
// Send two data packets at the end, and ensure if the last one is acked,
// the least unacked is raised above the ack packets.
ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
.WillByDefault(Return(true));
SendStreamDataToPeer(1, "bar", 6, false, nullptr); // Packet 6
SendStreamDataToPeer(1, "bar", 9, false, nullptr); // Packet 7
EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
frame = InitAckFrame(7);
NackPacket(5, &frame);
NackPacket(6, &frame);