blob: 06488e5265a38d7364d77aa8c57dcee850076eaf [file] [log] [blame]
QUICHE teama6ef0a62019-03-07 20:34:33 -05001// 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/third_party/quiche/src/quic/core/quic_connection.h"
6
7#include <errno.h>
zhongyi546cc452019-04-12 15:27:49 -07008
QUICHE teama6ef0a62019-03-07 20:34:33 -05009#include <memory>
10#include <ostream>
zhongyi9e843642019-04-12 09:04:54 -070011#include <string>
zhongyi546cc452019-04-12 15:27:49 -070012#include <utility>
zhongyi9e843642019-04-12 09:04:54 -070013
QUICHE teama6ef0a62019-03-07 20:34:33 -050014#include "net/third_party/quiche/src/quic/core/congestion_control/loss_detection_interface.h"
15#include "net/third_party/quiche/src/quic/core/congestion_control/send_algorithm_interface.h"
zhongyi546cc452019-04-12 15:27:49 -070016#include "net/third_party/quiche/src/quic/core/crypto/null_decrypter.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050017#include "net/third_party/quiche/src/quic/core/crypto/null_encrypter.h"
18#include "net/third_party/quiche/src/quic/core/crypto/quic_decrypter.h"
19#include "net/third_party/quiche/src/quic/core/crypto/quic_encrypter.h"
20#include "net/third_party/quiche/src/quic/core/quic_connection_id.h"
wub50d4c712020-05-19 15:48:28 -070021#include "net/third_party/quiche/src/quic/core/quic_constants.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050022#include "net/third_party/quiche/src/quic/core/quic_packets.h"
23#include "net/third_party/quiche/src/quic/core/quic_simple_buffer_allocator.h"
24#include "net/third_party/quiche/src/quic/core/quic_types.h"
25#include "net/third_party/quiche/src/quic/core/quic_utils.h"
dschinazi278efae2020-01-28 17:03:09 -080026#include "net/third_party/quiche/src/quic/core/quic_versions.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050027#include "net/third_party/quiche/src/quic/platform/api/quic_expect_bug.h"
28#include "net/third_party/quiche/src/quic/platform/api/quic_flags.h"
29#include "net/third_party/quiche/src/quic/platform/api/quic_logging.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050030#include "net/third_party/quiche/src/quic/platform/api/quic_reference_counted.h"
renjietang5b245892020-05-18 11:57:26 -070031#include "net/third_party/quiche/src/quic/platform/api/quic_socket_address.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050032#include "net/third_party/quiche/src/quic/platform/api/quic_test.h"
33#include "net/third_party/quiche/src/quic/test_tools/mock_clock.h"
34#include "net/third_party/quiche/src/quic/test_tools/mock_random.h"
35#include "net/third_party/quiche/src/quic/test_tools/quic_config_peer.h"
36#include "net/third_party/quiche/src/quic/test_tools/quic_connection_peer.h"
37#include "net/third_party/quiche/src/quic/test_tools/quic_framer_peer.h"
38#include "net/third_party/quiche/src/quic/test_tools/quic_packet_creator_peer.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050039#include "net/third_party/quiche/src/quic/test_tools/quic_sent_packet_manager_peer.h"
40#include "net/third_party/quiche/src/quic/test_tools/quic_test_utils.h"
41#include "net/third_party/quiche/src/quic/test_tools/simple_data_producer.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050042#include "net/third_party/quiche/src/quic/test_tools/simple_session_notifier.h"
dschinazi278efae2020-01-28 17:03:09 -080043#include "net/third_party/quiche/src/common/platform/api/quiche_arraysize.h"
dmcardlecf0bfcf2019-12-13 08:08:21 -080044#include "net/third_party/quiche/src/common/platform/api/quiche_str_cat.h"
45#include "net/third_party/quiche/src/common/platform/api/quiche_string_piece.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050046
47using testing::_;
48using testing::AnyNumber;
49using testing::AtLeast;
50using testing::DoAll;
QUICHE teama6ef0a62019-03-07 20:34:33 -050051using testing::Ge;
52using testing::IgnoreResult;
53using testing::InSequence;
54using testing::Invoke;
55using testing::InvokeWithoutArgs;
56using testing::Lt;
57using testing::Ref;
58using testing::Return;
59using testing::SaveArg;
60using testing::SetArgPointee;
61using testing::StrictMock;
62
63namespace quic {
64namespace test {
65namespace {
66
nharper55fa6132019-05-07 19:37:21 -070067const char data1[] = "foo data";
68const char data2[] = "bar data";
QUICHE teama6ef0a62019-03-07 20:34:33 -050069
70const bool kHasStopWaiting = true;
71
72const int kDefaultRetransmissionTimeMs = 500;
73
QUICHE team548d51b2019-03-14 10:06:54 -070074DiversificationNonce kTestDiversificationNonce = {
75 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a',
76 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b',
77 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b',
78};
79
QUICHE teama6ef0a62019-03-07 20:34:33 -050080const QuicSocketAddress kPeerAddress =
81 QuicSocketAddress(QuicIpAddress::Loopback6(),
82 /*port=*/12345);
83const QuicSocketAddress kSelfAddress =
84 QuicSocketAddress(QuicIpAddress::Loopback6(),
85 /*port=*/443);
86
QUICHE teama6ef0a62019-03-07 20:34:33 -050087QuicStreamId GetNthClientInitiatedStreamId(int n,
88 QuicTransportVersion version) {
dschinazi552accc2019-06-17 17:07:34 -070089 return QuicUtils::GetFirstBidirectionalStreamId(version,
90 Perspective::IS_CLIENT) +
91 n * 2;
QUICHE teama6ef0a62019-03-07 20:34:33 -050092}
93
QUICHE team8c1daa22019-03-13 08:33:41 -070094QuicLongHeaderType EncryptionlevelToLongHeaderType(EncryptionLevel level) {
95 switch (level) {
QUICHE team6987b4a2019-03-15 16:23:04 -070096 case ENCRYPTION_INITIAL:
QUICHE team8c1daa22019-03-13 08:33:41 -070097 return INITIAL;
QUICHE team88ea0082019-03-15 10:05:26 -070098 case ENCRYPTION_HANDSHAKE:
99 return HANDSHAKE;
QUICHE team8c1daa22019-03-13 08:33:41 -0700100 case ENCRYPTION_ZERO_RTT:
101 return ZERO_RTT_PROTECTED;
102 case ENCRYPTION_FORWARD_SECURE:
103 DCHECK(false);
104 return INVALID_PACKET_TYPE;
105 default:
106 DCHECK(false);
107 return INVALID_PACKET_TYPE;
108 }
109}
110
QUICHE teama6ef0a62019-03-07 20:34:33 -0500111// StringTaggingDecrypter ensures that the final kTagSize bytes of the message
112// match the expected value.
113class StrictTaggingDecrypter : public TaggingDecrypter {
114 public:
115 explicit StrictTaggingDecrypter(uint8_t tag) : tag_(tag) {}
116 ~StrictTaggingDecrypter() override {}
117
118 // TaggingQuicDecrypter
dmcardlecf0bfcf2019-12-13 08:08:21 -0800119 uint8_t GetTag(quiche::QuicheStringPiece /*ciphertext*/) override {
120 return tag_;
121 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500122
123 // Use a distinct value starting with 0xFFFFFF, which is never used by TLS.
124 uint32_t cipher_id() const override { return 0xFFFFFFF1; }
125
126 private:
127 const uint8_t tag_;
128};
129
130class TestConnectionHelper : public QuicConnectionHelperInterface {
131 public:
132 TestConnectionHelper(MockClock* clock, MockRandom* random_generator)
133 : clock_(clock), random_generator_(random_generator) {
134 clock_->AdvanceTime(QuicTime::Delta::FromSeconds(1));
135 }
136 TestConnectionHelper(const TestConnectionHelper&) = delete;
137 TestConnectionHelper& operator=(const TestConnectionHelper&) = delete;
138
139 // QuicConnectionHelperInterface
140 const QuicClock* GetClock() const override { return clock_; }
141
142 QuicRandom* GetRandomGenerator() override { return random_generator_; }
143
144 QuicBufferAllocator* GetStreamSendBufferAllocator() override {
145 return &buffer_allocator_;
146 }
147
148 private:
149 MockClock* clock_;
150 MockRandom* random_generator_;
151 SimpleBufferAllocator buffer_allocator_;
152};
153
154class TestAlarmFactory : public QuicAlarmFactory {
155 public:
156 class TestAlarm : public QuicAlarm {
157 public:
158 explicit TestAlarm(QuicArenaScopedPtr<QuicAlarm::Delegate> delegate)
159 : QuicAlarm(std::move(delegate)) {}
160
161 void SetImpl() override {}
162 void CancelImpl() override {}
163 using QuicAlarm::Fire;
164 };
165
166 TestAlarmFactory() {}
167 TestAlarmFactory(const TestAlarmFactory&) = delete;
168 TestAlarmFactory& operator=(const TestAlarmFactory&) = delete;
169
170 QuicAlarm* CreateAlarm(QuicAlarm::Delegate* delegate) override {
171 return new TestAlarm(QuicArenaScopedPtr<QuicAlarm::Delegate>(delegate));
172 }
173
174 QuicArenaScopedPtr<QuicAlarm> CreateAlarm(
175 QuicArenaScopedPtr<QuicAlarm::Delegate> delegate,
176 QuicConnectionArena* arena) override {
177 return arena->New<TestAlarm>(std::move(delegate));
178 }
179};
180
QUICHE teama6ef0a62019-03-07 20:34:33 -0500181class TestConnection : public QuicConnection {
182 public:
183 TestConnection(QuicConnectionId connection_id,
wub5df36632020-10-01 14:42:17 -0700184 QuicSocketAddress initial_self_address,
185 QuicSocketAddress initial_peer_address,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500186 TestConnectionHelper* helper,
187 TestAlarmFactory* alarm_factory,
188 TestPacketWriter* writer,
189 Perspective perspective,
190 ParsedQuicVersion version)
191 : QuicConnection(connection_id,
wub5df36632020-10-01 14:42:17 -0700192 initial_self_address,
193 initial_peer_address,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500194 helper,
195 alarm_factory,
196 writer,
197 /* owns_writer= */ false,
198 perspective,
199 SupportedVersions(version)),
200 notifier_(nullptr) {
201 writer->set_perspective(perspective);
202 SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -0700203 std::make_unique<NullEncrypter>(perspective));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500204 SetDataProducer(&producer_);
205 }
206 TestConnection(const TestConnection&) = delete;
207 TestConnection& operator=(const TestConnection&) = delete;
208
QUICHE teama6ef0a62019-03-07 20:34:33 -0500209 void SetSendAlgorithm(SendAlgorithmInterface* send_algorithm) {
210 QuicConnectionPeer::SetSendAlgorithm(this, send_algorithm);
211 }
212
213 void SetLossAlgorithm(LossDetectionInterface* loss_algorithm) {
214 QuicConnectionPeer::SetLossAlgorithm(this, loss_algorithm);
215 }
216
dschinazi17d42422019-06-18 16:35:07 -0700217 void SendPacket(EncryptionLevel /*level*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500218 uint64_t packet_number,
219 std::unique_ptr<QuicPacket> packet,
220 HasRetransmittableData retransmittable,
221 bool has_ack,
222 bool has_pending_frames) {
fayang58f71072019-11-05 08:47:02 -0800223 ScopedPacketFlusher flusher(this);
dschinazi66dea072019-04-09 11:41:06 -0700224 char buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -0500225 size_t encrypted_length =
226 QuicConnectionPeer::GetFramer(this)->EncryptPayload(
QUICHE team6987b4a2019-03-15 16:23:04 -0700227 ENCRYPTION_INITIAL, QuicPacketNumber(packet_number), *packet,
dschinazi66dea072019-04-09 11:41:06 -0700228 buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500229 SerializedPacket serialized_packet(
230 QuicPacketNumber(packet_number), PACKET_4BYTE_PACKET_NUMBER, buffer,
231 encrypted_length, has_ack, has_pending_frames);
danzh8a27a1a2020-09-02 10:26:28 -0700232 serialized_packet.peer_address = kPeerAddress;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500233 if (retransmittable == HAS_RETRANSMITTABLE_DATA) {
234 serialized_packet.retransmittable_frames.push_back(
fayang58f71072019-11-05 08:47:02 -0800235 QuicFrame(QuicPingFrame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500236 }
wub8a5dafa2020-05-13 12:30:17 -0700237 OnSerializedPacket(std::move(serialized_packet));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500238 }
239
240 QuicConsumedData SaveAndSendStreamData(QuicStreamId id,
241 const struct iovec* iov,
242 int iov_count,
243 size_t total_length,
244 QuicStreamOffset offset,
245 StreamSendingState state) {
fayanga4b37b22019-06-18 13:37:47 -0700246 ScopedPacketFlusher flusher(this);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500247 producer_.SaveStreamData(id, iov, iov_count, 0u, total_length);
248 if (notifier_ != nullptr) {
249 return notifier_->WriteOrBufferData(id, total_length, state);
250 }
251 return QuicConnection::SendStreamData(id, total_length, offset, state);
252 }
253
254 QuicConsumedData SendStreamDataWithString(QuicStreamId id,
dmcardlecf0bfcf2019-12-13 08:08:21 -0800255 quiche::QuicheStringPiece data,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500256 QuicStreamOffset offset,
257 StreamSendingState state) {
fayanga4b37b22019-06-18 13:37:47 -0700258 ScopedPacketFlusher flusher(this);
nharper46833c32019-05-15 21:33:05 -0700259 if (!QuicUtils::IsCryptoStreamId(transport_version(), id) &&
QUICHE team6987b4a2019-03-15 16:23:04 -0700260 this->encryption_level() == ENCRYPTION_INITIAL) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500261 this->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
fayangfa3b1d62019-11-18 08:02:13 -0800262 if (perspective() == Perspective::IS_CLIENT && !IsHandshakeComplete()) {
fayang5f135052019-08-22 17:59:40 -0700263 OnHandshakeComplete();
264 }
265 if (version().SupportsAntiAmplificationLimit()) {
266 QuicConnectionPeer::SetAddressValidated(this);
267 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500268 }
269 struct iovec iov;
270 MakeIOVector(data, &iov);
271 return SaveAndSendStreamData(id, &iov, 1, data.length(), offset, state);
272 }
273
QUICHE teamcd098022019-03-22 18:49:55 -0700274 QuicConsumedData SendApplicationDataAtLevel(EncryptionLevel encryption_level,
275 QuicStreamId id,
dmcardlecf0bfcf2019-12-13 08:08:21 -0800276 quiche::QuicheStringPiece data,
QUICHE teamcd098022019-03-22 18:49:55 -0700277 QuicStreamOffset offset,
278 StreamSendingState state) {
fayanga4b37b22019-06-18 13:37:47 -0700279 ScopedPacketFlusher flusher(this);
QUICHE teamcd098022019-03-22 18:49:55 -0700280 DCHECK(encryption_level >= ENCRYPTION_ZERO_RTT);
vasilvv0fc587f2019-09-06 13:33:08 -0700281 SetEncrypter(encryption_level, std::make_unique<TaggingEncrypter>(0x01));
QUICHE teamcd098022019-03-22 18:49:55 -0700282 SetDefaultEncryptionLevel(encryption_level);
283 struct iovec iov;
284 MakeIOVector(data, &iov);
285 return SaveAndSendStreamData(id, &iov, 1, data.length(), offset, state);
286 }
287
QUICHE teama6ef0a62019-03-07 20:34:33 -0500288 QuicConsumedData SendStreamData3() {
289 return SendStreamDataWithString(
290 GetNthClientInitiatedStreamId(1, transport_version()), "food", 0,
291 NO_FIN);
292 }
293
294 QuicConsumedData SendStreamData5() {
295 return SendStreamDataWithString(
296 GetNthClientInitiatedStreamId(2, transport_version()), "food2", 0,
297 NO_FIN);
298 }
299
300 // Ensures the connection can write stream data before writing.
301 QuicConsumedData EnsureWritableAndSendStreamData5() {
ianswettfc16a2b2020-05-18 16:05:49 -0700302 EXPECT_TRUE(CanWrite(HAS_RETRANSMITTABLE_DATA));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500303 return SendStreamData5();
304 }
305
306 // The crypto stream has special semantics so that it is not blocked by a
307 // congestion window limitation, and also so that it gets put into a separate
308 // packet (so that it is easier to reason about a crypto frame not being
309 // split needlessly across packet boundaries). As a result, we have separate
310 // tests for some cases for this stream.
311 QuicConsumedData SendCryptoStreamData() {
312 QuicStreamOffset offset = 0;
dmcardlecf0bfcf2019-12-13 08:08:21 -0800313 quiche::QuicheStringPiece data("chlo");
fayang2ce66082019-10-02 06:29:04 -0700314 if (!QuicVersionUsesCryptoFrames(transport_version())) {
315 return SendCryptoDataWithString(data, offset);
316 }
317 producer_.SaveCryptoData(ENCRYPTION_INITIAL, offset, data);
318 size_t bytes_written;
319 if (notifier_) {
320 bytes_written =
321 notifier_->WriteCryptoData(ENCRYPTION_INITIAL, data.length(), offset);
322 } else {
323 bytes_written = QuicConnection::SendCryptoData(ENCRYPTION_INITIAL,
324 data.length(), offset);
325 }
326 return QuicConsumedData(bytes_written, /*fin_consumed*/ false);
nharper46833c32019-05-15 21:33:05 -0700327 }
328
dmcardlecf0bfcf2019-12-13 08:08:21 -0800329 QuicConsumedData SendCryptoDataWithString(quiche::QuicheStringPiece data,
nharper46833c32019-05-15 21:33:05 -0700330 QuicStreamOffset offset) {
fayang18ff23b2020-01-28 09:19:00 -0800331 return SendCryptoDataWithString(data, offset, ENCRYPTION_INITIAL);
332 }
333
334 QuicConsumedData SendCryptoDataWithString(quiche::QuicheStringPiece data,
335 QuicStreamOffset offset,
336 EncryptionLevel encryption_level) {
QUICHE teamea740082019-03-11 17:58:43 -0700337 if (!QuicVersionUsesCryptoFrames(transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500338 return SendStreamDataWithString(
339 QuicUtils::GetCryptoStreamId(transport_version()), data, offset,
340 NO_FIN);
341 }
fayang18ff23b2020-01-28 09:19:00 -0800342 producer_.SaveCryptoData(encryption_level, offset, data);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500343 size_t bytes_written;
344 if (notifier_) {
345 bytes_written =
fayang18ff23b2020-01-28 09:19:00 -0800346 notifier_->WriteCryptoData(encryption_level, data.length(), offset);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500347 } else {
fayang18ff23b2020-01-28 09:19:00 -0800348 bytes_written = QuicConnection::SendCryptoData(encryption_level,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500349 data.length(), offset);
350 }
351 return QuicConsumedData(bytes_written, /*fin_consumed*/ false);
352 }
353
354 void set_version(ParsedQuicVersion version) {
355 QuicConnectionPeer::GetFramer(this)->set_version(version);
356 }
357
358 void SetSupportedVersions(const ParsedQuicVersionVector& versions) {
359 QuicConnectionPeer::GetFramer(this)->SetSupportedVersions(versions);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500360 writer()->SetSupportedVersions(versions);
361 }
362
danzhc19a9502020-09-29 16:02:33 -0700363 // This should be called before setting customized encrypters/decrypters for
364 // connection and peer creator.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500365 void set_perspective(Perspective perspective) {
366 writer()->set_perspective(perspective);
367 QuicConnectionPeer::SetPerspective(this, perspective);
fayang5d91f082020-09-11 14:47:26 -0700368 QuicSentPacketManagerPeer::SetPerspective(
369 QuicConnectionPeer::GetSentPacketManager(this), perspective);
danzhc19a9502020-09-29 16:02:33 -0700370 QuicConnectionPeer::GetFramer(this)->SetInitialObfuscators(
371 TestConnectionId());
372 for (EncryptionLevel level : {ENCRYPTION_ZERO_RTT, ENCRYPTION_HANDSHAKE,
373 ENCRYPTION_FORWARD_SECURE}) {
374 if (QuicConnectionPeer::GetFramer(this)->HasEncrypterOfEncryptionLevel(
375 level)) {
376 SetEncrypter(level, std::make_unique<NullEncrypter>(perspective));
377 }
378 if (QuicConnectionPeer::GetFramer(this)->HasDecrypterOfEncryptionLevel(
379 level)) {
380 InstallDecrypter(level, std::make_unique<NullDecrypter>(perspective));
381 }
382 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500383 }
384
385 // Enable path MTU discovery. Assumes that the test is performed from the
wub031d47c2019-11-21 08:04:07 -0800386 // server perspective and the higher value of MTU target is used.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500387 void EnablePathMtuDiscovery(MockSendAlgorithm* send_algorithm) {
wub031d47c2019-11-21 08:04:07 -0800388 ASSERT_EQ(Perspective::IS_SERVER, perspective());
QUICHE teama6ef0a62019-03-07 20:34:33 -0500389
wub610f7ce2020-08-14 14:19:02 -0700390 if (GetQuicReloadableFlag(quic_enable_mtu_discovery_at_server)) {
391 OnConfigNegotiated();
392 } else {
393 QuicConfig config;
394 QuicTagVector connection_options;
395 connection_options.push_back(kMTUH);
396 config.SetInitialReceivedConnectionOptions(connection_options);
397 EXPECT_CALL(*send_algorithm, SetFromConfig(_, _));
398 SetFromConfig(config);
399 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500400
401 // Normally, the pacing would be disabled in the test, but calling
402 // SetFromConfig enables it. Set nearly-infinite bandwidth to make the
403 // pacing algorithm work.
404 EXPECT_CALL(*send_algorithm, PacingRate(_))
405 .WillRepeatedly(Return(QuicBandwidth::Infinite()));
406 }
407
408 TestAlarmFactory::TestAlarm* GetAckAlarm() {
409 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
410 QuicConnectionPeer::GetAckAlarm(this));
411 }
412
413 TestAlarmFactory::TestAlarm* GetPingAlarm() {
414 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
415 QuicConnectionPeer::GetPingAlarm(this));
416 }
417
418 TestAlarmFactory::TestAlarm* GetRetransmissionAlarm() {
419 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
420 QuicConnectionPeer::GetRetransmissionAlarm(this));
421 }
422
423 TestAlarmFactory::TestAlarm* GetSendAlarm() {
424 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
425 QuicConnectionPeer::GetSendAlarm(this));
426 }
427
428 TestAlarmFactory::TestAlarm* GetTimeoutAlarm() {
429 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
fayang3a58dc42020-06-29 11:27:14 -0700430 QuicConnectionPeer::GetIdleNetworkDetectorAlarm(this));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500431 }
432
433 TestAlarmFactory::TestAlarm* GetMtuDiscoveryAlarm() {
434 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
435 QuicConnectionPeer::GetMtuDiscoveryAlarm(this));
436 }
437
QUICHE teama6ef0a62019-03-07 20:34:33 -0500438 TestAlarmFactory::TestAlarm* GetProcessUndecryptablePacketsAlarm() {
439 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
440 QuicConnectionPeer::GetProcessUndecryptablePacketsAlarm(this));
441 }
442
fayangb59c6f12020-03-23 15:06:14 -0700443 TestAlarmFactory::TestAlarm* GetBlackholeDetectorAlarm() {
fayangb59c6f12020-03-23 15:06:14 -0700444 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
445 QuicConnectionPeer::GetBlackholeDetectorAlarm(this));
446 }
447
448 void PathDegradingTimeout() {
449 DCHECK(PathDegradingDetectionInProgress());
fayang2205d952020-05-12 13:45:56 -0700450 GetBlackholeDetectorAlarm()->Fire();
fayangb59c6f12020-03-23 15:06:14 -0700451 }
452
453 bool PathDegradingDetectionInProgress() {
fayang2205d952020-05-12 13:45:56 -0700454 return QuicConnectionPeer::GetPathDegradingDeadline(this).IsInitialized();
fayangb59c6f12020-03-23 15:06:14 -0700455 }
456
457 bool BlackholeDetectionInProgress() {
fayangb59c6f12020-03-23 15:06:14 -0700458 return QuicConnectionPeer::GetBlackholeDetectionDeadline(this)
459 .IsInitialized();
460 }
461
wub8add68a2020-07-27 12:07:38 -0700462 bool PathMtuReductionDetectionInProgress() {
463 return QuicConnectionPeer::GetPathMtuReductionDetectionDeadline(this)
464 .IsInitialized();
465 }
466
QUICHE teama6ef0a62019-03-07 20:34:33 -0500467 void SetMaxTailLossProbes(size_t max_tail_loss_probes) {
468 QuicSentPacketManagerPeer::SetMaxTailLossProbes(
469 QuicConnectionPeer::GetSentPacketManager(this), max_tail_loss_probes);
470 }
471
472 QuicByteCount GetBytesInFlight() {
ianswett9f459cb2019-04-21 06:39:59 -0700473 return QuicConnectionPeer::GetSentPacketManager(this)->GetBytesInFlight();
QUICHE teama6ef0a62019-03-07 20:34:33 -0500474 }
475
476 void set_notifier(SimpleSessionNotifier* notifier) { notifier_ = notifier; }
477
478 void ReturnEffectivePeerAddressForNextPacket(const QuicSocketAddress& addr) {
vasilvv0fc587f2019-09-06 13:33:08 -0700479 next_effective_peer_addr_ = std::make_unique<QuicSocketAddress>(addr);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500480 }
481
fayang5f135052019-08-22 17:59:40 -0700482 bool PtoEnabled() {
483 if (QuicConnectionPeer::GetSentPacketManager(this)->pto_enabled()) {
484 // PTO mode is default enabled for T099. And TLP/RTO related tests are
485 // stale.
fayang5d011982020-05-13 14:14:38 -0700486 DCHECK(PROTOCOL_TLS1_3 == version().handshake_protocol ||
487 GetQuicReloadableFlag(quic_default_on_pto));
fayang5f135052019-08-22 17:59:40 -0700488 return true;
489 }
490 return false;
491 }
492
nharper46833c32019-05-15 21:33:05 -0700493 SimpleDataProducer* producer() { return &producer_; }
494
QUICHE teama6ef0a62019-03-07 20:34:33 -0500495 using QuicConnection::active_effective_peer_migration_type;
496 using QuicConnection::IsCurrentPacketConnectivityProbing;
497 using QuicConnection::SelectMutualVersion;
498 using QuicConnection::SendProbingRetransmissions;
499 using QuicConnection::set_defer_send_in_response_to_packets;
500
501 protected:
502 QuicSocketAddress GetEffectivePeerAddressFromCurrentPacket() const override {
503 if (next_effective_peer_addr_) {
504 return *std::move(next_effective_peer_addr_);
505 }
506 return QuicConnection::GetEffectivePeerAddressFromCurrentPacket();
507 }
508
509 private:
510 TestPacketWriter* writer() {
511 return static_cast<TestPacketWriter*>(QuicConnection::writer());
512 }
513
514 SimpleDataProducer producer_;
515
516 SimpleSessionNotifier* notifier_;
517
518 std::unique_ptr<QuicSocketAddress> next_effective_peer_addr_;
519};
520
521enum class AckResponse { kDefer, kImmediate };
522
523// Run tests with combinations of {ParsedQuicVersion, AckResponse}.
524struct TestParams {
525 TestParams(ParsedQuicVersion version,
526 AckResponse ack_response,
527 bool no_stop_waiting)
528 : version(version),
529 ack_response(ack_response),
530 no_stop_waiting(no_stop_waiting) {}
531
QUICHE teama6ef0a62019-03-07 20:34:33 -0500532 ParsedQuicVersion version;
533 AckResponse ack_response;
534 bool no_stop_waiting;
535};
536
dschinazi142051a2019-09-18 18:17:29 -0700537// Used by ::testing::PrintToStringParamName().
538std::string PrintToString(const TestParams& p) {
dmcardlecf0bfcf2019-12-13 08:08:21 -0800539 return quiche::QuicheStrCat(
dschinazi142051a2019-09-18 18:17:29 -0700540 ParsedQuicVersionToString(p.version), "_",
541 (p.ack_response == AckResponse::kDefer ? "defer" : "immediate"), "_",
542 (p.no_stop_waiting ? "No" : ""), "StopWaiting");
543}
544
QUICHE teama6ef0a62019-03-07 20:34:33 -0500545// Constructs various test permutations.
546std::vector<TestParams> GetTestParams() {
547 QuicFlagSaver flags;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500548 std::vector<TestParams> params;
549 ParsedQuicVersionVector all_supported_versions = AllSupportedVersions();
550 for (size_t i = 0; i < all_supported_versions.size(); ++i) {
551 for (AckResponse ack_response :
552 {AckResponse::kDefer, AckResponse::kImmediate}) {
dschinazi142051a2019-09-18 18:17:29 -0700553 params.push_back(
554 TestParams(all_supported_versions[i], ack_response, true));
555 if (!VersionHasIetfInvariantHeader(
556 all_supported_versions[i].transport_version)) {
fayangd4291e42019-05-30 10:31:21 -0700557 params.push_back(
dschinazi142051a2019-09-18 18:17:29 -0700558 TestParams(all_supported_versions[i], ack_response, false));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500559 }
560 }
561 }
562 return params;
563}
564
565class QuicConnectionTest : public QuicTestWithParam<TestParams> {
fkastenholz5d880a92019-06-21 09:01:56 -0700566 public:
567 // For tests that do silent connection closes, no such packet is generated. In
568 // order to verify the contents of the OnConnectionClosed upcall, EXPECTs
569 // should invoke this method, saving the frame, and then the test can verify
570 // the contents.
571 void SaveConnectionCloseFrame(const QuicConnectionCloseFrame& frame,
572 ConnectionCloseSource /*source*/) {
573 saved_connection_close_frame_ = frame;
574 connection_close_frame_count_++;
575 }
576
QUICHE teama6ef0a62019-03-07 20:34:33 -0500577 protected:
578 QuicConnectionTest()
579 : connection_id_(TestConnectionId()),
580 framer_(SupportedVersions(version()),
581 QuicTime::Zero(),
582 Perspective::IS_CLIENT,
583 connection_id_.length()),
584 send_algorithm_(new StrictMock<MockSendAlgorithm>),
585 loss_algorithm_(new MockLossAlgorithm()),
586 helper_(new TestConnectionHelper(&clock_, &random_generator_)),
587 alarm_factory_(new TestAlarmFactory()),
588 peer_framer_(SupportedVersions(version()),
589 QuicTime::Zero(),
590 Perspective::IS_SERVER,
591 connection_id_.length()),
592 peer_creator_(connection_id_,
593 &peer_framer_,
594 /*delegate=*/nullptr),
danzhc19a9502020-09-29 16:02:33 -0700595 writer_(
596 new TestPacketWriter(version(), &clock_, Perspective::IS_CLIENT)),
QUICHE teama6ef0a62019-03-07 20:34:33 -0500597 connection_(connection_id_,
wub5df36632020-10-01 14:42:17 -0700598 kSelfAddress,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500599 kPeerAddress,
600 helper_.get(),
601 alarm_factory_.get(),
602 writer_.get(),
603 Perspective::IS_CLIENT,
604 version()),
605 creator_(QuicConnectionPeer::GetPacketCreator(&connection_)),
QUICHE teama6ef0a62019-03-07 20:34:33 -0500606 manager_(QuicConnectionPeer::GetSentPacketManager(&connection_)),
dmcardlecf0bfcf2019-12-13 08:08:21 -0800607 frame1_(0, false, 0, quiche::QuicheStringPiece(data1)),
608 frame2_(0, false, 3, quiche::QuicheStringPiece(data2)),
609 crypto_frame_(ENCRYPTION_INITIAL, 0, quiche::QuicheStringPiece(data1)),
QUICHE teama6ef0a62019-03-07 20:34:33 -0500610 packet_number_length_(PACKET_4BYTE_PACKET_NUMBER),
611 connection_id_included_(CONNECTION_ID_PRESENT),
fkastenholz5d880a92019-06-21 09:01:56 -0700612 notifier_(&connection_),
613 connection_close_frame_count_(0) {
dschinazi142051a2019-09-18 18:17:29 -0700614 QUIC_DVLOG(2) << "QuicConnectionTest(" << PrintToString(GetParam()) << ")";
QUICHE teama6ef0a62019-03-07 20:34:33 -0500615 connection_.set_defer_send_in_response_to_packets(GetParam().ack_response ==
616 AckResponse::kDefer);
nharperc6b99512019-09-19 11:13:48 -0700617 framer_.SetInitialObfuscators(TestConnectionId());
618 connection_.InstallInitialCrypters(TestConnectionId());
619 CrypterPair crypters;
620 CryptoUtils::CreateInitialObfuscators(Perspective::IS_SERVER, version(),
621 TestConnectionId(), &crypters);
622 peer_creator_.SetEncrypter(ENCRYPTION_INITIAL,
623 std::move(crypters.encrypter));
624 if (version().KnowsWhichDecrypterToUse()) {
625 peer_framer_.InstallDecrypter(ENCRYPTION_INITIAL,
626 std::move(crypters.decrypter));
627 } else {
628 peer_framer_.SetDecrypter(ENCRYPTION_INITIAL,
629 std::move(crypters.decrypter));
630 }
nharper2c9f02a2019-05-08 10:25:50 -0700631 for (EncryptionLevel level :
632 {ENCRYPTION_ZERO_RTT, ENCRYPTION_FORWARD_SECURE}) {
633 peer_creator_.SetEncrypter(
vasilvv0fc587f2019-09-06 13:33:08 -0700634 level, std::make_unique<NullEncrypter>(peer_framer_.perspective()));
nharper2c9f02a2019-05-08 10:25:50 -0700635 }
dschinazi7b9278c2019-05-20 07:36:21 -0700636 QuicFramerPeer::SetLastSerializedServerConnectionId(
QUICHE teama6ef0a62019-03-07 20:34:33 -0500637 QuicConnectionPeer::GetFramer(&connection_), connection_id_);
nharperc6b99512019-09-19 11:13:48 -0700638 QuicFramerPeer::SetLastWrittenPacketNumberLength(
639 QuicConnectionPeer::GetFramer(&connection_), packet_number_length_);
fayangd4291e42019-05-30 10:31:21 -0700640 if (VersionHasIetfInvariantHeader(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500641 EXPECT_TRUE(QuicConnectionPeer::GetNoStopWaitingFrames(&connection_));
642 } else {
643 QuicConnectionPeer::SetNoStopWaitingFrames(&connection_,
644 GetParam().no_stop_waiting);
645 }
nharper46833c32019-05-15 21:33:05 -0700646 QuicStreamId stream_id;
647 if (QuicVersionUsesCryptoFrames(version().transport_version)) {
648 stream_id = QuicUtils::GetFirstBidirectionalStreamId(
649 version().transport_version, Perspective::IS_CLIENT);
650 } else {
651 stream_id = QuicUtils::GetCryptoStreamId(version().transport_version);
652 }
653 frame1_.stream_id = stream_id;
654 frame2_.stream_id = stream_id;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500655 connection_.set_visitor(&visitor_);
fayangcff885a2019-10-22 07:39:04 -0700656 connection_.SetSessionNotifier(&notifier_);
657 connection_.set_notifier(&notifier_);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500658 connection_.SetSendAlgorithm(send_algorithm_);
659 connection_.SetLossAlgorithm(loss_algorithm_.get());
660 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
661 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
662 .Times(AnyNumber());
wubf4ab9652020-02-20 14:45:43 -0800663 EXPECT_CALL(*send_algorithm_, OnPacketNeutered(_)).Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -0500664 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
665 .WillRepeatedly(Return(kDefaultTCPMSS));
666 EXPECT_CALL(*send_algorithm_, PacingRate(_))
667 .WillRepeatedly(Return(QuicBandwidth::Zero()));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500668 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
669 .Times(AnyNumber())
670 .WillRepeatedly(Return(QuicBandwidth::Zero()));
wub5cd49592019-11-25 15:17:13 -0800671 EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_))
672 .Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -0500673 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
674 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
675 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
676 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).Times(AnyNumber());
fayangd58736d2019-11-27 13:35:31 -0800677 EXPECT_CALL(visitor_, OnPacketDecrypted(_)).Times(AnyNumber());
fayangcff885a2019-10-22 07:39:04 -0700678 EXPECT_CALL(visitor_, OnCanWrite())
679 .WillRepeatedly(Invoke(&notifier_, &SimpleSessionNotifier::OnCanWrite));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500680 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
681 .WillRepeatedly(Return(false));
682 EXPECT_CALL(visitor_, OnCongestionWindowChange(_)).Times(AnyNumber());
zhongyi83161e42019-08-19 09:06:25 -0700683 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(AnyNumber());
wub256b2d62019-11-25 08:46:55 -0800684 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
fayang2f2915d2020-01-24 06:47:15 -0800685 EXPECT_CALL(visitor_, OnOneRttPacketAcknowledged())
686 .Times(testing::AtMost(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500687 EXPECT_CALL(*loss_algorithm_, GetLossTimeout())
688 .WillRepeatedly(Return(QuicTime::Zero()));
689 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
690 .Times(AnyNumber());
fayang5014e922020-01-22 12:28:11 -0800691 EXPECT_CALL(visitor_, GetHandshakeState())
692 .WillRepeatedly(Return(HANDSHAKE_START));
zhongyi546cc452019-04-12 15:27:49 -0700693 if (connection_.version().KnowsWhichDecrypterToUse()) {
694 connection_.InstallDecrypter(
695 ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -0700696 std::make_unique<NullDecrypter>(Perspective::IS_CLIENT));
zhongyi546cc452019-04-12 15:27:49 -0700697 }
danzh8a27a1a2020-09-02 10:26:28 -0700698 peer_creator_.SetDefaultPeerAddress(kSelfAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500699 }
700
701 QuicConnectionTest(const QuicConnectionTest&) = delete;
702 QuicConnectionTest& operator=(const QuicConnectionTest&) = delete;
703
704 ParsedQuicVersion version() { return GetParam().version; }
705
QUICHE teama6ef0a62019-03-07 20:34:33 -0500706 QuicStopWaitingFrame* stop_waiting() {
707 QuicConnectionPeer::PopulateStopWaitingFrame(&connection_, &stop_waiting_);
708 return &stop_waiting_;
709 }
710
711 QuicPacketNumber least_unacked() {
712 if (writer_->stop_waiting_frames().empty()) {
713 return QuicPacketNumber();
714 }
715 return writer_->stop_waiting_frames()[0].least_unacked;
716 }
717
718 void use_tagging_decrypter() { writer_->use_tagging_decrypter(); }
719
zhongyi546cc452019-04-12 15:27:49 -0700720 void SetDecrypter(EncryptionLevel level,
721 std::unique_ptr<QuicDecrypter> decrypter) {
722 if (connection_.version().KnowsWhichDecrypterToUse()) {
723 connection_.InstallDecrypter(level, std::move(decrypter));
724 connection_.RemoveDecrypter(ENCRYPTION_INITIAL);
725 } else {
726 connection_.SetDecrypter(level, std::move(decrypter));
727 }
728 }
729
QUICHE teama6ef0a62019-03-07 20:34:33 -0500730 void ProcessPacket(uint64_t number) {
731 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
732 ProcessDataPacket(number);
733 if (connection_.GetSendAlarm()->IsSet()) {
734 connection_.GetSendAlarm()->Fire();
735 }
736 }
737
738 void ProcessReceivedPacket(const QuicSocketAddress& self_address,
739 const QuicSocketAddress& peer_address,
740 const QuicReceivedPacket& packet) {
741 connection_.ProcessUdpPacket(self_address, peer_address, packet);
742 if (connection_.GetSendAlarm()->IsSet()) {
743 connection_.GetSendAlarm()->Fire();
744 }
745 }
746
wub8a5dafa2020-05-13 12:30:17 -0700747 QuicFrame MakeCryptoFrame() const {
748 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
749 return QuicFrame(new QuicCryptoFrame(crypto_frame_));
750 }
751 return QuicFrame(QuicStreamFrame(
752 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
753 0u, quiche::QuicheStringPiece()));
754 }
755
QUICHE teama6ef0a62019-03-07 20:34:33 -0500756 void ProcessFramePacket(QuicFrame frame) {
fayangf08e1792020-09-30 13:23:42 -0700757 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress,
758 ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500759 }
760
761 void ProcessFramePacketWithAddresses(QuicFrame frame,
762 QuicSocketAddress self_address,
fayangf08e1792020-09-30 13:23:42 -0700763 QuicSocketAddress peer_address,
764 EncryptionLevel level) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500765 QuicFrames frames;
766 frames.push_back(QuicFrame(frame));
fayangf08e1792020-09-30 13:23:42 -0700767 return ProcessFramesPacketWithAddresses(frames, self_address, peer_address,
768 level);
zhongyif06ca342020-02-24 14:11:13 -0800769 }
770
771 void ProcessFramesPacketWithAddresses(QuicFrames frames,
772 QuicSocketAddress self_address,
fayangf08e1792020-09-30 13:23:42 -0700773 QuicSocketAddress peer_address,
774 EncryptionLevel level) {
775 DCHECK(peer_framer_.HasEncrypterOfEncryptionLevel(level));
776 peer_creator_.set_encryption_level(level);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500777 QuicPacketCreatorPeer::SetSendVersionInPacket(
wub031d47c2019-11-21 08:04:07 -0800778 &peer_creator_,
fayangf08e1792020-09-30 13:23:42 -0700779 level < ENCRYPTION_FORWARD_SECURE &&
wub031d47c2019-11-21 08:04:07 -0800780 connection_.perspective() == Perspective::IS_SERVER);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500781
dschinazi66dea072019-04-09 11:41:06 -0700782 char buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -0500783 SerializedPacket serialized_packet =
dschinazi66dea072019-04-09 11:41:06 -0700784 QuicPacketCreatorPeer::SerializeAllFrames(
785 &peer_creator_, frames, buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500786 connection_.ProcessUdpPacket(
787 self_address, peer_address,
788 QuicReceivedPacket(serialized_packet.encrypted_buffer,
789 serialized_packet.encrypted_length, clock_.Now()));
790 if (connection_.GetSendAlarm()->IsSet()) {
791 connection_.GetSendAlarm()->Fire();
792 }
793 }
794
795 // Bypassing the packet creator is unrealistic, but allows us to process
796 // packets the QuicPacketCreator won't allow us to create.
797 void ForceProcessFramePacket(QuicFrame frame) {
798 QuicFrames frames;
799 frames.push_back(QuicFrame(frame));
zhongyi546cc452019-04-12 15:27:49 -0700800 bool send_version = connection_.perspective() == Perspective::IS_SERVER;
801 if (connection_.version().KnowsWhichDecrypterToUse()) {
802 send_version = true;
803 }
804 QuicPacketCreatorPeer::SetSendVersionInPacket(&peer_creator_, send_version);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500805 QuicPacketHeader header;
806 QuicPacketCreatorPeer::FillPacketHeader(&peer_creator_, &header);
dschinazi66dea072019-04-09 11:41:06 -0700807 char encrypted_buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -0500808 size_t length = peer_framer_.BuildDataPacket(
dschinazi66dea072019-04-09 11:41:06 -0700809 header, frames, encrypted_buffer, kMaxOutgoingPacketSize,
810 ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500811 DCHECK_GT(length, 0u);
812
813 const size_t encrypted_length = peer_framer_.EncryptInPlace(
QUICHE team6987b4a2019-03-15 16:23:04 -0700814 ENCRYPTION_INITIAL, header.packet_number,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500815 GetStartOfEncryptedData(peer_framer_.version().transport_version,
816 header),
dschinazi66dea072019-04-09 11:41:06 -0700817 length, kMaxOutgoingPacketSize, encrypted_buffer);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500818 DCHECK_GT(encrypted_length, 0u);
819
820 connection_.ProcessUdpPacket(
821 kSelfAddress, kPeerAddress,
822 QuicReceivedPacket(encrypted_buffer, encrypted_length, clock_.Now()));
823 }
824
825 size_t ProcessFramePacketAtLevel(uint64_t number,
826 QuicFrame frame,
827 EncryptionLevel level) {
fayang01062942020-01-22 07:23:23 -0800828 QuicFrames frames;
829 frames.push_back(frame);
830 return ProcessFramesPacketAtLevel(number, frames, level);
831 }
832
833 size_t ProcessFramesPacketAtLevel(uint64_t number,
834 const QuicFrames& frames,
835 EncryptionLevel level) {
fayang5c2c7b52020-07-09 13:47:16 -0400836 QuicPacketHeader header = ConstructPacketHeader(number, level);
QUICHE teamcd098022019-03-22 18:49:55 -0700837 // Set the correct encryption level and encrypter on peer_creator and
838 // peer_framer, respectively.
839 peer_creator_.set_encryption_level(level);
840 if (QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_) >
841 ENCRYPTION_INITIAL) {
842 peer_framer_.SetEncrypter(
843 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
vasilvv0fc587f2019-09-06 13:33:08 -0700844 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teamcd098022019-03-22 18:49:55 -0700845 // Set the corresponding decrypter.
zhongyi546cc452019-04-12 15:27:49 -0700846 if (connection_.version().KnowsWhichDecrypterToUse()) {
847 connection_.InstallDecrypter(
848 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
vasilvv0fc587f2019-09-06 13:33:08 -0700849 std::make_unique<StrictTaggingDecrypter>(0x01));
zhongyi546cc452019-04-12 15:27:49 -0700850 connection_.RemoveDecrypter(ENCRYPTION_INITIAL);
851 } else {
852 connection_.SetDecrypter(
853 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
vasilvv0fc587f2019-09-06 13:33:08 -0700854 std::make_unique<StrictTaggingDecrypter>(0x01));
zhongyi546cc452019-04-12 15:27:49 -0700855 }
QUICHE teamcd098022019-03-22 18:49:55 -0700856 }
fayang5c2c7b52020-07-09 13:47:16 -0400857 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500858
dschinazi66dea072019-04-09 11:41:06 -0700859 char buffer[kMaxOutgoingPacketSize];
860 size_t encrypted_length =
861 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
862 buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500863 connection_.ProcessUdpPacket(
864 kSelfAddress, kPeerAddress,
QUICHE teamcd098022019-03-22 18:49:55 -0700865 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
866 if (connection_.GetSendAlarm()->IsSet()) {
867 connection_.GetSendAlarm()->Fire();
868 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500869 return encrypted_length;
870 }
871
fayangba9d95e2020-09-24 14:30:45 -0700872 struct PacketInfo {
873 PacketInfo(uint64_t packet_number, QuicFrames frames, EncryptionLevel level)
874 : packet_number(packet_number), frames(frames), level(level) {}
875
876 uint64_t packet_number;
877 QuicFrames frames;
878 EncryptionLevel level;
879 };
880
881 size_t ProcessCoalescedPacket(std::vector<PacketInfo> packets) {
882 char coalesced_buffer[kMaxOutgoingPacketSize];
883 size_t coalesced_size = 0;
884 bool contains_initial = false;
885 for (const auto& packet : packets) {
886 QuicPacketHeader header =
887 ConstructPacketHeader(packet.packet_number, packet.level);
888 // Set the correct encryption level and encrypter on peer_creator and
889 // peer_framer, respectively.
890 peer_creator_.set_encryption_level(packet.level);
891 if (packet.level == ENCRYPTION_INITIAL) {
892 contains_initial = true;
893 }
894 if (QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_) >
895 ENCRYPTION_INITIAL) {
896 peer_framer_.SetEncrypter(
897 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
898 std::make_unique<TaggingEncrypter>(0x01));
899 // Set the corresponding decrypter.
900 if (connection_.version().KnowsWhichDecrypterToUse()) {
901 connection_.InstallDecrypter(
902 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
903 std::make_unique<StrictTaggingDecrypter>(0x01));
904 } else {
905 connection_.SetDecrypter(
906 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
907 std::make_unique<StrictTaggingDecrypter>(0x01));
908 }
909 }
910 std::unique_ptr<QuicPacket> constructed_packet(
911 ConstructPacket(header, packet.frames));
912
913 char buffer[kMaxOutgoingPacketSize];
914 size_t encrypted_length = peer_framer_.EncryptPayload(
915 packet.level, QuicPacketNumber(packet.packet_number),
916 *constructed_packet, buffer, kMaxOutgoingPacketSize);
917 DCHECK_LE(coalesced_size + encrypted_length, kMaxOutgoingPacketSize);
918 memcpy(coalesced_buffer + coalesced_size, buffer, encrypted_length);
919 coalesced_size += encrypted_length;
920 }
921 if (contains_initial) {
922 // Padded coalesced packet to full if it contains initial packet.
923 memset(coalesced_buffer + coalesced_size, '0',
924 kMaxOutgoingPacketSize - coalesced_size);
925 }
926 connection_.ProcessUdpPacket(
927 kSelfAddress, kPeerAddress,
928 QuicReceivedPacket(coalesced_buffer, coalesced_size, clock_.Now(),
929 false));
930 if (connection_.GetSendAlarm()->IsSet()) {
931 connection_.GetSendAlarm()->Fire();
932 }
933 return coalesced_size;
934 }
935
QUICHE teama6ef0a62019-03-07 20:34:33 -0500936 size_t ProcessDataPacket(uint64_t number) {
nharper2c9f02a2019-05-08 10:25:50 -0700937 return ProcessDataPacketAtLevel(number, false, ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500938 }
939
940 size_t ProcessDataPacket(QuicPacketNumber packet_number) {
nharper2c9f02a2019-05-08 10:25:50 -0700941 return ProcessDataPacketAtLevel(packet_number, false,
942 ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500943 }
944
945 size_t ProcessDataPacketAtLevel(QuicPacketNumber packet_number,
946 bool has_stop_waiting,
947 EncryptionLevel level) {
948 return ProcessDataPacketAtLevel(packet_number.ToUint64(), has_stop_waiting,
949 level);
950 }
951
fayanga39d0362020-06-22 08:57:35 -0700952 size_t ProcessCryptoPacketAtLevel(uint64_t number, EncryptionLevel level) {
953 QuicPacketHeader header = ConstructPacketHeader(number, level);
nharper46833c32019-05-15 21:33:05 -0700954 QuicFrames frames;
955 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
956 frames.push_back(QuicFrame(&crypto_frame_));
957 } else {
958 frames.push_back(QuicFrame(frame1_));
959 }
fayang5d91f082020-09-11 14:47:26 -0700960 if (level == ENCRYPTION_INITIAL) {
961 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
962 }
nharper46833c32019-05-15 21:33:05 -0700963 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
964 char buffer[kMaxOutgoingPacketSize];
fayanga39d0362020-06-22 08:57:35 -0700965 peer_creator_.set_encryption_level(level);
966 size_t encrypted_length =
967 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
968 buffer, kMaxOutgoingPacketSize);
nharper46833c32019-05-15 21:33:05 -0700969 connection_.ProcessUdpPacket(
970 kSelfAddress, kPeerAddress,
971 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
972 if (connection_.GetSendAlarm()->IsSet()) {
973 connection_.GetSendAlarm()->Fire();
974 }
975 return encrypted_length;
976 }
977
QUICHE teama6ef0a62019-03-07 20:34:33 -0500978 size_t ProcessDataPacketAtLevel(uint64_t number,
979 bool has_stop_waiting,
980 EncryptionLevel level) {
981 std::unique_ptr<QuicPacket> packet(
QUICHE team8c1daa22019-03-13 08:33:41 -0700982 ConstructDataPacket(number, has_stop_waiting, level));
dschinazi66dea072019-04-09 11:41:06 -0700983 char buffer[kMaxOutgoingPacketSize];
QUICHE teamcd098022019-03-22 18:49:55 -0700984 peer_creator_.set_encryption_level(level);
dschinazi66dea072019-04-09 11:41:06 -0700985 size_t encrypted_length =
986 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
987 buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500988 connection_.ProcessUdpPacket(
989 kSelfAddress, kPeerAddress,
990 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
991 if (connection_.GetSendAlarm()->IsSet()) {
992 connection_.GetSendAlarm()->Fire();
993 }
994 return encrypted_length;
995 }
996
997 void ProcessClosePacket(uint64_t number) {
998 std::unique_ptr<QuicPacket> packet(ConstructClosePacket(number));
dschinazi66dea072019-04-09 11:41:06 -0700999 char buffer[kMaxOutgoingPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07001000 size_t encrypted_length = peer_framer_.EncryptPayload(
nharperc6b99512019-09-19 11:13:48 -07001001 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(number), *packet, buffer,
dschinazi66dea072019-04-09 11:41:06 -07001002 kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001003 connection_.ProcessUdpPacket(
1004 kSelfAddress, kPeerAddress,
1005 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
1006 }
1007
1008 QuicByteCount SendStreamDataToPeer(QuicStreamId id,
dmcardlecf0bfcf2019-12-13 08:08:21 -08001009 quiche::QuicheStringPiece data,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001010 QuicStreamOffset offset,
1011 StreamSendingState state,
1012 QuicPacketNumber* last_packet) {
1013 QuicByteCount packet_size;
fayang0fcbf352019-08-30 11:15:58 -07001014 // Save the last packet's size.
QUICHE teama6ef0a62019-03-07 20:34:33 -05001015 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
fayang0fcbf352019-08-30 11:15:58 -07001016 .Times(AnyNumber())
1017 .WillRepeatedly(SaveArg<3>(&packet_size));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001018 connection_.SendStreamDataWithString(id, data, offset, state);
1019 if (last_packet != nullptr) {
1020 *last_packet = creator_->packet_number();
1021 }
1022 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1023 .Times(AnyNumber());
1024 return packet_size;
1025 }
1026
1027 void SendAckPacketToPeer() {
1028 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1029 {
fayanga4b37b22019-06-18 13:37:47 -07001030 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001031 connection_.SendAck();
1032 }
1033 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1034 .Times(AnyNumber());
1035 }
1036
1037 void SendRstStream(QuicStreamId id,
1038 QuicRstStreamErrorCode error,
1039 QuicStreamOffset bytes_written) {
fayangcff885a2019-10-22 07:39:04 -07001040 notifier_.WriteOrBufferRstStream(id, error, bytes_written);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001041 connection_.OnStreamReset(id, error);
1042 }
1043
fayangcff885a2019-10-22 07:39:04 -07001044 void SendPing() { notifier_.WriteOrBufferPing(); }
zhongyifbb25772019-04-10 16:54:08 -07001045
fayang61453cb2020-03-11 11:32:26 -07001046 MessageStatus SendMessage(quiche::QuicheStringPiece message) {
1047 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1048 QuicMemSliceStorage storage(nullptr, 0, nullptr, 0);
1049 return connection_.SendMessage(
1050 1,
1051 MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(), message,
1052 &storage),
1053 false);
1054 }
1055
QUICHE teama6ef0a62019-03-07 20:34:33 -05001056 void ProcessAckPacket(uint64_t packet_number, QuicAckFrame* frame) {
1057 if (packet_number > 1) {
1058 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, packet_number - 1);
1059 } else {
1060 QuicPacketCreatorPeer::ClearPacketNumber(&peer_creator_);
1061 }
1062 ProcessFramePacket(QuicFrame(frame));
1063 }
1064
1065 void ProcessAckPacket(QuicAckFrame* frame) {
1066 ProcessFramePacket(QuicFrame(frame));
1067 }
1068
1069 void ProcessStopWaitingPacket(QuicStopWaitingFrame frame) {
1070 ProcessFramePacket(QuicFrame(frame));
1071 }
1072
1073 size_t ProcessStopWaitingPacketAtLevel(uint64_t number,
1074 QuicStopWaitingFrame frame,
dschinazi17d42422019-06-18 16:35:07 -07001075 EncryptionLevel /*level*/) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001076 return ProcessFramePacketAtLevel(number, QuicFrame(frame),
1077 ENCRYPTION_ZERO_RTT);
1078 }
1079
1080 void ProcessGoAwayPacket(QuicGoAwayFrame* frame) {
1081 ProcessFramePacket(QuicFrame(frame));
1082 }
1083
1084 bool IsMissing(uint64_t number) {
fayangc31c9952019-06-05 13:54:48 -07001085 return IsAwaitingPacket(connection_.ack_frame(), QuicPacketNumber(number),
QUICHE teama6ef0a62019-03-07 20:34:33 -05001086 QuicPacketNumber());
1087 }
1088
1089 std::unique_ptr<QuicPacket> ConstructPacket(const QuicPacketHeader& header,
1090 const QuicFrames& frames) {
1091 auto packet = BuildUnsizedDataPacket(&peer_framer_, header, frames);
1092 EXPECT_NE(nullptr, packet.get());
1093 return packet;
1094 }
1095
nharper46833c32019-05-15 21:33:05 -07001096 QuicPacketHeader ConstructPacketHeader(uint64_t number,
1097 EncryptionLevel level) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001098 QuicPacketHeader header;
fayangd4291e42019-05-30 10:31:21 -07001099 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version()) &&
QUICHE team8c1daa22019-03-13 08:33:41 -07001100 level < ENCRYPTION_FORWARD_SECURE) {
1101 // Set long header type accordingly.
1102 header.version_flag = true;
nharperc6b99512019-09-19 11:13:48 -07001103 header.form = IETF_QUIC_LONG_HEADER_PACKET;
QUICHE team8c1daa22019-03-13 08:33:41 -07001104 header.long_packet_type = EncryptionlevelToLongHeaderType(level);
1105 if (QuicVersionHasLongHeaderLengths(
1106 peer_framer_.version().transport_version)) {
1107 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
1108 if (header.long_packet_type == INITIAL) {
1109 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
1110 }
1111 }
1112 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001113 // Set connection_id to peer's in memory representation as this data packet
1114 // is created by peer_framer.
dschinazi5e1a7b22019-07-31 12:23:21 -07001115 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
QUICHE team2252b702019-05-14 23:55:14 -04001116 header.source_connection_id = connection_id_;
1117 header.source_connection_id_included = connection_id_included_;
1118 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1119 } else {
1120 header.destination_connection_id = connection_id_;
1121 header.destination_connection_id_included = connection_id_included_;
1122 }
fayangd4291e42019-05-30 10:31:21 -07001123 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version()) &&
QUICHE teama6ef0a62019-03-07 20:34:33 -05001124 peer_framer_.perspective() == Perspective::IS_SERVER) {
1125 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
QUICHE team8c1daa22019-03-13 08:33:41 -07001126 if (header.version_flag) {
1127 header.source_connection_id = connection_id_;
1128 header.source_connection_id_included = CONNECTION_ID_PRESENT;
1129 if (GetParam().version.handshake_protocol == PROTOCOL_QUIC_CRYPTO &&
1130 header.long_packet_type == ZERO_RTT_PROTECTED) {
QUICHE team548d51b2019-03-14 10:06:54 -07001131 header.nonce = &kTestDiversificationNonce;
QUICHE team8c1daa22019-03-13 08:33:41 -07001132 }
1133 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001134 }
QUICHE team2252b702019-05-14 23:55:14 -04001135 header.packet_number_length = packet_number_length_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001136 header.packet_number = QuicPacketNumber(number);
nharper46833c32019-05-15 21:33:05 -07001137 return header;
1138 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001139
nharper46833c32019-05-15 21:33:05 -07001140 std::unique_ptr<QuicPacket> ConstructDataPacket(uint64_t number,
1141 bool has_stop_waiting,
1142 EncryptionLevel level) {
1143 QuicPacketHeader header = ConstructPacketHeader(number, level);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001144 QuicFrames frames;
1145 frames.push_back(QuicFrame(frame1_));
1146 if (has_stop_waiting) {
1147 frames.push_back(QuicFrame(stop_waiting_));
1148 }
1149 return ConstructPacket(header, frames);
1150 }
1151
wub8a5dafa2020-05-13 12:30:17 -07001152 std::unique_ptr<SerializedPacket> ConstructProbingPacket() {
fayangf08e1792020-09-30 13:23:42 -07001153 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
fkastenholz305e1732019-06-18 05:01:22 -07001154 if (VersionHasIetfQuicFrames(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001155 QuicPathFrameBuffer payload = {
1156 {0xde, 0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xfe}};
1157 return QuicPacketCreatorPeer::
1158 SerializePathChallengeConnectivityProbingPacket(&peer_creator_,
1159 &payload);
1160 }
1161 return QuicPacketCreatorPeer::SerializeConnectivityProbingPacket(
1162 &peer_creator_);
1163 }
1164
1165 std::unique_ptr<QuicPacket> ConstructClosePacket(uint64_t number) {
fayangf08e1792020-09-30 13:23:42 -07001166 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001167 QuicPacketHeader header;
1168 // Set connection_id to peer's in memory representation as this connection
1169 // close packet is created by peer_framer.
dschinazi5e1a7b22019-07-31 12:23:21 -07001170 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
QUICHE team2252b702019-05-14 23:55:14 -04001171 header.source_connection_id = connection_id_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001172 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
fayangd4291e42019-05-30 10:31:21 -07001173 if (!VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04001174 header.source_connection_id_included = CONNECTION_ID_PRESENT;
1175 }
1176 } else {
1177 header.destination_connection_id = connection_id_;
fayangd4291e42019-05-30 10:31:21 -07001178 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04001179 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1180 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001181 }
1182
QUICHE team2252b702019-05-14 23:55:14 -04001183 header.packet_number = QuicPacketNumber(number);
1184
fkastenholz0d6554a2019-08-05 12:20:35 -07001185 QuicErrorCode kQuicErrorCode = QUIC_PEER_GOING_AWAY;
fkastenholz591814c2019-09-06 12:11:46 -07001186 QuicConnectionCloseFrame qccf(peer_framer_.transport_version(),
1187 kQuicErrorCode, "",
1188 /*transport_close_frame_type=*/0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001189 QuicFrames frames;
1190 frames.push_back(QuicFrame(&qccf));
1191 return ConstructPacket(header, frames);
1192 }
1193
1194 QuicTime::Delta DefaultRetransmissionTime() {
1195 return QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
1196 }
1197
1198 QuicTime::Delta DefaultDelayedAckTime() {
1199 return QuicTime::Delta::FromMilliseconds(kDefaultDelayedAckTimeMs);
1200 }
1201
1202 const QuicStopWaitingFrame InitStopWaitingFrame(uint64_t least_unacked) {
1203 QuicStopWaitingFrame frame;
1204 frame.least_unacked = QuicPacketNumber(least_unacked);
1205 return frame;
1206 }
1207
1208 // Construct a ack_frame that acks all packet numbers between 1 and
1209 // |largest_acked|, except |missing|.
1210 // REQUIRES: 1 <= |missing| < |largest_acked|
1211 QuicAckFrame ConstructAckFrame(uint64_t largest_acked, uint64_t missing) {
1212 return ConstructAckFrame(QuicPacketNumber(largest_acked),
1213 QuicPacketNumber(missing));
1214 }
1215
1216 QuicAckFrame ConstructAckFrame(QuicPacketNumber largest_acked,
1217 QuicPacketNumber missing) {
1218 if (missing == QuicPacketNumber(1)) {
1219 return InitAckFrame({{missing + 1, largest_acked + 1}});
1220 }
1221 return InitAckFrame(
1222 {{QuicPacketNumber(1), missing}, {missing + 1, largest_acked + 1}});
1223 }
1224
1225 // Undo nacking a packet within the frame.
1226 void AckPacket(QuicPacketNumber arrived, QuicAckFrame* frame) {
1227 EXPECT_FALSE(frame->packets.Contains(arrived));
1228 frame->packets.Add(arrived);
1229 }
1230
1231 void TriggerConnectionClose() {
1232 // Send an erroneous packet to close the connection.
fkastenholz5d880a92019-06-21 09:01:56 -07001233 EXPECT_CALL(visitor_,
1234 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
1235 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
1236
QUICHE teamcd098022019-03-22 18:49:55 -07001237 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1238 // Triggers a connection by receiving ACK of unsent packet.
1239 QuicAckFrame frame = InitAckFrame(10000);
1240 ProcessAckPacket(1, &frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001241 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1242 nullptr);
fkastenholz5d880a92019-06-21 09:01:56 -07001243 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08001244 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
1245 IsError(QUIC_INVALID_ACK_DATA));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001246 }
1247
1248 void BlockOnNextWrite() {
1249 writer_->BlockOnNextWrite();
1250 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
1251 }
1252
1253 void SimulateNextPacketTooLarge() { writer_->SimulateNextPacketTooLarge(); }
1254
1255 void AlwaysGetPacketTooLarge() { writer_->AlwaysGetPacketTooLarge(); }
1256
1257 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
1258 writer_->SetWritePauseTimeDelta(delta);
1259 }
1260
1261 void CongestionBlockWrites() {
1262 EXPECT_CALL(*send_algorithm_, CanSend(_))
1263 .WillRepeatedly(testing::Return(false));
1264 }
1265
1266 void CongestionUnblockWrites() {
1267 EXPECT_CALL(*send_algorithm_, CanSend(_))
1268 .WillRepeatedly(testing::Return(true));
1269 }
1270
1271 void set_perspective(Perspective perspective) {
1272 connection_.set_perspective(perspective);
1273 if (perspective == Perspective::IS_SERVER) {
1274 connection_.set_can_truncate_connection_ids(true);
wub256b2d62019-11-25 08:46:55 -08001275 QuicConnectionPeer::SetNegotiatedVersion(&connection_);
wubbea386e2020-01-27 09:04:51 -08001276 connection_.OnSuccessfulVersionNegotiation();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001277 }
1278 QuicFramerPeer::SetPerspective(&peer_framer_,
nharper4eba09b2019-06-26 20:17:25 -07001279 QuicUtils::InvertPerspective(perspective));
danzhc19a9502020-09-29 16:02:33 -07001280 peer_framer_.SetInitialObfuscators(TestConnectionId());
1281 for (EncryptionLevel level : {ENCRYPTION_ZERO_RTT, ENCRYPTION_HANDSHAKE,
1282 ENCRYPTION_FORWARD_SECURE}) {
1283 if (peer_framer_.HasEncrypterOfEncryptionLevel(level)) {
1284 peer_creator_.SetEncrypter(
1285 level, std::make_unique<NullEncrypter>(peer_framer_.perspective()));
1286 }
1287 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001288 }
1289
1290 void set_packets_between_probes_base(
1291 const QuicPacketCount packets_between_probes_base) {
wub173916e2019-11-27 14:36:24 -08001292 QuicConnectionPeer::ReInitializeMtuDiscoverer(
1293 &connection_, packets_between_probes_base,
1294 QuicPacketNumber(packets_between_probes_base));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001295 }
1296
1297 bool IsDefaultTestConfiguration() {
1298 TestParams p = GetParam();
1299 return p.ack_response == AckResponse::kImmediate &&
1300 p.version == AllSupportedVersions()[0] && p.no_stop_waiting;
1301 }
1302
fkastenholz5d880a92019-06-21 09:01:56 -07001303 void TestConnectionCloseQuicErrorCode(QuicErrorCode expected_code) {
1304 // Not strictly needed for this test, but is commonly done.
1305 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1306 nullptr);
1307 const std::vector<QuicConnectionCloseFrame>& connection_close_frames =
1308 writer_->connection_close_frames();
1309 ASSERT_EQ(1u, connection_close_frames.size());
bnc77e77b82020-04-05 10:36:49 -07001310
dschinazi39e5e552020-05-06 13:55:24 -07001311 EXPECT_THAT(connection_close_frames[0].quic_error_code,
1312 IsError(expected_code));
bnc77e77b82020-04-05 10:36:49 -07001313
fkastenholz0d6554a2019-08-05 12:20:35 -07001314 if (!VersionHasIetfQuicFrames(version().transport_version)) {
dschinazi39e5e552020-05-06 13:55:24 -07001315 EXPECT_THAT(connection_close_frames[0].wire_error_code,
1316 IsError(expected_code));
fkastenholz0d6554a2019-08-05 12:20:35 -07001317 EXPECT_EQ(GOOGLE_QUIC_CONNECTION_CLOSE,
1318 connection_close_frames[0].close_type);
1319 return;
1320 }
1321
1322 QuicErrorCodeToIetfMapping mapping =
1323 QuicErrorCodeToTransportErrorCode(expected_code);
1324
bnc0054cc62020-04-09 18:22:57 -07001325 if (mapping.is_transport_close) {
fkastenholz0d6554a2019-08-05 12:20:35 -07001326 // This Google QUIC Error Code maps to a transport close,
1327 EXPECT_EQ(IETF_QUIC_TRANSPORT_CONNECTION_CLOSE,
1328 connection_close_frames[0].close_type);
fkastenholz0d6554a2019-08-05 12:20:35 -07001329 } else {
1330 // This maps to an application close.
fkastenholz0d6554a2019-08-05 12:20:35 -07001331 EXPECT_EQ(IETF_QUIC_APPLICATION_CONNECTION_CLOSE,
1332 connection_close_frames[0].close_type);
fkastenholz0d6554a2019-08-05 12:20:35 -07001333 }
bnc0054cc62020-04-09 18:22:57 -07001334 EXPECT_EQ(mapping.error_code, connection_close_frames[0].wire_error_code);
fkastenholz5d880a92019-06-21 09:01:56 -07001335 }
1336
wub031d47c2019-11-21 08:04:07 -08001337 void MtuDiscoveryTestInit() {
1338 set_perspective(Perspective::IS_SERVER);
wub031d47c2019-11-21 08:04:07 -08001339 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
fayang6a258412020-05-28 08:57:12 -07001340 if (version().SupportsAntiAmplificationLimit()) {
1341 QuicConnectionPeer::SetAddressValidated(&connection_);
1342 }
wub031d47c2019-11-21 08:04:07 -08001343 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1344 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
1345 // QuicFramer::GetMaxPlaintextSize uses the smallest max plaintext size
1346 // across all encrypters. The initial encrypter used with IETF QUIC has a
1347 // 16-byte overhead, while the NullEncrypter used throughout this test has a
1348 // 12-byte overhead. This test tests behavior that relies on computing the
1349 // packet size correctly, so by unsetting the initial encrypter, we avoid
1350 // having a mismatch between the overheads for the encrypters used. In
1351 // non-test scenarios all encrypters used for a given connection have the
1352 // same overhead, either 12 bytes for ones using Google QUIC crypto, or 16
1353 // bytes for ones using TLS.
1354 connection_.SetEncrypter(ENCRYPTION_INITIAL, nullptr);
wubecb643f2020-03-19 08:58:46 -07001355 // Prevent packets from being coalesced.
1356 EXPECT_CALL(visitor_, GetHandshakeState())
1357 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
wub031d47c2019-11-21 08:04:07 -08001358 EXPECT_TRUE(connection_.connected());
1359 }
1360
dschinazi1c6e5922020-06-19 10:35:03 -07001361 void PathProbeTestInit(Perspective perspective) {
1362 set_perspective(perspective);
1363 EXPECT_EQ(connection_.perspective(), perspective);
1364 if (perspective == Perspective::IS_SERVER) {
1365 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1366 }
1367 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1368 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
danzh8a27a1a2020-09-02 10:26:28 -07001369 // Prevent packets from being coalesced.
1370 EXPECT_CALL(visitor_, GetHandshakeState())
1371 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
dschinazi1c6e5922020-06-19 10:35:03 -07001372 }
1373
dschinazi39e5e552020-05-06 13:55:24 -07001374 void TestClientRetryHandling(bool invalid_retry_tag,
dschinazie7c38a52020-05-29 15:25:45 -07001375 bool missing_original_id_in_config,
1376 bool wrong_original_id_in_config,
1377 bool missing_retry_id_in_config,
1378 bool wrong_retry_id_in_config);
dschinazi39e5e552020-05-06 13:55:24 -07001379
QUICHE teama6ef0a62019-03-07 20:34:33 -05001380 QuicConnectionId connection_id_;
1381 QuicFramer framer_;
1382
1383 MockSendAlgorithm* send_algorithm_;
1384 std::unique_ptr<MockLossAlgorithm> loss_algorithm_;
1385 MockClock clock_;
1386 MockRandom random_generator_;
1387 SimpleBufferAllocator buffer_allocator_;
1388 std::unique_ptr<TestConnectionHelper> helper_;
1389 std::unique_ptr<TestAlarmFactory> alarm_factory_;
1390 QuicFramer peer_framer_;
1391 QuicPacketCreator peer_creator_;
1392 std::unique_ptr<TestPacketWriter> writer_;
1393 TestConnection connection_;
1394 QuicPacketCreator* creator_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001395 QuicSentPacketManager* manager_;
1396 StrictMock<MockQuicConnectionVisitor> visitor_;
1397
1398 QuicStreamFrame frame1_;
1399 QuicStreamFrame frame2_;
nharper46833c32019-05-15 21:33:05 -07001400 QuicCryptoFrame crypto_frame_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001401 QuicAckFrame ack_;
1402 QuicStopWaitingFrame stop_waiting_;
1403 QuicPacketNumberLength packet_number_length_;
1404 QuicConnectionIdIncluded connection_id_included_;
1405
1406 SimpleSessionNotifier notifier_;
fkastenholz5d880a92019-06-21 09:01:56 -07001407
1408 QuicConnectionCloseFrame saved_connection_close_frame_;
1409 int connection_close_frame_count_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001410};
1411
1412// Run all end to end tests with all supported versions.
dschinazi39e5e552020-05-06 13:55:24 -07001413INSTANTIATE_TEST_SUITE_P(QuicConnectionTests,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001414 QuicConnectionTest,
dschinazi142051a2019-09-18 18:17:29 -07001415 ::testing::ValuesIn(GetTestParams()),
1416 ::testing::PrintToStringParamName());
QUICHE teama6ef0a62019-03-07 20:34:33 -05001417
fkastenholz0d6554a2019-08-05 12:20:35 -07001418// These two tests ensure that the QuicErrorCode mapping works correctly.
1419// Both tests expect to see a Google QUIC close if not running IETF QUIC.
1420// If running IETF QUIC, the first will generate a transport connection
1421// close, the second an application connection close.
1422// The connection close codes for the two tests are manually chosen;
1423// they are expected to always map to transport- and application-
dschinazi39e5e552020-05-06 13:55:24 -07001424// closes, respectively. If that changes, new codes should be chosen.
fkastenholz0d6554a2019-08-05 12:20:35 -07001425TEST_P(QuicConnectionTest, CloseErrorCodeTestTransport) {
1426 EXPECT_TRUE(connection_.connected());
1427 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
1428 connection_.CloseConnection(
1429 IETF_QUIC_PROTOCOL_VIOLATION, "Should be transport close",
1430 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1431 EXPECT_FALSE(connection_.connected());
1432 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
1433}
1434
1435// Test that the IETF QUIC Error code mapping function works
1436// properly for application connection close codes.
1437TEST_P(QuicConnectionTest, CloseErrorCodeTestApplication) {
1438 EXPECT_TRUE(connection_.connected());
1439 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
1440 connection_.CloseConnection(
1441 QUIC_HEADERS_STREAM_DATA_DECOMPRESS_FAILURE,
1442 "Should be application close",
1443 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1444 EXPECT_FALSE(connection_.connected());
1445 TestConnectionCloseQuicErrorCode(QUIC_HEADERS_STREAM_DATA_DECOMPRESS_FAILURE);
1446}
1447
QUICHE teama6ef0a62019-03-07 20:34:33 -05001448TEST_P(QuicConnectionTest, SelfAddressChangeAtClient) {
1449 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1450
1451 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
1452 EXPECT_TRUE(connection_.connected());
1453
nharper46833c32019-05-15 21:33:05 -07001454 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07001455 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1456 } else {
nharper46833c32019-05-15 21:33:05 -07001457 EXPECT_CALL(visitor_, OnStreamFrame(_));
1458 }
fayangf08e1792020-09-30 13:23:42 -07001459 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
1460 ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001461 // Cause change in self_address.
1462 QuicIpAddress host;
1463 host.FromString("1.1.1.1");
1464 QuicSocketAddress self_address(host, 123);
nharper46833c32019-05-15 21:33:05 -07001465 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1466 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1467 } else {
1468 EXPECT_CALL(visitor_, OnStreamFrame(_));
1469 }
fayangf08e1792020-09-30 13:23:42 -07001470 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address, kPeerAddress,
1471 ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001472 EXPECT_TRUE(connection_.connected());
1473}
1474
1475TEST_P(QuicConnectionTest, SelfAddressChangeAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001476 set_perspective(Perspective::IS_SERVER);
1477 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1478
1479 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1480 EXPECT_TRUE(connection_.connected());
1481
nharper46833c32019-05-15 21:33:05 -07001482 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07001483 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1484 } else {
nharper46833c32019-05-15 21:33:05 -07001485 EXPECT_CALL(visitor_, OnStreamFrame(_));
1486 }
fayangf08e1792020-09-30 13:23:42 -07001487 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
1488 ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001489 // Cause change in self_address.
1490 QuicIpAddress host;
1491 host.FromString("1.1.1.1");
1492 QuicSocketAddress self_address(host, 123);
1493 EXPECT_CALL(visitor_, AllowSelfAddressChange()).WillOnce(Return(false));
fkastenholz5d880a92019-06-21 09:01:56 -07001494 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
fayangf08e1792020-09-30 13:23:42 -07001495 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address, kPeerAddress,
1496 ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001497 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07001498 TestConnectionCloseQuicErrorCode(QUIC_ERROR_MIGRATING_ADDRESS);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001499}
1500
1501TEST_P(QuicConnectionTest, AllowSelfAddressChangeToMappedIpv4AddressAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001502 set_perspective(Perspective::IS_SERVER);
1503 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1504
1505 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1506 EXPECT_TRUE(connection_.connected());
1507
nharper46833c32019-05-15 21:33:05 -07001508 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07001509 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(3);
1510 } else {
nharper46833c32019-05-15 21:33:05 -07001511 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(3);
1512 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001513 QuicIpAddress host;
1514 host.FromString("1.1.1.1");
1515 QuicSocketAddress self_address1(host, 443);
wub5df36632020-10-01 14:42:17 -07001516 connection_.SetSelfAddress(self_address1);
wub8a5dafa2020-05-13 12:30:17 -07001517 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address1,
fayangf08e1792020-09-30 13:23:42 -07001518 kPeerAddress, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001519 // Cause self_address change to mapped Ipv4 address.
1520 QuicIpAddress host2;
dmcardlecf0bfcf2019-12-13 08:08:21 -08001521 host2.FromString(quiche::QuicheStrCat(
1522 "::ffff:", connection_.self_address().host().ToString()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001523 QuicSocketAddress self_address2(host2, connection_.self_address().port());
wub8a5dafa2020-05-13 12:30:17 -07001524 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address2,
fayangf08e1792020-09-30 13:23:42 -07001525 kPeerAddress, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001526 EXPECT_TRUE(connection_.connected());
1527 // self_address change back to Ipv4 address.
wub8a5dafa2020-05-13 12:30:17 -07001528 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address1,
fayangf08e1792020-09-30 13:23:42 -07001529 kPeerAddress, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001530 EXPECT_TRUE(connection_.connected());
1531}
1532
1533TEST_P(QuicConnectionTest, ClientAddressChangeAndPacketReordered) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001534 set_perspective(Perspective::IS_SERVER);
1535 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1536
1537 // Clear direct_peer_address.
1538 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1539 // Clear effective_peer_address, it is the same as direct_peer_address for
1540 // this test.
1541 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1542 QuicSocketAddress());
1543
nharper46833c32019-05-15 21:33:05 -07001544 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07001545 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1546 } else {
nharper46833c32019-05-15 21:33:05 -07001547 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1548 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001549 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001550 const QuicSocketAddress kNewPeerAddress =
1551 QuicSocketAddress(QuicIpAddress::Loopback6(),
1552 /*port=*/23456);
wub8a5dafa2020-05-13 12:30:17 -07001553 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
fayangf08e1792020-09-30 13:23:42 -07001554 kNewPeerAddress, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001555 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1556 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1557
1558 // Decrease packet number to simulate out-of-order packets.
1559 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 4);
1560 // This is an old packet, do not migrate.
1561 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
fayangf08e1792020-09-30 13:23:42 -07001562 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
1563 ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001564 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1565 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1566}
1567
1568TEST_P(QuicConnectionTest, PeerAddressChangeAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001569 set_perspective(Perspective::IS_SERVER);
1570 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1571 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
danzh623f6ef2020-08-25 16:44:37 -07001572 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
danzh623f6ef2020-08-25 16:44:37 -07001573 // Prevent packets from being coalesced.
1574 EXPECT_CALL(visitor_, GetHandshakeState())
1575 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001576
1577 // Clear direct_peer_address.
1578 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1579 // Clear effective_peer_address, it is the same as direct_peer_address for
1580 // this test.
1581 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1582 QuicSocketAddress());
1583 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1584
danzh623f6ef2020-08-25 16:44:37 -07001585 const QuicSocketAddress kNewPeerAddress =
1586 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
1587 EXPECT_CALL(visitor_, OnStreamFrame(_))
1588 .WillOnce(Invoke(
1589 [=]() { EXPECT_EQ(kPeerAddress, connection_.peer_address()); }))
1590 .WillOnce(Invoke([=]() {
1591 EXPECT_EQ((GetQuicReloadableFlag(quic_start_peer_migration_earlier) ||
1592 !GetParam().version.HasIetfQuicFrames()
1593 ? kNewPeerAddress
1594 : kPeerAddress),
1595 connection_.peer_address());
1596 }));
1597 QuicFrames frames;
1598 frames.push_back(QuicFrame(frame1_));
fayangf08e1792020-09-30 13:23:42 -07001599 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress,
1600 ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001601 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1602 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1603
1604 // Process another packet with a different peer address on server side will
1605 // start connection migration.
QUICHE teama6ef0a62019-03-07 20:34:33 -05001606 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
danzh623f6ef2020-08-25 16:44:37 -07001607 QuicFrames frames2;
1608 frames2.push_back(QuicFrame(frame2_));
fayangf08e1792020-09-30 13:23:42 -07001609 ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress,
1610 ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001611 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1612 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1613}
1614
1615TEST_P(QuicConnectionTest, EffectivePeerAddressChangeAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001616 set_perspective(Perspective::IS_SERVER);
1617 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1618 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
fayang6a258412020-05-28 08:57:12 -07001619 if (version().SupportsAntiAmplificationLimit()) {
1620 QuicConnectionPeer::SetAddressValidated(&connection_);
1621 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001622
1623 // Clear direct_peer_address.
1624 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1625 // Clear effective_peer_address, it is different from direct_peer_address for
1626 // this test.
1627 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1628 QuicSocketAddress());
1629 const QuicSocketAddress kEffectivePeerAddress =
1630 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/43210);
1631 connection_.ReturnEffectivePeerAddressForNextPacket(kEffectivePeerAddress);
1632
nharper46833c32019-05-15 21:33:05 -07001633 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07001634 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1635 } else {
nharper46833c32019-05-15 21:33:05 -07001636 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1637 }
fayangf08e1792020-09-30 13:23:42 -07001638 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
1639 ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001640 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1641 EXPECT_EQ(kEffectivePeerAddress, connection_.effective_peer_address());
1642
1643 // Process another packet with the same direct peer address and different
1644 // effective peer address on server side will start connection migration.
1645 const QuicSocketAddress kNewEffectivePeerAddress =
1646 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/54321);
1647 connection_.ReturnEffectivePeerAddressForNextPacket(kNewEffectivePeerAddress);
1648 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
fayangf08e1792020-09-30 13:23:42 -07001649 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
1650 ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001651 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1652 EXPECT_EQ(kNewEffectivePeerAddress, connection_.effective_peer_address());
1653
1654 // Process another packet with a different direct peer address and the same
1655 // effective peer address on server side will not start connection migration.
1656 const QuicSocketAddress kNewPeerAddress =
1657 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
1658 connection_.ReturnEffectivePeerAddressForNextPacket(kNewEffectivePeerAddress);
1659 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
1660 // ack_frame is used to complete the migration started by the last packet, we
1661 // need to make sure a new migration does not start after the previous one is
1662 // completed.
1663 QuicAckFrame ack_frame = InitAckFrame(1);
1664 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
1665 ProcessFramePacketWithAddresses(QuicFrame(&ack_frame), kSelfAddress,
fayangf08e1792020-09-30 13:23:42 -07001666 kNewPeerAddress, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001667 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1668 EXPECT_EQ(kNewEffectivePeerAddress, connection_.effective_peer_address());
1669
1670 // Process another packet with different direct peer address and different
1671 // effective peer address on server side will start connection migration.
1672 const QuicSocketAddress kNewerEffectivePeerAddress =
1673 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/65432);
1674 const QuicSocketAddress kFinalPeerAddress =
1675 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/34567);
1676 connection_.ReturnEffectivePeerAddressForNextPacket(
1677 kNewerEffectivePeerAddress);
1678 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
wub8a5dafa2020-05-13 12:30:17 -07001679 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
fayangf08e1792020-09-30 13:23:42 -07001680 kFinalPeerAddress, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001681 EXPECT_EQ(kFinalPeerAddress, connection_.peer_address());
1682 EXPECT_EQ(kNewerEffectivePeerAddress, connection_.effective_peer_address());
1683 EXPECT_EQ(PORT_CHANGE, connection_.active_effective_peer_migration_type());
1684
1685 // While the previous migration is ongoing, process another packet with the
1686 // same direct peer address and different effective peer address on server
1687 // side will start a new connection migration.
1688 const QuicSocketAddress kNewestEffectivePeerAddress =
1689 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/65430);
1690 connection_.ReturnEffectivePeerAddressForNextPacket(
1691 kNewestEffectivePeerAddress);
1692 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
1693 EXPECT_CALL(*send_algorithm_, OnConnectionMigration()).Times(1);
wub8a5dafa2020-05-13 12:30:17 -07001694 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
fayangf08e1792020-09-30 13:23:42 -07001695 kFinalPeerAddress, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001696 EXPECT_EQ(kFinalPeerAddress, connection_.peer_address());
1697 EXPECT_EQ(kNewestEffectivePeerAddress, connection_.effective_peer_address());
1698 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
1699 connection_.active_effective_peer_migration_type());
1700}
1701
zhongyif06ca342020-02-24 14:11:13 -08001702TEST_P(QuicConnectionTest, ReceivePathProbeWithNoAddressChangeAtServer) {
dschinazi1c6e5922020-06-19 10:35:03 -07001703 PathProbeTestInit(Perspective::IS_SERVER);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001704
1705 // Clear direct_peer_address.
1706 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1707 // Clear effective_peer_address, it is the same as direct_peer_address for
1708 // this test.
1709 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1710 QuicSocketAddress());
1711 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1712
nharper46833c32019-05-15 21:33:05 -07001713 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07001714 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1715 } else {
nharper46833c32019-05-15 21:33:05 -07001716 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1717 }
fayangf08e1792020-09-30 13:23:42 -07001718 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
1719 ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001720 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1721 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1722
1723 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyi83161e42019-08-19 09:06:25 -07001724 EXPECT_CALL(visitor_, OnPacketReceived(_, _, false)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001725
danzh8a27a1a2020-09-02 10:26:28 -07001726 // Process a padded PING packet with no peer address change on server side
1727 // will be ignored. But a PATH CHALLENGE packet with no peer address change
1728 // will be considered as path probing.
wub8a5dafa2020-05-13 12:30:17 -07001729 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
zhongyif06ca342020-02-24 14:11:13 -08001730
QUICHE teama6ef0a62019-03-07 20:34:33 -05001731 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
1732 QuicEncryptedPacket(probing_packet->encrypted_buffer,
1733 probing_packet->encrypted_length),
1734 clock_.Now()));
1735
1736 uint64_t num_probing_received =
1737 connection_.GetStats().num_connectivity_probing_received;
1738 ProcessReceivedPacket(kSelfAddress, kPeerAddress, *received);
1739
danzh8a27a1a2020-09-02 10:26:28 -07001740 EXPECT_EQ(num_probing_received + (GetParam().version.HasIetfQuicFrames() &&
1741 connection_.send_path_response()
1742 ? 1u
1743 : 0u),
QUICHE teama6ef0a62019-03-07 20:34:33 -05001744 connection_.GetStats().num_connectivity_probing_received);
1745 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1746 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1747}
1748
wub54bd5bf2020-05-13 13:02:16 -07001749// Regression test for b/150161358.
1750TEST_P(QuicConnectionTest, BufferedMtuPacketTooBig) {
wub54bd5bf2020-05-13 13:02:16 -07001751 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
1752 writer_->SetWriteBlocked();
1753
1754 // Send a MTU packet while blocked. It should be buffered.
1755 connection_.SendMtuDiscoveryPacket(kMaxOutgoingPacketSize);
1756 EXPECT_EQ(1u, connection_.NumQueuedPackets());
1757 EXPECT_TRUE(writer_->IsWriteBlocked());
1758
1759 writer_->AlwaysGetPacketTooLarge();
1760 writer_->SetWritable();
1761 connection_.OnCanWrite();
1762}
1763
QUICHE teama6ef0a62019-03-07 20:34:33 -05001764TEST_P(QuicConnectionTest, WriteOutOfOrderQueuedPackets) {
1765 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
fayangc31c9952019-06-05 13:54:48 -07001766 if (!IsDefaultTestConfiguration()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001767 return;
1768 }
1769
1770 set_perspective(Perspective::IS_CLIENT);
1771
1772 BlockOnNextWrite();
1773
1774 QuicStreamId stream_id = 2;
1775 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
1776
1777 EXPECT_EQ(1u, connection_.NumQueuedPackets());
1778
1779 writer_->SetWritable();
1780 connection_.SendConnectivityProbingPacket(writer_.get(),
1781 connection_.peer_address());
fayange62e63c2019-12-04 07:16:25 -08001782 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
1783 connection_.OnCanWrite();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001784}
1785
1786TEST_P(QuicConnectionTest, DiscardQueuedPacketsAfterConnectionClose) {
1787 // Regression test for b/74073386.
1788 {
1789 InSequence seq;
rch39c88ab2019-10-16 19:24:40 -07001790 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1791 .Times(AtLeast(1));
1792 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001793 }
1794
1795 set_perspective(Perspective::IS_CLIENT);
1796
1797 writer_->SimulateNextPacketTooLarge();
1798
1799 // This packet write should fail, which should cause the connection to close
1800 // after sending a connection close packet, then the failed packet should be
1801 // queued.
1802 connection_.SendStreamDataWithString(/*id=*/2, "foo", 0, NO_FIN);
1803
1804 EXPECT_FALSE(connection_.connected());
fayange62e63c2019-12-04 07:16:25 -08001805 // No need to buffer packets.
1806 EXPECT_EQ(0u, connection_.NumQueuedPackets());
QUICHE teama6ef0a62019-03-07 20:34:33 -05001807
1808 EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
1809 connection_.OnCanWrite();
fayang0f0c4e62019-07-16 08:55:54 -07001810 EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001811}
1812
zhongyif06ca342020-02-24 14:11:13 -08001813// Receive a path probe request at the server side, i.e.,
1814// in non-IETF version: receive a padded PING packet with a peer addess change;
1815// in IETF version: receive a packet contains PATH CHALLENGE with peer address
1816// change.
1817TEST_P(QuicConnectionTest, ReceivePathProbingAtServer) {
dschinazi1c6e5922020-06-19 10:35:03 -07001818 PathProbeTestInit(Perspective::IS_SERVER);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001819
1820 // Clear direct_peer_address.
1821 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1822 // Clear effective_peer_address, it is the same as direct_peer_address for
1823 // this test.
1824 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1825 QuicSocketAddress());
1826 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1827
nharper46833c32019-05-15 21:33:05 -07001828 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07001829 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1830 } else {
nharper46833c32019-05-15 21:33:05 -07001831 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1832 }
fayangf08e1792020-09-30 13:23:42 -07001833 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
1834 ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001835 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1836 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1837
1838 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyif06ca342020-02-24 14:11:13 -08001839 if (!GetParam().version.HasIetfQuicFrames()) {
1840 EXPECT_CALL(visitor_,
1841 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
1842 .Times(1);
1843 } else {
1844 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
1845 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001846 // Process a padded PING packet from a new peer address on server side
1847 // is effectively receiving a connectivity probing.
1848 const QuicSocketAddress kNewPeerAddress =
1849 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
1850
wub8a5dafa2020-05-13 12:30:17 -07001851 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001852 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
1853 QuicEncryptedPacket(probing_packet->encrypted_buffer,
1854 probing_packet->encrypted_length),
1855 clock_.Now()));
1856
1857 uint64_t num_probing_received =
1858 connection_.GetStats().num_connectivity_probing_received;
1859 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
1860
1861 EXPECT_EQ(num_probing_received + 1,
1862 connection_.GetStats().num_connectivity_probing_received);
1863 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1864 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1865
1866 // Process another packet with the old peer address on server side will not
1867 // start peer migration.
1868 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
fayangf08e1792020-09-30 13:23:42 -07001869 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
1870 ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001871 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1872 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1873}
1874
zhongyif06ca342020-02-24 14:11:13 -08001875// Receive a padded PING packet with a port change on server side.
1876TEST_P(QuicConnectionTest, ReceivePaddedPingWithPortChangeAtServer) {
1877 set_perspective(Perspective::IS_SERVER);
1878 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1879 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1880
1881 // Clear direct_peer_address.
1882 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1883 // Clear effective_peer_address, it is the same as direct_peer_address for
1884 // this test.
1885 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1886 QuicSocketAddress());
1887 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1888
zhongyif06ca342020-02-24 14:11:13 -08001889 if (GetParam().version.UsesCryptoFrames()) {
zhongyif06ca342020-02-24 14:11:13 -08001890 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1891 } else {
zhongyif06ca342020-02-24 14:11:13 -08001892 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1893 }
fayangf08e1792020-09-30 13:23:42 -07001894 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
1895 ENCRYPTION_INITIAL);
zhongyif06ca342020-02-24 14:11:13 -08001896 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1897 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1898
1899 if (GetParam().version.HasIetfQuicFrames()) {
1900 // In IETF version, a padded PING packet with port change is not taken as
1901 // connectivity probe.
1902 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
1903 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
1904 } else {
1905 // In non-IETF version, process a padded PING packet from a new peer
1906 // address on server side is effectively receiving a connectivity probing.
1907 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
1908 EXPECT_CALL(visitor_,
1909 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
1910 .Times(1);
1911 }
1912 const QuicSocketAddress kNewPeerAddress =
1913 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
1914
1915 QuicFrames frames;
1916 // Write a PING frame, which has no data payload.
1917 QuicPingFrame ping_frame;
1918 frames.push_back(QuicFrame(ping_frame));
1919
1920 // Add padding to the rest of the packet.
1921 QuicPaddingFrame padding_frame;
1922 frames.push_back(QuicFrame(padding_frame));
1923
1924 uint64_t num_probing_received =
1925 connection_.GetStats().num_connectivity_probing_received;
1926
fayangf08e1792020-09-30 13:23:42 -07001927 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
1928 ENCRYPTION_INITIAL);
zhongyif06ca342020-02-24 14:11:13 -08001929
1930 if (GetParam().version.HasIetfQuicFrames()) {
1931 // Padded PING with port changen is not considered as connectivity probe but
1932 // a PORT CHANGE.
1933 EXPECT_EQ(num_probing_received,
1934 connection_.GetStats().num_connectivity_probing_received);
1935 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1936 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1937 } else {
1938 EXPECT_EQ(num_probing_received + 1,
1939 connection_.GetStats().num_connectivity_probing_received);
1940 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1941 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1942 }
1943
1944 // Process another packet with the old peer address on server side.
1945 if (GetParam().version.HasIetfQuicFrames()) {
1946 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
1947 } else {
1948 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
1949 }
fayangf08e1792020-09-30 13:23:42 -07001950 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
1951 ENCRYPTION_INITIAL);
zhongyif06ca342020-02-24 14:11:13 -08001952 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1953 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1954}
1955
1956TEST_P(QuicConnectionTest, ReceiveReorderedPathProbingAtServer) {
dschinazi1c6e5922020-06-19 10:35:03 -07001957 PathProbeTestInit(Perspective::IS_SERVER);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001958
1959 // Clear direct_peer_address.
1960 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1961 // Clear effective_peer_address, it is the same as direct_peer_address for
1962 // this test.
1963 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1964 QuicSocketAddress());
1965 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1966
nharper46833c32019-05-15 21:33:05 -07001967 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07001968 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1969 } else {
nharper46833c32019-05-15 21:33:05 -07001970 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1971 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001972 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
fayangf08e1792020-09-30 13:23:42 -07001973 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
1974 ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001975 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1976 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1977
1978 // Decrease packet number to simulate out-of-order packets.
1979 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 4);
1980
1981 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyif06ca342020-02-24 14:11:13 -08001982 if (!GetParam().version.HasIetfQuicFrames()) {
1983 EXPECT_CALL(visitor_,
1984 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
1985 .Times(1);
1986 } else {
1987 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
1988 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001989
1990 // Process a padded PING packet from a new peer address on server side
1991 // is effectively receiving a connectivity probing, even if a newer packet has
1992 // been received before this one.
1993 const QuicSocketAddress kNewPeerAddress =
1994 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
1995
wub8a5dafa2020-05-13 12:30:17 -07001996 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001997 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
1998 QuicEncryptedPacket(probing_packet->encrypted_buffer,
1999 probing_packet->encrypted_length),
2000 clock_.Now()));
2001
2002 uint64_t num_probing_received =
2003 connection_.GetStats().num_connectivity_probing_received;
2004 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2005
2006 EXPECT_EQ(num_probing_received + 1,
2007 connection_.GetStats().num_connectivity_probing_received);
2008 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2009 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2010}
2011
2012TEST_P(QuicConnectionTest, MigrateAfterProbingAtServer) {
dschinazi1c6e5922020-06-19 10:35:03 -07002013 PathProbeTestInit(Perspective::IS_SERVER);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002014
2015 // Clear direct_peer_address.
2016 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2017 // Clear effective_peer_address, it is the same as direct_peer_address for
2018 // this test.
2019 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2020 QuicSocketAddress());
2021 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2022
nharper46833c32019-05-15 21:33:05 -07002023 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07002024 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2025 } else {
nharper46833c32019-05-15 21:33:05 -07002026 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2027 }
fayangf08e1792020-09-30 13:23:42 -07002028 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
2029 ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002030 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2031 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2032
2033 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyif06ca342020-02-24 14:11:13 -08002034 if (!GetParam().version.HasIetfQuicFrames()) {
2035 EXPECT_CALL(visitor_,
2036 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2037 .Times(1);
2038 } else {
2039 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2040 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002041
2042 // Process a padded PING packet from a new peer address on server side
2043 // is effectively receiving a connectivity probing.
2044 const QuicSocketAddress kNewPeerAddress =
2045 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2046
wub8a5dafa2020-05-13 12:30:17 -07002047 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
QUICHE teama6ef0a62019-03-07 20:34:33 -05002048 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2049 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2050 probing_packet->encrypted_length),
2051 clock_.Now()));
2052 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2053 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2054 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2055
2056 // Process another non-probing packet with the new peer address on server
2057 // side will start peer migration.
2058 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2059
wub8a5dafa2020-05-13 12:30:17 -07002060 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
fayangf08e1792020-09-30 13:23:42 -07002061 kNewPeerAddress, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002062 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2063 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2064}
2065
danzh8a27a1a2020-09-02 10:26:28 -07002066TEST_P(QuicConnectionTest, ReceiveConnectivityProbingPacketAtClient) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002067 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
dschinazi1c6e5922020-06-19 10:35:03 -07002068 PathProbeTestInit(Perspective::IS_CLIENT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002069
2070 // Clear direct_peer_address.
2071 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2072 // Clear effective_peer_address, it is the same as direct_peer_address for
2073 // this test.
2074 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2075 QuicSocketAddress());
2076 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2077
nharper46833c32019-05-15 21:33:05 -07002078 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07002079 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2080 } else {
nharper46833c32019-05-15 21:33:05 -07002081 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2082 }
fayangf08e1792020-09-30 13:23:42 -07002083 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
2084 ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002085 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2086 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2087
2088 // Client takes all padded PING packet as speculative connectivity
2089 // probing packet, and reports to visitor.
2090 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
danzh8a27a1a2020-09-02 10:26:28 -07002091 if (!connection_.send_path_response()) {
2092 EXPECT_CALL(visitor_, OnPacketReceived(_, _, false)).Times(1);
2093 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002094
wub8a5dafa2020-05-13 12:30:17 -07002095 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
QUICHE teama6ef0a62019-03-07 20:34:33 -05002096 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2097 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2098 probing_packet->encrypted_length),
2099 clock_.Now()));
2100 uint64_t num_probing_received =
2101 connection_.GetStats().num_connectivity_probing_received;
2102 ProcessReceivedPacket(kSelfAddress, kPeerAddress, *received);
2103
danzh8a27a1a2020-09-02 10:26:28 -07002104 EXPECT_EQ(num_probing_received + (GetParam().version.HasIetfQuicFrames() &&
2105 connection_.send_path_response()
2106 ? 1u
2107 : 0u),
QUICHE teama6ef0a62019-03-07 20:34:33 -05002108 connection_.GetStats().num_connectivity_probing_received);
2109 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2110 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2111}
2112
zhongyif06ca342020-02-24 14:11:13 -08002113TEST_P(QuicConnectionTest, ReceiveConnectivityProbingResponseAtClient) {
2114 // TODO(b/150095484): add test coverage for IETF to verify that client takes
2115 // PATH RESPONSE with peer address change as correct validation on the new
2116 // path.
2117 if (GetParam().version.HasIetfQuicFrames()) {
2118 return;
2119 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002120 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
dschinazi1c6e5922020-06-19 10:35:03 -07002121 PathProbeTestInit(Perspective::IS_CLIENT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002122
2123 // Clear direct_peer_address.
2124 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2125 // Clear effective_peer_address, it is the same as direct_peer_address for
2126 // this test.
2127 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2128 QuicSocketAddress());
2129 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2130
nharper46833c32019-05-15 21:33:05 -07002131 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07002132 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2133 } else {
nharper46833c32019-05-15 21:33:05 -07002134 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2135 }
fayangf08e1792020-09-30 13:23:42 -07002136 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
2137 ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002138 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2139 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2140
2141 // Process a padded PING packet with a different self address on client side
2142 // is effectively receiving a connectivity probing.
2143 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyif06ca342020-02-24 14:11:13 -08002144 if (!GetParam().version.HasIetfQuicFrames()) {
2145 EXPECT_CALL(visitor_,
2146 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2147 .Times(1);
2148 } else {
2149 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2150 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002151
2152 const QuicSocketAddress kNewSelfAddress =
2153 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2154
wub8a5dafa2020-05-13 12:30:17 -07002155 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
QUICHE teama6ef0a62019-03-07 20:34:33 -05002156 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2157 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2158 probing_packet->encrypted_length),
2159 clock_.Now()));
2160 uint64_t num_probing_received =
2161 connection_.GetStats().num_connectivity_probing_received;
2162 ProcessReceivedPacket(kNewSelfAddress, kPeerAddress, *received);
2163
2164 EXPECT_EQ(num_probing_received + 1,
2165 connection_.GetStats().num_connectivity_probing_received);
2166 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2167 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2168}
2169
2170TEST_P(QuicConnectionTest, PeerAddressChangeAtClient) {
2171 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2172 set_perspective(Perspective::IS_CLIENT);
2173 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2174
2175 // Clear direct_peer_address.
2176 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2177 // Clear effective_peer_address, it is the same as direct_peer_address for
2178 // this test.
2179 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2180 QuicSocketAddress());
2181 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2182
nharper46833c32019-05-15 21:33:05 -07002183 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07002184 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2185 } else {
nharper46833c32019-05-15 21:33:05 -07002186 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2187 }
fayangf08e1792020-09-30 13:23:42 -07002188 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
2189 ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002190 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2191 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2192
2193 // Process another packet with a different peer address on client side will
2194 // only update peer address.
2195 const QuicSocketAddress kNewPeerAddress =
2196 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2197 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
wub8a5dafa2020-05-13 12:30:17 -07002198 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
fayangf08e1792020-09-30 13:23:42 -07002199 kNewPeerAddress, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002200 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2201 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2202}
2203
2204TEST_P(QuicConnectionTest, MaxPacketSize) {
2205 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2206 EXPECT_EQ(1350u, connection_.max_packet_length());
2207}
2208
dschinazi4ad1f462020-01-16 11:56:52 -08002209TEST_P(QuicConnectionTest, PeerLowersMaxPacketSize) {
2210 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2211
2212 // SetFromConfig is always called after construction from InitializeSession.
2213 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
2214 constexpr uint32_t kTestMaxPacketSize = 1233u;
2215 QuicConfig config;
2216 QuicConfigPeer::SetReceivedMaxPacketSize(&config, kTestMaxPacketSize);
2217 connection_.SetFromConfig(config);
2218
2219 EXPECT_EQ(kTestMaxPacketSize, connection_.max_packet_length());
2220}
2221
vasilvvebc5d0c2020-01-16 15:19:21 -08002222TEST_P(QuicConnectionTest, PeerCannotRaiseMaxPacketSize) {
2223 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2224
2225 // SetFromConfig is always called after construction from InitializeSession.
2226 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
2227 constexpr uint32_t kTestMaxPacketSize = 1450u;
2228 QuicConfig config;
2229 QuicConfigPeer::SetReceivedMaxPacketSize(&config, kTestMaxPacketSize);
2230 connection_.SetFromConfig(config);
2231
2232 EXPECT_EQ(kDefaultMaxPacketSize, connection_.max_packet_length());
2233}
2234
QUICHE teama6ef0a62019-03-07 20:34:33 -05002235TEST_P(QuicConnectionTest, SmallerServerMaxPacketSize) {
wub5df36632020-10-01 14:42:17 -07002236 TestConnection connection(TestConnectionId(), kSelfAddress, kPeerAddress,
2237 helper_.get(), alarm_factory_.get(), writer_.get(),
QUICHE teama6ef0a62019-03-07 20:34:33 -05002238 Perspective::IS_SERVER, version());
2239 EXPECT_EQ(Perspective::IS_SERVER, connection.perspective());
2240 EXPECT_EQ(1000u, connection.max_packet_length());
2241}
2242
2243TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSize) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002244 set_perspective(Perspective::IS_SERVER);
2245 connection_.SetMaxPacketLength(1000);
2246
2247 QuicPacketHeader header;
2248 header.destination_connection_id = connection_id_;
2249 header.version_flag = true;
nharper21af28e2019-06-17 15:54:34 -07002250 header.packet_number = QuicPacketNumber(12);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002251
2252 if (QuicVersionHasLongHeaderLengths(
2253 peer_framer_.version().transport_version)) {
2254 header.long_packet_type = INITIAL;
2255 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
2256 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
2257 }
2258
2259 QuicFrames frames;
2260 QuicPaddingFrame padding;
nharper46833c32019-05-15 21:33:05 -07002261 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2262 frames.push_back(QuicFrame(&crypto_frame_));
2263 } else {
2264 frames.push_back(QuicFrame(frame1_));
2265 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002266 frames.push_back(QuicFrame(padding));
2267 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
dschinazi66dea072019-04-09 11:41:06 -07002268 char buffer[kMaxOutgoingPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07002269 size_t encrypted_length =
2270 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12),
dschinazi66dea072019-04-09 11:41:06 -07002271 *packet, buffer, kMaxOutgoingPacketSize);
2272 EXPECT_EQ(kMaxOutgoingPacketSize, encrypted_length);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002273
2274 framer_.set_version(version());
nharper46833c32019-05-15 21:33:05 -07002275 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2276 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
2277 } else {
2278 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2279 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002280 connection_.ProcessUdpPacket(
2281 kSelfAddress, kPeerAddress,
2282 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
2283
dschinazi66dea072019-04-09 11:41:06 -07002284 EXPECT_EQ(kMaxOutgoingPacketSize, connection_.max_packet_length());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002285}
2286
2287TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSizeWhileWriterLimited) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002288 const QuicByteCount lower_max_packet_size = 1240;
2289 writer_->set_max_packet_size(lower_max_packet_size);
2290 set_perspective(Perspective::IS_SERVER);
2291 connection_.SetMaxPacketLength(1000);
2292 EXPECT_EQ(1000u, connection_.max_packet_length());
2293
2294 QuicPacketHeader header;
2295 header.destination_connection_id = connection_id_;
2296 header.version_flag = true;
nharper21af28e2019-06-17 15:54:34 -07002297 header.packet_number = QuicPacketNumber(12);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002298
2299 if (QuicVersionHasLongHeaderLengths(
2300 peer_framer_.version().transport_version)) {
2301 header.long_packet_type = INITIAL;
2302 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
2303 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
2304 }
2305
2306 QuicFrames frames;
2307 QuicPaddingFrame padding;
nharper46833c32019-05-15 21:33:05 -07002308 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2309 frames.push_back(QuicFrame(&crypto_frame_));
2310 } else {
2311 frames.push_back(QuicFrame(frame1_));
2312 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002313 frames.push_back(QuicFrame(padding));
2314 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
dschinazi66dea072019-04-09 11:41:06 -07002315 char buffer[kMaxOutgoingPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07002316 size_t encrypted_length =
2317 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12),
dschinazi66dea072019-04-09 11:41:06 -07002318 *packet, buffer, kMaxOutgoingPacketSize);
2319 EXPECT_EQ(kMaxOutgoingPacketSize, encrypted_length);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002320
2321 framer_.set_version(version());
nharper46833c32019-05-15 21:33:05 -07002322 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2323 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
2324 } else {
2325 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2326 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002327 connection_.ProcessUdpPacket(
2328 kSelfAddress, kPeerAddress,
2329 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
2330
2331 // Here, the limit imposed by the writer is lower than the size of the packet
2332 // received, so the writer max packet size is used.
2333 EXPECT_EQ(lower_max_packet_size, connection_.max_packet_length());
2334}
2335
2336TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriter) {
2337 const QuicByteCount lower_max_packet_size = 1240;
2338 writer_->set_max_packet_size(lower_max_packet_size);
2339
2340 static_assert(lower_max_packet_size < kDefaultMaxPacketSize,
2341 "Default maximum packet size is too low");
2342 connection_.SetMaxPacketLength(kDefaultMaxPacketSize);
2343
2344 EXPECT_EQ(lower_max_packet_size, connection_.max_packet_length());
2345}
2346
2347TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriterForNewConnection) {
2348 const QuicConnectionId connection_id = TestConnectionId(17);
2349 const QuicByteCount lower_max_packet_size = 1240;
2350 writer_->set_max_packet_size(lower_max_packet_size);
wub5df36632020-10-01 14:42:17 -07002351 TestConnection connection(connection_id, kSelfAddress, kPeerAddress,
2352 helper_.get(), alarm_factory_.get(), writer_.get(),
QUICHE teama6ef0a62019-03-07 20:34:33 -05002353 Perspective::IS_CLIENT, version());
2354 EXPECT_EQ(Perspective::IS_CLIENT, connection.perspective());
2355 EXPECT_EQ(lower_max_packet_size, connection.max_packet_length());
2356}
2357
2358TEST_P(QuicConnectionTest, PacketsInOrder) {
2359 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2360
2361 ProcessPacket(1);
fayangc31c9952019-06-05 13:54:48 -07002362 EXPECT_EQ(QuicPacketNumber(1u), LargestAcked(connection_.ack_frame()));
2363 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002364
2365 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07002366 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(connection_.ack_frame()));
2367 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002368
2369 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002370 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
2371 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002372}
2373
2374TEST_P(QuicConnectionTest, PacketsOutOfOrder) {
2375 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2376
2377 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002378 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002379 EXPECT_TRUE(IsMissing(2));
2380 EXPECT_TRUE(IsMissing(1));
2381
2382 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07002383 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002384 EXPECT_FALSE(IsMissing(2));
2385 EXPECT_TRUE(IsMissing(1));
2386
2387 ProcessPacket(1);
fayangc31c9952019-06-05 13:54:48 -07002388 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002389 EXPECT_FALSE(IsMissing(2));
2390 EXPECT_FALSE(IsMissing(1));
2391}
2392
2393TEST_P(QuicConnectionTest, DuplicatePacket) {
2394 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2395
2396 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002397 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002398 EXPECT_TRUE(IsMissing(2));
2399 EXPECT_TRUE(IsMissing(1));
2400
2401 // Send packet 3 again, but do not set the expectation that
2402 // the visitor OnStreamFrame() will be called.
2403 ProcessDataPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002404 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002405 EXPECT_TRUE(IsMissing(2));
2406 EXPECT_TRUE(IsMissing(1));
2407}
2408
2409TEST_P(QuicConnectionTest, PacketsOutOfOrderWithAdditionsAndLeastAwaiting) {
QUICHE teamcd098022019-03-22 18:49:55 -07002410 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2411 return;
2412 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002413 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2414
2415 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002416 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002417 EXPECT_TRUE(IsMissing(2));
2418 EXPECT_TRUE(IsMissing(1));
2419
2420 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07002421 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002422 EXPECT_TRUE(IsMissing(1));
2423
2424 ProcessPacket(5);
fayangc31c9952019-06-05 13:54:48 -07002425 EXPECT_EQ(QuicPacketNumber(5u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002426 EXPECT_TRUE(IsMissing(1));
2427 EXPECT_TRUE(IsMissing(4));
2428
2429 // Pretend at this point the client has gotten acks for 2 and 3 and 1 is a
2430 // packet the peer will not retransmit. It indicates this by sending 'least
2431 // awaiting' is 4. The connection should then realize 1 will not be
2432 // retransmitted, and will remove it from the missing list.
2433 QuicAckFrame frame = InitAckFrame(1);
2434 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
2435 ProcessAckPacket(6, &frame);
2436
2437 // Force an ack to be sent.
2438 SendAckPacketToPeer();
2439 EXPECT_TRUE(IsMissing(4));
2440}
2441
QUICHE teama6ef0a62019-03-07 20:34:33 -05002442TEST_P(QuicConnectionTest, RejectUnencryptedStreamData) {
2443 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
2444 if (!IsDefaultTestConfiguration()) {
2445 return;
2446 }
2447
2448 // Process an unencrypted packet from the non-crypto stream.
2449 frame1_.stream_id = 3;
2450 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fkastenholz5d880a92019-06-21 09:01:56 -07002451 EXPECT_CALL(visitor_,
2452 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
nharper2c9f02a2019-05-08 10:25:50 -07002453 EXPECT_QUIC_PEER_BUG(ProcessDataPacketAtLevel(1, false, ENCRYPTION_INITIAL),
2454 "");
fkastenholz5d880a92019-06-21 09:01:56 -07002455 TestConnectionCloseQuicErrorCode(QUIC_UNENCRYPTED_STREAM_DATA);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002456}
2457
2458TEST_P(QuicConnectionTest, OutOfOrderReceiptCausesAckSend) {
2459 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2460
2461 ProcessPacket(3);
fayang6dba4902019-06-17 10:04:23 -07002462 // Should not cause an ack.
2463 EXPECT_EQ(0u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002464
2465 ProcessPacket(2);
fayang6dba4902019-06-17 10:04:23 -07002466 // Should ack immediately, since this fills the last hole.
2467 EXPECT_EQ(1u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002468
2469 ProcessPacket(1);
2470 // Should ack immediately, since this fills the last hole.
fayang6dba4902019-06-17 10:04:23 -07002471 EXPECT_EQ(2u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002472
2473 ProcessPacket(4);
2474 // Should not cause an ack.
fayang6dba4902019-06-17 10:04:23 -07002475 EXPECT_EQ(2u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002476}
2477
2478TEST_P(QuicConnectionTest, OutOfOrderAckReceiptCausesNoAck) {
2479 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2480
2481 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
2482 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
2483 EXPECT_EQ(2u, writer_->packets_write_attempts());
2484
2485 QuicAckFrame ack1 = InitAckFrame(1);
2486 QuicAckFrame ack2 = InitAckFrame(2);
2487 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
fayang2f2915d2020-01-24 06:47:15 -08002488 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2489 EXPECT_CALL(visitor_, OnOneRttPacketAcknowledged()).Times(1);
2490 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002491 ProcessAckPacket(2, &ack2);
2492 // Should ack immediately since we have missing packets.
2493 EXPECT_EQ(2u, writer_->packets_write_attempts());
2494
fayang2f2915d2020-01-24 06:47:15 -08002495 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2496 EXPECT_CALL(visitor_, OnOneRttPacketAcknowledged()).Times(0);
2497 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002498 ProcessAckPacket(1, &ack1);
2499 // Should not ack an ack filling a missing packet.
2500 EXPECT_EQ(2u, writer_->packets_write_attempts());
2501}
2502
2503TEST_P(QuicConnectionTest, AckReceiptCausesAckSend) {
2504 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2505 QuicPacketNumber original, second;
2506
2507 QuicByteCount packet_size =
2508 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &original); // 1st packet.
2509 SendStreamDataToPeer(3, "bar", 3, NO_FIN, &second); // 2nd packet.
2510
2511 QuicAckFrame frame = InitAckFrame({{second, second + 1}});
2512 // First nack triggers early retransmit.
2513 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07002514 lost_packets.push_back(LostPacket(original, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002515 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07002516 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
2517 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002518 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2519 QuicPacketNumber retransmission;
2520 // Packet 1 is short header for IETF QUIC because the encryption level
2521 // switched to ENCRYPTION_FORWARD_SECURE in SendStreamDataToPeer.
fayangd4291e42019-05-30 10:31:21 -07002522 EXPECT_CALL(*send_algorithm_,
2523 OnPacketSent(_, _, _,
2524 VersionHasIetfInvariantHeader(
2525 GetParam().version.transport_version)
2526 ? packet_size
2527 : packet_size - kQuicVersionSize,
2528 _))
QUICHE teama6ef0a62019-03-07 20:34:33 -05002529 .WillOnce(SaveArg<2>(&retransmission));
2530
2531 ProcessAckPacket(&frame);
2532
2533 QuicAckFrame frame2 = ConstructAckFrame(retransmission, original);
2534 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2535 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
2536 ProcessAckPacket(&frame2);
2537
2538 // Now if the peer sends an ack which still reports the retransmitted packet
2539 // as missing, that will bundle an ack with data after two acks in a row
2540 // indicate the high water mark needs to be raised.
2541 EXPECT_CALL(*send_algorithm_,
2542 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA));
2543 connection_.SendStreamDataWithString(3, "foo", 6, NO_FIN);
2544 // No ack sent.
nharper55fa6132019-05-07 19:37:21 -07002545 size_t padding_frame_count = writer_->padding_frames().size();
2546 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002547 EXPECT_EQ(1u, writer_->stream_frames().size());
2548
2549 // No more packet loss for the rest of the test.
2550 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
2551 .Times(AnyNumber());
2552 ProcessAckPacket(&frame2);
2553 EXPECT_CALL(*send_algorithm_,
2554 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA));
fayang03916692019-05-22 17:57:18 -07002555 connection_.SendStreamDataWithString(3, "foofoofoo", 9, NO_FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002556 // Ack bundled.
2557 if (GetParam().no_stop_waiting) {
fayang8a27b0f2019-11-04 11:27:40 -08002558 // Do not ACK acks.
2559 EXPECT_EQ(1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002560 } else {
2561 EXPECT_EQ(3u, writer_->frame_count());
2562 }
2563 EXPECT_EQ(1u, writer_->stream_frames().size());
fayang8a27b0f2019-11-04 11:27:40 -08002564 if (GetParam().no_stop_waiting) {
fayang03916692019-05-22 17:57:18 -07002565 EXPECT_TRUE(writer_->ack_frames().empty());
2566 } else {
2567 EXPECT_FALSE(writer_->ack_frames().empty());
2568 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002569
2570 // But an ack with no missing packets will not send an ack.
2571 AckPacket(original, &frame2);
2572 ProcessAckPacket(&frame2);
2573 ProcessAckPacket(&frame2);
2574}
2575
haoyuewang2d2fdd12020-09-16 11:26:56 -07002576TEST_P(QuicConnectionTest, AckFrequencyUpdatedFromAckFrequencyFrame) {
2577 if (!GetParam().version.HasIetfQuicFrames()) {
2578 return;
2579 }
haoyuewang2d2fdd12020-09-16 11:26:56 -07002580 connection_.set_can_receive_ack_frequency_frame();
QUICHE teama6ef0a62019-03-07 20:34:33 -05002581
haoyuewangf324bb82020-09-22 09:19:36 -07002582 // Expect 13 acks, every 3rd packet including the first packet with
2583 // AckFrequencyFrame.
QUICHE teama6ef0a62019-03-07 20:34:33 -05002584 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(13);
haoyuewangf324bb82020-09-22 09:19:36 -07002585 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2586
2587 QuicAckFrequencyFrame ack_frequency_frame;
2588 ack_frequency_frame.packet_tolerance = 3;
2589 ProcessFramePacketAtLevel(1, QuicFrame(&ack_frequency_frame),
2590 ENCRYPTION_FORWARD_SECURE);
2591
2592 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(38);
2593 // Receives packets 2 - 39.
2594 for (size_t i = 2; i <= 39; ++i) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002595 ProcessDataPacket(i);
2596 }
2597}
2598
haoyuewang2d2fdd12020-09-16 11:26:56 -07002599TEST_P(QuicConnectionTest,
2600 AckFrequencyFrameOutsideApplicationDataNumberSpaceIsIgnored) {
2601 if (!GetParam().version.HasIetfQuicFrames()) {
2602 return;
2603 }
haoyuewang2d2fdd12020-09-16 11:26:56 -07002604 connection_.set_can_receive_ack_frequency_frame();
haoyuewang2d2fdd12020-09-16 11:26:56 -07002605
haoyuewangf324bb82020-09-22 09:19:36 -07002606 QuicAckFrequencyFrame ack_frequency_frame;
2607 ack_frequency_frame.packet_tolerance = 3;
2608 ProcessFramePacketAtLevel(1, QuicFrame(&ack_frequency_frame),
2609 ENCRYPTION_HANDSHAKE);
2610
2611 // Expect 30 acks, every 2nd (instead of 3rd) packet including the first
2612 // packet with AckFrequencyFrame.
haoyuewang2d2fdd12020-09-16 11:26:56 -07002613 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(30);
haoyuewangf324bb82020-09-22 09:19:36 -07002614 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(60);
2615 // Receives packets 2 - 61.
2616 for (size_t i = 2; i <= 61; ++i) {
haoyuewang2d2fdd12020-09-16 11:26:56 -07002617 ProcessDataPacket(i);
2618 }
2619}
2620
QUICHE teama6ef0a62019-03-07 20:34:33 -05002621TEST_P(QuicConnectionTest, AckDecimationReducesAcks) {
2622 const size_t kMinRttMs = 40;
2623 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
2624 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
2625 QuicTime::Delta::Zero(), QuicTime::Zero());
2626 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
2627
QUICHE teama6ef0a62019-03-07 20:34:33 -05002628 // Start ack decimation from 10th packet.
2629 connection_.set_min_received_before_ack_decimation(10);
2630
2631 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2632 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(30);
2633
2634 // Expect 6 acks: 5 acks between packets 1-10, and ack at 20.
2635 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(6);
2636 // Receives packets 1 - 29.
2637 for (size_t i = 1; i <= 29; ++i) {
2638 ProcessDataPacket(i);
2639 }
2640
2641 // We now receive the 30th packet, and so we send an ack.
2642 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2643 ProcessDataPacket(30);
2644}
2645
2646TEST_P(QuicConnectionTest, AckNeedsRetransmittableFrames) {
ianswett68cf0042019-05-09 08:37:58 -07002647 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002648 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2649 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(99);
2650
2651 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(19);
2652 // Receives packets 1 - 39.
2653 for (size_t i = 1; i <= 39; ++i) {
2654 ProcessDataPacket(i);
2655 }
2656 // Receiving Packet 40 causes 20th ack to send. Session is informed and adds
2657 // WINDOW_UPDATE.
2658 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
2659 .WillOnce(Invoke([this]() {
2660 connection_.SendControlFrame(
2661 QuicFrame(new QuicWindowUpdateFrame(1, 0, 0)));
2662 }));
2663 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2664 EXPECT_EQ(0u, writer_->window_update_frames().size());
2665 ProcessDataPacket(40);
2666 EXPECT_EQ(1u, writer_->window_update_frames().size());
2667
2668 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(9);
2669 // Receives packets 41 - 59.
2670 for (size_t i = 41; i <= 59; ++i) {
2671 ProcessDataPacket(i);
2672 }
2673 // Send a packet containing stream frame.
QUICHE team8c1daa22019-03-13 08:33:41 -07002674 SendStreamDataToPeer(
nharper46833c32019-05-15 21:33:05 -07002675 QuicUtils::GetFirstBidirectionalStreamId(
2676 connection_.version().transport_version, Perspective::IS_CLIENT),
QUICHE team8c1daa22019-03-13 08:33:41 -07002677 "bar", 0, NO_FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002678
2679 // Session will not be informed until receiving another 20 packets.
2680 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(19);
2681 for (size_t i = 60; i <= 98; ++i) {
2682 ProcessDataPacket(i);
2683 EXPECT_EQ(0u, writer_->window_update_frames().size());
2684 }
2685 // Session does not add a retransmittable frame.
2686 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
2687 .WillOnce(Invoke([this]() {
2688 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
2689 }));
2690 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2691 EXPECT_EQ(0u, writer_->ping_frames().size());
2692 ProcessDataPacket(99);
2693 EXPECT_EQ(0u, writer_->window_update_frames().size());
2694 // A ping frame will be added.
2695 EXPECT_EQ(1u, writer_->ping_frames().size());
2696}
2697
ianswett6083a102020-02-09 12:04:04 -08002698TEST_P(QuicConnectionTest, AckNeedsRetransmittableFramesAfterPto) {
ianswett6083a102020-02-09 12:04:04 -08002699 // Disable TLP so the RTO fires immediately.
2700 connection_.SetMaxTailLossProbes(0);
2701 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
2702 QuicConfig config;
2703 QuicTagVector connection_options;
2704 connection_options.push_back(kEACK);
2705 config.SetConnectionOptionsToSend(connection_options);
2706 connection_.SetFromConfig(config);
2707
2708 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
fayang37b3c5c2020-09-16 15:20:41 -07002709 connection_.OnHandshakeComplete();
2710
ianswett6083a102020-02-09 12:04:04 -08002711 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2712 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(10);
2713
2714 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(4);
2715 // Receive packets 1 - 9.
2716 for (size_t i = 1; i <= 9; ++i) {
2717 ProcessDataPacket(i);
2718 }
2719
2720 // Send a ping and fire the retransmission alarm.
2721 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
2722 SendPing();
2723 QuicTime retransmission_time =
2724 connection_.GetRetransmissionAlarm()->deadline();
2725 clock_.AdvanceTime(retransmission_time - clock_.Now());
2726 connection_.GetRetransmissionAlarm()->Fire();
2727 ASSERT_TRUE(manager_->GetConsecutiveRtoCount() > 0 ||
2728 manager_->GetConsecutivePtoCount() > 0);
2729
2730 // Process a packet, which requests a retransmittable frame be bundled
2731 // with the ACK.
2732 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
2733 .WillOnce(Invoke([this]() {
2734 connection_.SendControlFrame(
2735 QuicFrame(new QuicWindowUpdateFrame(1, 0, 0)));
2736 }));
2737 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2738 ProcessDataPacket(11);
2739 EXPECT_EQ(1u, writer_->window_update_frames().size());
2740}
2741
QUICHE teama6ef0a62019-03-07 20:34:33 -05002742TEST_P(QuicConnectionTest, LeastUnackedLower) {
fayangc31c9952019-06-05 13:54:48 -07002743 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002744 return;
2745 }
2746 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2747
2748 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
2749 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
2750 SendStreamDataToPeer(1, "eep", 6, NO_FIN, nullptr);
2751
2752 // Start out saying the least unacked is 2.
2753 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
2754 ProcessStopWaitingPacket(InitStopWaitingFrame(2));
2755
2756 // Change it to 1, but lower the packet number to fake out-of-order packets.
2757 // This should be fine.
2758 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 1);
2759 // The scheduler will not process out of order acks, but all packet processing
2760 // causes the connection to try to write.
2761 if (!GetParam().no_stop_waiting) {
2762 EXPECT_CALL(visitor_, OnCanWrite());
2763 }
2764 ProcessStopWaitingPacket(InitStopWaitingFrame(1));
2765
2766 // Now claim it's one, but set the ordering so it was sent "after" the first
2767 // one. This should cause a connection error.
2768 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 7);
2769 if (!GetParam().no_stop_waiting) {
rch39c88ab2019-10-16 19:24:40 -07002770 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2771 .Times(AtLeast(1));
fkastenholz5d880a92019-06-21 09:01:56 -07002772 EXPECT_CALL(visitor_,
rch39c88ab2019-10-16 19:24:40 -07002773 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
2774 .Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002775 }
2776 ProcessStopWaitingPacket(InitStopWaitingFrame(1));
fkastenholz5d880a92019-06-21 09:01:56 -07002777 if (!GetParam().no_stop_waiting) {
2778 TestConnectionCloseQuicErrorCode(QUIC_INVALID_STOP_WAITING_DATA);
2779 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002780}
2781
2782TEST_P(QuicConnectionTest, TooManySentPackets) {
2783 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2784
2785 QuicPacketCount max_tracked_packets = 50;
2786 QuicConnectionPeer::SetMaxTrackedPackets(&connection_, max_tracked_packets);
2787
2788 const int num_packets = max_tracked_packets + 5;
2789
2790 for (int i = 0; i < num_packets; ++i) {
2791 SendStreamDataToPeer(1, "foo", 3 * i, NO_FIN, nullptr);
2792 }
2793
2794 // Ack packet 1, which leaves more than the limit outstanding.
2795 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2796 EXPECT_CALL(visitor_,
fkastenholz5d880a92019-06-21 09:01:56 -07002797 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002798
2799 // Nack the first packet and ack the rest, leaving a huge gap.
2800 QuicAckFrame frame1 = ConstructAckFrame(num_packets, 1);
2801 ProcessAckPacket(&frame1);
fkastenholz5d880a92019-06-21 09:01:56 -07002802 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002803}
2804
2805TEST_P(QuicConnectionTest, LargestObservedLower) {
2806 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2807
2808 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
2809 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
2810 SendStreamDataToPeer(1, "eep", 6, NO_FIN, nullptr);
2811 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2812
2813 // Start out saying the largest observed is 2.
2814 QuicAckFrame frame1 = InitAckFrame(1);
2815 QuicAckFrame frame2 = InitAckFrame(2);
2816 ProcessAckPacket(&frame2);
2817
fayang745c93a2019-06-21 13:43:04 -07002818 EXPECT_CALL(visitor_, OnCanWrite());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002819 ProcessAckPacket(&frame1);
2820}
2821
2822TEST_P(QuicConnectionTest, AckUnsentData) {
2823 // Ack a packet which has not been sent.
fkastenholz5d880a92019-06-21 09:01:56 -07002824 EXPECT_CALL(visitor_,
2825 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002826 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
rch39c88ab2019-10-16 19:24:40 -07002827 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002828 QuicAckFrame frame = InitAckFrame(1);
2829 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
2830 ProcessAckPacket(&frame);
fkastenholz5d880a92019-06-21 09:01:56 -07002831 TestConnectionCloseQuicErrorCode(QUIC_INVALID_ACK_DATA);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002832}
2833
2834TEST_P(QuicConnectionTest, BasicSending) {
QUICHE teamcd098022019-03-22 18:49:55 -07002835 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2836 return;
2837 }
fayang643c7dd2020-05-18 07:11:27 -07002838 const QuicConnectionStats& stats = connection_.GetStats();
2839 EXPECT_FALSE(stats.first_decrypted_packet.IsInitialized());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002840 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2841 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2842 ProcessDataPacket(1);
fayang643c7dd2020-05-18 07:11:27 -07002843 EXPECT_EQ(QuicPacketNumber(1), stats.first_decrypted_packet);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002844 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
2845 QuicPacketNumber last_packet;
2846 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
2847 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
2848 SendAckPacketToPeer(); // Packet 2
2849
2850 if (GetParam().no_stop_waiting) {
2851 // Expect no stop waiting frame is sent.
2852 EXPECT_FALSE(least_unacked().IsInitialized());
2853 } else {
2854 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
2855 }
2856
2857 SendAckPacketToPeer(); // Packet 3
2858 if (GetParam().no_stop_waiting) {
2859 // Expect no stop waiting frame is sent.
2860 EXPECT_FALSE(least_unacked().IsInitialized());
2861 } else {
2862 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
2863 }
2864
2865 SendStreamDataToPeer(1, "bar", 3, NO_FIN, &last_packet); // Packet 4
2866 EXPECT_EQ(QuicPacketNumber(4u), last_packet);
2867 SendAckPacketToPeer(); // Packet 5
2868 if (GetParam().no_stop_waiting) {
2869 // Expect no stop waiting frame is sent.
2870 EXPECT_FALSE(least_unacked().IsInitialized());
2871 } else {
2872 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
2873 }
2874
2875 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2876
2877 // Peer acks up to packet 3.
2878 QuicAckFrame frame = InitAckFrame(3);
2879 ProcessAckPacket(&frame);
2880 SendAckPacketToPeer(); // Packet 6
2881
2882 // As soon as we've acked one, we skip ack packets 2 and 3 and note lack of
2883 // ack for 4.
2884 if (GetParam().no_stop_waiting) {
2885 // Expect no stop waiting frame is sent.
2886 EXPECT_FALSE(least_unacked().IsInitialized());
2887 } else {
2888 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
2889 }
2890
2891 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2892
2893 // Peer acks up to packet 4, the last packet.
2894 QuicAckFrame frame2 = InitAckFrame(6);
2895 ProcessAckPacket(&frame2); // Acks don't instigate acks.
2896
2897 // Verify that we did not send an ack.
2898 EXPECT_EQ(QuicPacketNumber(6u), writer_->header().packet_number);
2899
2900 // So the last ack has not changed.
2901 if (GetParam().no_stop_waiting) {
2902 // Expect no stop waiting frame is sent.
2903 EXPECT_FALSE(least_unacked().IsInitialized());
2904 } else {
2905 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
2906 }
2907
2908 // If we force an ack, we shouldn't change our retransmit state.
2909 SendAckPacketToPeer(); // Packet 7
2910 if (GetParam().no_stop_waiting) {
2911 // Expect no stop waiting frame is sent.
2912 EXPECT_FALSE(least_unacked().IsInitialized());
2913 } else {
2914 EXPECT_EQ(QuicPacketNumber(7u), least_unacked());
2915 }
2916
2917 // But if we send more data it should.
2918 SendStreamDataToPeer(1, "eep", 6, NO_FIN, &last_packet); // Packet 8
2919 EXPECT_EQ(QuicPacketNumber(8u), last_packet);
2920 SendAckPacketToPeer(); // Packet 9
2921 if (GetParam().no_stop_waiting) {
2922 // Expect no stop waiting frame is sent.
2923 EXPECT_FALSE(least_unacked().IsInitialized());
2924 } else {
2925 EXPECT_EQ(QuicPacketNumber(7u), least_unacked());
2926 }
fayang643c7dd2020-05-18 07:11:27 -07002927 EXPECT_EQ(QuicPacketNumber(1), stats.first_decrypted_packet);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002928}
2929
2930// QuicConnection should record the packet sent-time prior to sending the
2931// packet.
2932TEST_P(QuicConnectionTest, RecordSentTimeBeforePacketSent) {
2933 // We're using a MockClock for the tests, so we have complete control over the
2934 // time.
2935 // Our recorded timestamp for the last packet sent time will be passed in to
2936 // the send_algorithm. Make sure that it is set to the correct value.
2937 QuicTime actual_recorded_send_time = QuicTime::Zero();
2938 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2939 .WillOnce(SaveArg<0>(&actual_recorded_send_time));
2940
2941 // First send without any pause and check the result.
2942 QuicTime expected_recorded_send_time = clock_.Now();
2943 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
2944 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
2945 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
2946 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
2947
2948 // Now pause during the write, and check the results.
2949 actual_recorded_send_time = QuicTime::Zero();
2950 const QuicTime::Delta write_pause_time_delta =
2951 QuicTime::Delta::FromMilliseconds(5000);
2952 SetWritePauseTimeDelta(write_pause_time_delta);
2953 expected_recorded_send_time = clock_.Now();
2954
2955 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2956 .WillOnce(SaveArg<0>(&actual_recorded_send_time));
2957 connection_.SendStreamDataWithString(2, "baz", 0, NO_FIN);
2958 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
2959 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
2960 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
2961}
2962
2963TEST_P(QuicConnectionTest, FramePacking) {
2964 // Send two stream frames in 1 packet by queueing them.
2965 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2966 {
fayanga4b37b22019-06-18 13:37:47 -07002967 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002968 connection_.SendStreamData3();
2969 connection_.SendStreamData5();
2970 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2971 }
2972 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2973 EXPECT_FALSE(connection_.HasQueuedData());
2974
2975 // Parse the last packet and ensure it's an ack and two stream frames from
2976 // two different streams.
2977 if (GetParam().no_stop_waiting) {
2978 EXPECT_EQ(2u, writer_->frame_count());
2979 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
2980 } else {
2981 EXPECT_EQ(2u, writer_->frame_count());
2982 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
2983 }
2984
2985 EXPECT_TRUE(writer_->ack_frames().empty());
2986
2987 ASSERT_EQ(2u, writer_->stream_frames().size());
2988 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
2989 writer_->stream_frames()[0]->stream_id);
2990 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
2991 writer_->stream_frames()[1]->stream_id);
2992}
2993
2994TEST_P(QuicConnectionTest, FramePackingNonCryptoThenCrypto) {
2995 // Send two stream frames (one non-crypto, then one crypto) in 2 packets by
2996 // queueing them.
2997 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2998 {
2999 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
fayanga4b37b22019-06-18 13:37:47 -07003000 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003001 connection_.SendStreamData3();
fayang58f71072019-11-05 08:47:02 -08003002 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003003 connection_.SendCryptoStreamData();
fayang58f71072019-11-05 08:47:02 -08003004 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003005 }
3006 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3007 EXPECT_FALSE(connection_.HasQueuedData());
3008
3009 // Parse the last packet and ensure it's the crypto stream frame.
3010 EXPECT_EQ(2u, writer_->frame_count());
3011 ASSERT_EQ(1u, writer_->padding_frames().size());
QUICHE teamea740082019-03-11 17:58:43 -07003012 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003013 ASSERT_EQ(1u, writer_->stream_frames().size());
3014 EXPECT_EQ(QuicUtils::GetCryptoStreamId(connection_.transport_version()),
3015 writer_->stream_frames()[0]->stream_id);
3016 } else {
3017 EXPECT_EQ(1u, writer_->crypto_frames().size());
3018 }
3019}
3020
3021TEST_P(QuicConnectionTest, FramePackingCryptoThenNonCrypto) {
3022 // Send two stream frames (one crypto, then one non-crypto) in 2 packets by
3023 // queueing them.
3024 {
3025 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3026 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
fayanga4b37b22019-06-18 13:37:47 -07003027 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003028 connection_.SendCryptoStreamData();
3029 connection_.SendStreamData3();
3030 }
3031 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3032 EXPECT_FALSE(connection_.HasQueuedData());
3033
3034 // Parse the last packet and ensure it's the stream frame from stream 3.
nharper55fa6132019-05-07 19:37:21 -07003035 size_t padding_frame_count = writer_->padding_frames().size();
3036 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003037 ASSERT_EQ(1u, writer_->stream_frames().size());
3038 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3039 writer_->stream_frames()[0]->stream_id);
3040}
3041
3042TEST_P(QuicConnectionTest, FramePackingAckResponse) {
3043 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3044 // Process a data packet to queue up a pending ack.
fayang3451f6e2019-06-11 08:18:12 -07003045 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3046 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
3047 } else {
3048 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3049 }
3050 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
3051
QUICHE teama6ef0a62019-03-07 20:34:33 -05003052 QuicPacketNumber last_packet;
nharper46833c32019-05-15 21:33:05 -07003053 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3054 connection_.SendCryptoDataWithString("foo", 0);
3055 } else {
3056 SendStreamDataToPeer(
3057 QuicUtils::GetCryptoStreamId(connection_.transport_version()), "foo", 0,
3058 NO_FIN, &last_packet);
3059 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003060 // Verify ack is bundled with outging packet.
3061 EXPECT_FALSE(writer_->ack_frames().empty());
3062
3063 EXPECT_CALL(visitor_, OnCanWrite())
3064 .WillOnce(DoAll(IgnoreResult(InvokeWithoutArgs(
3065 &connection_, &TestConnection::SendStreamData3)),
3066 IgnoreResult(InvokeWithoutArgs(
3067 &connection_, &TestConnection::SendStreamData5))));
3068
3069 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3070
3071 // Process a data packet to cause the visitor's OnCanWrite to be invoked.
3072 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
QUICHE team8c1daa22019-03-13 08:33:41 -07003073 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07003074 std::make_unique<TaggingEncrypter>(0x01));
zhongyi546cc452019-04-12 15:27:49 -07003075 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07003076 std::make_unique<StrictTaggingDecrypter>(0x01));
nharper2c9f02a2019-05-08 10:25:50 -07003077 ProcessDataPacket(2);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003078
3079 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3080 EXPECT_FALSE(connection_.HasQueuedData());
3081
3082 // Parse the last packet and ensure it's an ack and two stream frames from
3083 // two different streams.
3084 if (GetParam().no_stop_waiting) {
3085 EXPECT_EQ(3u, writer_->frame_count());
3086 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
3087 } else {
3088 EXPECT_EQ(4u, writer_->frame_count());
3089 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3090 }
3091 EXPECT_FALSE(writer_->ack_frames().empty());
3092 ASSERT_EQ(2u, writer_->stream_frames().size());
3093 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3094 writer_->stream_frames()[0]->stream_id);
3095 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3096 writer_->stream_frames()[1]->stream_id);
3097}
3098
3099TEST_P(QuicConnectionTest, FramePackingSendv) {
nharper46833c32019-05-15 21:33:05 -07003100 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003101 // Send data in 1 packet by writing multiple blocks in a single iovector
3102 // using writev.
3103 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3104
3105 char data[] = "ABCDEF";
3106 struct iovec iov[2];
3107 iov[0].iov_base = data;
3108 iov[0].iov_len = 4;
3109 iov[1].iov_base = data + 4;
3110 iov[1].iov_len = 2;
nharper46833c32019-05-15 21:33:05 -07003111 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
3112 connection_.transport_version(), Perspective::IS_CLIENT);
3113 connection_.SaveAndSendStreamData(stream_id, iov, 2, 6, 0, NO_FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003114
3115 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3116 EXPECT_FALSE(connection_.HasQueuedData());
3117
3118 // Parse the last packet and ensure multiple iovector blocks have
3119 // been packed into a single stream frame from one stream.
nharper46833c32019-05-15 21:33:05 -07003120 EXPECT_EQ(1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003121 EXPECT_EQ(1u, writer_->stream_frames().size());
nharper46833c32019-05-15 21:33:05 -07003122 EXPECT_EQ(0u, writer_->padding_frames().size());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003123 QuicStreamFrame* frame = writer_->stream_frames()[0].get();
nharper46833c32019-05-15 21:33:05 -07003124 EXPECT_EQ(stream_id, frame->stream_id);
dmcardlecf0bfcf2019-12-13 08:08:21 -08003125 EXPECT_EQ("ABCDEF",
3126 quiche::QuicheStringPiece(frame->data_buffer, frame->data_length));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003127}
3128
3129TEST_P(QuicConnectionTest, FramePackingSendvQueued) {
nharper46833c32019-05-15 21:33:05 -07003130 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003131 // Try to send two stream frames in 1 packet by using writev.
3132 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3133
3134 BlockOnNextWrite();
3135 char data[] = "ABCDEF";
3136 struct iovec iov[2];
3137 iov[0].iov_base = data;
3138 iov[0].iov_len = 4;
3139 iov[1].iov_base = data + 4;
3140 iov[1].iov_len = 2;
nharper46833c32019-05-15 21:33:05 -07003141 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
3142 connection_.transport_version(), Perspective::IS_CLIENT);
3143 connection_.SaveAndSendStreamData(stream_id, iov, 2, 6, 0, NO_FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003144
3145 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3146 EXPECT_TRUE(connection_.HasQueuedData());
3147
3148 // Unblock the writes and actually send.
3149 writer_->SetWritable();
3150 connection_.OnCanWrite();
3151 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3152
3153 // Parse the last packet and ensure it's one stream frame from one stream.
nharper46833c32019-05-15 21:33:05 -07003154 EXPECT_EQ(1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003155 EXPECT_EQ(1u, writer_->stream_frames().size());
nharper46833c32019-05-15 21:33:05 -07003156 EXPECT_EQ(0u, writer_->padding_frames().size());
3157 EXPECT_EQ(stream_id, writer_->stream_frames()[0]->stream_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003158}
3159
3160TEST_P(QuicConnectionTest, SendingZeroBytes) {
3161 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3162 // Send a zero byte write with a fin using writev.
3163 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
nharper46833c32019-05-15 21:33:05 -07003164 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
3165 connection_.transport_version(), Perspective::IS_CLIENT);
3166 connection_.SaveAndSendStreamData(stream_id, nullptr, 0, 0, 0, FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003167
3168 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3169 EXPECT_FALSE(connection_.HasQueuedData());
3170
nharper55fa6132019-05-07 19:37:21 -07003171 // Padding frames are added by v99 to ensure a minimum packet size.
3172 size_t extra_padding_frames = 0;
3173 if (GetParam().version.HasHeaderProtection()) {
3174 extra_padding_frames = 1;
3175 }
3176
QUICHE teama6ef0a62019-03-07 20:34:33 -05003177 // Parse the last packet and ensure it's one stream frame from one stream.
nharper55fa6132019-05-07 19:37:21 -07003178 EXPECT_EQ(1u + extra_padding_frames, writer_->frame_count());
3179 EXPECT_EQ(extra_padding_frames, writer_->padding_frames().size());
3180 ASSERT_EQ(1u, writer_->stream_frames().size());
nharper46833c32019-05-15 21:33:05 -07003181 EXPECT_EQ(stream_id, writer_->stream_frames()[0]->stream_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003182 EXPECT_TRUE(writer_->stream_frames()[0]->fin);
3183}
3184
3185TEST_P(QuicConnectionTest, LargeSendWithPendingAck) {
3186 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
fayang15042962020-07-01 12:14:29 -07003187 EXPECT_CALL(visitor_, GetHandshakeState())
3188 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003189 // Set the ack alarm by processing a ping frame.
3190 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3191
3192 // Processs a PING frame.
3193 ProcessFramePacket(QuicFrame(QuicPingFrame()));
3194 // Ensure that this has caused the ACK alarm to be set.
fayang9adfb532020-06-04 06:58:45 -07003195 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003196
3197 // Send data and ensure the ack is bundled.
3198 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(8);
3199 size_t len = 10000;
3200 std::unique_ptr<char[]> data_array(new char[len]);
3201 memset(data_array.get(), '?', len);
3202 struct iovec iov;
3203 iov.iov_base = data_array.get();
3204 iov.iov_len = len;
3205 QuicConsumedData consumed = connection_.SaveAndSendStreamData(
dschinazi552accc2019-06-17 17:07:34 -07003206 GetNthClientInitiatedStreamId(0, connection_.transport_version()), &iov,
3207 1, len, 0, FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003208 EXPECT_EQ(len, consumed.bytes_consumed);
3209 EXPECT_TRUE(consumed.fin_consumed);
3210 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3211 EXPECT_FALSE(connection_.HasQueuedData());
3212
3213 // Parse the last packet and ensure it's one stream frame with a fin.
3214 EXPECT_EQ(1u, writer_->frame_count());
nharper55fa6132019-05-07 19:37:21 -07003215 ASSERT_EQ(1u, writer_->stream_frames().size());
dschinazi552accc2019-06-17 17:07:34 -07003216 EXPECT_EQ(GetNthClientInitiatedStreamId(0, connection_.transport_version()),
QUICHE teama6ef0a62019-03-07 20:34:33 -05003217 writer_->stream_frames()[0]->stream_id);
3218 EXPECT_TRUE(writer_->stream_frames()[0]->fin);
3219 // Ensure the ack alarm was cancelled when the ack was sent.
fayang9adfb532020-06-04 06:58:45 -07003220 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003221}
3222
3223TEST_P(QuicConnectionTest, OnCanWrite) {
3224 // Visitor's OnCanWrite will send data, but will have more pending writes.
3225 EXPECT_CALL(visitor_, OnCanWrite())
3226 .WillOnce(DoAll(IgnoreResult(InvokeWithoutArgs(
3227 &connection_, &TestConnection::SendStreamData3)),
3228 IgnoreResult(InvokeWithoutArgs(
3229 &connection_, &TestConnection::SendStreamData5))));
3230 {
3231 InSequence seq;
3232 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillOnce(Return(true));
3233 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
3234 .WillRepeatedly(Return(false));
3235 }
3236
3237 EXPECT_CALL(*send_algorithm_, CanSend(_))
3238 .WillRepeatedly(testing::Return(true));
3239
3240 connection_.OnCanWrite();
3241
3242 // Parse the last packet and ensure it's the two stream frames from
3243 // two different streams.
3244 EXPECT_EQ(2u, writer_->frame_count());
3245 EXPECT_EQ(2u, writer_->stream_frames().size());
3246 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3247 writer_->stream_frames()[0]->stream_id);
3248 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3249 writer_->stream_frames()[1]->stream_id);
3250}
3251
3252TEST_P(QuicConnectionTest, RetransmitOnNack) {
3253 QuicPacketNumber last_packet;
3254 QuicByteCount second_packet_size;
3255 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet); // Packet 1
3256 second_packet_size =
3257 SendStreamDataToPeer(3, "foos", 3, NO_FIN, &last_packet); // Packet 2
3258 SendStreamDataToPeer(3, "fooos", 7, NO_FIN, &last_packet); // Packet 3
3259
3260 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3261
3262 // Don't lose a packet on an ack, and nothing is retransmitted.
3263 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3264 QuicAckFrame ack_one = InitAckFrame(1);
3265 ProcessAckPacket(&ack_one);
3266
3267 // Lose a packet and ensure it triggers retransmission.
3268 QuicAckFrame nack_two = ConstructAckFrame(3, 2);
3269 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003270 lost_packets.push_back(
3271 LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003272 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07003273 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
3274 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003275 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3276 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3277 EXPECT_FALSE(QuicPacketCreatorPeer::SendVersionInPacket(creator_));
3278 ProcessAckPacket(&nack_two);
3279}
3280
3281TEST_P(QuicConnectionTest, DoNotSendQueuedPacketForResetStream) {
3282 // Block the connection to queue the packet.
3283 BlockOnNextWrite();
3284
3285 QuicStreamId stream_id = 2;
3286 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
3287
3288 // Now that there is a queued packet, reset the stream.
3289 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
3290
3291 // Unblock the connection and verify that only the RST_STREAM is sent.
3292 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3293 writer_->SetWritable();
3294 connection_.OnCanWrite();
nharper55fa6132019-05-07 19:37:21 -07003295 size_t padding_frame_count = writer_->padding_frames().size();
3296 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003297 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3298}
3299
3300TEST_P(QuicConnectionTest, SendQueuedPacketForQuicRstStreamNoError) {
3301 // Block the connection to queue the packet.
3302 BlockOnNextWrite();
3303
3304 QuicStreamId stream_id = 2;
fayange62e63c2019-12-04 07:16:25 -08003305 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003306 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
3307
3308 // Now that there is a queued packet, reset the stream.
3309 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 3);
3310
3311 // Unblock the connection and verify that the RST_STREAM is sent and the data
3312 // packet is sent.
fayange62e63c2019-12-04 07:16:25 -08003313 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003314 writer_->SetWritable();
3315 connection_.OnCanWrite();
nharper55fa6132019-05-07 19:37:21 -07003316 size_t padding_frame_count = writer_->padding_frames().size();
3317 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003318 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3319}
3320
3321TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnNack) {
3322 QuicStreamId stream_id = 2;
3323 QuicPacketNumber last_packet;
3324 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3325 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3326 SendStreamDataToPeer(stream_id, "fooos", 7, NO_FIN, &last_packet);
3327
3328 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3329 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 12);
3330
3331 // Lose a packet and ensure it does not trigger retransmission.
3332 QuicAckFrame nack_two = ConstructAckFrame(last_packet, last_packet - 1);
3333 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3334 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3335 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3336 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3337 ProcessAckPacket(&nack_two);
3338}
3339
3340TEST_P(QuicConnectionTest, RetransmitForQuicRstStreamNoErrorOnNack) {
3341 QuicStreamId stream_id = 2;
3342 QuicPacketNumber last_packet;
3343 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3344 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3345 SendStreamDataToPeer(stream_id, "fooos", 7, NO_FIN, &last_packet);
3346
3347 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3348 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 12);
3349
3350 // Lose a packet, ensure it triggers retransmission.
3351 QuicAckFrame nack_two = ConstructAckFrame(last_packet, last_packet - 1);
3352 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3353 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003354 lost_packets.push_back(LostPacket(last_packet - 1, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003355 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07003356 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
3357 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003358 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3359 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
3360 ProcessAckPacket(&nack_two);
3361}
3362
3363TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnRTO) {
3364 QuicStreamId stream_id = 2;
3365 QuicPacketNumber last_packet;
3366 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3367
3368 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3369 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
3370
3371 // Fire the RTO and verify that the RST_STREAM is resent, not stream data.
3372 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3373 clock_.AdvanceTime(DefaultRetransmissionTime());
3374 connection_.GetRetransmissionAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07003375 size_t padding_frame_count = writer_->padding_frames().size();
3376 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003377 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3378 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
3379}
3380
3381// Ensure that if the only data in flight is non-retransmittable, the
3382// retransmission alarm is not set.
3383TEST_P(QuicConnectionTest, CancelRetransmissionAlarmAfterResetStream) {
3384 QuicStreamId stream_id = 2;
3385 QuicPacketNumber last_data_packet;
3386 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
3387
3388 // Cancel the stream.
3389 const QuicPacketNumber rst_packet = last_data_packet + 1;
3390 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, rst_packet, _, _)).Times(1);
3391 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
3392
3393 // Ack the RST_STREAM frame (since it's retransmittable), but not the data
3394 // packet, which is no longer retransmittable since the stream was cancelled.
3395 QuicAckFrame nack_stream_data =
3396 ConstructAckFrame(rst_packet, last_data_packet);
3397 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3398 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3399 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3400 ProcessAckPacket(&nack_stream_data);
3401
3402 // Ensure that the data is still in flight, but the retransmission alarm is no
3403 // longer set.
ianswett9f459cb2019-04-21 06:39:59 -07003404 EXPECT_GT(manager_->GetBytesInFlight(), 0u);
fayangcff885a2019-10-22 07:39:04 -07003405 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003406}
3407
3408TEST_P(QuicConnectionTest, RetransmitForQuicRstStreamNoErrorOnRTO) {
3409 connection_.SetMaxTailLossProbes(0);
3410
3411 QuicStreamId stream_id = 2;
3412 QuicPacketNumber last_packet;
3413 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3414
3415 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3416 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 3);
3417
3418 // Fire the RTO and verify that the RST_STREAM is resent, the stream data
3419 // is sent.
fayang1c2d1ab2020-03-11 12:08:41 -07003420 const size_t num_retransmissions =
3421 connection_.SupportsMultiplePacketNumberSpaces() ? 1 : 2;
3422 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3423 .Times(AtLeast(num_retransmissions));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003424 clock_.AdvanceTime(DefaultRetransmissionTime());
3425 connection_.GetRetransmissionAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07003426 size_t padding_frame_count = writer_->padding_frames().size();
3427 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
fayang1c2d1ab2020-03-11 12:08:41 -07003428 if (num_retransmissions == 2) {
3429 ASSERT_EQ(1u, writer_->rst_stream_frames().size());
3430 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
3431 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003432}
3433
3434TEST_P(QuicConnectionTest, DoNotSendPendingRetransmissionForResetStream) {
3435 QuicStreamId stream_id = 2;
3436 QuicPacketNumber last_packet;
3437 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3438 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3439 BlockOnNextWrite();
3440 connection_.SendStreamDataWithString(stream_id, "fooos", 7, NO_FIN);
3441
3442 // Lose a packet which will trigger a pending retransmission.
3443 QuicAckFrame ack = ConstructAckFrame(last_packet, last_packet - 1);
3444 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3445 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3446 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3447 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3448 ProcessAckPacket(&ack);
3449
3450 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 12);
3451
3452 // Unblock the connection and verify that the RST_STREAM is sent but not the
3453 // second data packet nor a retransmit.
3454 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3455 writer_->SetWritable();
3456 connection_.OnCanWrite();
nharper55fa6132019-05-07 19:37:21 -07003457 size_t padding_frame_count = writer_->padding_frames().size();
3458 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
zhongyi546cc452019-04-12 15:27:49 -07003459 ASSERT_EQ(1u, writer_->rst_stream_frames().size());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003460 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
3461}
3462
3463TEST_P(QuicConnectionTest, SendPendingRetransmissionForQuicRstStreamNoError) {
3464 QuicStreamId stream_id = 2;
3465 QuicPacketNumber last_packet;
3466 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3467 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3468 BlockOnNextWrite();
3469 connection_.SendStreamDataWithString(stream_id, "fooos", 7, NO_FIN);
3470
3471 // Lose a packet which will trigger a pending retransmission.
3472 QuicAckFrame ack = ConstructAckFrame(last_packet, last_packet - 1);
3473 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3474 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003475 lost_packets.push_back(LostPacket(last_packet - 1, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003476 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07003477 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
3478 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003479 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3480 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3481 ProcessAckPacket(&ack);
3482
3483 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 12);
3484
3485 // Unblock the connection and verify that the RST_STREAM is sent and the
3486 // second data packet or a retransmit is sent.
3487 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(2));
3488 writer_->SetWritable();
3489 connection_.OnCanWrite();
3490 // The RST_STREAM_FRAME is sent after queued packets and pending
3491 // retransmission.
3492 connection_.SendControlFrame(QuicFrame(
3493 new QuicRstStreamFrame(1, stream_id, QUIC_STREAM_NO_ERROR, 14)));
nharper55fa6132019-05-07 19:37:21 -07003494 size_t padding_frame_count = writer_->padding_frames().size();
3495 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003496 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3497}
3498
3499TEST_P(QuicConnectionTest, RetransmitAckedPacket) {
3500 QuicPacketNumber last_packet;
3501 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
3502 SendStreamDataToPeer(1, "foos", 3, NO_FIN, &last_packet); // Packet 2
3503 SendStreamDataToPeer(1, "fooos", 7, NO_FIN, &last_packet); // Packet 3
3504
3505 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3506
3507 // Instigate a loss with an ack.
3508 QuicAckFrame nack_two = ConstructAckFrame(3, 2);
3509 // The first nack should trigger a fast retransmission, but we'll be
3510 // write blocked, so the packet will be queued.
3511 BlockOnNextWrite();
3512
3513 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003514 lost_packets.push_back(
3515 LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003516 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07003517 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
3518 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003519 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
fayange62e63c2019-12-04 07:16:25 -08003520 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _))
3521 .Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003522 ProcessAckPacket(&nack_two);
3523 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3524
3525 // Now, ack the previous transmission.
3526 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3527 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(false, _, _, _, _));
3528 QuicAckFrame ack_all = InitAckFrame(3);
3529 ProcessAckPacket(&ack_all);
3530
fayange62e63c2019-12-04 07:16:25 -08003531 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _))
3532 .Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003533
3534 writer_->SetWritable();
3535 connection_.OnCanWrite();
3536
3537 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3538 // We do not store retransmittable frames of this retransmission.
3539 EXPECT_FALSE(QuicConnectionPeer::HasRetransmittableFrames(&connection_, 4));
3540}
3541
3542TEST_P(QuicConnectionTest, RetransmitNackedLargestObserved) {
3543 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3544 QuicPacketNumber original, second;
3545
3546 QuicByteCount packet_size =
3547 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &original); // 1st packet.
3548 SendStreamDataToPeer(3, "bar", 3, NO_FIN, &second); // 2nd packet.
3549
3550 QuicAckFrame frame = InitAckFrame({{second, second + 1}});
3551 // The first nack should retransmit the largest observed packet.
3552 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003553 lost_packets.push_back(LostPacket(original, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003554 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07003555 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
3556 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003557 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3558 // Packet 1 is short header for IETF QUIC because the encryption level
3559 // switched to ENCRYPTION_FORWARD_SECURE in SendStreamDataToPeer.
fayangd4291e42019-05-30 10:31:21 -07003560 EXPECT_CALL(*send_algorithm_,
3561 OnPacketSent(_, _, _,
3562 VersionHasIetfInvariantHeader(
3563 GetParam().version.transport_version)
3564 ? packet_size
3565 : packet_size - kQuicVersionSize,
3566 _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003567 ProcessAckPacket(&frame);
3568}
3569
3570TEST_P(QuicConnectionTest, QueueAfterTwoRTOs) {
fayangcff885a2019-10-22 07:39:04 -07003571 if (connection_.PtoEnabled()) {
fayang5f135052019-08-22 17:59:40 -07003572 return;
3573 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003574 connection_.SetMaxTailLossProbes(0);
3575
3576 for (int i = 0; i < 10; ++i) {
3577 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3578 connection_.SendStreamDataWithString(3, "foo", i * 3, NO_FIN);
3579 }
3580
3581 // Block the writer and ensure they're queued.
3582 BlockOnNextWrite();
3583 clock_.AdvanceTime(DefaultRetransmissionTime());
fayange62e63c2019-12-04 07:16:25 -08003584 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003585 connection_.GetRetransmissionAlarm()->Fire();
3586 EXPECT_TRUE(connection_.HasQueuedData());
3587
3588 // Unblock the writer.
3589 writer_->SetWritable();
3590 clock_.AdvanceTime(QuicTime::Delta::FromMicroseconds(
3591 2 * DefaultRetransmissionTime().ToMicroseconds()));
fayange62e63c2019-12-04 07:16:25 -08003592 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003593 connection_.GetRetransmissionAlarm()->Fire();
3594 connection_.OnCanWrite();
3595}
3596
3597TEST_P(QuicConnectionTest, WriteBlockedBufferedThenSent) {
3598 BlockOnNextWrite();
3599 writer_->set_is_write_blocked_data_buffered(true);
3600 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3601 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3602 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3603
3604 writer_->SetWritable();
3605 connection_.OnCanWrite();
3606 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3607}
3608
3609TEST_P(QuicConnectionTest, WriteBlockedThenSent) {
3610 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3611 BlockOnNextWrite();
fayange62e63c2019-12-04 07:16:25 -08003612 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003613 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
fayange62e63c2019-12-04 07:16:25 -08003614 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003615 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3616
3617 // The second packet should also be queued, in order to ensure packets are
3618 // never sent out of order.
3619 writer_->SetWritable();
fayange62e63c2019-12-04 07:16:25 -08003620 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003621 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3622 EXPECT_EQ(2u, connection_.NumQueuedPackets());
3623
3624 // Now both are sent in order when we unblock.
fayange62e63c2019-12-04 07:16:25 -08003625 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003626 connection_.OnCanWrite();
3627 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
fayang2ce66082019-10-02 06:29:04 -07003628 EXPECT_EQ(0u, connection_.NumQueuedPackets());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003629}
3630
3631TEST_P(QuicConnectionTest, RetransmitWriteBlockedAckedOriginalThenSent) {
3632 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3633 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
3634 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3635
3636 BlockOnNextWrite();
3637 writer_->set_is_write_blocked_data_buffered(true);
3638 // Simulate the retransmission alarm firing.
3639 clock_.AdvanceTime(DefaultRetransmissionTime());
3640 connection_.GetRetransmissionAlarm()->Fire();
3641
3642 // Ack the sent packet before the callback returns, which happens in
3643 // rare circumstances with write blocked sockets.
3644 QuicAckFrame ack = InitAckFrame(1);
3645 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3646 ProcessAckPacket(&ack);
3647
3648 writer_->SetWritable();
3649 connection_.OnCanWrite();
fayangcff885a2019-10-22 07:39:04 -07003650 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
fayang5d011982020-05-13 14:14:38 -07003651 uint64_t retransmission = connection_.SupportsMultiplePacketNumberSpaces() &&
3652 !GetQuicReloadableFlag(quic_default_on_pto)
3653 ? 3
3654 : 2;
fayang1c2d1ab2020-03-11 12:08:41 -07003655 EXPECT_FALSE(QuicConnectionPeer::HasRetransmittableFrames(&connection_,
3656 retransmission));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003657}
3658
3659TEST_P(QuicConnectionTest, AlarmsWhenWriteBlocked) {
3660 // Block the connection.
3661 BlockOnNextWrite();
3662 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
3663 EXPECT_EQ(1u, writer_->packets_write_attempts());
3664 EXPECT_TRUE(writer_->IsWriteBlocked());
3665
3666 // Set the send alarm. Fire the alarm and ensure it doesn't attempt to write.
3667 connection_.GetSendAlarm()->Set(clock_.ApproximateNow());
3668 connection_.GetSendAlarm()->Fire();
3669 EXPECT_TRUE(writer_->IsWriteBlocked());
3670 EXPECT_EQ(1u, writer_->packets_write_attempts());
3671}
3672
3673TEST_P(QuicConnectionTest, NoSendAlarmAfterProcessPacketWhenWriteBlocked) {
3674 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3675
3676 // Block the connection.
3677 BlockOnNextWrite();
3678 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
3679 EXPECT_TRUE(writer_->IsWriteBlocked());
3680 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3681 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
3682
3683 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3684 // Process packet number 1. Can not call ProcessPacket or ProcessDataPacket
3685 // here, because they will fire the alarm after QuicConnection::ProcessPacket
3686 // is returned.
3687 const uint64_t received_packet_num = 1;
3688 const bool has_stop_waiting = false;
nharperc6b99512019-09-19 11:13:48 -07003689 const EncryptionLevel level = ENCRYPTION_FORWARD_SECURE;
3690 std::unique_ptr<QuicPacket> packet(
3691 ConstructDataPacket(received_packet_num, has_stop_waiting, level));
dschinazi66dea072019-04-09 11:41:06 -07003692 char buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05003693 size_t encrypted_length =
3694 peer_framer_.EncryptPayload(level, QuicPacketNumber(received_packet_num),
dschinazi66dea072019-04-09 11:41:06 -07003695 *packet, buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003696 connection_.ProcessUdpPacket(
3697 kSelfAddress, kPeerAddress,
3698 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
3699
3700 EXPECT_TRUE(writer_->IsWriteBlocked());
3701 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
3702}
3703
3704TEST_P(QuicConnectionTest, AddToWriteBlockedListIfWriterBlockedWhenProcessing) {
3705 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3706 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
3707
3708 // Simulate the case where a shared writer gets blocked by another connection.
3709 writer_->SetWriteBlocked();
3710
3711 // Process an ACK, make sure the connection calls visitor_->OnWriteBlocked().
3712 QuicAckFrame ack1 = InitAckFrame(1);
3713 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
3714 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
3715 ProcessAckPacket(1, &ack1);
3716}
3717
3718TEST_P(QuicConnectionTest, DoNotAddToWriteBlockedListAfterDisconnect) {
3719 writer_->SetBatchMode(true);
3720 EXPECT_TRUE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07003721 // Have to explicitly grab the OnConnectionClosed frame and check
3722 // its parameters because this is a silent connection close and the
3723 // frame is not also transmitted to the peer.
3724 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
3725 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003726
3727 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
3728
3729 {
fayanga4b37b22019-06-18 13:37:47 -07003730 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003731 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
3732 ConnectionCloseBehavior::SILENT_CLOSE);
3733
3734 EXPECT_FALSE(connection_.connected());
3735 writer_->SetWriteBlocked();
3736 }
fkastenholz5d880a92019-06-21 09:01:56 -07003737 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08003738 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
3739 IsError(QUIC_PEER_GOING_AWAY));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003740}
3741
3742TEST_P(QuicConnectionTest, AddToWriteBlockedListIfBlockedOnFlushPackets) {
3743 writer_->SetBatchMode(true);
3744 writer_->BlockOnNextFlush();
3745
3746 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
3747 {
fayanga4b37b22019-06-18 13:37:47 -07003748 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003749 // flusher's destructor will call connection_.FlushPackets, which should add
3750 // the connection to the write blocked list.
3751 }
3752}
3753
3754TEST_P(QuicConnectionTest, NoLimitPacketsPerNack) {
3755 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3756 int offset = 0;
3757 // Send packets 1 to 15.
3758 for (int i = 0; i < 15; ++i) {
3759 SendStreamDataToPeer(1, "foo", offset, NO_FIN, nullptr);
3760 offset += 3;
3761 }
3762
3763 // Ack 15, nack 1-14.
3764
3765 QuicAckFrame nack =
3766 InitAckFrame({{QuicPacketNumber(15), QuicPacketNumber(16)}});
3767
3768 // 14 packets have been NACK'd and lost.
3769 LostPacketVector lost_packets;
3770 for (int i = 1; i < 15; ++i) {
dschinazi66dea072019-04-09 11:41:06 -07003771 lost_packets.push_back(
3772 LostPacket(QuicPacketNumber(i), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003773 }
3774 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07003775 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
3776 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003777 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
fayangcff885a2019-10-22 07:39:04 -07003778 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003779 ProcessAckPacket(&nack);
3780}
3781
3782// Test sending multiple acks from the connection to the session.
3783TEST_P(QuicConnectionTest, MultipleAcks) {
QUICHE teamcd098022019-03-22 18:49:55 -07003784 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3785 return;
3786 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003787 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3788 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3789 ProcessDataPacket(1);
3790 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
3791 QuicPacketNumber last_packet;
3792 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
3793 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
3794 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet); // Packet 2
3795 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
3796 SendAckPacketToPeer(); // Packet 3
3797 SendStreamDataToPeer(5, "foo", 0, NO_FIN, &last_packet); // Packet 4
3798 EXPECT_EQ(QuicPacketNumber(4u), last_packet);
3799 SendStreamDataToPeer(1, "foo", 3, NO_FIN, &last_packet); // Packet 5
3800 EXPECT_EQ(QuicPacketNumber(5u), last_packet);
3801 SendStreamDataToPeer(3, "foo", 3, NO_FIN, &last_packet); // Packet 6
3802 EXPECT_EQ(QuicPacketNumber(6u), last_packet);
3803
3804 // Client will ack packets 1, 2, [!3], 4, 5.
3805 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3806 QuicAckFrame frame1 = ConstructAckFrame(5, 3);
3807 ProcessAckPacket(&frame1);
3808
3809 // Now the client implicitly acks 3, and explicitly acks 6.
3810 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3811 QuicAckFrame frame2 = InitAckFrame(6);
3812 ProcessAckPacket(&frame2);
3813}
3814
3815TEST_P(QuicConnectionTest, DontLatchUnackedPacket) {
QUICHE teamcd098022019-03-22 18:49:55 -07003816 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3817 return;
3818 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003819 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3820 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3821 ProcessDataPacket(1);
3822 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
3823 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr); // Packet 1;
3824 // From now on, we send acks, so the send algorithm won't mark them pending.
3825 SendAckPacketToPeer(); // Packet 2
3826
3827 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3828 QuicAckFrame frame = InitAckFrame(1);
3829 ProcessAckPacket(&frame);
3830
3831 // Verify that our internal state has least-unacked as 2, because we're still
3832 // waiting for a potential ack for 2.
3833
3834 EXPECT_EQ(QuicPacketNumber(2u), stop_waiting()->least_unacked);
3835
3836 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3837 frame = InitAckFrame(2);
3838 ProcessAckPacket(&frame);
3839 EXPECT_EQ(QuicPacketNumber(3u), stop_waiting()->least_unacked);
3840
3841 // When we send an ack, we make sure our least-unacked makes sense. In this
3842 // case since we're not waiting on an ack for 2 and all packets are acked, we
3843 // set it to 3.
3844 SendAckPacketToPeer(); // Packet 3
3845 // Least_unacked remains at 3 until another ack is received.
3846 EXPECT_EQ(QuicPacketNumber(3u), stop_waiting()->least_unacked);
3847 if (GetParam().no_stop_waiting) {
3848 // Expect no stop waiting frame is sent.
3849 EXPECT_FALSE(least_unacked().IsInitialized());
3850 } else {
3851 // Check that the outgoing ack had its packet number as least_unacked.
3852 EXPECT_EQ(QuicPacketNumber(3u), least_unacked());
3853 }
3854
3855 // Ack the ack, which updates the rtt and raises the least unacked.
3856 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3857 frame = InitAckFrame(3);
3858 ProcessAckPacket(&frame);
3859
3860 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr); // Packet 4
3861 EXPECT_EQ(QuicPacketNumber(4u), stop_waiting()->least_unacked);
3862 SendAckPacketToPeer(); // Packet 5
3863 if (GetParam().no_stop_waiting) {
3864 // Expect no stop waiting frame is sent.
3865 EXPECT_FALSE(least_unacked().IsInitialized());
3866 } else {
3867 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
3868 }
3869
3870 // Send two data packets at the end, and ensure if the last one is acked,
3871 // the least unacked is raised above the ack packets.
3872 SendStreamDataToPeer(1, "bar", 6, NO_FIN, nullptr); // Packet 6
3873 SendStreamDataToPeer(1, "bar", 9, NO_FIN, nullptr); // Packet 7
3874
3875 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3876 frame = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(5)},
3877 {QuicPacketNumber(7), QuicPacketNumber(8)}});
3878 ProcessAckPacket(&frame);
3879
3880 EXPECT_EQ(QuicPacketNumber(6u), stop_waiting()->least_unacked);
3881}
3882
3883TEST_P(QuicConnectionTest, TLP) {
fayang5d011982020-05-13 14:14:38 -07003884 if (connection_.PtoEnabled()) {
3885 return;
3886 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003887 connection_.SetMaxTailLossProbes(1);
3888
3889 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
3890 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
3891 QuicTime retransmission_time =
3892 connection_.GetRetransmissionAlarm()->deadline();
3893 EXPECT_NE(QuicTime::Zero(), retransmission_time);
3894
3895 EXPECT_EQ(QuicPacketNumber(1u), writer_->header().packet_number);
3896 // Simulate the retransmission alarm firing and sending a tlp,
3897 // so send algorithm's OnRetransmissionTimeout is not called.
3898 clock_.AdvanceTime(retransmission_time - clock_.Now());
fayang1c2d1ab2020-03-11 12:08:41 -07003899 const QuicPacketNumber retransmission(
3900 connection_.SupportsMultiplePacketNumberSpaces() ? 3 : 2);
3901 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, retransmission, _, _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003902 connection_.GetRetransmissionAlarm()->Fire();
fayang1c2d1ab2020-03-11 12:08:41 -07003903 EXPECT_EQ(retransmission, writer_->header().packet_number);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003904 // We do not raise the high water mark yet.
3905 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
3906}
3907
zhongyifbb25772019-04-10 16:54:08 -07003908TEST_P(QuicConnectionTest, TailLossProbeDelayForStreamDataInTLPR) {
fayangcff885a2019-10-22 07:39:04 -07003909 if (connection_.PtoEnabled()) {
zhongyi1b2f7832019-06-14 13:31:34 -07003910 return;
3911 }
3912
zhongyifbb25772019-04-10 16:54:08 -07003913 // Set TLPR from QuicConfig.
3914 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3915 QuicConfig config;
3916 QuicTagVector options;
3917 options.push_back(kTLPR);
3918 config.SetConnectionOptionsToSend(options);
3919 connection_.SetFromConfig(config);
3920 connection_.SetMaxTailLossProbes(1);
3921
3922 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
3923 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
3924
3925 QuicTime retransmission_time =
3926 connection_.GetRetransmissionAlarm()->deadline();
3927 EXPECT_NE(QuicTime::Zero(), retransmission_time);
3928 QuicTime::Delta expected_tlp_delay =
3929 0.5 * manager_->GetRttStats()->SmoothedOrInitialRtt();
3930 EXPECT_EQ(expected_tlp_delay, retransmission_time - clock_.Now());
3931
3932 EXPECT_EQ(QuicPacketNumber(1u), writer_->header().packet_number);
3933 // Simulate firing of the retransmission alarm and retransmit the packet.
3934 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
3935 clock_.AdvanceTime(retransmission_time - clock_.Now());
3936 connection_.GetRetransmissionAlarm()->Fire();
3937 EXPECT_EQ(QuicPacketNumber(2u), writer_->header().packet_number);
3938
3939 // We do not raise the high water mark yet.
3940 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
3941}
3942
3943TEST_P(QuicConnectionTest, TailLossProbeDelayForNonStreamDataInTLPR) {
fayangcff885a2019-10-22 07:39:04 -07003944 if (connection_.PtoEnabled()) {
zhongyi1b2f7832019-06-14 13:31:34 -07003945 return;
3946 }
3947
zhongyifbb25772019-04-10 16:54:08 -07003948 // Set TLPR from QuicConfig.
3949 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3950 QuicConfig config;
3951 QuicTagVector options;
3952 options.push_back(kTLPR);
3953 config.SetConnectionOptionsToSend(options);
dschinazif7c6a912020-05-05 11:39:53 -07003954 QuicConfigPeer::SetNegotiated(&config, true);
dschinazie7c38a52020-05-29 15:25:45 -07003955 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
3956 QuicConfigPeer::SetReceivedOriginalConnectionId(
3957 &config, connection_.connection_id());
3958 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
3959 &config, connection_.connection_id());
3960 }
zhongyifbb25772019-04-10 16:54:08 -07003961 connection_.SetFromConfig(config);
3962 connection_.SetMaxTailLossProbes(1);
3963
3964 // Sets retransmittable on wire.
3965 const QuicTime::Delta retransmittable_on_wire_timeout =
3966 QuicTime::Delta::FromMilliseconds(50);
zhongyi79ace162019-10-21 15:57:09 -07003967 connection_.set_initial_retransmittable_on_wire_timeout(
zhongyifbb25772019-04-10 16:54:08 -07003968 retransmittable_on_wire_timeout);
3969
3970 EXPECT_TRUE(connection_.connected());
3971 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
3972 .WillRepeatedly(Return(true));
fayangb59c6f12020-03-23 15:06:14 -07003973 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
zhongyifbb25772019-04-10 16:54:08 -07003974 EXPECT_FALSE(connection_.IsPathDegrading());
3975 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
3976
3977 const char data[] = "data";
3978 size_t data_size = strlen(data);
3979 QuicStreamOffset offset = 0;
3980
3981 // Send a data packet.
3982 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
3983 offset += data_size;
3984
3985 // Path degrading alarm should be set when there is a retransmittable packet
3986 // on the wire.
fayangb59c6f12020-03-23 15:06:14 -07003987 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
zhongyifbb25772019-04-10 16:54:08 -07003988
3989 // Verify the path degrading delay.
3990 // First TLP with stream data.
3991 QuicTime::Delta srtt = manager_->GetRttStats()->SmoothedOrInitialRtt();
3992 QuicTime::Delta expected_delay = 0.5 * srtt;
3993 // Add 1st RTO.
3994 QuicTime::Delta retransmission_delay =
3995 QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
3996 expected_delay = expected_delay + retransmission_delay;
3997 // Add 2nd RTO.
3998 expected_delay = expected_delay + retransmission_delay * 2;
3999 EXPECT_EQ(expected_delay,
4000 QuicConnectionPeer::GetSentPacketManager(&connection_)
4001 ->GetPathDegradingDelay());
4002 ASSERT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
4003
4004 // The ping alarm is set for the ping timeout, not the shorter
4005 // retransmittable_on_wire_timeout.
4006 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004007 EXPECT_EQ(connection_.ping_timeout(),
zhongyifbb25772019-04-10 16:54:08 -07004008 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
4009
4010 // Receive an ACK for the data packet.
4011 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4012 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4013 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4014 QuicAckFrame frame =
4015 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
4016 ProcessAckPacket(&frame);
4017
4018 // Path degrading alarm should be cancelled as there is no more
4019 // reretransmittable packets on the wire.
fayangb59c6f12020-03-23 15:06:14 -07004020 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
zhongyifbb25772019-04-10 16:54:08 -07004021 // The ping alarm should be set to the retransmittable_on_wire_timeout.
4022 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4023 EXPECT_EQ(retransmittable_on_wire_timeout,
4024 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
4025
4026 // Simulate firing of the retransmittable on wire and send a PING.
fayangec14d2b2020-10-02 12:00:05 -07004027 if (!GetQuicReloadableFlag(quic_let_connection_handle_pings)) {
4028 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
4029 SendPing();
4030 }));
4031 }
zhongyifbb25772019-04-10 16:54:08 -07004032 clock_.AdvanceTime(retransmittable_on_wire_timeout);
4033 connection_.GetPingAlarm()->Fire();
4034
4035 // The retransmission alarm and the path degrading alarm should be set as
4036 // there is a retransmittable packet (PING) on the wire,
4037 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
fayangb59c6f12020-03-23 15:06:14 -07004038 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
zhongyifbb25772019-04-10 16:54:08 -07004039
4040 // Verify the retransmission delay.
4041 QuicTime::Delta min_rto_timeout =
4042 QuicTime::Delta::FromMilliseconds(kMinRetransmissionTimeMs);
4043 srtt = manager_->GetRttStats()->SmoothedOrInitialRtt();
zhongyi9fa2be32019-09-10 12:39:01 -07004044
fayangec14d2b2020-10-02 12:00:05 -07004045 if (GetQuicReloadableFlag(quic_let_connection_handle_pings)) {
4046 // Arm RTO mode since there is only PING in flight.
4047 expected_delay = manager_->GetPtoDelay();
4048 } else {
4049 // First TLP without unacked stream data will no longer use TLPR.
4050 expected_delay = std::max(2 * srtt, 1.5 * srtt + 0.5 * min_rto_timeout);
4051 }
zhongyifbb25772019-04-10 16:54:08 -07004052 EXPECT_EQ(expected_delay,
4053 connection_.GetRetransmissionAlarm()->deadline() - clock_.Now());
4054
zhongyi1b2f7832019-06-14 13:31:34 -07004055 // Verify the path degrading delay = TLP delay + 1st RTO + 2nd RTO.
zhongyifbb25772019-04-10 16:54:08 -07004056 // Add 1st RTO.
fayangec14d2b2020-10-02 12:00:05 -07004057 if (GetQuicReloadableFlag(quic_let_connection_handle_pings)) {
4058 expected_delay = std::max(2 * srtt, 1.5 * srtt + 0.5 * min_rto_timeout);
4059 }
zhongyifbb25772019-04-10 16:54:08 -07004060 retransmission_delay =
4061 std::max(manager_->GetRttStats()->smoothed_rtt() +
4062 4 * manager_->GetRttStats()->mean_deviation(),
4063 min_rto_timeout);
4064 expected_delay = expected_delay + retransmission_delay;
4065 // Add 2nd RTO.
4066 expected_delay = expected_delay + retransmission_delay * 2;
4067 EXPECT_EQ(expected_delay,
4068 QuicConnectionPeer::GetSentPacketManager(&connection_)
4069 ->GetPathDegradingDelay());
4070
4071 // The ping alarm is set for the ping timeout, not the shorter
4072 // retransmittable_on_wire_timeout.
4073 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004074 EXPECT_EQ(connection_.ping_timeout(),
zhongyifbb25772019-04-10 16:54:08 -07004075 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
zhongyi1b2f7832019-06-14 13:31:34 -07004076
4077 // Advance a small period of time: 5ms. And receive a retransmitted ACK.
4078 // This will update the retransmission alarm, verify the retransmission delay
4079 // is correct.
4080 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4081 QuicAckFrame ack = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
4082 ProcessAckPacket(&ack);
4083
4084 // Verify the retransmission delay.
zhongyi9fa2be32019-09-10 12:39:01 -07004085 // First TLP without unacked stream data will no longer use TLPR.
fayangec14d2b2020-10-02 12:00:05 -07004086 if (GetQuicReloadableFlag(quic_let_connection_handle_pings)) {
4087 // Arm RTO mode since there is only PING in flight.
4088 expected_delay = manager_->GetPtoDelay();
4089 } else {
4090 expected_delay = std::max(2 * srtt, 1.5 * srtt + 0.5 * min_rto_timeout);
4091 }
zhongyi1b2f7832019-06-14 13:31:34 -07004092 expected_delay = expected_delay - QuicTime::Delta::FromMilliseconds(5);
4093 EXPECT_EQ(expected_delay,
4094 connection_.GetRetransmissionAlarm()->deadline() - clock_.Now());
zhongyifbb25772019-04-10 16:54:08 -07004095}
4096
QUICHE teama6ef0a62019-03-07 20:34:33 -05004097TEST_P(QuicConnectionTest, RTO) {
fayang5f135052019-08-22 17:59:40 -07004098 if (connection_.PtoEnabled()) {
4099 return;
4100 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004101 connection_.SetMaxTailLossProbes(0);
4102
4103 QuicTime default_retransmission_time =
4104 clock_.ApproximateNow() + DefaultRetransmissionTime();
4105 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
4106 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4107
4108 EXPECT_EQ(QuicPacketNumber(1u), writer_->header().packet_number);
4109 EXPECT_EQ(default_retransmission_time,
4110 connection_.GetRetransmissionAlarm()->deadline());
4111 // Simulate the retransmission alarm firing.
4112 clock_.AdvanceTime(DefaultRetransmissionTime());
4113 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
4114 connection_.GetRetransmissionAlarm()->Fire();
4115 EXPECT_EQ(QuicPacketNumber(2u), writer_->header().packet_number);
4116 // We do not raise the high water mark yet.
4117 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4118}
4119
fayanga29eb242019-07-16 12:25:38 -07004120// Regression test of b/133771183.
4121TEST_P(QuicConnectionTest, RtoWithNoDataToRetransmit) {
fayangcff885a2019-10-22 07:39:04 -07004122 if (connection_.PtoEnabled()) {
fayanga29eb242019-07-16 12:25:38 -07004123 return;
4124 }
4125 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4126 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4127 connection_.SetMaxTailLossProbes(0);
4128
4129 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
4130 // Connection is cwnd limited.
4131 CongestionBlockWrites();
4132 // Stream gets reset.
4133 SendRstStream(3, QUIC_ERROR_PROCESSING_STREAM, 3);
4134 // Simulate the retransmission alarm firing.
4135 clock_.AdvanceTime(DefaultRetransmissionTime());
4136 // RTO fires, but there is no packet to be RTOed.
fayange861aee2019-10-16 13:40:39 -07004137 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
fayanga29eb242019-07-16 12:25:38 -07004138 connection_.GetRetransmissionAlarm()->Fire();
fayange861aee2019-10-16 13:40:39 -07004139 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
fayanga29eb242019-07-16 12:25:38 -07004140
4141 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(40);
4142 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(20);
fayange861aee2019-10-16 13:40:39 -07004143 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(false));
4144 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(1);
fayanga29eb242019-07-16 12:25:38 -07004145 // Receives packets 1 - 40.
4146 for (size_t i = 1; i <= 40; ++i) {
4147 ProcessDataPacket(i);
4148 }
4149}
4150
QUICHE teama6ef0a62019-03-07 20:34:33 -05004151TEST_P(QuicConnectionTest, SendHandshakeMessages) {
4152 use_tagging_decrypter();
4153 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
4154 // the end of the packet. We can test this to check which encrypter was used.
QUICHE team6987b4a2019-03-15 16:23:04 -07004155 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07004156 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004157
4158 // Attempt to send a handshake message and have the socket block.
4159 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
4160 BlockOnNextWrite();
nharper46833c32019-05-15 21:33:05 -07004161 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004162 // The packet should be serialized, but not queued.
4163 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4164
4165 // Switch to the new encrypter.
4166 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004167 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004168 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4169
4170 // Now become writeable and flush the packets.
4171 writer_->SetWritable();
4172 EXPECT_CALL(visitor_, OnCanWrite());
4173 connection_.OnCanWrite();
4174 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4175
4176 // Verify that the handshake packet went out at the null encryption.
4177 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
4178}
4179
4180TEST_P(QuicConnectionTest,
4181 DropRetransmitsForNullEncryptedPacketAfterForwardSecure) {
4182 use_tagging_decrypter();
QUICHE team6987b4a2019-03-15 16:23:04 -07004183 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07004184 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004185 connection_.SendCryptoStreamData();
4186
4187 // Simulate the retransmission alarm firing and the socket blocking.
4188 BlockOnNextWrite();
4189 clock_.AdvanceTime(DefaultRetransmissionTime());
fayange62e63c2019-12-04 07:16:25 -08004190 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004191 connection_.GetRetransmissionAlarm()->Fire();
fayang2ce66082019-10-02 06:29:04 -07004192 EXPECT_EQ(1u, connection_.NumQueuedPackets());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004193
4194 // Go forward secure.
4195 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07004196 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004197 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4198 notifier_.NeuterUnencryptedData();
4199 connection_.NeuterUnencryptedPackets();
fayang2ce66082019-10-02 06:29:04 -07004200 connection_.OnHandshakeComplete();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004201
4202 EXPECT_EQ(QuicTime::Zero(), connection_.GetRetransmissionAlarm()->deadline());
4203 // Unblock the socket and ensure that no packets are sent.
4204 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4205 writer_->SetWritable();
4206 connection_.OnCanWrite();
4207}
4208
4209TEST_P(QuicConnectionTest, RetransmitPacketsWithInitialEncryption) {
4210 use_tagging_decrypter();
QUICHE team6987b4a2019-03-15 16:23:04 -07004211 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07004212 std::make_unique<TaggingEncrypter>(0x01));
QUICHE team6987b4a2019-03-15 16:23:04 -07004213 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004214
nharper46833c32019-05-15 21:33:05 -07004215 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004216
4217 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004218 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004219 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4220
4221 SendStreamDataToPeer(2, "bar", 0, NO_FIN, nullptr);
renjietang37d4ae12020-06-18 11:18:31 -07004222 EXPECT_FALSE(notifier_.HasLostStreamData());
renjietangf71e8062020-09-14 12:01:15 -07004223 connection_.MarkZeroRttPacketsForRetransmission(0);
renjietang37d4ae12020-06-18 11:18:31 -07004224 EXPECT_TRUE(notifier_.HasLostStreamData());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004225}
4226
4227TEST_P(QuicConnectionTest, BufferNonDecryptablePackets) {
QUICHE teamcd098022019-03-22 18:49:55 -07004228 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4229 return;
4230 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004231 // SetFromConfig is always called after construction from InitializeSession.
4232 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4233 QuicConfig config;
4234 connection_.SetFromConfig(config);
4235 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4236 use_tagging_decrypter();
4237
4238 const uint8_t tag = 0x07;
4239 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004240 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004241
4242 // Process an encrypted packet which can not yet be decrypted which should
4243 // result in the packet being buffered.
4244 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4245
4246 // Transition to the new encryption state and process another encrypted packet
4247 // which should result in the original packet being processed.
zhongyi546cc452019-04-12 15:27:49 -07004248 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004249 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004250 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004251 std::make_unique<TaggingEncrypter>(tag));
fayangd01e9962020-09-24 11:29:31 -07004252 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004253 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(2);
4254 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4255
4256 // Finally, process a third packet and note that we do not reprocess the
4257 // buffered packet.
4258 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4259 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4260}
4261
4262TEST_P(QuicConnectionTest, TestRetransmitOrder) {
fayang5f135052019-08-22 17:59:40 -07004263 if (connection_.PtoEnabled()) {
4264 return;
4265 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004266 connection_.SetMaxTailLossProbes(0);
4267
4268 QuicByteCount first_packet_size;
4269 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4270 .WillOnce(SaveArg<3>(&first_packet_size));
4271
4272 connection_.SendStreamDataWithString(3, "first_packet", 0, NO_FIN);
4273 QuicByteCount second_packet_size;
4274 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4275 .WillOnce(SaveArg<3>(&second_packet_size));
4276 connection_.SendStreamDataWithString(3, "second_packet", 12, NO_FIN);
4277 EXPECT_NE(first_packet_size, second_packet_size);
4278 // Advance the clock by huge time to make sure packets will be retransmitted.
4279 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
4280 {
4281 InSequence s;
4282 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, first_packet_size, _));
4283 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, second_packet_size, _));
4284 }
4285 connection_.GetRetransmissionAlarm()->Fire();
4286
4287 // Advance again and expect the packets to be sent again in the same order.
4288 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(20));
4289 {
4290 InSequence s;
4291 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, first_packet_size, _));
4292 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, second_packet_size, _));
4293 }
4294 connection_.GetRetransmissionAlarm()->Fire();
4295}
4296
4297TEST_P(QuicConnectionTest, Buffer100NonDecryptablePacketsThenKeyChange) {
QUICHE teamcd098022019-03-22 18:49:55 -07004298 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4299 return;
4300 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004301 // SetFromConfig is always called after construction from InitializeSession.
4302 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4303 QuicConfig config;
4304 config.set_max_undecryptable_packets(100);
4305 connection_.SetFromConfig(config);
4306 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4307 use_tagging_decrypter();
4308
4309 const uint8_t tag = 0x07;
4310 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004311 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004312
4313 // Process an encrypted packet which can not yet be decrypted which should
4314 // result in the packet being buffered.
4315 for (uint64_t i = 1; i <= 100; ++i) {
4316 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4317 }
4318
4319 // Transition to the new encryption state and process another encrypted packet
4320 // which should result in the original packets being processed.
4321 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
zhongyi546cc452019-04-12 15:27:49 -07004322 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004323 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004324 EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004325 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004326 std::make_unique<TaggingEncrypter>(tag));
fayangd01e9962020-09-24 11:29:31 -07004327 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004328
4329 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(100);
4330 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
4331
4332 // Finally, process a third packet and note that we do not reprocess the
4333 // buffered packet.
4334 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4335 ProcessDataPacketAtLevel(102, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4336}
4337
4338TEST_P(QuicConnectionTest, SetRTOAfterWritingToSocket) {
4339 BlockOnNextWrite();
fayange62e63c2019-12-04 07:16:25 -08004340 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004341 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
fayange62e63c2019-12-04 07:16:25 -08004342 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004343
4344 // Test that RTO is started once we write to the socket.
4345 writer_->SetWritable();
fayange62e63c2019-12-04 07:16:25 -08004346 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004347 connection_.OnCanWrite();
4348 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4349}
4350
4351TEST_P(QuicConnectionTest, DelayRTOWithAckReceipt) {
fayang5f135052019-08-22 17:59:40 -07004352 if (connection_.PtoEnabled()) {
4353 return;
4354 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004355 connection_.SetMaxTailLossProbes(0);
4356
4357 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4358 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
4359 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
4360 connection_.SendStreamDataWithString(3, "bar", 0, NO_FIN);
4361 QuicAlarm* retransmission_alarm = connection_.GetRetransmissionAlarm();
4362 EXPECT_TRUE(retransmission_alarm->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004363 EXPECT_EQ(DefaultRetransmissionTime(),
4364 retransmission_alarm->deadline() - clock_.Now());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004365
4366 // Advance the time right before the RTO, then receive an ack for the first
4367 // packet to delay the RTO.
4368 clock_.AdvanceTime(DefaultRetransmissionTime());
4369 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4370 QuicAckFrame ack = InitAckFrame(1);
4371 ProcessAckPacket(&ack);
4372 // Now we have an RTT sample of DefaultRetransmissionTime(500ms),
4373 // so the RTO has increased to 2 * SRTT.
4374 EXPECT_TRUE(retransmission_alarm->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004375 EXPECT_EQ(retransmission_alarm->deadline() - clock_.Now(),
4376 2 * DefaultRetransmissionTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004377
4378 // Move forward past the original RTO and ensure the RTO is still pending.
4379 clock_.AdvanceTime(2 * DefaultRetransmissionTime());
4380
4381 // Ensure the second packet gets retransmitted when it finally fires.
4382 EXPECT_TRUE(retransmission_alarm->IsSet());
4383 EXPECT_EQ(retransmission_alarm->deadline(), clock_.ApproximateNow());
4384 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4385 // Manually cancel the alarm to simulate a real test.
4386 connection_.GetRetransmissionAlarm()->Fire();
4387
4388 // The new retransmitted packet number should set the RTO to a larger value
4389 // than previously.
4390 EXPECT_TRUE(retransmission_alarm->IsSet());
4391 QuicTime next_rto_time = retransmission_alarm->deadline();
4392 QuicTime expected_rto_time =
4393 connection_.sent_packet_manager().GetRetransmissionTime();
4394 EXPECT_EQ(next_rto_time, expected_rto_time);
4395}
4396
4397TEST_P(QuicConnectionTest, TestQueued) {
4398 connection_.SetMaxTailLossProbes(0);
4399
4400 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4401 BlockOnNextWrite();
4402 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4403 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4404
4405 // Unblock the writes and actually send.
4406 writer_->SetWritable();
4407 connection_.OnCanWrite();
4408 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4409}
4410
4411TEST_P(QuicConnectionTest, InitialTimeout) {
4412 EXPECT_TRUE(connection_.connected());
4413 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4414 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4415
4416 // SetFromConfig sets the initial timeouts before negotiation.
4417 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4418 QuicConfig config;
4419 connection_.SetFromConfig(config);
4420 // Subtract a second from the idle timeout on the client side.
4421 QuicTime default_timeout =
4422 clock_.ApproximateNow() +
4423 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4424 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
4425
fkastenholz5d880a92019-06-21 09:01:56 -07004426 EXPECT_CALL(visitor_,
4427 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004428 // Simulate the timeout alarm firing.
4429 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1));
4430 connection_.GetTimeoutAlarm()->Fire();
4431
4432 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4433 EXPECT_FALSE(connection_.connected());
4434
fayang9adfb532020-06-04 06:58:45 -07004435 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004436 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4437 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4438 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4439 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
renjietang11e4a3d2019-05-03 11:27:26 -07004440 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07004441 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004442}
4443
4444TEST_P(QuicConnectionTest, IdleTimeoutAfterFirstSentPacket) {
4445 EXPECT_TRUE(connection_.connected());
4446 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4447 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4448
4449 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4450 QuicConfig config;
4451 connection_.SetFromConfig(config);
4452 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4453 QuicTime initial_ddl =
4454 clock_.ApproximateNow() +
4455 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4456 EXPECT_EQ(initial_ddl, connection_.GetTimeoutAlarm()->deadline());
4457 EXPECT_TRUE(connection_.connected());
4458
4459 // Advance the time and send the first packet to the peer.
fayangb9c88442020-03-26 07:03:57 -07004460 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004461 QuicPacketNumber last_packet;
4462 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4463 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4464 // This will be the updated deadline for the connection to idle time out.
4465 QuicTime new_ddl = clock_.ApproximateNow() +
4466 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4467
4468 // Simulate the timeout alarm firing, the connection should not be closed as
4469 // a new packet has been sent.
fkastenholz5d880a92019-06-21 09:01:56 -07004470 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004471 QuicTime::Delta delay = initial_ddl - clock_.ApproximateNow();
4472 clock_.AdvanceTime(delay);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004473 // Verify the timeout alarm deadline is updated.
4474 EXPECT_TRUE(connection_.connected());
4475 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4476 EXPECT_EQ(new_ddl, connection_.GetTimeoutAlarm()->deadline());
4477
4478 // Simulate the timeout alarm firing again, the connection now should be
4479 // closed.
fkastenholz5d880a92019-06-21 09:01:56 -07004480 EXPECT_CALL(visitor_,
4481 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004482 clock_.AdvanceTime(new_ddl - clock_.ApproximateNow());
4483 connection_.GetTimeoutAlarm()->Fire();
4484 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4485 EXPECT_FALSE(connection_.connected());
4486
fayang9adfb532020-06-04 06:58:45 -07004487 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004488 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4489 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4490 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4491 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07004492 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004493}
4494
4495TEST_P(QuicConnectionTest, IdleTimeoutAfterSendTwoPackets) {
4496 EXPECT_TRUE(connection_.connected());
4497 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4498 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4499
4500 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4501 QuicConfig config;
4502 connection_.SetFromConfig(config);
4503 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4504 QuicTime initial_ddl =
4505 clock_.ApproximateNow() +
4506 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4507 EXPECT_EQ(initial_ddl, connection_.GetTimeoutAlarm()->deadline());
4508 EXPECT_TRUE(connection_.connected());
4509
4510 // Immediately send the first packet, this is a rare case but test code will
4511 // hit this issue often as MockClock used for tests doesn't move with code
4512 // execution until manually adjusted.
4513 QuicPacketNumber last_packet;
4514 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4515 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4516
4517 // Advance the time and send the second packet to the peer.
4518 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
4519 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4520 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
4521
zhongyic1cab062019-06-19 12:02:24 -07004522 // Simulate the timeout alarm firing, the connection will be closed.
fkastenholz5d880a92019-06-21 09:01:56 -07004523 EXPECT_CALL(visitor_,
4524 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
zhongyic1cab062019-06-19 12:02:24 -07004525 clock_.AdvanceTime(initial_ddl - clock_.ApproximateNow());
4526 connection_.GetTimeoutAlarm()->Fire();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004527
4528 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4529 EXPECT_FALSE(connection_.connected());
4530
fayang9adfb532020-06-04 06:58:45 -07004531 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004532 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4533 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4534 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4535 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07004536 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004537}
4538
4539TEST_P(QuicConnectionTest, HandshakeTimeout) {
4540 // Use a shorter handshake timeout than idle timeout for this test.
4541 const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(5);
4542 connection_.SetNetworkTimeouts(timeout, timeout);
4543 EXPECT_TRUE(connection_.connected());
4544 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4545
4546 QuicTime handshake_timeout =
4547 clock_.ApproximateNow() + timeout - QuicTime::Delta::FromSeconds(1);
4548 EXPECT_EQ(handshake_timeout, connection_.GetTimeoutAlarm()->deadline());
4549 EXPECT_TRUE(connection_.connected());
4550
4551 // Send and ack new data 3 seconds later to lengthen the idle timeout.
4552 SendStreamDataToPeer(
dschinazi552accc2019-06-17 17:07:34 -07004553 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
4554 "GET /", 0, FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004555 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(3));
4556 QuicAckFrame frame = InitAckFrame(1);
4557 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4558 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4559 ProcessAckPacket(&frame);
4560
QUICHE teama6ef0a62019-03-07 20:34:33 -05004561 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4562 EXPECT_TRUE(connection_.connected());
4563
4564 clock_.AdvanceTime(timeout - QuicTime::Delta::FromSeconds(2));
4565
fkastenholz5d880a92019-06-21 09:01:56 -07004566 EXPECT_CALL(visitor_,
4567 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004568 // Simulate the timeout alarm firing.
4569 connection_.GetTimeoutAlarm()->Fire();
4570
4571 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4572 EXPECT_FALSE(connection_.connected());
4573
fayang9adfb532020-06-04 06:58:45 -07004574 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004575 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4576 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4577 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07004578 TestConnectionCloseQuicErrorCode(QUIC_HANDSHAKE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004579}
4580
4581TEST_P(QuicConnectionTest, PingAfterSend) {
QUICHE teamcd098022019-03-22 18:49:55 -07004582 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4583 return;
4584 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004585 EXPECT_TRUE(connection_.connected());
4586 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4587 .WillRepeatedly(Return(true));
4588 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4589
4590 // Advance to 5ms, and send a packet to the peer, which will set
4591 // the ping alarm.
4592 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4593 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4594 SendStreamDataToPeer(
dschinazi552accc2019-06-17 17:07:34 -07004595 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
4596 "GET /", 0, FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004597 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004598 EXPECT_EQ(QuicTime::Delta::FromSeconds(15),
4599 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004600
4601 // Now recevie an ACK of the previous packet, which will move the
4602 // ping alarm forward.
4603 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4604 QuicAckFrame frame = InitAckFrame(1);
4605 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4606 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4607 ProcessAckPacket(&frame);
4608 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4609 // The ping timer is set slightly less than 15 seconds in the future, because
4610 // of the 1s ping timer alarm granularity.
zhongyieef848f2019-10-18 07:09:37 -07004611 EXPECT_EQ(
4612 QuicTime::Delta::FromSeconds(15) - QuicTime::Delta::FromMilliseconds(5),
4613 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004614
4615 writer_->Reset();
4616 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15));
fayangec14d2b2020-10-02 12:00:05 -07004617 if (!GetQuicReloadableFlag(quic_let_connection_handle_pings)) {
4618 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
4619 SendPing();
4620 }));
4621 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004622 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07004623 size_t padding_frame_count = writer_->padding_frames().size();
4624 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004625 ASSERT_EQ(1u, writer_->ping_frames().size());
4626 writer_->Reset();
4627
4628 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4629 .WillRepeatedly(Return(false));
4630 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4631 SendAckPacketToPeer();
4632
4633 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4634}
4635
4636TEST_P(QuicConnectionTest, ReducedPingTimeout) {
QUICHE teamcd098022019-03-22 18:49:55 -07004637 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4638 return;
4639 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004640 EXPECT_TRUE(connection_.connected());
4641 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4642 .WillRepeatedly(Return(true));
4643 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4644
4645 // Use a reduced ping timeout for this connection.
4646 connection_.set_ping_timeout(QuicTime::Delta::FromSeconds(10));
4647
4648 // Advance to 5ms, and send a packet to the peer, which will set
4649 // the ping alarm.
4650 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4651 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4652 SendStreamDataToPeer(
dschinazi552accc2019-06-17 17:07:34 -07004653 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
4654 "GET /", 0, FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004655 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004656 EXPECT_EQ(QuicTime::Delta::FromSeconds(10),
4657 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004658
4659 // Now recevie an ACK of the previous packet, which will move the
4660 // ping alarm forward.
4661 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4662 QuicAckFrame frame = InitAckFrame(1);
4663 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4664 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4665 ProcessAckPacket(&frame);
4666 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4667 // The ping timer is set slightly less than 10 seconds in the future, because
4668 // of the 1s ping timer alarm granularity.
zhongyieef848f2019-10-18 07:09:37 -07004669 EXPECT_EQ(
4670 QuicTime::Delta::FromSeconds(10) - QuicTime::Delta::FromMilliseconds(5),
4671 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004672
4673 writer_->Reset();
4674 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
fayangec14d2b2020-10-02 12:00:05 -07004675 if (!GetQuicReloadableFlag(quic_let_connection_handle_pings)) {
4676 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
4677 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
4678 }));
4679 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004680 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07004681 size_t padding_frame_count = writer_->padding_frames().size();
4682 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004683 ASSERT_EQ(1u, writer_->ping_frames().size());
4684 writer_->Reset();
4685
4686 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4687 .WillRepeatedly(Return(false));
4688 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4689 SendAckPacketToPeer();
4690
4691 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4692}
4693
4694// Tests whether sending an MTU discovery packet to peer successfully causes the
4695// maximum packet size to increase.
4696TEST_P(QuicConnectionTest, SendMtuDiscoveryPacket) {
wub031d47c2019-11-21 08:04:07 -08004697 MtuDiscoveryTestInit();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004698
4699 // Send an MTU probe.
4700 const size_t new_mtu = kDefaultMaxPacketSize + 100;
4701 QuicByteCount mtu_probe_size;
4702 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4703 .WillOnce(SaveArg<3>(&mtu_probe_size));
4704 connection_.SendMtuDiscoveryPacket(new_mtu);
4705 EXPECT_EQ(new_mtu, mtu_probe_size);
4706 EXPECT_EQ(QuicPacketNumber(1u), creator_->packet_number());
4707
4708 // Send more than MTU worth of data. No acknowledgement was received so far,
4709 // so the MTU should be at its old value.
vasilvvc48c8712019-03-11 13:38:16 -07004710 const std::string data(kDefaultMaxPacketSize + 1, '.');
QUICHE teama6ef0a62019-03-07 20:34:33 -05004711 QuicByteCount size_before_mtu_change;
4712 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4713 .Times(2)
4714 .WillOnce(SaveArg<3>(&size_before_mtu_change))
4715 .WillOnce(Return());
4716 connection_.SendStreamDataWithString(3, data, 0, FIN);
4717 EXPECT_EQ(QuicPacketNumber(3u), creator_->packet_number());
4718 EXPECT_EQ(kDefaultMaxPacketSize, size_before_mtu_change);
4719
4720 // Acknowledge all packets so far.
4721 QuicAckFrame probe_ack = InitAckFrame(3);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004722 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4723 ProcessAckPacket(&probe_ack);
4724 EXPECT_EQ(new_mtu, connection_.max_packet_length());
4725
4726 // Send the same data again. Check that it fits into a single packet now.
4727 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4728 connection_.SendStreamDataWithString(3, data, 0, FIN);
4729 EXPECT_EQ(QuicPacketNumber(4u), creator_->packet_number());
4730}
4731
wubb442b862020-01-31 08:16:21 -08004732// Verifies that when a MTU probe packet is sent and buffered in a batch writer,
4733// the writer is flushed immediately.
4734TEST_P(QuicConnectionTest, BatchWriterFlushedAfterMtuDiscoveryPacket) {
4735 writer_->SetBatchMode(true);
4736 MtuDiscoveryTestInit();
4737
4738 // Send an MTU probe.
4739 const size_t target_mtu = kDefaultMaxPacketSize + 100;
4740 QuicByteCount mtu_probe_size;
4741 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4742 .WillOnce(SaveArg<3>(&mtu_probe_size));
4743 const uint32_t prior_flush_attempts = writer_->flush_attempts();
4744 connection_.SendMtuDiscoveryPacket(target_mtu);
4745 EXPECT_EQ(target_mtu, mtu_probe_size);
wub18f47342020-03-16 15:56:03 -07004746 EXPECT_EQ(writer_->flush_attempts(), prior_flush_attempts + 1);
wubb442b862020-01-31 08:16:21 -08004747}
4748
QUICHE teama6ef0a62019-03-07 20:34:33 -05004749// Tests whether MTU discovery does not happen when it is not explicitly enabled
4750// by the connection options.
4751TEST_P(QuicConnectionTest, MtuDiscoveryDisabled) {
wub031d47c2019-11-21 08:04:07 -08004752 MtuDiscoveryTestInit();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004753
4754 const QuicPacketCount packets_between_probes_base = 10;
4755 set_packets_between_probes_base(packets_between_probes_base);
4756
4757 const QuicPacketCount number_of_packets = packets_between_probes_base * 2;
4758 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
4759 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
4760 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4761 EXPECT_EQ(0u, connection_.mtu_probe_count());
4762 }
4763}
4764
wubf76cf2a2019-10-11 18:49:07 -07004765// Tests whether MTU discovery works when all probes are acknowledged on the
QUICHE teama6ef0a62019-03-07 20:34:33 -05004766// first try.
4767TEST_P(QuicConnectionTest, MtuDiscoveryEnabled) {
wub031d47c2019-11-21 08:04:07 -08004768 MtuDiscoveryTestInit();
nharperc6b99512019-09-19 11:13:48 -07004769
QUICHE teama6ef0a62019-03-07 20:34:33 -05004770 const QuicPacketCount packets_between_probes_base = 5;
4771 set_packets_between_probes_base(packets_between_probes_base);
4772
wubf76cf2a2019-10-11 18:49:07 -07004773 connection_.EnablePathMtuDiscovery(send_algorithm_);
4774
QUICHE teama6ef0a62019-03-07 20:34:33 -05004775 // Send enough packets so that the next one triggers path MTU discovery.
4776 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
4777 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
4778 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4779 }
4780
4781 // Trigger the probe.
4782 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
4783 nullptr);
4784 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4785 QuicByteCount probe_size;
4786 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4787 .WillOnce(SaveArg<3>(&probe_size));
4788 connection_.GetMtuDiscoveryAlarm()->Fire();
wub173916e2019-11-27 14:36:24 -08004789
4790 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(),
4791 kMtuDiscoveryTargetPacketSizeHigh));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004792
4793 const QuicPacketNumber probe_packet_number =
4794 FirstSendingPacketNumber() + packets_between_probes_base;
4795 ASSERT_EQ(probe_packet_number, creator_->packet_number());
4796
4797 // Acknowledge all packets sent so far.
4798 QuicAckFrame probe_ack = InitAckFrame(probe_packet_number);
wubf76cf2a2019-10-11 18:49:07 -07004799 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
4800 .Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004801 ProcessAckPacket(&probe_ack);
wubf76cf2a2019-10-11 18:49:07 -07004802 EXPECT_EQ(probe_size, connection_.max_packet_length());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004803 EXPECT_EQ(0u, connection_.GetBytesInFlight());
4804
wubf76cf2a2019-10-11 18:49:07 -07004805 EXPECT_EQ(1u, connection_.mtu_probe_count());
4806
wubf76cf2a2019-10-11 18:49:07 -07004807 QuicStreamOffset stream_offset = packets_between_probes_base;
wubecb643f2020-03-19 08:58:46 -07004808 QuicByteCount last_probe_size = 0;
wubf76cf2a2019-10-11 18:49:07 -07004809 for (size_t num_probes = 1; num_probes < kMtuDiscoveryAttempts;
4810 ++num_probes) {
4811 // Send just enough packets without triggering the next probe.
4812 for (QuicPacketCount i = 0;
4813 i < (packets_between_probes_base << num_probes) - 1; ++i) {
4814 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
4815 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4816 }
4817
4818 // Trigger the next probe.
4819 SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
4820 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4821 QuicByteCount new_probe_size;
4822 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4823 .WillOnce(SaveArg<3>(&new_probe_size));
4824 connection_.GetMtuDiscoveryAlarm()->Fire();
4825 EXPECT_THAT(new_probe_size,
4826 InRange(probe_size, kMtuDiscoveryTargetPacketSizeHigh));
4827 EXPECT_EQ(num_probes + 1, connection_.mtu_probe_count());
4828
4829 // Acknowledge all packets sent so far.
4830 QuicAckFrame probe_ack = InitAckFrame(creator_->packet_number());
4831 ProcessAckPacket(&probe_ack);
4832 EXPECT_EQ(new_probe_size, connection_.max_packet_length());
4833 EXPECT_EQ(0u, connection_.GetBytesInFlight());
4834
wubecb643f2020-03-19 08:58:46 -07004835 last_probe_size = probe_size;
wubf76cf2a2019-10-11 18:49:07 -07004836 probe_size = new_probe_size;
4837 }
4838
4839 // The last probe size should be equal to the target.
4840 EXPECT_EQ(probe_size, kMtuDiscoveryTargetPacketSizeHigh);
wubecb643f2020-03-19 08:58:46 -07004841
wubae6581a2020-05-04 12:13:05 -07004842 writer_->SetShouldWriteFail();
wubecb643f2020-03-19 08:58:46 -07004843
wubae6581a2020-05-04 12:13:05 -07004844 // Ignore PACKET_WRITE_ERROR once.
4845 SendStreamDataToPeer(3, "(", stream_offset++, NO_FIN, nullptr);
4846 EXPECT_EQ(last_probe_size, connection_.max_packet_length());
4847 EXPECT_TRUE(connection_.connected());
wubecb643f2020-03-19 08:58:46 -07004848
wubae6581a2020-05-04 12:13:05 -07004849 // Close connection on another PACKET_WRITE_ERROR.
4850 EXPECT_CALL(visitor_, OnConnectionClosed(_, _))
4851 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
4852 SendStreamDataToPeer(3, ")", stream_offset++, NO_FIN, nullptr);
4853 EXPECT_EQ(last_probe_size, connection_.max_packet_length());
4854 EXPECT_FALSE(connection_.connected());
4855 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
4856 IsError(QUIC_PACKET_WRITE_ERROR));
wubf76cf2a2019-10-11 18:49:07 -07004857}
4858
wub748e20b2020-03-20 14:33:59 -07004859// After a successful MTU probe, one and only one write error should be ignored
4860// if it happened in QuicConnection::FlushPacket.
4861TEST_P(QuicConnectionTest,
4862 MtuDiscoveryIgnoreOneWriteErrorInFlushAfterSuccessfulProbes) {
4863 MtuDiscoveryTestInit();
4864 writer_->SetBatchMode(true);
4865
4866 const QuicPacketCount packets_between_probes_base = 5;
4867 set_packets_between_probes_base(packets_between_probes_base);
4868
4869 connection_.EnablePathMtuDiscovery(send_algorithm_);
4870
4871 const QuicByteCount original_max_packet_length =
4872 connection_.max_packet_length();
4873 // Send enough packets so that the next one triggers path MTU discovery.
4874 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
4875 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
4876 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4877 }
4878
4879 // Trigger the probe.
4880 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
4881 nullptr);
4882 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4883 QuicByteCount probe_size;
4884 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4885 .WillOnce(SaveArg<3>(&probe_size));
4886 connection_.GetMtuDiscoveryAlarm()->Fire();
4887
4888 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(),
4889 kMtuDiscoveryTargetPacketSizeHigh));
4890
4891 const QuicPacketNumber probe_packet_number =
4892 FirstSendingPacketNumber() + packets_between_probes_base;
4893 ASSERT_EQ(probe_packet_number, creator_->packet_number());
4894
4895 // Acknowledge all packets sent so far.
4896 QuicAckFrame probe_ack = InitAckFrame(probe_packet_number);
4897 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
4898 .Times(AnyNumber());
4899 ProcessAckPacket(&probe_ack);
4900 EXPECT_EQ(probe_size, connection_.max_packet_length());
4901 EXPECT_EQ(0u, connection_.GetBytesInFlight());
4902
4903 EXPECT_EQ(1u, connection_.mtu_probe_count());
4904
wubae6581a2020-05-04 12:13:05 -07004905 writer_->SetShouldWriteFail();
wub748e20b2020-03-20 14:33:59 -07004906
wubae6581a2020-05-04 12:13:05 -07004907 // Ignore PACKET_WRITE_ERROR once.
4908 {
4909 QuicConnection::ScopedPacketFlusher flusher(&connection_);
4910 // flusher's destructor will call connection_.FlushPackets, which should
4911 // get a WRITE_STATUS_ERROR from the writer and ignore it.
wub748e20b2020-03-20 14:33:59 -07004912 }
wubae6581a2020-05-04 12:13:05 -07004913 EXPECT_EQ(original_max_packet_length, connection_.max_packet_length());
4914 EXPECT_TRUE(connection_.connected());
4915
4916 // Close connection on another PACKET_WRITE_ERROR.
4917 EXPECT_CALL(visitor_, OnConnectionClosed(_, _))
4918 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
4919 {
4920 QuicConnection::ScopedPacketFlusher flusher(&connection_);
4921 // flusher's destructor will call connection_.FlushPackets, which should
4922 // get a WRITE_STATUS_ERROR from the writer and ignore it.
4923 }
4924 EXPECT_EQ(original_max_packet_length, connection_.max_packet_length());
4925 EXPECT_FALSE(connection_.connected());
4926 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
4927 IsError(QUIC_PACKET_WRITE_ERROR));
wub748e20b2020-03-20 14:33:59 -07004928}
4929
wubf76cf2a2019-10-11 18:49:07 -07004930// Simulate the case where the first attempt to send a probe is write blocked,
4931// and after unblock, the second attempt returns a MSG_TOO_BIG error.
4932TEST_P(QuicConnectionTest, MtuDiscoveryWriteBlocked) {
wub031d47c2019-11-21 08:04:07 -08004933 MtuDiscoveryTestInit();
wubf76cf2a2019-10-11 18:49:07 -07004934
4935 const QuicPacketCount packets_between_probes_base = 5;
4936 set_packets_between_probes_base(packets_between_probes_base);
4937
4938 connection_.EnablePathMtuDiscovery(send_algorithm_);
4939
4940 // Send enough packets so that the next one triggers path MTU discovery.
4941 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
4942 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004943 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4944 }
4945
wubf76cf2a2019-10-11 18:49:07 -07004946 QuicByteCount original_max_packet_length = connection_.max_packet_length();
4947
4948 // Trigger the probe.
4949 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
4950 nullptr);
4951 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
fayange62e63c2019-12-04 07:16:25 -08004952 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
wubf76cf2a2019-10-11 18:49:07 -07004953 BlockOnNextWrite();
4954 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4955 connection_.GetMtuDiscoveryAlarm()->Fire();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004956 EXPECT_EQ(1u, connection_.mtu_probe_count());
wubf76cf2a2019-10-11 18:49:07 -07004957 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4958 ASSERT_TRUE(connection_.connected());
4959
4960 writer_->SetWritable();
4961 SimulateNextPacketTooLarge();
4962 connection_.OnCanWrite();
4963 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4964 EXPECT_EQ(original_max_packet_length, connection_.max_packet_length());
4965 EXPECT_TRUE(connection_.connected());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004966}
4967
4968// Tests whether MTU discovery works correctly when the probes never get
4969// acknowledged.
4970TEST_P(QuicConnectionTest, MtuDiscoveryFailed) {
wub031d47c2019-11-21 08:04:07 -08004971 MtuDiscoveryTestInit();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004972
QUICHE teama6ef0a62019-03-07 20:34:33 -05004973 // Lower the number of probes between packets in order to make the test go
4974 // much faster.
4975 const QuicPacketCount packets_between_probes_base = 5;
4976 set_packets_between_probes_base(packets_between_probes_base);
4977
wubf76cf2a2019-10-11 18:49:07 -07004978 connection_.EnablePathMtuDiscovery(send_algorithm_);
4979
4980 const QuicTime::Delta rtt = QuicTime::Delta::FromMilliseconds(100);
4981
4982 EXPECT_EQ(packets_between_probes_base,
4983 QuicConnectionPeer::GetPacketsBetweenMtuProbes(&connection_));
4984
QUICHE teama6ef0a62019-03-07 20:34:33 -05004985 // This tests sends more packets than strictly necessary to make sure that if
4986 // the connection was to send more discovery packets than needed, those would
4987 // get caught as well.
4988 const QuicPacketCount number_of_packets =
4989 packets_between_probes_base * (1 << (kMtuDiscoveryAttempts + 1));
4990 std::vector<QuicPacketNumber> mtu_discovery_packets;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004991 // Called on many acks.
4992 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
4993 .Times(AnyNumber());
4994 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
4995 SendStreamDataToPeer(3, "!", i, NO_FIN, nullptr);
4996 clock_.AdvanceTime(rtt);
4997
4998 // Receive an ACK, which marks all data packets as received, and all MTU
4999 // discovery packets as missing.
5000
5001 QuicAckFrame ack;
5002
5003 if (!mtu_discovery_packets.empty()) {
5004 QuicPacketNumber min_packet = *min_element(mtu_discovery_packets.begin(),
5005 mtu_discovery_packets.end());
5006 QuicPacketNumber max_packet = *max_element(mtu_discovery_packets.begin(),
5007 mtu_discovery_packets.end());
5008 ack.packets.AddRange(QuicPacketNumber(1), min_packet);
5009 ack.packets.AddRange(QuicPacketNumber(max_packet + 1),
5010 creator_->packet_number() + 1);
5011 ack.largest_acked = creator_->packet_number();
5012
5013 } else {
5014 ack.packets.AddRange(QuicPacketNumber(1), creator_->packet_number() + 1);
5015 ack.largest_acked = creator_->packet_number();
5016 }
5017
5018 ProcessAckPacket(&ack);
5019
5020 // Trigger MTU probe if it would be scheduled now.
5021 if (!connection_.GetMtuDiscoveryAlarm()->IsSet()) {
5022 continue;
5023 }
5024
5025 // Fire the alarm. The alarm should cause a packet to be sent.
5026 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5027 connection_.GetMtuDiscoveryAlarm()->Fire();
5028 // Record the packet number of the MTU discovery packet in order to
5029 // mark it as NACK'd.
5030 mtu_discovery_packets.push_back(creator_->packet_number());
5031 }
5032
5033 // Ensure the number of packets between probes grows exponentially by checking
5034 // it against the closed-form expression for the packet number.
5035 ASSERT_EQ(kMtuDiscoveryAttempts, mtu_discovery_packets.size());
5036 for (uint64_t i = 0; i < kMtuDiscoveryAttempts; i++) {
5037 // 2^0 + 2^1 + 2^2 + ... + 2^n = 2^(n + 1) - 1
5038 const QuicPacketCount packets_between_probes =
5039 packets_between_probes_base * ((1 << (i + 1)) - 1);
5040 EXPECT_EQ(QuicPacketNumber(packets_between_probes + (i + 1)),
5041 mtu_discovery_packets[i]);
5042 }
5043
5044 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5045 EXPECT_EQ(kDefaultMaxPacketSize, connection_.max_packet_length());
5046 EXPECT_EQ(kMtuDiscoveryAttempts, connection_.mtu_probe_count());
5047}
5048
wubf76cf2a2019-10-11 18:49:07 -07005049// Probe 3 times, the first one succeeds, then fails, then succeeds again.
5050TEST_P(QuicConnectionTest, MtuDiscoverySecondProbeFailed) {
wub031d47c2019-11-21 08:04:07 -08005051 MtuDiscoveryTestInit();
wubf76cf2a2019-10-11 18:49:07 -07005052
5053 const QuicPacketCount packets_between_probes_base = 5;
5054 set_packets_between_probes_base(packets_between_probes_base);
5055
5056 connection_.EnablePathMtuDiscovery(send_algorithm_);
5057
5058 // Send enough packets so that the next one triggers path MTU discovery.
5059 QuicStreamOffset stream_offset = 0;
5060 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5061 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5062 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5063 }
5064
5065 // Trigger the probe.
5066 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5067 nullptr);
5068 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5069 QuicByteCount probe_size;
5070 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5071 .WillOnce(SaveArg<3>(&probe_size));
5072 connection_.GetMtuDiscoveryAlarm()->Fire();
5073 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(),
5074 kMtuDiscoveryTargetPacketSizeHigh));
5075
5076 const QuicPacketNumber probe_packet_number =
5077 FirstSendingPacketNumber() + packets_between_probes_base;
5078 ASSERT_EQ(probe_packet_number, creator_->packet_number());
5079
5080 // Acknowledge all packets sent so far.
5081 QuicAckFrame first_ack = InitAckFrame(probe_packet_number);
wubf76cf2a2019-10-11 18:49:07 -07005082 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5083 .Times(AnyNumber());
5084 ProcessAckPacket(&first_ack);
5085 EXPECT_EQ(probe_size, connection_.max_packet_length());
5086 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5087
5088 EXPECT_EQ(1u, connection_.mtu_probe_count());
5089
5090 // Send just enough packets without triggering the second probe.
5091 for (QuicPacketCount i = 0; i < (packets_between_probes_base << 1) - 1; ++i) {
5092 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5093 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5094 }
5095
5096 // Trigger the second probe.
5097 SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
5098 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5099 QuicByteCount second_probe_size;
5100 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5101 .WillOnce(SaveArg<3>(&second_probe_size));
5102 connection_.GetMtuDiscoveryAlarm()->Fire();
5103 EXPECT_THAT(second_probe_size,
5104 InRange(probe_size, kMtuDiscoveryTargetPacketSizeHigh));
5105 EXPECT_EQ(2u, connection_.mtu_probe_count());
5106
5107 // Acknowledge all packets sent so far, except the second probe.
5108 QuicPacketNumber second_probe_packet_number = creator_->packet_number();
5109 QuicAckFrame second_ack = InitAckFrame(second_probe_packet_number - 1);
5110 ProcessAckPacket(&first_ack);
5111 EXPECT_EQ(probe_size, connection_.max_packet_length());
5112
5113 // Send just enough packets without triggering the third probe.
5114 for (QuicPacketCount i = 0; i < (packets_between_probes_base << 2) - 1; ++i) {
5115 SendStreamDataToPeer(3, "@", stream_offset++, NO_FIN, nullptr);
5116 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5117 }
5118
5119 // Trigger the third probe.
5120 SendStreamDataToPeer(3, "#", stream_offset++, NO_FIN, nullptr);
5121 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5122 QuicByteCount third_probe_size;
5123 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5124 .WillOnce(SaveArg<3>(&third_probe_size));
5125 connection_.GetMtuDiscoveryAlarm()->Fire();
5126 EXPECT_THAT(third_probe_size, InRange(probe_size, second_probe_size));
5127 EXPECT_EQ(3u, connection_.mtu_probe_count());
5128
5129 // Acknowledge all packets sent so far, except the second probe.
5130 QuicAckFrame third_ack =
5131 ConstructAckFrame(creator_->packet_number(), second_probe_packet_number);
5132 ProcessAckPacket(&third_ack);
5133 EXPECT_EQ(third_probe_size, connection_.max_packet_length());
wub8add68a2020-07-27 12:07:38 -07005134
5135 SendStreamDataToPeer(3, "$", stream_offset++, NO_FIN, nullptr);
wub8add68a2020-07-27 12:07:38 -07005136 EXPECT_TRUE(connection_.PathMtuReductionDetectionInProgress());
5137
5138 if (connection_.PathDegradingDetectionInProgress() &&
5139 QuicConnectionPeer::GetPathDegradingDeadline(&connection_) <
5140 QuicConnectionPeer::GetPathMtuReductionDetectionDeadline(
5141 &connection_)) {
5142 // Fire path degrading alarm first.
5143 connection_.PathDegradingTimeout();
5144 }
5145
5146 // Verify the max packet size has not reduced.
5147 EXPECT_EQ(third_probe_size, connection_.max_packet_length());
5148
5149 // Fire alarm to get path mtu reduction callback called.
5150 EXPECT_TRUE(connection_.PathMtuReductionDetectionInProgress());
5151 connection_.GetBlackholeDetectorAlarm()->Fire();
5152
5153 // Verify the max packet size has reduced to the previous value.
5154 EXPECT_EQ(probe_size, connection_.max_packet_length());
wubf76cf2a2019-10-11 18:49:07 -07005155}
5156
QUICHE teama6ef0a62019-03-07 20:34:33 -05005157// Tests whether MTU discovery works when the writer has a limit on how large a
5158// packet can be.
5159TEST_P(QuicConnectionTest, MtuDiscoveryWriterLimited) {
wub031d47c2019-11-21 08:04:07 -08005160 MtuDiscoveryTestInit();
nharperc6b99512019-09-19 11:13:48 -07005161
QUICHE teama6ef0a62019-03-07 20:34:33 -05005162 const QuicByteCount mtu_limit = kMtuDiscoveryTargetPacketSizeHigh - 1;
5163 writer_->set_max_packet_size(mtu_limit);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005164
5165 const QuicPacketCount packets_between_probes_base = 5;
5166 set_packets_between_probes_base(packets_between_probes_base);
5167
wubf76cf2a2019-10-11 18:49:07 -07005168 connection_.EnablePathMtuDiscovery(send_algorithm_);
5169
QUICHE teama6ef0a62019-03-07 20:34:33 -05005170 // Send enough packets so that the next one triggers path MTU discovery.
5171 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5172 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5173 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5174 }
5175
5176 // Trigger the probe.
5177 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5178 nullptr);
5179 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5180 QuicByteCount probe_size;
5181 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5182 .WillOnce(SaveArg<3>(&probe_size));
5183 connection_.GetMtuDiscoveryAlarm()->Fire();
wub173916e2019-11-27 14:36:24 -08005184
5185 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(), mtu_limit));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005186
5187 const QuicPacketNumber probe_sequence_number =
5188 FirstSendingPacketNumber() + packets_between_probes_base;
5189 ASSERT_EQ(probe_sequence_number, creator_->packet_number());
5190
5191 // Acknowledge all packets sent so far.
5192 QuicAckFrame probe_ack = InitAckFrame(probe_sequence_number);
wubf76cf2a2019-10-11 18:49:07 -07005193 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5194 .Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005195 ProcessAckPacket(&probe_ack);
wubf76cf2a2019-10-11 18:49:07 -07005196 EXPECT_EQ(probe_size, connection_.max_packet_length());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005197 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5198
wubf76cf2a2019-10-11 18:49:07 -07005199 EXPECT_EQ(1u, connection_.mtu_probe_count());
5200
wubf76cf2a2019-10-11 18:49:07 -07005201 QuicStreamOffset stream_offset = packets_between_probes_base;
5202 for (size_t num_probes = 1; num_probes < kMtuDiscoveryAttempts;
5203 ++num_probes) {
5204 // Send just enough packets without triggering the next probe.
5205 for (QuicPacketCount i = 0;
5206 i < (packets_between_probes_base << num_probes) - 1; ++i) {
5207 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5208 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5209 }
5210
5211 // Trigger the next probe.
5212 SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
5213 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5214 QuicByteCount new_probe_size;
5215 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5216 .WillOnce(SaveArg<3>(&new_probe_size));
5217 connection_.GetMtuDiscoveryAlarm()->Fire();
5218 EXPECT_THAT(new_probe_size, InRange(probe_size, mtu_limit));
5219 EXPECT_EQ(num_probes + 1, connection_.mtu_probe_count());
5220
5221 // Acknowledge all packets sent so far.
5222 QuicAckFrame probe_ack = InitAckFrame(creator_->packet_number());
5223 ProcessAckPacket(&probe_ack);
5224 EXPECT_EQ(new_probe_size, connection_.max_packet_length());
5225 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5226
5227 probe_size = new_probe_size;
5228 }
5229
5230 // The last probe size should be equal to the target.
5231 EXPECT_EQ(probe_size, mtu_limit);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005232}
5233
5234// Tests whether MTU discovery works when the writer returns an error despite
5235// advertising higher packet length.
5236TEST_P(QuicConnectionTest, MtuDiscoveryWriterFailed) {
wub031d47c2019-11-21 08:04:07 -08005237 MtuDiscoveryTestInit();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005238
5239 const QuicByteCount mtu_limit = kMtuDiscoveryTargetPacketSizeHigh - 1;
5240 const QuicByteCount initial_mtu = connection_.max_packet_length();
5241 EXPECT_LT(initial_mtu, mtu_limit);
5242 writer_->set_max_packet_size(mtu_limit);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005243
5244 const QuicPacketCount packets_between_probes_base = 5;
5245 set_packets_between_probes_base(packets_between_probes_base);
5246
wubf76cf2a2019-10-11 18:49:07 -07005247 connection_.EnablePathMtuDiscovery(send_algorithm_);
5248
QUICHE teama6ef0a62019-03-07 20:34:33 -05005249 // Send enough packets so that the next one triggers path MTU discovery.
5250 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5251 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5252 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5253 }
5254
5255 // Trigger the probe.
5256 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5257 nullptr);
5258 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5259 writer_->SimulateNextPacketTooLarge();
5260 connection_.GetMtuDiscoveryAlarm()->Fire();
5261 ASSERT_TRUE(connection_.connected());
5262
5263 // Send more data.
5264 QuicPacketNumber probe_number = creator_->packet_number();
5265 QuicPacketCount extra_packets = packets_between_probes_base * 3;
5266 for (QuicPacketCount i = 0; i < extra_packets; i++) {
5267 connection_.EnsureWritableAndSendStreamData5();
5268 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5269 }
5270
5271 // Acknowledge all packets sent so far, except for the lost probe.
5272 QuicAckFrame probe_ack =
5273 ConstructAckFrame(creator_->packet_number(), probe_number);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005274 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5275 ProcessAckPacket(&probe_ack);
5276 EXPECT_EQ(initial_mtu, connection_.max_packet_length());
5277
5278 // Send more packets, and ensure that none of them sets the alarm.
5279 for (QuicPacketCount i = 0; i < 4 * packets_between_probes_base; i++) {
5280 connection_.EnsureWritableAndSendStreamData5();
5281 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5282 }
5283
5284 EXPECT_EQ(initial_mtu, connection_.max_packet_length());
5285 EXPECT_EQ(1u, connection_.mtu_probe_count());
5286}
5287
5288TEST_P(QuicConnectionTest, NoMtuDiscoveryAfterConnectionClosed) {
wub031d47c2019-11-21 08:04:07 -08005289 MtuDiscoveryTestInit();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005290
QUICHE teama6ef0a62019-03-07 20:34:33 -05005291 const QuicPacketCount packets_between_probes_base = 10;
5292 set_packets_between_probes_base(packets_between_probes_base);
5293
wubf76cf2a2019-10-11 18:49:07 -07005294 connection_.EnablePathMtuDiscovery(send_algorithm_);
5295
QUICHE teama6ef0a62019-03-07 20:34:33 -05005296 // Send enough packets so that the next one triggers path MTU discovery.
5297 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5298 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5299 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5300 }
5301
5302 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5303 nullptr);
5304 EXPECT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5305
fkastenholz5d880a92019-06-21 09:01:56 -07005306 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005307 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
5308 ConnectionCloseBehavior::SILENT_CLOSE);
5309 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5310}
5311
dschinazi9a6194e2020-04-30 16:21:09 -07005312TEST_P(QuicConnectionTest, TimeoutAfterSendDuringHandshake) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005313 EXPECT_TRUE(connection_.connected());
5314 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5315 QuicConfig config;
5316 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005317
5318 const QuicTime::Delta initial_idle_timeout =
5319 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5320 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5321 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
5322
5323 // When we send a packet, the timeout will change to 5ms +
5324 // kInitialIdleTimeoutSecs.
5325 clock_.AdvanceTime(five_ms);
5326 SendStreamDataToPeer(
5327 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5328 0, FIN, nullptr);
fayang3a58dc42020-06-29 11:27:14 -07005329 EXPECT_EQ(default_timeout + five_ms,
5330 connection_.GetTimeoutAlarm()->deadline());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005331
5332 // Now send more data. This will not move the timeout because
5333 // no data has been received since the previous write.
5334 clock_.AdvanceTime(five_ms);
5335 SendStreamDataToPeer(
5336 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5337 3, FIN, nullptr);
fayang3a58dc42020-06-29 11:27:14 -07005338 EXPECT_EQ(default_timeout + five_ms,
5339 connection_.GetTimeoutAlarm()->deadline());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005340
5341 // The original alarm will fire. We should not time out because we had a
5342 // network event at t=5ms. The alarm will reregister.
5343 clock_.AdvanceTime(initial_idle_timeout - five_ms - five_ms);
5344 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005345 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5346 EXPECT_TRUE(connection_.connected());
5347 EXPECT_EQ(default_timeout + five_ms,
5348 connection_.GetTimeoutAlarm()->deadline());
5349
5350 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07005351 EXPECT_CALL(visitor_,
5352 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07005353 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005354 clock_.AdvanceTime(five_ms);
5355 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5356 connection_.GetTimeoutAlarm()->Fire();
5357 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5358 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005359 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005360}
5361
5362TEST_P(QuicConnectionTest, TimeoutAfterRetransmission) {
fayang5f135052019-08-22 17:59:40 -07005363 if (connection_.PtoEnabled()) {
5364 return;
5365 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005366 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5367 EXPECT_TRUE(connection_.connected());
5368 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5369 QuicConfig config;
5370 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005371
5372 const QuicTime start_time = clock_.Now();
5373 const QuicTime::Delta initial_idle_timeout =
5374 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5375 QuicTime default_timeout = clock_.Now() + initial_idle_timeout;
5376
5377 connection_.SetMaxTailLossProbes(0);
5378 const QuicTime default_retransmission_time =
5379 start_time + DefaultRetransmissionTime();
5380
5381 ASSERT_LT(default_retransmission_time, default_timeout);
5382
5383 // When we send a packet, the timeout will change to 5 ms +
5384 // kInitialIdleTimeoutSecs (but it will not reschedule the alarm).
5385 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5386 const QuicTime send_time = start_time + five_ms;
5387 clock_.AdvanceTime(five_ms);
5388 ASSERT_EQ(send_time, clock_.Now());
5389 SendStreamDataToPeer(
5390 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5391 0, FIN, nullptr);
fayang3a58dc42020-06-29 11:27:14 -07005392 EXPECT_EQ(default_timeout + five_ms,
5393 connection_.GetTimeoutAlarm()->deadline());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005394
5395 // Move forward 5 ms and receive a packet, which will move the timeout
5396 // forward 5 ms more (but will not reschedule the alarm).
5397 const QuicTime receive_time = send_time + five_ms;
5398 clock_.AdvanceTime(receive_time - clock_.Now());
5399 ASSERT_EQ(receive_time, clock_.Now());
5400 ProcessPacket(1);
5401
5402 // Now move forward to the retransmission time and retransmit the
5403 // packet, which should move the timeout forward again (but will not
5404 // reschedule the alarm).
5405 EXPECT_EQ(default_retransmission_time + five_ms,
5406 connection_.GetRetransmissionAlarm()->deadline());
5407 // Simulate the retransmission alarm firing.
5408 const QuicTime rto_time = send_time + DefaultRetransmissionTime();
5409 const QuicTime final_timeout = rto_time + initial_idle_timeout;
5410 clock_.AdvanceTime(rto_time - clock_.Now());
5411 ASSERT_EQ(rto_time, clock_.Now());
5412 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _));
5413 connection_.GetRetransmissionAlarm()->Fire();
5414
5415 // Advance to the original timeout and fire the alarm. The connection should
5416 // timeout, and the alarm should be registered based on the time of the
5417 // retransmission.
5418 clock_.AdvanceTime(default_timeout - clock_.Now());
5419 ASSERT_EQ(default_timeout.ToDebuggingValue(),
5420 clock_.Now().ToDebuggingValue());
5421 EXPECT_EQ(default_timeout, clock_.Now());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005422 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5423 EXPECT_TRUE(connection_.connected());
5424 ASSERT_EQ(final_timeout.ToDebuggingValue(),
5425 connection_.GetTimeoutAlarm()->deadline().ToDebuggingValue());
5426
5427 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07005428 EXPECT_CALL(visitor_,
5429 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07005430 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005431 clock_.AdvanceTime(final_timeout - clock_.Now());
5432 EXPECT_EQ(connection_.GetTimeoutAlarm()->deadline(), clock_.Now());
5433 EXPECT_EQ(final_timeout, clock_.Now());
5434 connection_.GetTimeoutAlarm()->Fire();
5435 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5436 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005437 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005438}
5439
dschinazi9a6194e2020-04-30 16:21:09 -07005440TEST_P(QuicConnectionTest, TimeoutAfterSendAfterHandshake) {
5441 // When the idle timeout fires, verify that by default we do not send any
5442 // connection close packets.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005443 EXPECT_TRUE(connection_.connected());
5444 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5445 QuicConfig config;
5446
5447 // Create a handshake message that also enables silent close.
5448 CryptoHandshakeMessage msg;
vasilvvc48c8712019-03-11 13:38:16 -07005449 std::string error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005450 QuicConfig client_config;
5451 client_config.SetInitialStreamFlowControlWindowToSend(
5452 kInitialStreamFlowControlWindowForTest);
5453 client_config.SetInitialSessionFlowControlWindowToSend(
5454 kInitialSessionFlowControlWindowForTest);
5455 client_config.SetIdleNetworkTimeout(
dschinazi027366e2020-05-01 14:31:19 -07005456 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs));
fkastenholzd3a1de92019-05-15 07:00:07 -07005457 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005458 const QuicErrorCode error =
5459 config.ProcessPeerHello(msg, CLIENT, &error_details);
bncf54082a2019-11-27 10:19:47 -08005460 EXPECT_THAT(error, IsQuicNoError());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005461
dschinazie7c38a52020-05-29 15:25:45 -07005462 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
5463 QuicConfigPeer::SetReceivedOriginalConnectionId(
5464 &config, connection_.connection_id());
5465 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
5466 &config, connection_.connection_id());
5467 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005468 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005469
5470 const QuicTime::Delta default_idle_timeout =
dschinazi027366e2020-05-01 14:31:19 -07005471 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs - 1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005472 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5473 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5474
5475 // When we send a packet, the timeout will change to 5ms +
5476 // kInitialIdleTimeoutSecs.
5477 clock_.AdvanceTime(five_ms);
5478 SendStreamDataToPeer(
5479 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5480 0, FIN, nullptr);
fayang3a58dc42020-06-29 11:27:14 -07005481 EXPECT_EQ(default_timeout + five_ms,
5482 connection_.GetTimeoutAlarm()->deadline());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005483
5484 // Now send more data. This will not move the timeout because
5485 // no data has been received since the previous write.
5486 clock_.AdvanceTime(five_ms);
5487 SendStreamDataToPeer(
5488 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5489 3, FIN, nullptr);
fayang3a58dc42020-06-29 11:27:14 -07005490 EXPECT_EQ(default_timeout + five_ms,
5491 connection_.GetTimeoutAlarm()->deadline());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005492
5493 // The original alarm will fire. We should not time out because we had a
5494 // network event at t=5ms. The alarm will reregister.
5495 clock_.AdvanceTime(default_idle_timeout - five_ms - five_ms);
5496 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005497 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5498 EXPECT_TRUE(connection_.connected());
5499 EXPECT_EQ(default_timeout + five_ms,
5500 connection_.GetTimeoutAlarm()->deadline());
5501
5502 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07005503 // This results in a SILENT_CLOSE, so the writer will not be invoked
5504 // and will not save the frame. Grab the frame from OnConnectionClosed
5505 // directly.
5506 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
5507 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
5508
QUICHE teama6ef0a62019-03-07 20:34:33 -05005509 clock_.AdvanceTime(five_ms);
5510 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5511 connection_.GetTimeoutAlarm()->Fire();
5512 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5513 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005514 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08005515 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
5516 IsError(QUIC_NETWORK_IDLE_TIMEOUT));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005517}
5518
5519TEST_P(QuicConnectionTest, TimeoutAfterSendSilentCloseAndTLP) {
fayang5f135052019-08-22 17:59:40 -07005520 if (connection_.PtoEnabled()) {
5521 return;
5522 }
dschinazi9a6194e2020-04-30 16:21:09 -07005523 // Same test as above, but sending TLPs causes a connection close to be sent.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005524 EXPECT_TRUE(connection_.connected());
5525 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5526 QuicConfig config;
5527
5528 // Create a handshake message that also enables silent close.
5529 CryptoHandshakeMessage msg;
vasilvvc48c8712019-03-11 13:38:16 -07005530 std::string error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005531 QuicConfig client_config;
5532 client_config.SetInitialStreamFlowControlWindowToSend(
5533 kInitialStreamFlowControlWindowForTest);
5534 client_config.SetInitialSessionFlowControlWindowToSend(
5535 kInitialSessionFlowControlWindowForTest);
5536 client_config.SetIdleNetworkTimeout(
dschinazi027366e2020-05-01 14:31:19 -07005537 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs));
fkastenholzd3a1de92019-05-15 07:00:07 -07005538 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005539 const QuicErrorCode error =
5540 config.ProcessPeerHello(msg, CLIENT, &error_details);
bncf54082a2019-11-27 10:19:47 -08005541 EXPECT_THAT(error, IsQuicNoError());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005542
5543 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005544
5545 const QuicTime::Delta default_idle_timeout =
dschinazi027366e2020-05-01 14:31:19 -07005546 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs - 1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005547 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5548 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5549
5550 // When we send a packet, the timeout will change to 5ms +
5551 // kInitialIdleTimeoutSecs.
5552 clock_.AdvanceTime(five_ms);
5553 SendStreamDataToPeer(
5554 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5555 0, FIN, nullptr);
fayang3a58dc42020-06-29 11:27:14 -07005556 EXPECT_EQ(default_timeout + five_ms,
5557 connection_.GetTimeoutAlarm()->deadline());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005558
5559 // Retransmit the packet via tail loss probe.
5560 clock_.AdvanceTime(connection_.GetRetransmissionAlarm()->deadline() -
5561 clock_.Now());
5562 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _));
5563 connection_.GetRetransmissionAlarm()->Fire();
5564
5565 // This time, we should time out and send a connection close due to the TLP.
fkastenholz5d880a92019-06-21 09:01:56 -07005566 EXPECT_CALL(visitor_,
5567 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07005568 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005569 clock_.AdvanceTime(connection_.GetTimeoutAlarm()->deadline() -
5570 clock_.ApproximateNow() + five_ms);
5571 connection_.GetTimeoutAlarm()->Fire();
5572 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5573 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005574 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005575}
5576
5577TEST_P(QuicConnectionTest, TimeoutAfterSendSilentCloseWithOpenStreams) {
dschinazi9a6194e2020-04-30 16:21:09 -07005578 // Same test as above, but having open streams causes a connection close
5579 // to be sent.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005580 EXPECT_TRUE(connection_.connected());
5581 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5582 QuicConfig config;
5583
5584 // Create a handshake message that also enables silent close.
5585 CryptoHandshakeMessage msg;
vasilvvc48c8712019-03-11 13:38:16 -07005586 std::string error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005587 QuicConfig client_config;
5588 client_config.SetInitialStreamFlowControlWindowToSend(
5589 kInitialStreamFlowControlWindowForTest);
5590 client_config.SetInitialSessionFlowControlWindowToSend(
5591 kInitialSessionFlowControlWindowForTest);
5592 client_config.SetIdleNetworkTimeout(
dschinazi027366e2020-05-01 14:31:19 -07005593 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs));
fkastenholzd3a1de92019-05-15 07:00:07 -07005594 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005595 const QuicErrorCode error =
5596 config.ProcessPeerHello(msg, CLIENT, &error_details);
bncf54082a2019-11-27 10:19:47 -08005597 EXPECT_THAT(error, IsQuicNoError());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005598
dschinazie7c38a52020-05-29 15:25:45 -07005599 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
5600 QuicConfigPeer::SetReceivedOriginalConnectionId(
5601 &config, connection_.connection_id());
5602 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
5603 &config, connection_.connection_id());
5604 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005605 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005606
5607 const QuicTime::Delta default_idle_timeout =
dschinazi027366e2020-05-01 14:31:19 -07005608 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs - 1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005609 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5610 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5611
5612 // When we send a packet, the timeout will change to 5ms +
5613 // kInitialIdleTimeoutSecs.
5614 clock_.AdvanceTime(five_ms);
5615 SendStreamDataToPeer(
5616 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5617 0, FIN, nullptr);
fayang3a58dc42020-06-29 11:27:14 -07005618 EXPECT_EQ(default_timeout + five_ms,
5619 connection_.GetTimeoutAlarm()->deadline());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005620
5621 // Indicate streams are still open.
5622 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
5623 .WillRepeatedly(Return(true));
fayanga330b7c2020-09-10 08:15:39 -07005624 if (GetQuicReloadableFlag(quic_add_stream_info_to_idle_close_detail)) {
5625 EXPECT_CALL(visitor_, GetStreamsInfoForLogging()).WillOnce(Return(""));
5626 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005627
5628 // This time, we should time out and send a connection close due to the TLP.
fkastenholz5d880a92019-06-21 09:01:56 -07005629 EXPECT_CALL(visitor_,
5630 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07005631 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005632 clock_.AdvanceTime(connection_.GetTimeoutAlarm()->deadline() -
5633 clock_.ApproximateNow() + five_ms);
5634 connection_.GetTimeoutAlarm()->Fire();
5635 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5636 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005637 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005638}
5639
5640TEST_P(QuicConnectionTest, TimeoutAfterReceive) {
5641 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5642 EXPECT_TRUE(connection_.connected());
5643 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5644 QuicConfig config;
5645 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005646
5647 const QuicTime::Delta initial_idle_timeout =
5648 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5649 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5650 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
5651
5652 connection_.SendStreamDataWithString(
5653 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5654 0, NO_FIN);
5655 connection_.SendStreamDataWithString(
5656 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5657 3, NO_FIN);
5658
5659 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5660 clock_.AdvanceTime(five_ms);
5661
5662 // When we receive a packet, the timeout will change to 5ms +
5663 // kInitialIdleTimeoutSecs.
5664 QuicAckFrame ack = InitAckFrame(2);
5665 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5666 ProcessAckPacket(&ack);
5667
5668 // The original alarm will fire. We should not time out because we had a
5669 // network event at t=5ms. The alarm will reregister.
5670 clock_.AdvanceTime(initial_idle_timeout - five_ms);
5671 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005672 EXPECT_TRUE(connection_.connected());
5673 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5674 EXPECT_EQ(default_timeout + five_ms,
5675 connection_.GetTimeoutAlarm()->deadline());
5676
5677 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07005678 EXPECT_CALL(visitor_,
5679 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07005680 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005681 clock_.AdvanceTime(five_ms);
5682 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5683 connection_.GetTimeoutAlarm()->Fire();
5684 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5685 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005686 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005687}
5688
5689TEST_P(QuicConnectionTest, TimeoutAfterReceiveNotSendWhenUnacked) {
5690 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5691 EXPECT_TRUE(connection_.connected());
5692 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5693 QuicConfig config;
5694 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005695
5696 const QuicTime::Delta initial_idle_timeout =
5697 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5698 connection_.SetNetworkTimeouts(
5699 QuicTime::Delta::Infinite(),
5700 initial_idle_timeout + QuicTime::Delta::FromSeconds(1));
5701 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5702 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
5703
5704 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5705 connection_.SendStreamDataWithString(
5706 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5707 0, NO_FIN);
5708 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5709 connection_.SendStreamDataWithString(
5710 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5711 3, NO_FIN);
5712
5713 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5714
5715 clock_.AdvanceTime(five_ms);
5716
5717 // When we receive a packet, the timeout will change to 5ms +
5718 // kInitialIdleTimeoutSecs.
5719 QuicAckFrame ack = InitAckFrame(2);
5720 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5721 ProcessAckPacket(&ack);
5722
5723 // The original alarm will fire. We should not time out because we had a
5724 // network event at t=5ms. The alarm will reregister.
5725 clock_.AdvanceTime(initial_idle_timeout - five_ms);
5726 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005727 EXPECT_TRUE(connection_.connected());
5728 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5729 EXPECT_EQ(default_timeout + five_ms,
5730 connection_.GetTimeoutAlarm()->deadline());
5731
5732 // Now, send packets while advancing the time and verify that the connection
5733 // eventually times out.
fkastenholz5d880a92019-06-21 09:01:56 -07005734 EXPECT_CALL(visitor_,
5735 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005736 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
5737 for (int i = 0; i < 100 && connection_.connected(); ++i) {
5738 QUIC_LOG(INFO) << "sending data packet";
5739 connection_.SendStreamDataWithString(
5740 GetNthClientInitiatedStreamId(1, connection_.transport_version()),
5741 "foo", 0, NO_FIN);
5742 connection_.GetTimeoutAlarm()->Fire();
5743 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
5744 }
5745 EXPECT_FALSE(connection_.connected());
5746 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07005747 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005748}
5749
5750TEST_P(QuicConnectionTest, TimeoutAfter5ClientRTOs) {
fayang5f135052019-08-22 17:59:40 -07005751 if (connection_.PtoEnabled()) {
5752 return;
5753 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005754 connection_.SetMaxTailLossProbes(2);
5755 EXPECT_TRUE(connection_.connected());
5756 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5757 QuicConfig config;
5758 QuicTagVector connection_options;
5759 connection_options.push_back(k5RTO);
5760 config.SetConnectionOptionsToSend(connection_options);
dschinazif7c6a912020-05-05 11:39:53 -07005761 QuicConfigPeer::SetNegotiated(&config, true);
fayang656cbb52020-06-09 13:29:35 -07005762 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangf78b6932020-06-08 08:36:45 -07005763 EXPECT_CALL(visitor_, GetHandshakeState())
5764 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
5765 }
dschinazie7c38a52020-05-29 15:25:45 -07005766 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
5767 QuicConfigPeer::SetReceivedOriginalConnectionId(
5768 &config, connection_.connection_id());
5769 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
5770 &config, connection_.connection_id());
5771 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005772 connection_.SetFromConfig(config);
5773
5774 // Send stream data.
5775 SendStreamDataToPeer(
5776 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5777 0, FIN, nullptr);
5778
5779 // Fire the retransmission alarm 6 times, twice for TLP and 4 times for RTO.
5780 for (int i = 0; i < 6; ++i) {
5781 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5782 connection_.GetRetransmissionAlarm()->Fire();
5783 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5784 EXPECT_TRUE(connection_.connected());
5785 }
fayang2205d952020-05-12 13:45:56 -07005786 EXPECT_CALL(visitor_, OnPathDegrading());
5787 connection_.PathDegradingTimeout();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005788
5789 EXPECT_EQ(2u, connection_.sent_packet_manager().GetConsecutiveTlpCount());
5790 EXPECT_EQ(4u, connection_.sent_packet_manager().GetConsecutiveRtoCount());
5791 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07005792 EXPECT_CALL(visitor_,
5793 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07005794 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
fayang2205d952020-05-12 13:45:56 -07005795 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
5796 connection_.GetBlackholeDetectorAlarm()->Fire();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005797 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5798 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005799 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005800}
5801
5802TEST_P(QuicConnectionTest, SendScheduler) {
5803 // Test that if we send a packet without delay, it is not queued.
5804 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
QUICHE team8c1daa22019-03-13 08:33:41 -07005805 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07005806 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005807 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
5808 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
QUICHE team6987b4a2019-03-15 16:23:04 -07005809 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05005810 HAS_RETRANSMITTABLE_DATA, false, false);
5811 EXPECT_EQ(0u, connection_.NumQueuedPackets());
5812}
5813
5814TEST_P(QuicConnectionTest, FailToSendFirstPacket) {
5815 // Test that the connection does not crash when it fails to send the first
5816 // packet at which point self_address_ might be uninitialized.
5817 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
fkastenholz5d880a92019-06-21 09:01:56 -07005818 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
QUICHE team8c1daa22019-03-13 08:33:41 -07005819 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07005820 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005821 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
5822 writer_->SetShouldWriteFail();
QUICHE team6987b4a2019-03-15 16:23:04 -07005823 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05005824 HAS_RETRANSMITTABLE_DATA, false, false);
5825}
5826
5827TEST_P(QuicConnectionTest, SendSchedulerEAGAIN) {
5828 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
QUICHE team8c1daa22019-03-13 08:33:41 -07005829 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07005830 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005831 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
5832 BlockOnNextWrite();
5833 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _))
5834 .Times(0);
QUICHE team6987b4a2019-03-15 16:23:04 -07005835 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05005836 HAS_RETRANSMITTABLE_DATA, false, false);
5837 EXPECT_EQ(1u, connection_.NumQueuedPackets());
5838}
5839
5840TEST_P(QuicConnectionTest, TestQueueLimitsOnSendStreamData) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005841 // Queue the first packet.
ianswett3085da82019-04-04 07:24:24 -07005842 size_t payload_length = connection_.max_packet_length();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005843 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(testing::Return(false));
vasilvvc48c8712019-03-11 13:38:16 -07005844 const std::string payload(payload_length, 'a');
ianswett3085da82019-04-04 07:24:24 -07005845 QuicStreamId first_bidi_stream_id(QuicUtils::GetFirstBidirectionalStreamId(
5846 connection_.version().transport_version, Perspective::IS_CLIENT));
5847 EXPECT_EQ(0u, connection_
5848 .SendStreamDataWithString(first_bidi_stream_id, payload, 0,
5849 NO_FIN)
QUICHE teama6ef0a62019-03-07 20:34:33 -05005850 .bytes_consumed);
5851 EXPECT_EQ(0u, connection_.NumQueuedPackets());
5852}
5853
ianswett3085da82019-04-04 07:24:24 -07005854TEST_P(QuicConnectionTest, SendingThreePackets) {
ianswett3085da82019-04-04 07:24:24 -07005855 // Make the payload twice the size of the packet, so 3 packets are written.
5856 size_t total_payload_length = 2 * connection_.max_packet_length();
vasilvvc48c8712019-03-11 13:38:16 -07005857 const std::string payload(total_payload_length, 'a');
ianswett3085da82019-04-04 07:24:24 -07005858 QuicStreamId first_bidi_stream_id(QuicUtils::GetFirstBidirectionalStreamId(
5859 connection_.version().transport_version, Perspective::IS_CLIENT));
5860 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
5861 EXPECT_EQ(payload.size(), connection_
5862 .SendStreamDataWithString(first_bidi_stream_id,
5863 payload, 0, NO_FIN)
5864 .bytes_consumed);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005865}
5866
5867TEST_P(QuicConnectionTest, LoopThroughSendingPacketsWithTruncation) {
5868 set_perspective(Perspective::IS_SERVER);
fayangd4291e42019-05-30 10:31:21 -07005869 if (!VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005870 // For IETF QUIC, encryption level will be switched to FORWARD_SECURE in
5871 // SendStreamDataWithString.
5872 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
5873 }
5874 // Set up a larger payload than will fit in one packet.
vasilvvc48c8712019-03-11 13:38:16 -07005875 const std::string payload(connection_.max_packet_length(), 'a');
QUICHE teama6ef0a62019-03-07 20:34:33 -05005876 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
5877
5878 // Now send some packets with no truncation.
5879 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
5880 EXPECT_EQ(payload.size(),
5881 connection_.SendStreamDataWithString(3, payload, 0, NO_FIN)
5882 .bytes_consumed);
5883 // Track the size of the second packet here. The overhead will be the largest
5884 // we see in this test, due to the non-truncated connection id.
5885 size_t non_truncated_packet_size = writer_->last_packet_size();
5886
5887 // Change to a 0 byte connection id.
5888 QuicConfig config;
5889 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
5890 connection_.SetFromConfig(config);
5891 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
5892 EXPECT_EQ(payload.size(),
5893 connection_.SendStreamDataWithString(3, payload, 1350, NO_FIN)
5894 .bytes_consumed);
fayangd4291e42019-05-30 10:31:21 -07005895 if (VersionHasIetfInvariantHeader(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005896 // Short header packets sent from server omit connection ID already, and
5897 // stream offset size increases from 0 to 2.
5898 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() - 2);
5899 } else {
5900 // Just like above, we save 8 bytes on payload, and 8 on truncation. -2
5901 // because stream offset size is 2 instead of 0.
5902 EXPECT_EQ(non_truncated_packet_size,
5903 writer_->last_packet_size() + 8 * 2 - 2);
5904 }
5905}
5906
5907TEST_P(QuicConnectionTest, SendDelayedAck) {
5908 QuicTime ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
5909 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07005910 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005911 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07005912 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07005913 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005914 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07005915 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005916 // Process a packet from the non-crypto stream.
5917 frame1_.stream_id = 3;
5918
5919 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07005920 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005921 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5922 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5923
5924 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07005925 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005926 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5927 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07005928 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005929 connection_.GetAckAlarm()->Fire();
5930 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07005931 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005932 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07005933 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005934 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
5935 } else {
nharper55fa6132019-05-07 19:37:21 -07005936 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005937 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
5938 }
5939 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07005940 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005941}
5942
QUICHE teama6ef0a62019-03-07 20:34:33 -05005943TEST_P(QuicConnectionTest, SendDelayedAckDecimation) {
5944 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005945
5946 const size_t kMinRttMs = 40;
5947 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
5948 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
5949 QuicTime::Delta::Zero(), QuicTime::Zero());
5950 // The ack time should be based on min_rtt/4, since it's less than the
5951 // default delayed ack time.
5952 QuicTime ack_time = clock_.ApproximateNow() +
5953 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
5954 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07005955 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005956 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07005957 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07005958 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005959 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07005960 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005961 // Process a packet from the non-crypto stream.
5962 frame1_.stream_id = 3;
5963
5964 // Process all the initial packets in order so there aren't missing packets.
5965 uint64_t kFirstDecimatedPacket = 101;
5966 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
5967 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5968 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5969 }
fayang9adfb532020-06-04 06:58:45 -07005970 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005971 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07005972 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005973 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5974 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
5975 ENCRYPTION_ZERO_RTT);
5976
5977 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07005978 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005979 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5980
5981 // The 10th received packet causes an ack to be sent.
5982 for (int i = 0; i < 9; ++i) {
fayang9adfb532020-06-04 06:58:45 -07005983 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005984 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5985 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
5986 ENCRYPTION_ZERO_RTT);
5987 }
5988 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07005989 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005990 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07005991 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005992 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
5993 } else {
nharperc32d8ab2019-10-09 11:09:06 -07005994 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005995 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
5996 }
5997 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07005998 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005999}
6000
QUICHE teama6ef0a62019-03-07 20:34:33 -05006001TEST_P(QuicConnectionTest, SendDelayedAckDecimationUnlimitedAggregation) {
6002 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6003 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6004 QuicConfig config;
6005 QuicTagVector connection_options;
6006 connection_options.push_back(kACKD);
6007 // No limit on the number of packets received before sending an ack.
6008 connection_options.push_back(kAKDU);
6009 config.SetConnectionOptionsToSend(connection_options);
6010 connection_.SetFromConfig(config);
6011
6012 const size_t kMinRttMs = 40;
6013 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6014 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6015 QuicTime::Delta::Zero(), QuicTime::Zero());
6016 // The ack time should be based on min_rtt/4, since it's less than the
6017 // default delayed ack time.
6018 QuicTime ack_time = clock_.ApproximateNow() +
6019 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6020 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006021 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006022 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006023 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006024 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006025 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006026 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006027 // Process a packet from the non-crypto stream.
6028 frame1_.stream_id = 3;
6029
6030 // Process all the initial packets in order so there aren't missing packets.
6031 uint64_t kFirstDecimatedPacket = 101;
6032 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6033 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6034 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6035 }
fayang9adfb532020-06-04 06:58:45 -07006036 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006037 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006038 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006039 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6040 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6041 ENCRYPTION_ZERO_RTT);
6042
6043 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006044 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006045 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6046
6047 // 18 packets will not cause an ack to be sent. 19 will because when
6048 // stop waiting frames are in use, we ack every 20 packets no matter what.
6049 for (int i = 0; i < 18; ++i) {
fayang9adfb532020-06-04 06:58:45 -07006050 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006051 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6052 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6053 ENCRYPTION_ZERO_RTT);
6054 }
6055 // The delayed ack timer should still be set to the expected deadline.
fayang9adfb532020-06-04 06:58:45 -07006056 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006057 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6058}
6059
6060TEST_P(QuicConnectionTest, SendDelayedAckDecimationEighthRtt) {
6061 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006062 QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
6063
6064 const size_t kMinRttMs = 40;
6065 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6066 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6067 QuicTime::Delta::Zero(), QuicTime::Zero());
6068 // The ack time should be based on min_rtt/8, since it's less than the
6069 // default delayed ack time.
6070 QuicTime ack_time = clock_.ApproximateNow() +
6071 QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
6072 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006073 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006074 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006075 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006076 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006077 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006078 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006079 // Process a packet from the non-crypto stream.
6080 frame1_.stream_id = 3;
6081
6082 // Process all the initial packets in order so there aren't missing packets.
6083 uint64_t kFirstDecimatedPacket = 101;
6084 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6085 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6086 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6087 }
fayang9adfb532020-06-04 06:58:45 -07006088 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006089 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006090 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006091 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6092 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6093 ENCRYPTION_ZERO_RTT);
6094
6095 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006096 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006097 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6098
6099 // The 10th received packet causes an ack to be sent.
6100 for (int i = 0; i < 9; ++i) {
fayang9adfb532020-06-04 06:58:45 -07006101 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006102 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6103 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6104 ENCRYPTION_ZERO_RTT);
6105 }
6106 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07006107 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006108 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07006109 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006110 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6111 } else {
nharperc32d8ab2019-10-09 11:09:06 -07006112 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006113 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6114 }
6115 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006116 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006117}
6118
QUICHE teama6ef0a62019-03-07 20:34:33 -05006119TEST_P(QuicConnectionTest, SendDelayedAckOnHandshakeConfirmed) {
6120 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6121 ProcessPacket(1);
6122 // Check that ack is sent and that delayed ack alarm is set.
fayang9adfb532020-06-04 06:58:45 -07006123 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006124 QuicTime ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6125 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6126
6127 // Completing the handshake as the server does nothing.
6128 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_SERVER);
6129 connection_.OnHandshakeComplete();
fayang9adfb532020-06-04 06:58:45 -07006130 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006131 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6132
6133 // Complete the handshake as the client decreases the delayed ack time to 0ms.
6134 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_CLIENT);
6135 connection_.OnHandshakeComplete();
fayang9adfb532020-06-04 06:58:45 -07006136 EXPECT_TRUE(connection_.HasPendingAcks());
fayangb296fb82020-02-11 08:14:28 -08006137 if (connection_.SupportsMultiplePacketNumberSpaces()) {
6138 EXPECT_EQ(clock_.ApproximateNow() + DefaultDelayedAckTime(),
6139 connection_.GetAckAlarm()->deadline());
6140 } else {
6141 EXPECT_EQ(clock_.ApproximateNow(), connection_.GetAckAlarm()->deadline());
6142 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006143}
6144
6145TEST_P(QuicConnectionTest, SendDelayedAckOnSecondPacket) {
6146 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6147 ProcessPacket(1);
6148 ProcessPacket(2);
6149 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006150 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006151 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006152 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006153 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6154 } else {
nharper55fa6132019-05-07 19:37:21 -07006155 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006156 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6157 }
6158 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006159 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006160}
6161
6162TEST_P(QuicConnectionTest, NoAckOnOldNacks) {
6163 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang6dba4902019-06-17 10:04:23 -07006164 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006165 ProcessPacket(2);
6166 size_t frames_per_ack = GetParam().no_stop_waiting ? 1 : 2;
QUICHE teama6ef0a62019-03-07 20:34:33 -05006167
6168 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
6169 ProcessPacket(3);
nharper55fa6132019-05-07 19:37:21 -07006170 size_t padding_frame_count = writer_->padding_frames().size();
6171 EXPECT_EQ(padding_frame_count + frames_per_ack, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006172 EXPECT_FALSE(writer_->ack_frames().empty());
6173 writer_->Reset();
6174
fayang6dba4902019-06-17 10:04:23 -07006175 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006176 ProcessPacket(4);
fayang6dba4902019-06-17 10:04:23 -07006177 EXPECT_EQ(0u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006178
6179 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
6180 ProcessPacket(5);
nharper55fa6132019-05-07 19:37:21 -07006181 padding_frame_count = writer_->padding_frames().size();
6182 EXPECT_EQ(padding_frame_count + frames_per_ack, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006183 EXPECT_FALSE(writer_->ack_frames().empty());
6184 writer_->Reset();
6185
6186 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6187 // Now only set the timer on the 6th packet, instead of sending another ack.
6188 ProcessPacket(6);
nharper55fa6132019-05-07 19:37:21 -07006189 padding_frame_count = writer_->padding_frames().size();
6190 EXPECT_EQ(padding_frame_count, writer_->frame_count());
fayang9adfb532020-06-04 06:58:45 -07006191 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006192}
6193
6194TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingPacket) {
6195 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
QUICHE team8c1daa22019-03-13 08:33:41 -07006196 EXPECT_CALL(visitor_, OnStreamFrame(_));
6197 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07006198 std::make_unique<TaggingEncrypter>(0x01));
zhongyi546cc452019-04-12 15:27:49 -07006199 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07006200 std::make_unique<StrictTaggingDecrypter>(0x01));
nharper2c9f02a2019-05-08 10:25:50 -07006201 ProcessDataPacket(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006202 connection_.SendStreamDataWithString(
6203 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6204 0, NO_FIN);
6205 // Check that ack is bundled with outgoing data and that delayed ack
6206 // alarm is reset.
6207 if (GetParam().no_stop_waiting) {
6208 EXPECT_EQ(2u, writer_->frame_count());
6209 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6210 } else {
6211 EXPECT_EQ(3u, writer_->frame_count());
6212 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6213 }
6214 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006215 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006216}
6217
6218TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingCryptoPacket) {
6219 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayangc31c9952019-06-05 13:54:48 -07006220 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6221 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
6222 } else {
6223 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6224 }
6225 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
nharper46833c32019-05-15 21:33:05 -07006226 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006227 // Check that ack is bundled with outgoing crypto data.
6228 if (GetParam().no_stop_waiting) {
6229 EXPECT_EQ(3u, writer_->frame_count());
6230 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6231 } else {
6232 EXPECT_EQ(4u, writer_->frame_count());
6233 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6234 }
fayang9adfb532020-06-04 06:58:45 -07006235 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006236}
6237
6238TEST_P(QuicConnectionTest, BlockAndBufferOnFirstCHLOPacketOfTwo) {
6239 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6240 ProcessPacket(1);
6241 BlockOnNextWrite();
6242 writer_->set_is_write_blocked_data_buffered(true);
fayang60d9c042020-07-06 08:42:40 -07006243 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
fayang6a258412020-05-28 08:57:12 -07006244 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
6245 } else {
6246 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
6247 }
nharper46833c32019-05-15 21:33:05 -07006248 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006249 EXPECT_TRUE(writer_->IsWriteBlocked());
6250 EXPECT_FALSE(connection_.HasQueuedData());
nharper46833c32019-05-15 21:33:05 -07006251 connection_.SendCryptoDataWithString("bar", 3);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006252 EXPECT_TRUE(writer_->IsWriteBlocked());
fayang60d9c042020-07-06 08:42:40 -07006253 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
fayang6a258412020-05-28 08:57:12 -07006254 // CRYPTO frames are not flushed when writer is blocked.
6255 EXPECT_FALSE(connection_.HasQueuedData());
6256 } else {
6257 EXPECT_TRUE(connection_.HasQueuedData());
6258 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006259}
6260
6261TEST_P(QuicConnectionTest, BundleAckForSecondCHLO) {
6262 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006263 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006264 EXPECT_CALL(visitor_, OnCanWrite())
6265 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6266 &connection_, &TestConnection::SendCryptoStreamData)));
6267 // Process a packet from the crypto stream, which is frame1_'s default.
6268 // Receiving the CHLO as packet 2 first will cause the connection to
6269 // immediately send an ack, due to the packet gap.
fayangc31c9952019-06-05 13:54:48 -07006270 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6271 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
6272 } else {
6273 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6274 }
6275 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006276 // Check that ack is sent and that delayed ack alarm is reset.
6277 if (GetParam().no_stop_waiting) {
6278 EXPECT_EQ(3u, writer_->frame_count());
6279 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6280 } else {
6281 EXPECT_EQ(4u, writer_->frame_count());
6282 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6283 }
QUICHE teamea740082019-03-11 17:58:43 -07006284 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006285 EXPECT_EQ(1u, writer_->stream_frames().size());
6286 } else {
6287 EXPECT_EQ(1u, writer_->crypto_frames().size());
6288 }
6289 EXPECT_EQ(1u, writer_->padding_frames().size());
6290 ASSERT_FALSE(writer_->ack_frames().empty());
6291 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(writer_->ack_frames().front()));
fayang9adfb532020-06-04 06:58:45 -07006292 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006293}
6294
6295TEST_P(QuicConnectionTest, BundleAckForSecondCHLOTwoPacketReject) {
6296 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006297 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006298
6299 // Process two packets from the crypto stream, which is frame1_'s default,
6300 // simulating a 2 packet reject.
6301 {
fayangc31c9952019-06-05 13:54:48 -07006302 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6303 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
6304 } else {
6305 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6306 }
6307 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006308 // Send the new CHLO when the REJ is processed.
fayangc31c9952019-06-05 13:54:48 -07006309 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6310 EXPECT_CALL(visitor_, OnCryptoFrame(_))
6311 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6312 &connection_, &TestConnection::SendCryptoStreamData)));
6313 } else {
6314 EXPECT_CALL(visitor_, OnStreamFrame(_))
6315 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6316 &connection_, &TestConnection::SendCryptoStreamData)));
6317 }
6318 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006319 }
6320 // Check that ack is sent and that delayed ack alarm is reset.
6321 if (GetParam().no_stop_waiting) {
6322 EXPECT_EQ(3u, writer_->frame_count());
6323 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6324 } else {
6325 EXPECT_EQ(4u, writer_->frame_count());
6326 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6327 }
QUICHE teamea740082019-03-11 17:58:43 -07006328 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006329 EXPECT_EQ(1u, writer_->stream_frames().size());
6330 } else {
6331 EXPECT_EQ(1u, writer_->crypto_frames().size());
6332 }
6333 EXPECT_EQ(1u, writer_->padding_frames().size());
6334 ASSERT_FALSE(writer_->ack_frames().empty());
6335 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(writer_->ack_frames().front()));
fayang9adfb532020-06-04 06:58:45 -07006336 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006337}
6338
6339TEST_P(QuicConnectionTest, BundleAckWithDataOnIncomingAck) {
6340 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6341 connection_.SendStreamDataWithString(
6342 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6343 0, NO_FIN);
6344 connection_.SendStreamDataWithString(
6345 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6346 3, NO_FIN);
6347 // Ack the second packet, which will retransmit the first packet.
6348 QuicAckFrame ack = ConstructAckFrame(2, 1);
6349 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07006350 lost_packets.push_back(
6351 LostPacket(QuicPacketNumber(1), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006352 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07006353 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
6354 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006355 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
6356 ProcessAckPacket(&ack);
nharper55fa6132019-05-07 19:37:21 -07006357 size_t padding_frame_count = writer_->padding_frames().size();
6358 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006359 EXPECT_EQ(1u, writer_->stream_frames().size());
6360 writer_->Reset();
6361
6362 // Now ack the retransmission, which will both raise the high water mark
6363 // and see if there is more data to send.
6364 ack = ConstructAckFrame(3, 1);
6365 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
6366 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
6367 ProcessAckPacket(&ack);
6368
6369 // Check that no packet is sent and the ack alarm isn't set.
6370 EXPECT_EQ(0u, writer_->frame_count());
fayang9adfb532020-06-04 06:58:45 -07006371 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006372 writer_->Reset();
6373
6374 // Send the same ack, but send both data and an ack together.
6375 ack = ConstructAckFrame(3, 1);
6376 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
6377 EXPECT_CALL(visitor_, OnCanWrite())
6378 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6379 &connection_, &TestConnection::EnsureWritableAndSendStreamData5)));
6380 ProcessAckPacket(&ack);
6381
6382 // Check that ack is bundled with outgoing data and the delayed ack
6383 // alarm is reset.
6384 if (GetParam().no_stop_waiting) {
fayang8a27b0f2019-11-04 11:27:40 -08006385 // Do not ACK acks.
6386 EXPECT_EQ(1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006387 } else {
6388 EXPECT_EQ(3u, writer_->frame_count());
6389 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6390 }
fayang8a27b0f2019-11-04 11:27:40 -08006391 if (GetParam().no_stop_waiting) {
fayang03916692019-05-22 17:57:18 -07006392 EXPECT_TRUE(writer_->ack_frames().empty());
6393 } else {
6394 EXPECT_FALSE(writer_->ack_frames().empty());
6395 EXPECT_EQ(QuicPacketNumber(3u),
6396 LargestAcked(writer_->ack_frames().front()));
6397 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006398 EXPECT_EQ(1u, writer_->stream_frames().size());
fayang9adfb532020-06-04 06:58:45 -07006399 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006400}
6401
6402TEST_P(QuicConnectionTest, NoAckSentForClose) {
6403 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6404 ProcessPacket(1);
fkastenholz5d880a92019-06-21 09:01:56 -07006405 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
6406 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006407 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6408 ProcessClosePacket(2);
fkastenholz5d880a92019-06-21 09:01:56 -07006409 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08006410 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6411 IsError(QUIC_PEER_GOING_AWAY));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006412}
6413
6414TEST_P(QuicConnectionTest, SendWhenDisconnected) {
6415 EXPECT_TRUE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07006416 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
6417 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006418 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
6419 ConnectionCloseBehavior::SILENT_CLOSE);
6420 EXPECT_FALSE(connection_.connected());
ianswettfc16a2b2020-05-18 16:05:49 -07006421 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
fayangfe77c032020-08-24 18:21:32 -07006422 EXPECT_EQ(DISCARD, connection_.GetSerializedPacketFate(
6423 /*is_mtu_discovery=*/false, ENCRYPTION_INITIAL));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006424}
6425
6426TEST_P(QuicConnectionTest, SendConnectivityProbingWhenDisconnected) {
6427 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
fayangc31c9952019-06-05 13:54:48 -07006428 if (!IsDefaultTestConfiguration()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006429 return;
6430 }
6431
6432 EXPECT_TRUE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07006433 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
6434 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006435 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
6436 ConnectionCloseBehavior::SILENT_CLOSE);
6437 EXPECT_FALSE(connection_.connected());
ianswettfc16a2b2020-05-18 16:05:49 -07006438 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006439
6440 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6441 .Times(0);
6442
6443 EXPECT_QUIC_BUG(connection_.SendConnectivityProbingPacket(
6444 writer_.get(), connection_.peer_address()),
6445 "Not sending connectivity probing packet as connection is "
6446 "disconnected.");
fkastenholz5d880a92019-06-21 09:01:56 -07006447 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08006448 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6449 IsError(QUIC_PEER_GOING_AWAY));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006450}
6451
6452TEST_P(QuicConnectionTest, WriteBlockedAfterClientSendsConnectivityProbe) {
dschinazi1c6e5922020-06-19 10:35:03 -07006453 PathProbeTestInit(Perspective::IS_CLIENT);
danzhc19a9502020-09-29 16:02:33 -07006454 TestPacketWriter probing_writer(version(), &clock_, Perspective::IS_CLIENT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006455 // Block next write so that sending connectivity probe will encounter a
6456 // blocked write when send a connectivity probe to the peer.
6457 probing_writer.BlockOnNextWrite();
6458 // Connection will not be marked as write blocked as connectivity probe only
6459 // affects the probing_writer which is not the default.
6460 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
6461
6462 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6463 .Times(1);
6464 connection_.SendConnectivityProbingPacket(&probing_writer,
6465 connection_.peer_address());
6466}
6467
6468TEST_P(QuicConnectionTest, WriterBlockedAfterServerSendsConnectivityProbe) {
dschinazi1c6e5922020-06-19 10:35:03 -07006469 PathProbeTestInit(Perspective::IS_SERVER);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006470
6471 // Block next write so that sending connectivity probe will encounter a
6472 // blocked write when send a connectivity probe to the peer.
6473 writer_->BlockOnNextWrite();
6474 // Connection will be marked as write blocked as server uses the default
6475 // writer to send connectivity probes.
6476 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
6477
6478 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6479 .Times(1);
6480 connection_.SendConnectivityProbingPacket(writer_.get(),
6481 connection_.peer_address());
6482}
6483
6484TEST_P(QuicConnectionTest, WriterErrorWhenClientSendsConnectivityProbe) {
dschinazi1c6e5922020-06-19 10:35:03 -07006485 PathProbeTestInit(Perspective::IS_CLIENT);
danzhc19a9502020-09-29 16:02:33 -07006486 TestPacketWriter probing_writer(version(), &clock_, Perspective::IS_CLIENT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006487 probing_writer.SetShouldWriteFail();
6488
6489 // Connection should not be closed if a connectivity probe is failed to be
6490 // sent.
fkastenholz5d880a92019-06-21 09:01:56 -07006491 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006492
6493 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6494 .Times(0);
6495 connection_.SendConnectivityProbingPacket(&probing_writer,
6496 connection_.peer_address());
6497}
6498
6499TEST_P(QuicConnectionTest, WriterErrorWhenServerSendsConnectivityProbe) {
dschinazi1c6e5922020-06-19 10:35:03 -07006500 PathProbeTestInit(Perspective::IS_SERVER);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006501
6502 writer_->SetShouldWriteFail();
6503 // Connection should not be closed if a connectivity probe is failed to be
6504 // sent.
fkastenholz5d880a92019-06-21 09:01:56 -07006505 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006506
6507 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6508 .Times(0);
6509 connection_.SendConnectivityProbingPacket(writer_.get(),
6510 connection_.peer_address());
6511}
6512
6513TEST_P(QuicConnectionTest, PublicReset) {
fayangc31c9952019-06-05 13:54:48 -07006514 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006515 return;
6516 }
6517 QuicPublicResetPacket header;
6518 // Public reset packet in only built by server.
6519 header.connection_id = connection_id_;
6520 std::unique_ptr<QuicEncryptedPacket> packet(
6521 framer_.BuildPublicResetPacket(header));
6522 std::unique_ptr<QuicReceivedPacket> received(
6523 ConstructReceivedPacket(*packet, QuicTime::Zero()));
fkastenholz5d880a92019-06-21 09:01:56 -07006524 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
6525 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006526 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
fkastenholz5d880a92019-06-21 09:01:56 -07006527 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08006528 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6529 IsError(QUIC_PUBLIC_RESET));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006530}
6531
6532TEST_P(QuicConnectionTest, IetfStatelessReset) {
fayangc31c9952019-06-05 13:54:48 -07006533 if (!VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006534 return;
6535 }
6536 const QuicUint128 kTestStatelessResetToken = 1010101;
6537 QuicConfig config;
6538 QuicConfigPeer::SetReceivedStatelessResetToken(&config,
6539 kTestStatelessResetToken);
6540 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6541 connection_.SetFromConfig(config);
6542 std::unique_ptr<QuicEncryptedPacket> packet(
6543 QuicFramer::BuildIetfStatelessResetPacket(connection_id_,
6544 kTestStatelessResetToken));
6545 std::unique_ptr<QuicReceivedPacket> received(
6546 ConstructReceivedPacket(*packet, QuicTime::Zero()));
renjietang7f483b52020-05-20 14:30:47 -07006547 EXPECT_CALL(visitor_, ValidateStatelessReset(_, _)).WillOnce(Return(true));
fkastenholz5d880a92019-06-21 09:01:56 -07006548 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
6549 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006550 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
fkastenholz5d880a92019-06-21 09:01:56 -07006551 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08006552 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6553 IsError(QUIC_PUBLIC_RESET));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006554}
6555
6556TEST_P(QuicConnectionTest, GoAway) {
fkastenholz305e1732019-06-18 05:01:22 -07006557 if (VersionHasIetfQuicFrames(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006558 // GoAway is not available in version 99.
6559 return;
6560 }
6561
6562 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6563
wub8a5dafa2020-05-13 12:30:17 -07006564 QuicGoAwayFrame* goaway = new QuicGoAwayFrame();
6565 goaway->last_good_stream_id = 1;
6566 goaway->error_code = QUIC_PEER_GOING_AWAY;
6567 goaway->reason_phrase = "Going away.";
QUICHE teama6ef0a62019-03-07 20:34:33 -05006568 EXPECT_CALL(visitor_, OnGoAway(_));
wub8a5dafa2020-05-13 12:30:17 -07006569 ProcessGoAwayPacket(goaway);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006570}
6571
6572TEST_P(QuicConnectionTest, WindowUpdate) {
6573 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6574
wub8a5dafa2020-05-13 12:30:17 -07006575 QuicWindowUpdateFrame* window_update = new QuicWindowUpdateFrame();
6576 window_update->stream_id = 3;
6577 window_update->max_data = 1234;
QUICHE teama6ef0a62019-03-07 20:34:33 -05006578 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
wub8a5dafa2020-05-13 12:30:17 -07006579 ProcessFramePacket(QuicFrame(window_update));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006580}
6581
6582TEST_P(QuicConnectionTest, Blocked) {
6583 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6584
wub8a5dafa2020-05-13 12:30:17 -07006585 QuicBlockedFrame* blocked = new QuicBlockedFrame();
6586 blocked->stream_id = 3;
QUICHE teama6ef0a62019-03-07 20:34:33 -05006587 EXPECT_CALL(visitor_, OnBlockedFrame(_));
wub8a5dafa2020-05-13 12:30:17 -07006588 ProcessFramePacket(QuicFrame(blocked));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006589 EXPECT_EQ(1u, connection_.GetStats().blocked_frames_received);
6590 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
6591}
6592
6593TEST_P(QuicConnectionTest, ZeroBytePacket) {
6594 // Don't close the connection for zero byte packets.
fkastenholz5d880a92019-06-21 09:01:56 -07006595 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006596 QuicReceivedPacket encrypted(nullptr, 0, QuicTime::Zero());
6597 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, encrypted);
6598}
6599
6600TEST_P(QuicConnectionTest, MissingPacketsBeforeLeastUnacked) {
fayangd4291e42019-05-30 10:31:21 -07006601 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006602 return;
6603 }
6604 // Set the packet number of the ack packet to be least unacked (4).
6605 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 3);
6606 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6607 ProcessStopWaitingPacket(InitStopWaitingFrame(4));
fayangc31c9952019-06-05 13:54:48 -07006608 EXPECT_FALSE(connection_.ack_frame().packets.Empty());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006609}
6610
QUICHE teama6ef0a62019-03-07 20:34:33 -05006611TEST_P(QuicConnectionTest, ClientHandlesVersionNegotiation) {
dschinazi48ac9192019-07-31 00:07:26 -07006612 // All supported versions except the one the connection supports.
6613 ParsedQuicVersionVector versions;
6614 for (auto version : AllSupportedVersions()) {
6615 if (version != connection_.version()) {
6616 versions.push_back(version);
6617 }
6618 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006619
6620 // Send a version negotiation packet.
6621 std::unique_ptr<QuicEncryptedPacket> encrypted(
dschinazib417d602019-05-29 13:08:45 -07006622 QuicFramer::BuildVersionNegotiationPacket(
6623 connection_id_, EmptyQuicConnectionId(),
fayangd4291e42019-05-30 10:31:21 -07006624 VersionHasIetfInvariantHeader(connection_.transport_version()),
dschinazi48ac9192019-07-31 00:07:26 -07006625 connection_.version().HasLengthPrefixedConnectionIds(), versions));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006626 std::unique_ptr<QuicReceivedPacket> received(
6627 ConstructReceivedPacket(*encrypted, QuicTime::Zero()));
fkastenholz5d880a92019-06-21 09:01:56 -07006628 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
6629 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
fayang95cef072019-10-10 12:44:14 -07006630 // Verify no connection close packet gets sent.
6631 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006632 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
fayang9ed391a2019-06-20 11:16:59 -07006633 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07006634 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08006635 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6636 IsError(QUIC_INVALID_VERSION));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006637}
6638
6639TEST_P(QuicConnectionTest, BadVersionNegotiation) {
6640 // Send a version negotiation packet with the version the client started with.
6641 // It should be rejected.
fkastenholz5d880a92019-06-21 09:01:56 -07006642 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
6643 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006644 std::unique_ptr<QuicEncryptedPacket> encrypted(
dschinazib417d602019-05-29 13:08:45 -07006645 QuicFramer::BuildVersionNegotiationPacket(
6646 connection_id_, EmptyQuicConnectionId(),
fayangd4291e42019-05-30 10:31:21 -07006647 VersionHasIetfInvariantHeader(connection_.transport_version()),
dschinazi48ac9192019-07-31 00:07:26 -07006648 connection_.version().HasLengthPrefixedConnectionIds(),
QUICHE teama6ef0a62019-03-07 20:34:33 -05006649 AllSupportedVersions()));
6650 std::unique_ptr<QuicReceivedPacket> received(
6651 ConstructReceivedPacket(*encrypted, QuicTime::Zero()));
6652 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
fkastenholz5d880a92019-06-21 09:01:56 -07006653 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08006654 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6655 IsError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006656}
6657
6658TEST_P(QuicConnectionTest, CheckSendStats) {
fayang5f135052019-08-22 17:59:40 -07006659 if (connection_.PtoEnabled()) {
6660 return;
6661 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006662 connection_.SetMaxTailLossProbes(0);
6663
6664 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
6665 connection_.SendStreamDataWithString(3, "first", 0, NO_FIN);
6666 size_t first_packet_size = writer_->last_packet_size();
6667
6668 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
6669 connection_.SendStreamDataWithString(5, "second", 0, NO_FIN);
6670 size_t second_packet_size = writer_->last_packet_size();
6671
6672 // 2 retransmissions due to rto, 1 due to explicit nack.
6673 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
6674 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
6675
6676 // Retransmit due to RTO.
6677 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
6678 connection_.GetRetransmissionAlarm()->Fire();
6679
6680 // Retransmit due to explicit nacks.
6681 QuicAckFrame nack_three =
6682 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)},
6683 {QuicPacketNumber(4), QuicPacketNumber(5)}});
6684
6685 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07006686 lost_packets.push_back(
6687 LostPacket(QuicPacketNumber(1), kMaxOutgoingPacketSize));
6688 lost_packets.push_back(
6689 LostPacket(QuicPacketNumber(3), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006690 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07006691 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
6692 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006693 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006694 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6695 ProcessAckPacket(&nack_three);
6696
6697 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
6698 .WillOnce(Return(QuicBandwidth::Zero()));
6699
6700 const QuicConnectionStats& stats = connection_.GetStats();
6701 // For IETF QUIC, version is not included as the encryption level switches to
6702 // FORWARD_SECURE in SendStreamDataWithString.
6703 size_t save_on_version =
fayangd4291e42019-05-30 10:31:21 -07006704 VersionHasIetfInvariantHeader(GetParam().version.transport_version)
6705 ? 0
6706 : kQuicVersionSize;
QUICHE teama6ef0a62019-03-07 20:34:33 -05006707 EXPECT_EQ(3 * first_packet_size + 2 * second_packet_size - save_on_version,
6708 stats.bytes_sent);
6709 EXPECT_EQ(5u, stats.packets_sent);
6710 EXPECT_EQ(2 * first_packet_size + second_packet_size - save_on_version,
6711 stats.bytes_retransmitted);
6712 EXPECT_EQ(3u, stats.packets_retransmitted);
6713 EXPECT_EQ(1u, stats.rto_count);
6714 EXPECT_EQ(kDefaultMaxPacketSize, stats.max_packet_size);
6715}
6716
6717TEST_P(QuicConnectionTest, ProcessFramesIfPacketClosedConnection) {
6718 // Construct a packet with stream frame and connection close frame.
6719 QuicPacketHeader header;
dschinazi5e1a7b22019-07-31 12:23:21 -07006720 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
QUICHE team2252b702019-05-14 23:55:14 -04006721 header.source_connection_id = connection_id_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05006722 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
fayangd4291e42019-05-30 10:31:21 -07006723 if (!VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04006724 header.source_connection_id_included = CONNECTION_ID_PRESENT;
6725 }
6726 } else {
6727 header.destination_connection_id = connection_id_;
fayangd4291e42019-05-30 10:31:21 -07006728 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04006729 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
6730 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006731 }
6732 header.packet_number = QuicPacketNumber(1);
6733 header.version_flag = false;
6734
fkastenholz488a4622019-08-26 06:24:46 -07006735 QuicErrorCode kQuicErrorCode = QUIC_PEER_GOING_AWAY;
6736 // This QuicConnectionCloseFrame will default to being for a Google QUIC
6737 // close. If doing IETF QUIC then set fields appropriately for CC/T or CC/A,
6738 // depending on the mapping.
fkastenholz591814c2019-09-06 12:11:46 -07006739 QuicConnectionCloseFrame qccf(peer_framer_.transport_version(),
6740 kQuicErrorCode, "",
6741 /*transport_close_frame_type=*/0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006742 QuicFrames frames;
6743 frames.push_back(QuicFrame(frame1_));
6744 frames.push_back(QuicFrame(&qccf));
6745 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
6746 EXPECT_TRUE(nullptr != packet);
dschinazi66dea072019-04-09 11:41:06 -07006747 char buffer[kMaxOutgoingPacketSize];
nharperc6b99512019-09-19 11:13:48 -07006748 size_t encrypted_length = peer_framer_.EncryptPayload(
6749 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
6750 kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006751
fkastenholz5d880a92019-06-21 09:01:56 -07006752 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
6753 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006754 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6755 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6756
6757 connection_.ProcessUdpPacket(
6758 kSelfAddress, kPeerAddress,
6759 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
fkastenholz5d880a92019-06-21 09:01:56 -07006760 EXPECT_EQ(1, connection_close_frame_count_);
bnc77e77b82020-04-05 10:36:49 -07006761 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
bncf54082a2019-11-27 10:19:47 -08006762 IsError(QUIC_PEER_GOING_AWAY));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006763}
6764
6765TEST_P(QuicConnectionTest, SelectMutualVersion) {
6766 connection_.SetSupportedVersions(AllSupportedVersions());
6767 // Set the connection to speak the lowest quic version.
6768 connection_.set_version(QuicVersionMin());
6769 EXPECT_EQ(QuicVersionMin(), connection_.version());
6770
6771 // Pass in available versions which includes a higher mutually supported
6772 // version. The higher mutually supported version should be selected.
6773 ParsedQuicVersionVector supported_versions = AllSupportedVersions();
6774 EXPECT_TRUE(connection_.SelectMutualVersion(supported_versions));
6775 EXPECT_EQ(QuicVersionMax(), connection_.version());
6776
6777 // Expect that the lowest version is selected.
6778 // Ensure the lowest supported version is less than the max, unless they're
6779 // the same.
6780 ParsedQuicVersionVector lowest_version_vector;
6781 lowest_version_vector.push_back(QuicVersionMin());
6782 EXPECT_TRUE(connection_.SelectMutualVersion(lowest_version_vector));
6783 EXPECT_EQ(QuicVersionMin(), connection_.version());
6784
6785 // Shouldn't be able to find a mutually supported version.
6786 ParsedQuicVersionVector unsupported_version;
6787 unsupported_version.push_back(UnsupportedQuicVersion());
6788 EXPECT_FALSE(connection_.SelectMutualVersion(unsupported_version));
6789}
6790
6791TEST_P(QuicConnectionTest, ConnectionCloseWhenWritable) {
6792 EXPECT_FALSE(writer_->IsWriteBlocked());
6793
6794 // Send a packet.
6795 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
6796 EXPECT_EQ(0u, connection_.NumQueuedPackets());
6797 EXPECT_EQ(1u, writer_->packets_write_attempts());
6798
6799 TriggerConnectionClose();
rch39c88ab2019-10-16 19:24:40 -07006800 EXPECT_LE(2u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006801}
6802
6803TEST_P(QuicConnectionTest, ConnectionCloseGettingWriteBlocked) {
6804 BlockOnNextWrite();
6805 TriggerConnectionClose();
6806 EXPECT_EQ(1u, writer_->packets_write_attempts());
6807 EXPECT_TRUE(writer_->IsWriteBlocked());
6808}
6809
6810TEST_P(QuicConnectionTest, ConnectionCloseWhenWriteBlocked) {
6811 BlockOnNextWrite();
6812 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
6813 EXPECT_EQ(1u, connection_.NumQueuedPackets());
6814 EXPECT_EQ(1u, writer_->packets_write_attempts());
6815 EXPECT_TRUE(writer_->IsWriteBlocked());
6816 TriggerConnectionClose();
6817 EXPECT_EQ(1u, writer_->packets_write_attempts());
6818}
6819
6820TEST_P(QuicConnectionTest, OnPacketSentDebugVisitor) {
dschinazi1c6e5922020-06-19 10:35:03 -07006821 PathProbeTestInit(Perspective::IS_CLIENT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006822 MockQuicConnectionDebugVisitor debug_visitor;
6823 connection_.set_debug_visitor(&debug_visitor);
6824
wubacc7c972020-09-14 16:16:32 -07006825 if (connection_.sent_packet_manager()
6826 .give_sent_packet_to_debug_visitor_after_sent()) {
6827 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _)).Times(1);
6828 } else {
6829 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(1);
6830 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006831 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
6832
wubacc7c972020-09-14 16:16:32 -07006833 if (connection_.sent_packet_manager()
6834 .give_sent_packet_to_debug_visitor_after_sent()) {
6835 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _)).Times(1);
6836 } else {
6837 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(1);
6838 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006839 connection_.SendConnectivityProbingPacket(writer_.get(),
6840 connection_.peer_address());
6841}
6842
6843TEST_P(QuicConnectionTest, OnPacketHeaderDebugVisitor) {
6844 QuicPacketHeader header;
6845 header.packet_number = QuicPacketNumber(1);
fayangd4291e42019-05-30 10:31:21 -07006846 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006847 header.form = IETF_QUIC_LONG_HEADER_PACKET;
6848 }
6849
6850 MockQuicConnectionDebugVisitor debug_visitor;
6851 connection_.set_debug_visitor(&debug_visitor);
fayang182ae362020-10-01 12:08:49 -07006852 EXPECT_CALL(debug_visitor, OnPacketHeader(Ref(header), _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006853 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(1);
6854 EXPECT_CALL(debug_visitor, OnSuccessfulVersionNegotiation(_)).Times(1);
6855 connection_.OnPacketHeader(header);
6856}
6857
6858TEST_P(QuicConnectionTest, Pacing) {
wub5df36632020-10-01 14:42:17 -07006859 TestConnection server(connection_id_, kPeerAddress, kSelfAddress,
6860 helper_.get(), alarm_factory_.get(), writer_.get(),
QUICHE teama6ef0a62019-03-07 20:34:33 -05006861 Perspective::IS_SERVER, version());
wub5df36632020-10-01 14:42:17 -07006862 TestConnection client(connection_id_, kSelfAddress, kPeerAddress,
6863 helper_.get(), alarm_factory_.get(), writer_.get(),
QUICHE teama6ef0a62019-03-07 20:34:33 -05006864 Perspective::IS_CLIENT, version());
6865 EXPECT_FALSE(QuicSentPacketManagerPeer::UsingPacing(
6866 static_cast<const QuicSentPacketManager*>(
6867 &client.sent_packet_manager())));
6868 EXPECT_FALSE(QuicSentPacketManagerPeer::UsingPacing(
6869 static_cast<const QuicSentPacketManager*>(
6870 &server.sent_packet_manager())));
6871}
6872
6873TEST_P(QuicConnectionTest, WindowUpdateInstigateAcks) {
6874 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6875
6876 // Send a WINDOW_UPDATE frame.
wub8a5dafa2020-05-13 12:30:17 -07006877 QuicWindowUpdateFrame* window_update = new QuicWindowUpdateFrame();
6878 window_update->stream_id = 3;
6879 window_update->max_data = 1234;
QUICHE teama6ef0a62019-03-07 20:34:33 -05006880 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
wub8a5dafa2020-05-13 12:30:17 -07006881 ProcessFramePacket(QuicFrame(window_update));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006882
6883 // Ensure that this has caused the ACK alarm to be set.
fayang9adfb532020-06-04 06:58:45 -07006884 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006885}
6886
6887TEST_P(QuicConnectionTest, BlockedFrameInstigateAcks) {
6888 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6889
6890 // Send a BLOCKED frame.
wub8a5dafa2020-05-13 12:30:17 -07006891 QuicBlockedFrame* blocked = new QuicBlockedFrame();
6892 blocked->stream_id = 3;
QUICHE teama6ef0a62019-03-07 20:34:33 -05006893 EXPECT_CALL(visitor_, OnBlockedFrame(_));
wub8a5dafa2020-05-13 12:30:17 -07006894 ProcessFramePacket(QuicFrame(blocked));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006895
6896 // Ensure that this has caused the ACK alarm to be set.
fayang9adfb532020-06-04 06:58:45 -07006897 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006898}
6899
6900TEST_P(QuicConnectionTest, ReevaluateTimeUntilSendOnAck) {
6901 // Enable pacing.
6902 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6903 QuicConfig config;
6904 connection_.SetFromConfig(config);
6905
6906 // Send two packets. One packet is not sufficient because if it gets acked,
6907 // there will be no packets in flight after that and the pacer will always
6908 // allow the next packet in that situation.
6909 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6910 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
6911 connection_.SendStreamDataWithString(
6912 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6913 0, NO_FIN);
6914 connection_.SendStreamDataWithString(
6915 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "bar",
6916 3, NO_FIN);
6917 connection_.OnCanWrite();
6918
6919 // Schedule the next packet for a few milliseconds in future.
6920 QuicSentPacketManagerPeer::DisablePacerBursts(manager_);
6921 QuicTime scheduled_pacing_time =
6922 clock_.Now() + QuicTime::Delta::FromMilliseconds(5);
6923 QuicSentPacketManagerPeer::SetNextPacedPacketTime(manager_,
6924 scheduled_pacing_time);
6925
6926 // Send a packet and have it be blocked by congestion control.
6927 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(false));
6928 connection_.SendStreamDataWithString(
6929 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "baz",
6930 6, NO_FIN);
6931 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
6932
6933 // Process an ack and the send alarm will be set to the new 5ms delay.
6934 QuicAckFrame ack = InitAckFrame(1);
6935 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
6936 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
6937 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
6938 ProcessAckPacket(&ack);
nharper55fa6132019-05-07 19:37:21 -07006939 size_t padding_frame_count = writer_->padding_frames().size();
6940 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006941 EXPECT_EQ(1u, writer_->stream_frames().size());
6942 EXPECT_TRUE(connection_.GetSendAlarm()->IsSet());
6943 EXPECT_EQ(scheduled_pacing_time, connection_.GetSendAlarm()->deadline());
6944 writer_->Reset();
6945}
6946
6947TEST_P(QuicConnectionTest, SendAcksImmediately) {
QUICHE teamcd098022019-03-22 18:49:55 -07006948 if (connection_.SupportsMultiplePacketNumberSpaces()) {
6949 return;
6950 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006951 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6952 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6953 ProcessDataPacket(1);
6954 CongestionBlockWrites();
6955 SendAckPacketToPeer();
6956}
6957
6958TEST_P(QuicConnectionTest, SendPingImmediately) {
6959 MockQuicConnectionDebugVisitor debug_visitor;
6960 connection_.set_debug_visitor(&debug_visitor);
6961
6962 CongestionBlockWrites();
fayang93cc53a2019-08-22 12:47:30 -07006963 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006964 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
wubacc7c972020-09-14 16:16:32 -07006965 if (connection_.sent_packet_manager()
6966 .give_sent_packet_to_debug_visitor_after_sent()) {
6967 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _)).Times(1);
6968 } else {
6969 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(1);
6970 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006971 EXPECT_CALL(debug_visitor, OnPingSent()).Times(1);
6972 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
6973 EXPECT_FALSE(connection_.HasQueuedData());
6974}
6975
6976TEST_P(QuicConnectionTest, SendBlockedImmediately) {
6977 MockQuicConnectionDebugVisitor debug_visitor;
6978 connection_.set_debug_visitor(&debug_visitor);
6979
fayang93cc53a2019-08-22 12:47:30 -07006980 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006981 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
wubacc7c972020-09-14 16:16:32 -07006982 if (connection_.sent_packet_manager()
6983 .give_sent_packet_to_debug_visitor_after_sent()) {
6984 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _)).Times(1);
6985 } else {
6986 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(1);
6987 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006988 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
6989 connection_.SendControlFrame(QuicFrame(new QuicBlockedFrame(1, 3)));
6990 EXPECT_EQ(1u, connection_.GetStats().blocked_frames_sent);
6991 EXPECT_FALSE(connection_.HasQueuedData());
6992}
6993
fayang93cc53a2019-08-22 12:47:30 -07006994TEST_P(QuicConnectionTest, FailedToSendBlockedFrames) {
6995 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
6996 return;
6997 }
6998 MockQuicConnectionDebugVisitor debug_visitor;
6999 connection_.set_debug_visitor(&debug_visitor);
7000 QuicBlockedFrame blocked(1, 3);
7001
7002 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
wubacc7c972020-09-14 16:16:32 -07007003 if (connection_.sent_packet_manager()
7004 .give_sent_packet_to_debug_visitor_after_sent()) {
7005 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _)).Times(0);
7006 } else {
7007 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(0);
7008 }
fayang93cc53a2019-08-22 12:47:30 -07007009 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7010 connection_.SendControlFrame(QuicFrame(&blocked));
7011 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7012 EXPECT_FALSE(connection_.HasQueuedData());
7013}
7014
QUICHE teama6ef0a62019-03-07 20:34:33 -05007015TEST_P(QuicConnectionTest, SendingUnencryptedStreamDataFails) {
7016 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
7017 if (!IsDefaultTestConfiguration()) {
7018 return;
7019 }
7020
fkastenholz5d880a92019-06-21 09:01:56 -07007021 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7022 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007023 struct iovec iov;
7024 MakeIOVector("", &iov);
7025 EXPECT_QUIC_BUG(connection_.SaveAndSendStreamData(3, &iov, 1, 0, 0, FIN),
fayang49523232019-05-03 06:28:22 -07007026 "Cannot send stream data with level: ENCRYPTION_INITIAL");
QUICHE teama6ef0a62019-03-07 20:34:33 -05007027 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07007028 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007029 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7030 IsError(QUIC_ATTEMPT_TO_SEND_UNENCRYPTED_STREAM_DATA));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007031}
7032
7033TEST_P(QuicConnectionTest, SetRetransmissionAlarmForCryptoPacket) {
7034 EXPECT_TRUE(connection_.connected());
7035 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
7036
7037 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7038 connection_.SendCryptoStreamData();
7039
7040 // Verify retransmission timer is correctly set after crypto packet has been
7041 // sent.
7042 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
7043 QuicTime retransmission_time =
7044 QuicConnectionPeer::GetSentPacketManager(&connection_)
7045 ->GetRetransmissionTime();
7046 EXPECT_NE(retransmission_time, clock_.ApproximateNow());
7047 EXPECT_EQ(retransmission_time,
7048 connection_.GetRetransmissionAlarm()->deadline());
7049
7050 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7051 connection_.GetRetransmissionAlarm()->Fire();
7052}
7053
vasilvv693d5b02019-04-09 21:58:56 -07007054// Includes regression test for b/69979024.
zhongyi3ae832d2020-06-15 13:03:31 -07007055TEST_P(QuicConnectionTest, PathDegradingDetectionForNonCryptoPackets) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007056 EXPECT_TRUE(connection_.connected());
fayangb59c6f12020-03-23 15:06:14 -07007057 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007058 EXPECT_FALSE(connection_.IsPathDegrading());
7059
7060 const char data[] = "data";
7061 size_t data_size = strlen(data);
7062 QuicStreamOffset offset = 0;
7063
7064 for (int i = 0; i < 2; ++i) {
7065 // Send a packet. Now there's a retransmittable packet on the wire, so the
zhongyi3ae832d2020-06-15 13:03:31 -07007066 // path degrading detection should be set.
QUICHE teama6ef0a62019-03-07 20:34:33 -05007067 connection_.SendStreamDataWithString(
7068 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
7069 offset, NO_FIN);
7070 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07007071 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
zhongyi3ae832d2020-06-15 13:03:31 -07007072 // Check the deadline of the path degrading detection.
QUICHE teama6ef0a62019-03-07 20:34:33 -05007073 QuicTime::Delta delay =
7074 QuicConnectionPeer::GetSentPacketManager(&connection_)
7075 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07007076 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7077 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007078
zhongyi3ae832d2020-06-15 13:03:31 -07007079 // Send a second packet. The path degrading detection's deadline should
7080 // remain the same.
vasilvv693d5b02019-04-09 21:58:56 -07007081 // Regression test for b/69979024.
QUICHE teama6ef0a62019-03-07 20:34:33 -05007082 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
fayang2205d952020-05-12 13:45:56 -07007083 QuicTime prev_deadline =
7084 connection_.GetBlackholeDetectorAlarm()->deadline();
QUICHE teama6ef0a62019-03-07 20:34:33 -05007085 connection_.SendStreamDataWithString(
7086 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
7087 offset, NO_FIN);
7088 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07007089 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
fayang2205d952020-05-12 13:45:56 -07007090 EXPECT_EQ(prev_deadline,
7091 connection_.GetBlackholeDetectorAlarm()->deadline());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007092
7093 // Now receive an ACK of the first packet. This should advance the path
zhongyi3ae832d2020-06-15 13:03:31 -07007094 // degrading detection's deadline since forward progress has been made.
QUICHE teama6ef0a62019-03-07 20:34:33 -05007095 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7096 if (i == 0) {
7097 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7098 }
7099 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7100 QuicAckFrame frame = InitAckFrame(
7101 {{QuicPacketNumber(1u + 2u * i), QuicPacketNumber(2u + 2u * i)}});
7102 ProcessAckPacket(&frame);
fayangb59c6f12020-03-23 15:06:14 -07007103 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
zhongyi3ae832d2020-06-15 13:03:31 -07007104 // Check the deadline of the path degrading detection.
QUICHE teama6ef0a62019-03-07 20:34:33 -05007105 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7106 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07007107 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7108 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007109
7110 if (i == 0) {
7111 // Now receive an ACK of the second packet. Since there are no more
7112 // retransmittable packets on the wire, this should cancel the path
zhongyi3ae832d2020-06-15 13:03:31 -07007113 // degrading detection.
QUICHE teama6ef0a62019-03-07 20:34:33 -05007114 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7115 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7116 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
7117 ProcessAckPacket(&frame);
fayangb59c6f12020-03-23 15:06:14 -07007118 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007119 } else {
7120 // Advance time to the path degrading alarm's deadline and simulate
7121 // firing the alarm.
7122 clock_.AdvanceTime(delay);
7123 EXPECT_CALL(visitor_, OnPathDegrading());
fayangb59c6f12020-03-23 15:06:14 -07007124 connection_.PathDegradingTimeout();
7125 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007126 }
7127 }
7128 EXPECT_TRUE(connection_.IsPathDegrading());
7129}
7130
7131TEST_P(QuicConnectionTest, RetransmittableOnWireSetsPingAlarm) {
7132 const QuicTime::Delta retransmittable_on_wire_timeout =
7133 QuicTime::Delta::FromMilliseconds(50);
zhongyi79ace162019-10-21 15:57:09 -07007134 connection_.set_initial_retransmittable_on_wire_timeout(
QUICHE teama6ef0a62019-03-07 20:34:33 -05007135 retransmittable_on_wire_timeout);
7136
7137 EXPECT_TRUE(connection_.connected());
7138 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7139 .WillRepeatedly(Return(true));
7140
fayangb59c6f12020-03-23 15:06:14 -07007141 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007142 EXPECT_FALSE(connection_.IsPathDegrading());
7143 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
7144
7145 const char data[] = "data";
7146 size_t data_size = strlen(data);
7147 QuicStreamOffset offset = 0;
7148
7149 // Send a packet.
7150 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7151 offset += data_size;
7152 // Now there's a retransmittable packet on the wire, so the path degrading
7153 // alarm should be set.
7154 // The retransmittable-on-wire alarm should not be set.
fayangb59c6f12020-03-23 15:06:14 -07007155 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007156 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7157 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07007158 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7159 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007160 ASSERT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
7161 // The ping alarm is set for the ping timeout, not the shorter
7162 // retransmittable_on_wire_timeout.
7163 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7164 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
zhongyieef848f2019-10-18 07:09:37 -07007165 EXPECT_EQ(ping_delay,
7166 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007167
7168 // Now receive an ACK of the packet.
7169 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7170 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7171 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7172 QuicAckFrame frame =
7173 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7174 ProcessAckPacket(&frame);
7175 // No more retransmittable packets on the wire, so the path degrading alarm
7176 // should be cancelled, and the ping alarm should be set to the
7177 // retransmittable_on_wire_timeout.
fayangb59c6f12020-03-23 15:06:14 -07007178 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007179 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07007180 EXPECT_EQ(retransmittable_on_wire_timeout,
7181 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007182
7183 // Simulate firing the ping alarm and sending a PING.
7184 clock_.AdvanceTime(retransmittable_on_wire_timeout);
fayangec14d2b2020-10-02 12:00:05 -07007185 if (!GetQuicReloadableFlag(quic_let_connection_handle_pings)) {
7186 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
7187 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
7188 }));
7189 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007190 connection_.GetPingAlarm()->Fire();
7191
7192 // Now there's a retransmittable packet (PING) on the wire, so the path
7193 // degrading alarm should be set.
fayangb59c6f12020-03-23 15:06:14 -07007194 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007195 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7196 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07007197 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7198 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007199}
7200
7201// This test verifies that the connection marks path as degrading and does not
7202// spin timer to detect path degrading when a new packet is sent on the
7203// degraded path.
zhongyi3ae832d2020-06-15 13:03:31 -07007204TEST_P(QuicConnectionTest, NoPathDegradingDetectionIfPathIsDegrading) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007205 EXPECT_TRUE(connection_.connected());
fayangb59c6f12020-03-23 15:06:14 -07007206 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007207 EXPECT_FALSE(connection_.IsPathDegrading());
7208
7209 const char data[] = "data";
7210 size_t data_size = strlen(data);
7211 QuicStreamOffset offset = 0;
7212
7213 // Send the first packet. Now there's a retransmittable packet on the wire, so
7214 // the path degrading alarm should be set.
7215 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7216 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07007217 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
zhongyi3ae832d2020-06-15 13:03:31 -07007218 // Check the deadline of the path degrading detection.
QUICHE teama6ef0a62019-03-07 20:34:33 -05007219 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7220 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07007221 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7222 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007223
zhongyi3ae832d2020-06-15 13:03:31 -07007224 // Send a second packet. The path degrading detection's deadline should remain
QUICHE teama6ef0a62019-03-07 20:34:33 -05007225 // the same.
7226 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
fayang2205d952020-05-12 13:45:56 -07007227 QuicTime prev_deadline = connection_.GetBlackholeDetectorAlarm()->deadline();
QUICHE teama6ef0a62019-03-07 20:34:33 -05007228 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7229 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07007230 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
fayang2205d952020-05-12 13:45:56 -07007231 EXPECT_EQ(prev_deadline, connection_.GetBlackholeDetectorAlarm()->deadline());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007232
7233 // Now receive an ACK of the first packet. This should advance the path
zhongyi3ae832d2020-06-15 13:03:31 -07007234 // degrading detection's deadline since forward progress has been made.
QUICHE teama6ef0a62019-03-07 20:34:33 -05007235 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7236 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7237 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7238 QuicAckFrame frame =
7239 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
7240 ProcessAckPacket(&frame);
fayangb59c6f12020-03-23 15:06:14 -07007241 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007242 // Check the deadline of the path degrading alarm.
7243 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7244 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07007245 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7246 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007247
zhongyi3ae832d2020-06-15 13:03:31 -07007248 // Advance time to the path degrading detection's deadline and simulate
7249 // firing the path degrading detection. This path will be considered as
QUICHE teama6ef0a62019-03-07 20:34:33 -05007250 // degrading.
7251 clock_.AdvanceTime(delay);
7252 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
fayangb59c6f12020-03-23 15:06:14 -07007253 connection_.PathDegradingTimeout();
7254 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007255 EXPECT_TRUE(connection_.IsPathDegrading());
7256
7257 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
fayangb59c6f12020-03-23 15:06:14 -07007258 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
zhongyi3ae832d2020-06-15 13:03:31 -07007259 // Send a third packet. The path degrading detection is no longer set but path
QUICHE teama6ef0a62019-03-07 20:34:33 -05007260 // should still be marked as degrading.
7261 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7262 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07007263 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007264 EXPECT_TRUE(connection_.IsPathDegrading());
7265}
7266
7267// This test verifies that the connection unmarks path as degrarding and spins
7268// the timer to detect future path degrading when forward progress is made
7269// after path has been marked degrading.
7270TEST_P(QuicConnectionTest, UnmarkPathDegradingOnForwardProgress) {
7271 EXPECT_TRUE(connection_.connected());
fayangb59c6f12020-03-23 15:06:14 -07007272 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007273 EXPECT_FALSE(connection_.IsPathDegrading());
7274
7275 const char data[] = "data";
7276 size_t data_size = strlen(data);
7277 QuicStreamOffset offset = 0;
7278
7279 // Send the first packet. Now there's a retransmittable packet on the wire, so
7280 // the path degrading alarm should be set.
7281 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7282 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07007283 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007284 // Check the deadline of the path degrading alarm.
7285 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7286 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07007287 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7288 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007289
7290 // Send a second packet. The path degrading alarm's deadline should remain
7291 // the same.
7292 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
fayang2205d952020-05-12 13:45:56 -07007293 QuicTime prev_deadline = connection_.GetBlackholeDetectorAlarm()->deadline();
QUICHE teama6ef0a62019-03-07 20:34:33 -05007294 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7295 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07007296 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
fayang2205d952020-05-12 13:45:56 -07007297 EXPECT_EQ(prev_deadline, connection_.GetBlackholeDetectorAlarm()->deadline());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007298
7299 // Now receive an ACK of the first packet. This should advance the path
7300 // degrading alarm's deadline since forward progress has been made.
7301 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7302 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7303 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7304 QuicAckFrame frame =
7305 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
7306 ProcessAckPacket(&frame);
fayangb59c6f12020-03-23 15:06:14 -07007307 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007308 // Check the deadline of the path degrading alarm.
7309 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7310 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07007311 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7312 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007313
7314 // Advance time to the path degrading alarm's deadline and simulate
7315 // firing the alarm.
7316 clock_.AdvanceTime(delay);
7317 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
fayangb59c6f12020-03-23 15:06:14 -07007318 connection_.PathDegradingTimeout();
7319 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007320 EXPECT_TRUE(connection_.IsPathDegrading());
7321
7322 // Send a third packet. The path degrading alarm is no longer set but path
7323 // should still be marked as degrading.
7324 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
fayangb59c6f12020-03-23 15:06:14 -07007325 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007326 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7327 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07007328 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007329 EXPECT_TRUE(connection_.IsPathDegrading());
7330
7331 // Now receive an ACK of the second packet. This should unmark the path as
7332 // degrading. And will set a timer to detect new path degrading.
7333 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7334 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
zhongyief1d6752020-06-11 16:19:28 -07007335 EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading()).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007336 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
7337 ProcessAckPacket(&frame);
7338 EXPECT_FALSE(connection_.IsPathDegrading());
fayangb59c6f12020-03-23 15:06:14 -07007339 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007340}
7341
7342TEST_P(QuicConnectionTest, NoPathDegradingOnServer) {
QUICHE teamcd098022019-03-22 18:49:55 -07007343 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7344 return;
7345 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007346 set_perspective(Perspective::IS_SERVER);
7347 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
7348
7349 EXPECT_FALSE(connection_.IsPathDegrading());
fayangb59c6f12020-03-23 15:06:14 -07007350 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007351
7352 // Send data.
7353 const char data[] = "data";
7354 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
7355 EXPECT_FALSE(connection_.IsPathDegrading());
fayangb59c6f12020-03-23 15:06:14 -07007356 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007357
7358 // Ack data.
7359 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007360 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7361 QuicAckFrame frame =
7362 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
7363 ProcessAckPacket(&frame);
7364 EXPECT_FALSE(connection_.IsPathDegrading());
fayangb59c6f12020-03-23 15:06:14 -07007365 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007366}
7367
7368TEST_P(QuicConnectionTest, NoPathDegradingAfterSendingAck) {
QUICHE teamcd098022019-03-22 18:49:55 -07007369 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7370 return;
7371 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007372 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7373 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7374 ProcessDataPacket(1);
7375 SendAckPacketToPeer();
7376 EXPECT_FALSE(connection_.sent_packet_manager().unacked_packets().empty());
7377 EXPECT_FALSE(connection_.sent_packet_manager().HasInFlightPackets());
7378 EXPECT_FALSE(connection_.IsPathDegrading());
fayangb59c6f12020-03-23 15:06:14 -07007379 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007380}
7381
7382TEST_P(QuicConnectionTest, MultipleCallsToCloseConnection) {
7383 // Verifies that multiple calls to CloseConnection do not
7384 // result in multiple attempts to close the connection - it will be marked as
7385 // disconnected after the first call.
fkastenholz5d880a92019-06-21 09:01:56 -07007386 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007387 connection_.CloseConnection(QUIC_NO_ERROR, "no reason",
7388 ConnectionCloseBehavior::SILENT_CLOSE);
7389 connection_.CloseConnection(QUIC_NO_ERROR, "no reason",
7390 ConnectionCloseBehavior::SILENT_CLOSE);
7391}
7392
7393TEST_P(QuicConnectionTest, ServerReceivesChloOnNonCryptoStream) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007394 set_perspective(Perspective::IS_SERVER);
7395 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
7396
7397 CryptoHandshakeMessage message;
7398 CryptoFramer framer;
7399 message.set_tag(kCHLO);
QUICHE team3fe6a8b2019-03-14 09:10:38 -07007400 std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007401 frame1_.stream_id = 10;
7402 frame1_.data_buffer = data->data();
7403 frame1_.data_length = data->length();
7404
fkastenholz5d880a92019-06-21 09:01:56 -07007405 EXPECT_CALL(visitor_,
7406 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007407 ForceProcessFramePacket(QuicFrame(frame1_));
fkastenholz5d880a92019-06-21 09:01:56 -07007408 TestConnectionCloseQuicErrorCode(QUIC_MAYBE_CORRUPTED_MEMORY);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007409}
7410
7411TEST_P(QuicConnectionTest, ClientReceivesRejOnNonCryptoStream) {
7412 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7413
7414 CryptoHandshakeMessage message;
7415 CryptoFramer framer;
7416 message.set_tag(kREJ);
QUICHE team3fe6a8b2019-03-14 09:10:38 -07007417 std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007418 frame1_.stream_id = 10;
7419 frame1_.data_buffer = data->data();
7420 frame1_.data_length = data->length();
7421
fkastenholz5d880a92019-06-21 09:01:56 -07007422 EXPECT_CALL(visitor_,
7423 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007424 ForceProcessFramePacket(QuicFrame(frame1_));
fkastenholz5d880a92019-06-21 09:01:56 -07007425 TestConnectionCloseQuicErrorCode(QUIC_MAYBE_CORRUPTED_MEMORY);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007426}
7427
7428TEST_P(QuicConnectionTest, CloseConnectionOnPacketTooLarge) {
7429 SimulateNextPacketTooLarge();
7430 // A connection close packet is sent
fkastenholz5d880a92019-06-21 09:01:56 -07007431 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
QUICHE teama6ef0a62019-03-07 20:34:33 -05007432 .Times(1);
7433 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
fkastenholz5d880a92019-06-21 09:01:56 -07007434 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007435}
7436
7437TEST_P(QuicConnectionTest, AlwaysGetPacketTooLarge) {
7438 // Test even we always get packet too large, we do not infinitely try to send
7439 // close packet.
7440 AlwaysGetPacketTooLarge();
fkastenholz5d880a92019-06-21 09:01:56 -07007441 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
QUICHE teama6ef0a62019-03-07 20:34:33 -05007442 .Times(1);
7443 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
fkastenholz5d880a92019-06-21 09:01:56 -07007444 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007445}
7446
nharperef468962019-07-02 14:15:38 -07007447TEST_P(QuicConnectionTest, CloseConnectionOnQueuedWriteError) {
nharperef468962019-07-02 14:15:38 -07007448 // Regression test for crbug.com/979507.
7449 //
7450 // If we get a write error when writing queued packets, we should attempt to
7451 // send a connection close packet, but if sending that fails, it shouldn't get
7452 // queued.
7453
7454 // Queue a packet to write.
7455 BlockOnNextWrite();
7456 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7457 EXPECT_EQ(1u, connection_.NumQueuedPackets());
7458
7459 // Configure writer to always fail.
7460 AlwaysGetPacketTooLarge();
7461
7462 // Expect that we attempt to close the connection exactly once.
7463 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7464 .Times(1);
7465
7466 // Unblock the writes and actually send.
7467 writer_->SetWritable();
7468 connection_.OnCanWrite();
7469 EXPECT_EQ(0u, connection_.NumQueuedPackets());
7470
7471 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
7472}
7473
QUICHE teama6ef0a62019-03-07 20:34:33 -05007474// Verify that if connection has no outstanding data, it notifies the send
7475// algorithm after the write.
7476TEST_P(QuicConnectionTest, SendDataAndBecomeApplicationLimited) {
7477 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
7478 {
7479 InSequence seq;
7480 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7481 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7482 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
7483 .WillRepeatedly(Return(false));
7484 }
7485
7486 connection_.SendStreamData3();
7487}
7488
7489// Verify that the connection does not become app-limited if there is
7490// outstanding data to send after the write.
7491TEST_P(QuicConnectionTest, NotBecomeApplicationLimitedIfMoreDataAvailable) {
7492 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
7493 {
7494 InSequence seq;
7495 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7496 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7497 }
7498
7499 connection_.SendStreamData3();
7500}
7501
7502// Verify that the connection does not become app-limited after blocked write
7503// even if there is outstanding data to send after the write.
7504TEST_P(QuicConnectionTest, NotBecomeApplicationLimitedDueToWriteBlock) {
7505 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
7506 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7507 BlockOnNextWrite();
7508
fayange62e63c2019-12-04 07:16:25 -08007509 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007510 connection_.SendStreamData3();
7511
7512 // Now unblock the writer, become congestion control blocked,
7513 // and ensure we become app-limited after writing.
7514 writer_->SetWritable();
7515 CongestionBlockWrites();
7516 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(false));
fayange62e63c2019-12-04 07:16:25 -08007517 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
fayang2ce66082019-10-02 06:29:04 -07007518 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007519 connection_.OnCanWrite();
7520}
7521
7522// Test the mode in which the link is filled up with probing retransmissions if
7523// the connection becomes application-limited.
7524TEST_P(QuicConnectionTest, SendDataWhenApplicationLimited) {
7525 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7526 EXPECT_CALL(*send_algorithm_, ShouldSendProbingPacket())
7527 .WillRepeatedly(Return(true));
7528 {
7529 InSequence seq;
7530 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7531 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7532 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
7533 .WillRepeatedly(Return(false));
7534 }
QUICHE teamb8343252019-04-29 13:58:01 -07007535 EXPECT_CALL(visitor_, SendProbingData()).WillRepeatedly([this] {
7536 return connection_.sent_packet_manager().MaybeRetransmitOldestPacket(
7537 PROBING_RETRANSMISSION);
7538 });
QUICHE teama6ef0a62019-03-07 20:34:33 -05007539 // Fix congestion window to be 20,000 bytes.
7540 EXPECT_CALL(*send_algorithm_, CanSend(Ge(20000u)))
7541 .WillRepeatedly(Return(false));
7542 EXPECT_CALL(*send_algorithm_, CanSend(Lt(20000u)))
7543 .WillRepeatedly(Return(true));
7544
7545 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
7546 ASSERT_EQ(0u, connection_.GetStats().packets_sent);
7547 connection_.set_fill_up_link_during_probing(true);
fayangedf9ad52020-03-05 13:49:18 -08007548 EXPECT_CALL(visitor_, GetHandshakeState())
fayang15042962020-07-01 12:14:29 -07007549 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007550 connection_.OnHandshakeComplete();
7551 connection_.SendStreamData3();
7552
7553 // We expect a lot of packets from a 20 kbyte window.
7554 EXPECT_GT(connection_.GetStats().packets_sent, 10u);
7555 // Ensure that the packets are padded.
7556 QuicByteCount average_packet_size =
7557 connection_.GetStats().bytes_sent / connection_.GetStats().packets_sent;
7558 EXPECT_GT(average_packet_size, 1000u);
7559
7560 // Acknowledge all packets sent, except for the last one.
7561 QuicAckFrame ack = InitAckFrame(
7562 connection_.sent_packet_manager().GetLargestSentPacket() - 1);
7563 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
7564 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7565
7566 // Ensure that since we no longer have retransmittable bytes in flight, this
7567 // will not cause any responses to be sent.
7568 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
7569 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
7570 ProcessAckPacket(&ack);
7571}
7572
rchd672c6d2019-11-27 15:30:54 -08007573TEST_P(QuicConnectionTest, DoNotForceSendingAckOnPacketTooLarge) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007574 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7575 // Send an ack by simulating delayed ack alarm firing.
7576 ProcessPacket(1);
fayang9adfb532020-06-04 06:58:45 -07007577 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007578 connection_.GetAckAlarm()->Fire();
7579 // Simulate data packet causes write error.
fkastenholz5d880a92019-06-21 09:01:56 -07007580 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007581 SimulateNextPacketTooLarge();
7582 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
rchd672c6d2019-11-27 15:30:54 -08007583 EXPECT_EQ(1u, writer_->connection_close_frames().size());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007584 // Ack frame is not bundled in connection close packet.
7585 EXPECT_TRUE(writer_->ack_frames().empty());
rchd672c6d2019-11-27 15:30:54 -08007586 if (writer_->padding_frames().empty()) {
7587 EXPECT_EQ(1u, writer_->frame_count());
7588 } else {
7589 EXPECT_EQ(2u, writer_->frame_count());
7590 }
7591
fkastenholz5d880a92019-06-21 09:01:56 -07007592 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007593}
7594
rchd672c6d2019-11-27 15:30:54 -08007595TEST_P(QuicConnectionTest, CloseConnectionAllLevels) {
fayangc303bfd2020-02-11 09:19:54 -08007596 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
7597 return;
7598 }
rchd672c6d2019-11-27 15:30:54 -08007599
7600 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
7601 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
7602 connection_.CloseConnection(
7603 kQuicErrorCode, "Some random error message",
7604 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
7605
7606 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
7607
7608 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
7609 EXPECT_EQ(1u, writer_->connection_close_frames().size());
7610
7611 if (!connection_.version().CanSendCoalescedPackets()) {
7612 // Each connection close packet should be sent in distinct UDP packets.
7613 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
7614 writer_->connection_close_packets());
7615 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
7616 writer_->packets_write_attempts());
7617 return;
7618 }
7619
7620 // A single UDP packet should be sent with multiple connection close packets
7621 // coalesced together.
7622 EXPECT_EQ(1u, writer_->packets_write_attempts());
7623
7624 // Only the first packet has been processed yet.
7625 EXPECT_EQ(1u, writer_->connection_close_packets());
7626
7627 // ProcessPacket resets the visitor and frees the coalesced packet.
7628 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
7629 auto packet = writer_->coalesced_packet()->Clone();
7630 writer_->framer()->ProcessPacket(*packet);
7631 EXPECT_EQ(1u, writer_->connection_close_packets());
7632 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
7633}
7634
7635TEST_P(QuicConnectionTest, CloseConnectionOneLevel) {
fayangc303bfd2020-02-11 09:19:54 -08007636 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7637 return;
7638 }
rchd672c6d2019-11-27 15:30:54 -08007639
7640 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
7641 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
7642 connection_.CloseConnection(
7643 kQuicErrorCode, "Some random error message",
7644 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
7645
7646 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
7647
7648 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
7649 EXPECT_EQ(1u, writer_->connection_close_frames().size());
7650 EXPECT_EQ(1u, writer_->connection_close_packets());
7651 EXPECT_EQ(1u, writer_->packets_write_attempts());
7652 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
7653}
7654
fayang9abdfec2020-02-13 12:34:58 -08007655TEST_P(QuicConnectionTest, DoNotPadServerInitialConnectionClose) {
7656 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
7657 return;
7658 }
7659 set_perspective(Perspective::IS_SERVER);
7660
7661 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
7662 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
7663 connection_.CloseConnection(
7664 kQuicErrorCode, "Some random error message",
7665 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
7666
7667 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
7668
7669 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
7670 EXPECT_EQ(1u, writer_->connection_close_frames().size());
7671 EXPECT_TRUE(writer_->padding_frames().empty());
7672 EXPECT_EQ(ENCRYPTION_INITIAL, writer_->framer()->last_decrypted_level());
7673}
7674
QUICHE teama6ef0a62019-03-07 20:34:33 -05007675// Regression test for b/63620844.
7676TEST_P(QuicConnectionTest, FailedToWriteHandshakePacket) {
7677 SimulateNextPacketTooLarge();
fkastenholz5d880a92019-06-21 09:01:56 -07007678 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
QUICHE teama6ef0a62019-03-07 20:34:33 -05007679 .Times(1);
fkastenholz5d880a92019-06-21 09:01:56 -07007680
QUICHE teama6ef0a62019-03-07 20:34:33 -05007681 connection_.SendCryptoStreamData();
fkastenholz5d880a92019-06-21 09:01:56 -07007682 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007683}
7684
7685TEST_P(QuicConnectionTest, MaxPacingRate) {
7686 EXPECT_EQ(0, connection_.MaxPacingRate().ToBytesPerSecond());
7687 connection_.SetMaxPacingRate(QuicBandwidth::FromBytesPerSecond(100));
7688 EXPECT_EQ(100, connection_.MaxPacingRate().ToBytesPerSecond());
7689}
7690
7691TEST_P(QuicConnectionTest, ClientAlwaysSendConnectionId) {
7692 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
7693 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7694 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7695 EXPECT_EQ(CONNECTION_ID_PRESENT,
7696 writer_->last_packet_header().destination_connection_id_included);
7697
7698 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7699 QuicConfig config;
7700 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
7701 connection_.SetFromConfig(config);
7702
7703 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7704 connection_.SendStreamDataWithString(3, "bar", 3, NO_FIN);
7705 // Verify connection id is still sent in the packet.
7706 EXPECT_EQ(CONNECTION_ID_PRESENT,
7707 writer_->last_packet_header().destination_connection_id_included);
7708}
7709
7710TEST_P(QuicConnectionTest, SendProbingRetransmissions) {
7711 MockQuicConnectionDebugVisitor debug_visitor;
7712 connection_.set_debug_visitor(&debug_visitor);
7713
7714 const QuicStreamId stream_id = 2;
7715 QuicPacketNumber last_packet;
7716 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
7717 SendStreamDataToPeer(stream_id, "bar", 3, NO_FIN, &last_packet);
7718 SendStreamDataToPeer(stream_id, "test", 6, NO_FIN, &last_packet);
7719
7720 const QuicByteCount old_bytes_in_flight =
7721 connection_.sent_packet_manager().GetBytesInFlight();
7722
7723 // Allow 9 probing retransmissions to be sent.
7724 {
7725 InSequence seq;
7726 EXPECT_CALL(*send_algorithm_, CanSend(_))
7727 .Times(9 * 2)
7728 .WillRepeatedly(Return(true));
7729 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(Return(false));
7730 }
7731 // Expect them retransmitted in cyclic order (foo, bar, test, foo, bar...).
7732 QuicPacketCount sent_count = 0;
wubacc7c972020-09-14 16:16:32 -07007733 if (connection_.sent_packet_manager()
7734 .give_sent_packet_to_debug_visitor_after_sent()) {
7735 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _))
7736 .WillRepeatedly(
7737 Invoke([this, &sent_count](QuicPacketNumber, QuicPacketLength, bool,
7738 TransmissionType, EncryptionLevel,
7739 const QuicFrames&, const QuicFrames&,
7740 QuicTime) {
7741 ASSERT_EQ(1u, writer_->stream_frames().size());
7742 if (connection_.version().CanSendCoalescedPackets()) {
7743 // There is a delay of sending coalesced packet, so (6, 0, 3, 6,
7744 // 0...).
7745 EXPECT_EQ(3 * ((sent_count + 2) % 3),
7746 writer_->stream_frames()[0]->offset);
7747 } else {
7748 // Identify the frames by stream offset (0, 3, 6, 0, 3...).
7749 EXPECT_EQ(3 * (sent_count % 3),
7750 writer_->stream_frames()[0]->offset);
7751 }
7752 sent_count++;
7753 }));
7754 } else {
7755 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _))
7756 .WillRepeatedly(Invoke([this, &sent_count](const SerializedPacket&,
7757 TransmissionType, QuicTime) {
7758 ASSERT_EQ(1u, writer_->stream_frames().size());
7759 if (connection_.version().CanSendCoalescedPackets()) {
7760 // There is a delay of sending coalesced packet, so (6, 0, 3, 6,
7761 // 0...).
7762 EXPECT_EQ(3 * ((sent_count + 2) % 3),
7763 writer_->stream_frames()[0]->offset);
7764 } else {
7765 // Identify the frames by stream offset (0, 3, 6, 0, 3...).
7766 EXPECT_EQ(3 * (sent_count % 3),
7767 writer_->stream_frames()[0]->offset);
7768 }
7769 sent_count++;
7770 }));
7771 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007772 EXPECT_CALL(*send_algorithm_, ShouldSendProbingPacket())
7773 .WillRepeatedly(Return(true));
QUICHE teamb8343252019-04-29 13:58:01 -07007774 EXPECT_CALL(visitor_, SendProbingData()).WillRepeatedly([this] {
7775 return connection_.sent_packet_manager().MaybeRetransmitOldestPacket(
7776 PROBING_RETRANSMISSION);
7777 });
QUICHE teama6ef0a62019-03-07 20:34:33 -05007778
7779 connection_.SendProbingRetransmissions();
7780
7781 // Ensure that the in-flight has increased.
7782 const QuicByteCount new_bytes_in_flight =
7783 connection_.sent_packet_manager().GetBytesInFlight();
7784 EXPECT_GT(new_bytes_in_flight, old_bytes_in_flight);
7785}
7786
7787// Ensure that SendProbingRetransmissions() does not retransmit anything when
7788// there are no outstanding packets.
7789TEST_P(QuicConnectionTest,
7790 SendProbingRetransmissionsFailsWhenNothingToRetransmit) {
7791 ASSERT_TRUE(connection_.sent_packet_manager().unacked_packets().empty());
7792
7793 MockQuicConnectionDebugVisitor debug_visitor;
7794 connection_.set_debug_visitor(&debug_visitor);
wubacc7c972020-09-14 16:16:32 -07007795 if (connection_.sent_packet_manager()
7796 .give_sent_packet_to_debug_visitor_after_sent()) {
7797 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _)).Times(0);
7798 } else {
7799 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(0);
7800 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007801 EXPECT_CALL(*send_algorithm_, ShouldSendProbingPacket())
7802 .WillRepeatedly(Return(true));
QUICHE teamb8343252019-04-29 13:58:01 -07007803 EXPECT_CALL(visitor_, SendProbingData()).WillRepeatedly([this] {
7804 return connection_.sent_packet_manager().MaybeRetransmitOldestPacket(
7805 PROBING_RETRANSMISSION);
7806 });
QUICHE teama6ef0a62019-03-07 20:34:33 -05007807
7808 connection_.SendProbingRetransmissions();
7809}
7810
7811TEST_P(QuicConnectionTest, PingAfterLastRetransmittablePacketAcked) {
7812 const QuicTime::Delta retransmittable_on_wire_timeout =
7813 QuicTime::Delta::FromMilliseconds(50);
zhongyi79ace162019-10-21 15:57:09 -07007814 connection_.set_initial_retransmittable_on_wire_timeout(
QUICHE teama6ef0a62019-03-07 20:34:33 -05007815 retransmittable_on_wire_timeout);
7816
7817 EXPECT_TRUE(connection_.connected());
7818 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7819 .WillRepeatedly(Return(true));
7820
7821 const char data[] = "data";
7822 size_t data_size = strlen(data);
7823 QuicStreamOffset offset = 0;
7824
7825 // Advance 5ms, send a retransmittable packet to the peer.
7826 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7827 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
7828 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7829 offset += data_size;
7830 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
7831 // The ping alarm is set for the ping timeout, not the shorter
7832 // retransmittable_on_wire_timeout.
7833 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7834 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
zhongyieef848f2019-10-18 07:09:37 -07007835 EXPECT_EQ(ping_delay,
7836 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007837
7838 // Advance 5ms, send a second retransmittable packet to the peer.
7839 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7840 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7841 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7842 offset += data_size;
7843 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7844
7845 // Now receive an ACK of the first packet. This should not set the
7846 // retransmittable-on-wire alarm since packet 2 is still on the wire.
7847 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7848 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7849 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7850 QuicAckFrame frame =
7851 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7852 ProcessAckPacket(&frame);
7853 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
7854 // The ping alarm is set for the ping timeout, not the shorter
7855 // retransmittable_on_wire_timeout.
7856 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7857 // The ping alarm has a 1 second granularity, and the clock has been advanced
7858 // 10ms since it was originally set.
zhongyieef848f2019-10-18 07:09:37 -07007859 EXPECT_EQ(ping_delay - QuicTime::Delta::FromMilliseconds(10),
7860 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007861
7862 // Now receive an ACK of the second packet. This should set the
7863 // retransmittable-on-wire alarm now that no retransmittable packets are on
7864 // the wire.
7865 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7866 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7867 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
7868 ProcessAckPacket(&frame);
7869 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07007870 EXPECT_EQ(retransmittable_on_wire_timeout,
7871 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007872
7873 // Now receive a duplicate ACK of the second packet. This should not update
7874 // the ping alarm.
7875 QuicTime prev_deadline = connection_.GetPingAlarm()->deadline();
7876 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7877 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
7878 ProcessAckPacket(&frame);
7879 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7880 EXPECT_EQ(prev_deadline, connection_.GetPingAlarm()->deadline());
7881
7882 // Now receive a non-ACK packet. This should not update the ping alarm.
7883 prev_deadline = connection_.GetPingAlarm()->deadline();
7884 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7885 ProcessPacket(4);
7886 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7887 EXPECT_EQ(prev_deadline, connection_.GetPingAlarm()->deadline());
7888
7889 // Simulate the alarm firing and check that a PING is sent.
fayangec14d2b2020-10-02 12:00:05 -07007890 if (!GetQuicReloadableFlag(quic_let_connection_handle_pings)) {
7891 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
7892 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
7893 }));
7894 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007895 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07007896 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05007897 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07007898 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007899 } else {
nharper55fa6132019-05-07 19:37:21 -07007900 EXPECT_EQ(padding_frame_count + 3u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007901 }
7902 ASSERT_EQ(1u, writer_->ping_frames().size());
7903}
7904
7905TEST_P(QuicConnectionTest, NoPingIfRetransmittablePacketSent) {
7906 const QuicTime::Delta retransmittable_on_wire_timeout =
7907 QuicTime::Delta::FromMilliseconds(50);
zhongyi79ace162019-10-21 15:57:09 -07007908 connection_.set_initial_retransmittable_on_wire_timeout(
QUICHE teama6ef0a62019-03-07 20:34:33 -05007909 retransmittable_on_wire_timeout);
7910
7911 EXPECT_TRUE(connection_.connected());
7912 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7913 .WillRepeatedly(Return(true));
7914
7915 const char data[] = "data";
7916 size_t data_size = strlen(data);
7917 QuicStreamOffset offset = 0;
7918
7919 // Advance 5ms, send a retransmittable packet to the peer.
7920 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7921 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
7922 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7923 offset += data_size;
7924 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
7925 // The ping alarm is set for the ping timeout, not the shorter
7926 // retransmittable_on_wire_timeout.
7927 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7928 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
zhongyieef848f2019-10-18 07:09:37 -07007929 EXPECT_EQ(ping_delay,
7930 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007931
7932 // Now receive an ACK of the first packet. This should set the
7933 // retransmittable-on-wire alarm now that no retransmittable packets are on
7934 // the wire.
7935 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7936 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7937 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7938 QuicAckFrame frame =
7939 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7940 ProcessAckPacket(&frame);
7941 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07007942 EXPECT_EQ(retransmittable_on_wire_timeout,
7943 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007944
7945 // Before the alarm fires, send another retransmittable packet. This should
7946 // cancel the retransmittable-on-wire alarm since now there's a
7947 // retransmittable packet on the wire.
7948 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7949 offset += data_size;
7950 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7951
7952 // Now receive an ACK of the second packet. This should set the
7953 // retransmittable-on-wire alarm now that no retransmittable packets are on
7954 // the wire.
7955 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7956 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7957 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
7958 ProcessAckPacket(&frame);
7959 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07007960 EXPECT_EQ(retransmittable_on_wire_timeout,
7961 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007962
7963 // Simulate the alarm firing and check that a PING is sent.
7964 writer_->Reset();
fayangec14d2b2020-10-02 12:00:05 -07007965 if (!GetQuicReloadableFlag(quic_let_connection_handle_pings)) {
7966 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
7967 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
7968 }));
7969 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007970 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07007971 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05007972 if (GetParam().no_stop_waiting) {
fayang8a27b0f2019-11-04 11:27:40 -08007973 // Do not ACK acks.
7974 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007975 } else {
nharper55fa6132019-05-07 19:37:21 -07007976 EXPECT_EQ(padding_frame_count + 3u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007977 }
7978 ASSERT_EQ(1u, writer_->ping_frames().size());
7979}
7980
zhongyi79ace162019-10-21 15:57:09 -07007981// When there is no stream data received but are open streams, send the
7982// first few consecutive pings with aggressive retransmittable-on-wire
7983// timeout. Exponentially back off the retransmittable-on-wire ping timeout
7984// afterwards until it exceeds the default ping timeout.
7985TEST_P(QuicConnectionTest, BackOffRetransmittableOnWireTimeout) {
7986 int max_aggressive_retransmittable_on_wire_ping_count = 5;
7987 SetQuicFlag(FLAGS_quic_max_aggressive_retransmittable_on_wire_ping_count,
7988 max_aggressive_retransmittable_on_wire_ping_count);
7989 const QuicTime::Delta initial_retransmittable_on_wire_timeout =
7990 QuicTime::Delta::FromMilliseconds(200);
7991 connection_.set_initial_retransmittable_on_wire_timeout(
7992 initial_retransmittable_on_wire_timeout);
7993
7994 EXPECT_TRUE(connection_.connected());
7995 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7996 .WillRepeatedly(Return(true));
7997
7998 const char data[] = "data";
7999 // Advance 5ms, send a retransmittable data packet to the peer.
8000 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8001 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8002 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
8003 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8004 // The ping alarm is set for the ping timeout, not the shorter
8005 // retransmittable_on_wire_timeout.
8006 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8007 EXPECT_EQ(connection_.ping_timeout(),
8008 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8009
8010 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
8011 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
8012 .Times(AnyNumber());
8013
8014 // Verify that the first few consecutive retransmittable on wire pings are
8015 // sent with aggressive timeout.
8016 for (int i = 0; i <= max_aggressive_retransmittable_on_wire_ping_count; i++) {
8017 // Receive an ACK of the previous packet. This should set the ping alarm
8018 // with the initial retransmittable-on-wire timeout.
8019 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8020 QuicPacketNumber ack_num = creator_->packet_number();
8021 QuicAckFrame frame = InitAckFrame(
8022 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8023 ProcessAckPacket(&frame);
8024 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8025 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8026 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8027 // Simulate the alarm firing and check that a PING is sent.
8028 writer_->Reset();
fayangec14d2b2020-10-02 12:00:05 -07008029 if (!GetQuicReloadableFlag(quic_let_connection_handle_pings)) {
8030 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8031 SendPing();
8032 }));
8033 }
zhongyi79ace162019-10-21 15:57:09 -07008034 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8035 connection_.GetPingAlarm()->Fire();
8036 }
8037
8038 QuicTime::Delta retransmittable_on_wire_timeout =
8039 initial_retransmittable_on_wire_timeout;
8040
8041 // Verify subsequent pings are sent with timeout that is exponentially backed
8042 // off.
8043 while (retransmittable_on_wire_timeout * 2 < connection_.ping_timeout()) {
8044 // Receive an ACK for the previous PING. This should set the
8045 // ping alarm with backed off retransmittable-on-wire timeout.
8046 retransmittable_on_wire_timeout = retransmittable_on_wire_timeout * 2;
8047 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8048 QuicPacketNumber ack_num = creator_->packet_number();
8049 QuicAckFrame frame = InitAckFrame(
8050 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8051 ProcessAckPacket(&frame);
8052 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8053 EXPECT_EQ(retransmittable_on_wire_timeout,
8054 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8055
8056 // Simulate the alarm firing and check that a PING is sent.
8057 writer_->Reset();
fayangec14d2b2020-10-02 12:00:05 -07008058 if (!GetQuicReloadableFlag(quic_let_connection_handle_pings)) {
8059 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8060 SendPing();
8061 }));
8062 }
zhongyi79ace162019-10-21 15:57:09 -07008063 clock_.AdvanceTime(retransmittable_on_wire_timeout);
8064 connection_.GetPingAlarm()->Fire();
8065 }
8066
8067 // The ping alarm is set with default ping timeout.
8068 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8069 EXPECT_EQ(connection_.ping_timeout(),
8070 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8071
8072 // Receive an ACK for the previous PING. The ping alarm is set with an
8073 // earlier deadline.
8074 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8075 QuicPacketNumber ack_num = creator_->packet_number();
8076 QuicAckFrame frame = InitAckFrame(
8077 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8078 ProcessAckPacket(&frame);
8079 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8080 EXPECT_EQ(connection_.ping_timeout() - QuicTime::Delta::FromMilliseconds(5),
8081 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8082}
8083
8084// This test verify that the count of consecutive aggressive pings is reset
8085// when new data is received. And it also verifies the connection resets
8086// the exponential back-off of the retransmittable-on-wire ping timeout
8087// after receiving new stream data.
8088TEST_P(QuicConnectionTest, ResetBackOffRetransmitableOnWireTimeout) {
8089 int max_aggressive_retransmittable_on_wire_ping_count = 3;
8090 SetQuicFlag(FLAGS_quic_max_aggressive_retransmittable_on_wire_ping_count, 3);
8091 const QuicTime::Delta initial_retransmittable_on_wire_timeout =
8092 QuicTime::Delta::FromMilliseconds(200);
8093 connection_.set_initial_retransmittable_on_wire_timeout(
8094 initial_retransmittable_on_wire_timeout);
8095
8096 EXPECT_TRUE(connection_.connected());
8097 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8098 .WillRepeatedly(Return(true));
8099 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
8100 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
8101 .Times(AnyNumber());
8102
8103 const char data[] = "data";
8104 // Advance 5ms, send a retransmittable data packet to the peer.
8105 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8106 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8107 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
8108 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8109 // The ping alarm is set for the ping timeout, not the shorter
8110 // retransmittable_on_wire_timeout.
8111 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8112 EXPECT_EQ(connection_.ping_timeout(),
8113 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8114
8115 // Receive an ACK of the first packet. This should set the ping alarm with
8116 // initial retransmittable-on-wire timeout since there is no retransmittable
8117 // packet on the wire.
8118 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8119 QuicAckFrame frame =
8120 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8121 ProcessAckPacket(&frame);
8122 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8123 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8124 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8125
8126 // Simulate the alarm firing and check that a PING is sent.
8127 writer_->Reset();
fayangec14d2b2020-10-02 12:00:05 -07008128 if (!GetQuicReloadableFlag(quic_let_connection_handle_pings)) {
8129 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8130 SendPing();
8131 }));
8132 }
zhongyi79ace162019-10-21 15:57:09 -07008133 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8134 connection_.GetPingAlarm()->Fire();
8135
8136 // Receive an ACK for the previous PING. Ping alarm will be set with
8137 // aggressive timeout.
8138 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8139 QuicPacketNumber ack_num = creator_->packet_number();
8140 frame = InitAckFrame(
8141 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8142 ProcessAckPacket(&frame);
8143 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8144 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8145 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8146
8147 // Process a data packet.
8148 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
8149 ProcessDataPacket(peer_creator_.packet_number() + 1);
8150 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_,
8151 peer_creator_.packet_number() + 1);
8152 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8153 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8154
8155 // Verify the count of consecutive aggressive pings is reset.
8156 for (int i = 0; i < max_aggressive_retransmittable_on_wire_ping_count; i++) {
8157 // Receive an ACK of the previous packet. This should set the ping alarm
8158 // with the initial retransmittable-on-wire timeout.
8159 QuicPacketNumber ack_num = creator_->packet_number();
8160 QuicAckFrame frame = InitAckFrame(
8161 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8162 ProcessAckPacket(&frame);
8163 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8164 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8165 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8166 // Simulate the alarm firing and check that a PING is sent.
8167 writer_->Reset();
fayangec14d2b2020-10-02 12:00:05 -07008168 if (!GetQuicReloadableFlag(quic_let_connection_handle_pings)) {
8169 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8170 SendPing();
8171 }));
8172 }
zhongyi79ace162019-10-21 15:57:09 -07008173 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8174 connection_.GetPingAlarm()->Fire();
8175 // Advance 5ms to receive next packet.
8176 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8177 }
8178
8179 // Receive another ACK for the previous PING. This should set the
8180 // ping alarm with backed off retransmittable-on-wire timeout.
8181 ack_num = creator_->packet_number();
8182 frame = InitAckFrame(
8183 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8184 ProcessAckPacket(&frame);
8185 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8186 EXPECT_EQ(initial_retransmittable_on_wire_timeout * 2,
8187 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8188
8189 writer_->Reset();
fayangec14d2b2020-10-02 12:00:05 -07008190 if (!GetQuicReloadableFlag(quic_let_connection_handle_pings)) {
8191 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8192 SendPing();
8193 }));
8194 }
zhongyi79ace162019-10-21 15:57:09 -07008195 clock_.AdvanceTime(2 * initial_retransmittable_on_wire_timeout);
8196 connection_.GetPingAlarm()->Fire();
8197
8198 // Process another data packet and a new ACK packet. The ping alarm is set
8199 // with aggressive ping timeout again.
8200 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
8201 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8202 ProcessDataPacket(peer_creator_.packet_number() + 1);
8203 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_,
8204 peer_creator_.packet_number() + 1);
8205 ack_num = creator_->packet_number();
8206 frame = InitAckFrame(
8207 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8208 ProcessAckPacket(&frame);
8209 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8210 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8211 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8212}
8213
QUICHE teama6ef0a62019-03-07 20:34:33 -05008214TEST_P(QuicConnectionTest, ValidStatelessResetToken) {
8215 const QuicUint128 kTestToken = 1010101;
8216 const QuicUint128 kWrongTestToken = 1010100;
8217 QuicConfig config;
8218 // No token has been received.
8219 EXPECT_FALSE(connection_.IsValidStatelessResetToken(kTestToken));
8220
8221 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(2);
8222 // Token is different from received token.
8223 QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestToken);
8224 connection_.SetFromConfig(config);
8225 EXPECT_FALSE(connection_.IsValidStatelessResetToken(kWrongTestToken));
8226
8227 QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestToken);
8228 connection_.SetFromConfig(config);
8229 EXPECT_TRUE(connection_.IsValidStatelessResetToken(kTestToken));
8230}
8231
8232TEST_P(QuicConnectionTest, WriteBlockedWithInvalidAck) {
8233 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayange62e63c2019-12-04 07:16:25 -08008234 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008235 BlockOnNextWrite();
fayange62e63c2019-12-04 07:16:25 -08008236 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008237 connection_.SendStreamDataWithString(5, "foo", 0, FIN);
8238 // This causes connection to be closed because packet 1 has not been sent yet.
8239 QuicAckFrame frame = InitAckFrame(1);
fayange62e63c2019-12-04 07:16:25 -08008240 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05008241 ProcessAckPacket(1, &frame);
fayange62e63c2019-12-04 07:16:25 -08008242 EXPECT_EQ(0, connection_close_frame_count_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008243}
8244
8245TEST_P(QuicConnectionTest, SendMessage) {
fayangc31c9952019-06-05 13:54:48 -07008246 if (!VersionSupportsMessageFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008247 return;
8248 }
dschinazied459c02020-05-07 16:12:23 -07008249 if (connection_.version().UsesTls()) {
8250 QuicConfig config;
8251 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
8252 &config, kMaxAcceptedDatagramFrameSize);
8253 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8254 connection_.SetFromConfig(config);
8255 }
ianswettb239f862019-04-05 09:15:06 -07008256 std::string message(connection_.GetCurrentLargestMessagePayload() * 2, 'a');
dmcardlecf0bfcf2019-12-13 08:08:21 -08008257 quiche::QuicheStringPiece message_data(message);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008258 QuicMemSliceStorage storage(nullptr, 0, nullptr, 0);
8259 {
fayanga4b37b22019-06-18 13:37:47 -07008260 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008261 connection_.SendStreamData3();
8262 // Send a message which cannot fit into current open packet, and 2 packets
8263 // get sent, one contains stream frame, and the other only contains the
8264 // message frame.
8265 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
QUICHE team350e9e62019-11-19 13:16:24 -08008266 EXPECT_EQ(MESSAGE_STATUS_SUCCESS,
8267 connection_.SendMessage(
8268 1,
8269 MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(),
dmcardlecf0bfcf2019-12-13 08:08:21 -08008270 quiche::QuicheStringPiece(
QUICHE team350e9e62019-11-19 13:16:24 -08008271 message_data.data(),
8272 connection_.GetCurrentLargestMessagePayload()),
8273 &storage),
8274 false));
QUICHE teama6ef0a62019-03-07 20:34:33 -05008275 }
8276 // Fail to send a message if connection is congestion control blocked.
8277 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(Return(false));
QUICHE team350e9e62019-11-19 13:16:24 -08008278 EXPECT_EQ(MESSAGE_STATUS_BLOCKED,
8279 connection_.SendMessage(
8280 2,
8281 MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(),
8282 "message", &storage),
8283 false));
QUICHE teama6ef0a62019-03-07 20:34:33 -05008284
8285 // Always fail to send a message which cannot fit into one packet.
8286 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE team350e9e62019-11-19 13:16:24 -08008287 EXPECT_EQ(MESSAGE_STATUS_TOO_LARGE,
8288 connection_.SendMessage(
8289 3,
8290 MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(),
dmcardlecf0bfcf2019-12-13 08:08:21 -08008291 quiche::QuicheStringPiece(
QUICHE team350e9e62019-11-19 13:16:24 -08008292 message_data.data(),
8293 connection_.GetCurrentLargestMessagePayload() + 1),
8294 &storage),
8295 false));
QUICHE teama6ef0a62019-03-07 20:34:33 -05008296}
8297
dschinazied459c02020-05-07 16:12:23 -07008298TEST_P(QuicConnectionTest, GetCurrentLargestMessagePayload) {
8299 if (!connection_.version().SupportsMessageFrames()) {
8300 return;
8301 }
8302 // Force use of this encrypter to simplify test expectations by making sure
8303 // that the encryption overhead is constant across versions.
8304 connection_.SetEncrypter(ENCRYPTION_INITIAL,
8305 std::make_unique<TaggingEncrypter>(0x00));
8306 QuicPacketLength expected_largest_payload = 1319;
8307 if (connection_.version().SendsVariableLengthPacketNumberInLongHeader()) {
8308 expected_largest_payload += 3;
8309 }
8310 if (connection_.version().HasLongHeaderLengths()) {
8311 expected_largest_payload -= 2;
8312 }
8313 if (connection_.version().HasLengthPrefixedConnectionIds()) {
8314 expected_largest_payload -= 1;
8315 }
8316 if (connection_.version().UsesTls()) {
8317 // QUIC+TLS disallows DATAGRAM/MESSAGE frames before the handshake.
8318 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), 0);
8319 QuicConfig config;
8320 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
8321 &config, kMaxAcceptedDatagramFrameSize);
8322 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8323 connection_.SetFromConfig(config);
8324 // Verify the value post-handshake.
8325 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(),
8326 expected_largest_payload);
8327 } else {
8328 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(),
8329 expected_largest_payload);
8330 }
8331}
8332
8333TEST_P(QuicConnectionTest, GetGuaranteedLargestMessagePayload) {
8334 if (!connection_.version().SupportsMessageFrames()) {
8335 return;
8336 }
8337 // Force use of this encrypter to simplify test expectations by making sure
8338 // that the encryption overhead is constant across versions.
8339 connection_.SetEncrypter(ENCRYPTION_INITIAL,
8340 std::make_unique<TaggingEncrypter>(0x00));
8341 QuicPacketLength expected_largest_payload = 1319;
8342 if (connection_.version().HasLongHeaderLengths()) {
8343 expected_largest_payload -= 2;
8344 }
8345 if (connection_.version().HasLengthPrefixedConnectionIds()) {
8346 expected_largest_payload -= 1;
8347 }
8348 if (connection_.version().UsesTls()) {
8349 // QUIC+TLS disallows DATAGRAM/MESSAGE frames before the handshake.
8350 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(), 0);
8351 QuicConfig config;
8352 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
8353 &config, kMaxAcceptedDatagramFrameSize);
8354 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8355 connection_.SetFromConfig(config);
8356 // Verify the value post-handshake.
8357 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(),
8358 expected_largest_payload);
8359 } else {
8360 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(),
8361 expected_largest_payload);
8362 }
8363}
8364
8365TEST_P(QuicConnectionTest, LimitedLargestMessagePayload) {
8366 if (!connection_.version().SupportsMessageFrames() ||
8367 !connection_.version().UsesTls()) {
8368 return;
8369 }
8370 constexpr QuicPacketLength kFrameSizeLimit = 1000;
8371 constexpr QuicPacketLength kPayloadSizeLimit =
8372 kFrameSizeLimit - kQuicFrameTypeSize;
8373 // QUIC+TLS disallows DATAGRAM/MESSAGE frames before the handshake.
8374 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), 0);
8375 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(), 0);
8376 QuicConfig config;
8377 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(&config, kFrameSizeLimit);
8378 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8379 connection_.SetFromConfig(config);
8380 // Verify the value post-handshake.
8381 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), kPayloadSizeLimit);
8382 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(),
8383 kPayloadSizeLimit);
8384}
8385
QUICHE teama6ef0a62019-03-07 20:34:33 -05008386// Test to check that the path challenge/path response logic works
8387// correctly. This test is only for version-99
danzh8a27a1a2020-09-02 10:26:28 -07008388TEST_P(QuicConnectionTest, ServerResponseToPathChallenge) {
fkastenholz305e1732019-06-18 05:01:22 -07008389 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008390 return;
8391 }
danzh8a27a1a2020-09-02 10:26:28 -07008392 PathProbeTestInit(Perspective::IS_SERVER);
8393 QuicConnectionPeer::SetAddressValidated(&connection_);
8394 // First check if the server can send probing packet.
QUICHE teama6ef0a62019-03-07 20:34:33 -05008395 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
8396
8397 // Create and send the probe request (PATH_CHALLENGE frame).
8398 // SendConnectivityProbingPacket ends up calling
8399 // TestPacketWriter::WritePacket() which in turns receives and parses the
8400 // packet by calling framer_.ProcessPacket() -- which in turn calls
8401 // SimpleQuicFramer::OnPathChallengeFrame(). SimpleQuicFramer saves
8402 // the packet in writer_->path_challenge_frames()
8403 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8404 connection_.SendConnectivityProbingPacket(writer_.get(),
8405 connection_.peer_address());
8406 // Save the random contents of the challenge for later comparison to the
8407 // response.
nharper55fa6132019-05-07 19:37:21 -07008408 ASSERT_GE(writer_->path_challenge_frames().size(), 1u);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008409 QuicPathFrameBuffer challenge_data =
8410 writer_->path_challenge_frames().front().data_buffer;
8411
8412 // Normally, QuicConnection::OnPathChallengeFrame and OnPaddingFrame would be
8413 // called and it will perform actions to ensure that the rest of the protocol
danzh8a27a1a2020-09-02 10:26:28 -07008414 // is performed.
8415 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008416 EXPECT_TRUE(connection_.OnPathChallengeFrame(
8417 writer_->path_challenge_frames().front()));
8418 EXPECT_TRUE(connection_.OnPaddingFrame(writer_->padding_frames().front()));
danzh8a27a1a2020-09-02 10:26:28 -07008419 if (!connection_.send_path_response()) {
8420 connection_.SendConnectivityProbingResponsePacket(
8421 connection_.peer_address());
8422 }
8423 creator_->FlushCurrentPacket();
QUICHE teama6ef0a62019-03-07 20:34:33 -05008424
8425 // The final check is to ensure that the random data in the response matches
8426 // the random data from the challenge.
danzh8a27a1a2020-09-02 10:26:28 -07008427 EXPECT_EQ(1u, writer_->path_response_frames().size());
8428 EXPECT_EQ(0, memcmp(&challenge_data,
8429 &(writer_->path_response_frames().front().data_buffer),
8430 sizeof(challenge_data)));
8431}
8432
8433TEST_P(QuicConnectionTest, ClientResponseToPathChallenge) {
8434 if (!VersionHasIetfQuicFrames(connection_.version().transport_version) ||
8435 !connection_.send_path_response()) {
8436 return;
8437 }
8438 PathProbeTestInit(Perspective::IS_CLIENT);
8439 // First check if the client can send probing packet.
8440 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
8441
8442 // Create and send the probe request (PATH_CHALLENGE frame).
8443 // SendConnectivityProbingPacket ends up calling
8444 // TestPacketWriter::WritePacket() which in turns receives and parses the
8445 // packet by calling framer_.ProcessPacket() -- which in turn calls
8446 // SimpleQuicFramer::OnPathChallengeFrame(). SimpleQuicFramer saves
8447 // the packet in writer_->path_challenge_frames()
8448 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8449 connection_.SendConnectivityProbingPacket(writer_.get(),
8450 connection_.peer_address());
8451 // Save the random contents of the challenge for later validation against the
8452 // response.
8453 ASSERT_GE(writer_->path_challenge_frames().size(), 1u);
8454 QuicPathFrameBuffer challenge_data =
8455 writer_->path_challenge_frames().front().data_buffer;
8456
8457 // Normally, QuicConnection::OnPathChallengeFrame would be
8458 // called and it will perform actions to ensure that the rest of the protocol
8459 // is performed.
8460 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8461 EXPECT_TRUE(connection_.OnPathChallengeFrame(
8462 writer_->path_challenge_frames().front()));
8463 EXPECT_TRUE(connection_.OnPaddingFrame(writer_->padding_frames().front()));
8464 creator_->FlushCurrentPacket();
8465
8466 // The final check is to ensure that the random data in the response matches
8467 // the random data from the challenge.
8468 EXPECT_EQ(1u, writer_->path_response_frames().size());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008469 EXPECT_EQ(0, memcmp(&challenge_data,
8470 &(writer_->path_response_frames().front().data_buffer),
8471 sizeof(challenge_data)));
8472}
8473
zhongyi2da16be2020-06-17 11:05:23 -07008474TEST_P(QuicConnectionTest,
8475 RestartPathDegradingDetectionAfterMigrationWithProbe) {
8476 // TODO(b/150095484): add test coverage for IETF to verify that client takes
8477 // PATH RESPONSE with peer address change as correct validation on the new
8478 // path.
8479 if (GetParam().version.HasIetfQuicFrames()) {
8480 return;
8481 }
8482 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
dschinazi1c6e5922020-06-19 10:35:03 -07008483 PathProbeTestInit(Perspective::IS_CLIENT);
zhongyi2da16be2020-06-17 11:05:23 -07008484
8485 // Clear direct_peer_address and effective_peer_address.
8486 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
8487 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
8488 QuicSocketAddress());
8489 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
8490
8491 EXPECT_TRUE(connection_.connected());
8492 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8493 .WillRepeatedly(Return(true));
8494 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
8495 EXPECT_FALSE(connection_.IsPathDegrading());
8496 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8497
8498 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
8499 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
8500 } else {
8501 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
8502 }
fayangf08e1792020-09-30 13:23:42 -07008503 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
8504 ENCRYPTION_INITIAL);
zhongyi2da16be2020-06-17 11:05:23 -07008505 EXPECT_EQ(kPeerAddress, connection_.peer_address());
8506 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
8507
8508 // Send data and verify the path degrading detection is set.
8509 const char data[] = "data";
8510 size_t data_size = strlen(data);
8511 QuicStreamOffset offset = 0;
8512 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8513 offset += data_size;
8514
8515 // Verify the path degrading detection is in progress.
8516 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
8517 EXPECT_FALSE(connection_.IsPathDegrading());
8518 QuicTime ddl = connection_.GetBlackholeDetectorAlarm()->deadline();
8519
8520 // Simulate the firing of path degrading.
8521 clock_.AdvanceTime(ddl - clock_.ApproximateNow());
8522 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
8523 connection_.PathDegradingTimeout();
8524 EXPECT_TRUE(connection_.IsPathDegrading());
8525 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
8526
8527 // Simulate path degrading handling by sending a probe on an alternet path.
8528 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
danzhc19a9502020-09-29 16:02:33 -07008529 TestPacketWriter probing_writer(version(), &clock_, Perspective::IS_CLIENT);
zhongyi2da16be2020-06-17 11:05:23 -07008530 connection_.SendConnectivityProbingPacket(&probing_writer,
8531 connection_.peer_address());
8532 // Verify that path degrading detection is not reset.
8533 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
8534
8535 // Simulate successful path degrading handling by receiving probe response.
8536 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
8537
8538 if (!GetParam().version.HasIetfQuicFrames()) {
8539 EXPECT_CALL(visitor_,
8540 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
8541 .Times(1);
8542 } else {
8543 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
8544 }
8545 const QuicSocketAddress kNewSelfAddress =
8546 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
8547
8548 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
8549 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
8550 QuicEncryptedPacket(probing_packet->encrypted_buffer,
8551 probing_packet->encrypted_length),
8552 clock_.Now()));
8553 uint64_t num_probing_received =
8554 connection_.GetStats().num_connectivity_probing_received;
8555 ProcessReceivedPacket(kNewSelfAddress, kPeerAddress, *received);
8556
8557 EXPECT_EQ(num_probing_received + 1,
8558 connection_.GetStats().num_connectivity_probing_received);
8559 EXPECT_EQ(kPeerAddress, connection_.peer_address());
8560 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
8561 EXPECT_TRUE(connection_.IsPathDegrading());
8562
8563 // Verify new path degrading detection is activated.
8564 EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading()).Times(1);
8565 connection_.OnSuccessfulMigrationAfterProbing();
8566 EXPECT_FALSE(connection_.IsPathDegrading());
8567 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
8568}
8569
QUICHE teama6ef0a62019-03-07 20:34:33 -05008570// Regression test for b/110259444
8571TEST_P(QuicConnectionTest, DoNotScheduleSpuriousAckAlarm) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008572 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8573 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
8574 writer_->SetWriteBlocked();
8575
8576 ProcessPacket(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008577 // Verify ack alarm is set.
fayang9adfb532020-06-04 06:58:45 -07008578 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008579 // Fire the ack alarm, verify no packet is sent because the writer is blocked.
8580 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8581 connection_.GetAckAlarm()->Fire();
8582
8583 writer_->SetWritable();
8584 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8585 ProcessPacket(2);
8586 // Verify ack alarm is not set.
fayang9adfb532020-06-04 06:58:45 -07008587 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008588}
8589
8590TEST_P(QuicConnectionTest, DisablePacingOffloadConnectionOptions) {
8591 EXPECT_FALSE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
8592 writer_->set_supports_release_time(true);
8593 QuicConfig config;
8594 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8595 connection_.SetFromConfig(config);
8596 EXPECT_TRUE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
8597
8598 QuicTagVector connection_options;
8599 connection_options.push_back(kNPCO);
8600 config.SetConnectionOptionsToSend(connection_options);
8601 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8602 connection_.SetFromConfig(config);
8603 // Verify pacing offload is disabled.
8604 EXPECT_FALSE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
8605}
8606
8607// Regression test for b/110259444
8608// Get a path response without having issued a path challenge...
8609TEST_P(QuicConnectionTest, OrphanPathResponse) {
8610 QuicPathFrameBuffer data = {{0, 1, 2, 3, 4, 5, 6, 7}};
8611
8612 QuicPathResponseFrame frame(99, data);
8613 EXPECT_TRUE(connection_.OnPathResponseFrame(frame));
8614 // If PATH_RESPONSE was accepted (payload matches the payload saved
8615 // in QuicConnection::transmitted_connectivity_probe_payload_) then
8616 // current_packet_content_ would be set to FIRST_FRAME_IS_PING.
8617 // Since this PATH_RESPONSE does not match, current_packet_content_
8618 // must not be FIRST_FRAME_IS_PING.
8619 EXPECT_NE(QuicConnection::FIRST_FRAME_IS_PING,
8620 QuicConnectionPeer::GetCurrentPacketContent(&connection_));
8621}
8622
8623// Regression test for b/120791670
8624TEST_P(QuicConnectionTest, StopProcessingGQuicPacketInIetfQuicConnection) {
dschinazi5c1d7d82020-07-29 16:42:50 -07008625 // This test mimics a problematic scenario where a QUIC connection using a
8626 // modern version received a Q043 packet and processed it incorrectly.
8627 // We can remove this test once Q043 is deprecated.
8628 if (!version().HasIetfInvariantHeader()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008629 return;
8630 }
8631 set_perspective(Perspective::IS_SERVER);
nharper46833c32019-05-15 21:33:05 -07008632 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07008633 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
8634 } else {
nharper46833c32019-05-15 21:33:05 -07008635 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
8636 }
fayangf08e1792020-09-30 13:23:42 -07008637 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
8638 ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008639
8640 // Let connection process a Google QUIC packet.
dschinazi5c1d7d82020-07-29 16:42:50 -07008641 peer_framer_.set_version_for_tests(ParsedQuicVersion::Q043());
QUICHE team8c1daa22019-03-13 08:33:41 -07008642 std::unique_ptr<QuicPacket> packet(
QUICHE team6987b4a2019-03-15 16:23:04 -07008643 ConstructDataPacket(2, !kHasStopWaiting, ENCRYPTION_INITIAL));
dschinazi66dea072019-04-09 11:41:06 -07008644 char buffer[kMaxOutgoingPacketSize];
8645 size_t encrypted_length =
8646 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(2),
8647 *packet, buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008648 // Make sure no stream frame is processed.
8649 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(0);
8650 connection_.ProcessUdpPacket(
8651 kSelfAddress, kPeerAddress,
8652 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
8653
8654 EXPECT_EQ(2u, connection_.GetStats().packets_received);
8655 EXPECT_EQ(1u, connection_.GetStats().packets_processed);
8656}
8657
8658TEST_P(QuicConnectionTest, AcceptPacketNumberZero) {
fkastenholz305e1732019-06-18 05:01:22 -07008659 if (!VersionHasIetfQuicFrames(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008660 return;
8661 }
8662 // Set first_sending_packet_number to be 0 to allow successfully processing
8663 // acks which ack packet number 0.
8664 QuicFramerPeer::SetFirstSendingPacketNumber(writer_->framer()->framer(), 0);
8665 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8666
8667 ProcessPacket(0);
fayangc31c9952019-06-05 13:54:48 -07008668 EXPECT_EQ(QuicPacketNumber(0), LargestAcked(connection_.ack_frame()));
8669 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008670
8671 ProcessPacket(1);
fayangc31c9952019-06-05 13:54:48 -07008672 EXPECT_EQ(QuicPacketNumber(1), LargestAcked(connection_.ack_frame()));
8673 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008674
8675 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07008676 EXPECT_EQ(QuicPacketNumber(2), LargestAcked(connection_.ack_frame()));
8677 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008678}
8679
QUICHE teamcd098022019-03-22 18:49:55 -07008680TEST_P(QuicConnectionTest, MultiplePacketNumberSpacesBasicSending) {
8681 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8682 return;
8683 }
8684 use_tagging_decrypter();
8685 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07008686 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teamcd098022019-03-22 18:49:55 -07008687
8688 connection_.SendCryptoStreamData();
8689 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8690 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
8691 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8692 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8693 QuicAckFrame frame1 = InitAckFrame(1);
8694 // Received ACK for packet 1.
8695 ProcessFramePacketAtLevel(30, QuicFrame(&frame1), ENCRYPTION_INITIAL);
8696
8697 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(4);
8698 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
8699 NO_FIN);
8700 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 4,
8701 NO_FIN);
8702 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
8703 8, NO_FIN);
8704 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
8705 12, FIN);
8706 // Received ACK for packets 2, 4, 5.
8707 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
8708 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8709 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8710 QuicAckFrame frame2 =
8711 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)},
8712 {QuicPacketNumber(4), QuicPacketNumber(6)}});
8713 // Make sure although the same packet number is used, but they are in
8714 // different packet number spaces.
8715 ProcessFramePacketAtLevel(30, QuicFrame(&frame2), ENCRYPTION_FORWARD_SECURE);
8716}
8717
8718TEST_P(QuicConnectionTest, PeerAcksPacketsInWrongPacketNumberSpace) {
8719 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8720 return;
8721 }
8722 use_tagging_decrypter();
8723 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07008724 std::make_unique<TaggingEncrypter>(0x01));
rch39c88ab2019-10-16 19:24:40 -07008725 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
8726 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teamcd098022019-03-22 18:49:55 -07008727
8728 connection_.SendCryptoStreamData();
8729 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8730 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
8731 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8732 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8733 QuicAckFrame frame1 = InitAckFrame(1);
8734 // Received ACK for packet 1.
8735 ProcessFramePacketAtLevel(30, QuicFrame(&frame1), ENCRYPTION_INITIAL);
8736
8737 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
8738 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
8739 NO_FIN);
8740 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 4,
8741 NO_FIN);
8742
8743 // Received ACK for packets 2 and 3 in wrong packet number space.
8744 QuicAckFrame invalid_ack =
8745 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(4)}});
fkastenholz5d880a92019-06-21 09:01:56 -07008746 EXPECT_CALL(visitor_,
8747 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07008748 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teamcd098022019-03-22 18:49:55 -07008749 ProcessFramePacketAtLevel(300, QuicFrame(&invalid_ack), ENCRYPTION_INITIAL);
fkastenholz5d880a92019-06-21 09:01:56 -07008750 TestConnectionCloseQuicErrorCode(QUIC_INVALID_ACK_DATA);
QUICHE teamcd098022019-03-22 18:49:55 -07008751}
8752
8753TEST_P(QuicConnectionTest, MultiplePacketNumberSpacesBasicReceiving) {
8754 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8755 return;
8756 }
8757 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
nharper46833c32019-05-15 21:33:05 -07008758 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
8759 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
8760 }
QUICHE teamcd098022019-03-22 18:49:55 -07008761 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
8762 use_tagging_decrypter();
8763 // Receives packet 1000 in initial data.
nharper46833c32019-05-15 21:33:05 -07008764 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
fayang9adfb532020-06-04 06:58:45 -07008765 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teamcd098022019-03-22 18:49:55 -07008766 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07008767 std::make_unique<TaggingEncrypter>(0x02));
zhongyi546cc452019-04-12 15:27:49 -07008768 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07008769 std::make_unique<StrictTaggingDecrypter>(0x02));
QUICHE teamcd098022019-03-22 18:49:55 -07008770 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07008771 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teamcd098022019-03-22 18:49:55 -07008772 // Receives packet 1000 in application data.
8773 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
fayang9adfb532020-06-04 06:58:45 -07008774 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teamcd098022019-03-22 18:49:55 -07008775 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
8776 NO_FIN);
8777 // Verify application data ACK gets bundled with outgoing data.
8778 EXPECT_EQ(2u, writer_->frame_count());
8779 // Make sure ACK alarm is still set because initial data is not ACKed.
fayang9adfb532020-06-04 06:58:45 -07008780 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teamcd098022019-03-22 18:49:55 -07008781 // Receive packet 1001 in application data.
8782 ProcessDataPacketAtLevel(1001, false, ENCRYPTION_ZERO_RTT);
8783 clock_.AdvanceTime(DefaultRetransmissionTime());
8784 // Simulates ACK alarm fires and verify two ACKs are flushed.
8785 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
8786 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07008787 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teamcd098022019-03-22 18:49:55 -07008788 connection_.GetAckAlarm()->Fire();
fayang9adfb532020-06-04 06:58:45 -07008789 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teamcd098022019-03-22 18:49:55 -07008790 // Receives more packets in application data.
8791 ProcessDataPacketAtLevel(1002, false, ENCRYPTION_ZERO_RTT);
fayang9adfb532020-06-04 06:58:45 -07008792 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teamcd098022019-03-22 18:49:55 -07008793
8794 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07008795 std::make_unique<TaggingEncrypter>(0x02));
zhongyi546cc452019-04-12 15:27:49 -07008796 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07008797 std::make_unique<StrictTaggingDecrypter>(0x02));
QUICHE teamcd098022019-03-22 18:49:55 -07008798 // Verify zero rtt and forward secure packets get acked in the same packet.
8799 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
nharper2c9f02a2019-05-08 10:25:50 -07008800 ProcessDataPacket(1003);
fayang9adfb532020-06-04 06:58:45 -07008801 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teamcd098022019-03-22 18:49:55 -07008802}
8803
QUICHE team552f71f2019-03-23 15:37:59 -07008804TEST_P(QuicConnectionTest, CancelAckAlarmOnWriteBlocked) {
8805 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8806 return;
8807 }
8808 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
nharper46833c32019-05-15 21:33:05 -07008809 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
8810 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
8811 }
QUICHE team552f71f2019-03-23 15:37:59 -07008812 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
8813 use_tagging_decrypter();
8814 // Receives packet 1000 in initial data.
nharper46833c32019-05-15 21:33:05 -07008815 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
fayang9adfb532020-06-04 06:58:45 -07008816 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE team552f71f2019-03-23 15:37:59 -07008817 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07008818 std::make_unique<TaggingEncrypter>(0x02));
zhongyi546cc452019-04-12 15:27:49 -07008819 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07008820 std::make_unique<StrictTaggingDecrypter>(0x02));
QUICHE team552f71f2019-03-23 15:37:59 -07008821 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07008822 std::make_unique<TaggingEncrypter>(0x02));
QUICHE team552f71f2019-03-23 15:37:59 -07008823 // Receives packet 1000 in application data.
8824 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
fayang9adfb532020-06-04 06:58:45 -07008825 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE team552f71f2019-03-23 15:37:59 -07008826
8827 writer_->SetWriteBlocked();
8828 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AnyNumber());
8829 // Simulates ACK alarm fires and verify no ACK is flushed because of write
8830 // blocked.
8831 clock_.AdvanceTime(DefaultDelayedAckTime());
8832 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8833 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07008834 std::make_unique<TaggingEncrypter>(0x02));
QUICHE team552f71f2019-03-23 15:37:59 -07008835 connection_.GetAckAlarm()->Fire();
8836 // Verify ACK alarm is not set.
fayang9adfb532020-06-04 06:58:45 -07008837 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE team552f71f2019-03-23 15:37:59 -07008838
8839 writer_->SetWritable();
8840 // Verify 2 ACKs are sent when connection gets unblocked.
8841 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
8842 connection_.OnCanWrite();
fayang9adfb532020-06-04 06:58:45 -07008843 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE team552f71f2019-03-23 15:37:59 -07008844}
8845
dschinazi346b7ce2019-06-05 01:38:18 -07008846// Make sure a packet received with the right client connection ID is processed.
8847TEST_P(QuicConnectionTest, ValidClientConnectionId) {
dschinazi346b7ce2019-06-05 01:38:18 -07008848 if (!framer_.version().SupportsClientConnectionIds()) {
8849 return;
8850 }
8851 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8852 connection_.set_client_connection_id(TestConnectionId(0x33));
8853 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_FORWARD_SECURE);
8854 header.destination_connection_id = TestConnectionId(0x33);
8855 header.destination_connection_id_included = CONNECTION_ID_PRESENT;
8856 header.source_connection_id_included = CONNECTION_ID_ABSENT;
8857 QuicFrames frames;
8858 QuicPingFrame ping_frame;
8859 QuicPaddingFrame padding_frame;
8860 frames.push_back(QuicFrame(ping_frame));
8861 frames.push_back(QuicFrame(padding_frame));
8862 std::unique_ptr<QuicPacket> packet =
8863 BuildUnsizedDataPacket(&framer_, header, frames);
8864 char buffer[kMaxOutgoingPacketSize];
8865 size_t encrypted_length = peer_framer_.EncryptPayload(
8866 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
8867 kMaxOutgoingPacketSize);
8868 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
8869 false);
8870 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
8871 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
8872 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
8873}
8874
8875// Make sure a packet received with a different client connection ID is dropped.
8876TEST_P(QuicConnectionTest, InvalidClientConnectionId) {
dschinazi346b7ce2019-06-05 01:38:18 -07008877 if (!framer_.version().SupportsClientConnectionIds()) {
8878 return;
8879 }
8880 connection_.set_client_connection_id(TestConnectionId(0x33));
8881 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_FORWARD_SECURE);
8882 header.destination_connection_id = TestConnectionId(0xbad);
8883 header.destination_connection_id_included = CONNECTION_ID_PRESENT;
8884 header.source_connection_id_included = CONNECTION_ID_ABSENT;
8885 QuicFrames frames;
8886 QuicPingFrame ping_frame;
8887 QuicPaddingFrame padding_frame;
8888 frames.push_back(QuicFrame(ping_frame));
8889 frames.push_back(QuicFrame(padding_frame));
8890 std::unique_ptr<QuicPacket> packet =
8891 BuildUnsizedDataPacket(&framer_, header, frames);
8892 char buffer[kMaxOutgoingPacketSize];
8893 size_t encrypted_length = peer_framer_.EncryptPayload(
8894 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
8895 kMaxOutgoingPacketSize);
8896 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
8897 false);
8898 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
8899 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
8900 EXPECT_EQ(1u, connection_.GetStats().packets_dropped);
8901}
8902
8903// Make sure the first packet received with a different client connection ID on
8904// the server is processed and it changes the client connection ID.
8905TEST_P(QuicConnectionTest, UpdateClientConnectionIdFromFirstPacket) {
dschinazi346b7ce2019-06-05 01:38:18 -07008906 if (!framer_.version().SupportsClientConnectionIds()) {
8907 return;
8908 }
dschinazi346b7ce2019-06-05 01:38:18 -07008909 set_perspective(Perspective::IS_SERVER);
8910 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_INITIAL);
8911 header.source_connection_id = TestConnectionId(0x33);
8912 header.source_connection_id_included = CONNECTION_ID_PRESENT;
8913 QuicFrames frames;
8914 QuicPingFrame ping_frame;
8915 QuicPaddingFrame padding_frame;
8916 frames.push_back(QuicFrame(ping_frame));
8917 frames.push_back(QuicFrame(padding_frame));
8918 std::unique_ptr<QuicPacket> packet =
8919 BuildUnsizedDataPacket(&framer_, header, frames);
8920 char buffer[kMaxOutgoingPacketSize];
nharperc6b99512019-09-19 11:13:48 -07008921 size_t encrypted_length =
8922 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(1),
8923 *packet, buffer, kMaxOutgoingPacketSize);
dschinazi346b7ce2019-06-05 01:38:18 -07008924 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
8925 false);
8926 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
8927 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
8928 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
8929 EXPECT_EQ(TestConnectionId(0x33), connection_.client_connection_id());
8930}
8931
fayang40ec3ac2019-06-05 09:07:54 -07008932// Regression test for b/134416344.
8933TEST_P(QuicConnectionTest, CheckConnectedBeforeFlush) {
8934 // This test mimics a scenario where a connection processes 2 packets and the
8935 // 2nd packet contains connection close frame. When the 2nd flusher goes out
8936 // of scope, a delayed ACK is pending, and ACK alarm should not be scheduled
8937 // because connection is disconnected.
8938 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fkastenholz5d880a92019-06-21 09:01:56 -07008939 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
fayang40ec3ac2019-06-05 09:07:54 -07008940 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
fkastenholz88d08f42019-09-06 07:38:04 -07008941 const QuicErrorCode kErrorCode = QUIC_INTERNAL_ERROR;
fayang40ec3ac2019-06-05 09:07:54 -07008942 std::unique_ptr<QuicConnectionCloseFrame> connection_close_frame(
fkastenholz591814c2019-09-06 12:11:46 -07008943 new QuicConnectionCloseFrame(connection_.transport_version(), kErrorCode,
8944 "",
8945 /*transport_close_frame_type=*/0));
8946
fayang40ec3ac2019-06-05 09:07:54 -07008947 // Received 2 packets.
fayang40ec3ac2019-06-05 09:07:54 -07008948 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
fayang40ec3ac2019-06-05 09:07:54 -07008949 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
8950 } else {
fayang40ec3ac2019-06-05 09:07:54 -07008951 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
8952 }
fayangf08e1792020-09-30 13:23:42 -07008953 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
8954 ENCRYPTION_INITIAL);
fayang9adfb532020-06-04 06:58:45 -07008955 EXPECT_TRUE(connection_.HasPendingAcks());
wub8a5dafa2020-05-13 12:30:17 -07008956 ProcessFramePacketWithAddresses(QuicFrame(connection_close_frame.release()),
fayangf08e1792020-09-30 13:23:42 -07008957 kSelfAddress, kPeerAddress,
8958 ENCRYPTION_INITIAL);
fayang0f0c4e62019-07-16 08:55:54 -07008959 // Verify ack alarm is not set.
fayang9adfb532020-06-04 06:58:45 -07008960 EXPECT_FALSE(connection_.HasPendingAcks());
fayang40ec3ac2019-06-05 09:07:54 -07008961}
8962
dschinazi8d551132019-08-02 19:17:16 -07008963// Verify that a packet containing three coalesced packets is parsed correctly.
8964TEST_P(QuicConnectionTest, CoalescedPacket) {
8965 if (!QuicVersionHasLongHeaderLengths(connection_.transport_version())) {
8966 // Coalesced packets can only be encoded using long header lengths.
8967 return;
8968 }
8969 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8970 EXPECT_TRUE(connection_.connected());
8971 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
8972 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(3);
8973 } else {
8974 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(3);
8975 }
8976
8977 uint64_t packet_numbers[3] = {1, 2, 3};
8978 EncryptionLevel encryption_levels[3] = {
8979 ENCRYPTION_INITIAL, ENCRYPTION_INITIAL, ENCRYPTION_FORWARD_SECURE};
8980 char buffer[kMaxOutgoingPacketSize] = {};
8981 size_t total_encrypted_length = 0;
8982 for (int i = 0; i < 3; i++) {
8983 QuicPacketHeader header =
8984 ConstructPacketHeader(packet_numbers[i], encryption_levels[i]);
8985 QuicFrames frames;
8986 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
8987 frames.push_back(QuicFrame(&crypto_frame_));
8988 } else {
8989 frames.push_back(QuicFrame(frame1_));
8990 }
8991 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
8992 peer_creator_.set_encryption_level(encryption_levels[i]);
8993 size_t encrypted_length = peer_framer_.EncryptPayload(
8994 encryption_levels[i], QuicPacketNumber(packet_numbers[i]), *packet,
8995 buffer + total_encrypted_length,
8996 sizeof(buffer) - total_encrypted_length);
8997 EXPECT_GT(encrypted_length, 0u);
8998 total_encrypted_length += encrypted_length;
8999 }
9000 connection_.ProcessUdpPacket(
9001 kSelfAddress, kPeerAddress,
9002 QuicReceivedPacket(buffer, total_encrypted_length, clock_.Now(), false));
9003 if (connection_.GetSendAlarm()->IsSet()) {
9004 connection_.GetSendAlarm()->Fire();
9005 }
9006
9007 EXPECT_TRUE(connection_.connected());
9008}
9009
dschinazi66fc0242019-08-16 10:00:25 -07009010// Regression test for crbug.com/992831.
9011TEST_P(QuicConnectionTest, CoalescedPacketThatSavesFrames) {
9012 if (!QuicVersionHasLongHeaderLengths(connection_.transport_version())) {
9013 // Coalesced packets can only be encoded using long header lengths.
9014 return;
9015 }
9016 if (connection_.SupportsMultiplePacketNumberSpaces()) {
9017 // TODO(b/129151114) Enable this test with multiple packet number spaces.
9018 return;
9019 }
9020 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9021 EXPECT_TRUE(connection_.connected());
9022 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9023 EXPECT_CALL(visitor_, OnCryptoFrame(_))
9024 .Times(3)
9025 .WillRepeatedly([this](const QuicCryptoFrame& /*frame*/) {
9026 // QuicFrame takes ownership of the QuicBlockedFrame.
9027 connection_.SendControlFrame(QuicFrame(new QuicBlockedFrame(1, 3)));
9028 });
9029 } else {
9030 EXPECT_CALL(visitor_, OnStreamFrame(_))
9031 .Times(3)
9032 .WillRepeatedly([this](const QuicStreamFrame& /*frame*/) {
9033 // QuicFrame takes ownership of the QuicBlockedFrame.
9034 connection_.SendControlFrame(QuicFrame(new QuicBlockedFrame(1, 3)));
9035 });
9036 }
9037
9038 uint64_t packet_numbers[3] = {1, 2, 3};
9039 EncryptionLevel encryption_levels[3] = {
9040 ENCRYPTION_INITIAL, ENCRYPTION_INITIAL, ENCRYPTION_FORWARD_SECURE};
9041 char buffer[kMaxOutgoingPacketSize] = {};
9042 size_t total_encrypted_length = 0;
9043 for (int i = 0; i < 3; i++) {
9044 QuicPacketHeader header =
9045 ConstructPacketHeader(packet_numbers[i], encryption_levels[i]);
9046 QuicFrames frames;
9047 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9048 frames.push_back(QuicFrame(&crypto_frame_));
9049 } else {
9050 frames.push_back(QuicFrame(frame1_));
9051 }
9052 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
9053 peer_creator_.set_encryption_level(encryption_levels[i]);
9054 size_t encrypted_length = peer_framer_.EncryptPayload(
9055 encryption_levels[i], QuicPacketNumber(packet_numbers[i]), *packet,
9056 buffer + total_encrypted_length,
9057 sizeof(buffer) - total_encrypted_length);
9058 EXPECT_GT(encrypted_length, 0u);
9059 total_encrypted_length += encrypted_length;
9060 }
9061 connection_.ProcessUdpPacket(
9062 kSelfAddress, kPeerAddress,
9063 QuicReceivedPacket(buffer, total_encrypted_length, clock_.Now(), false));
9064 if (connection_.GetSendAlarm()->IsSet()) {
9065 connection_.GetSendAlarm()->Fire();
9066 }
9067
9068 EXPECT_TRUE(connection_.connected());
9069
9070 SendAckPacketToPeer();
9071}
9072
fayangd3016832019-08-08 07:24:45 -07009073// Regresstion test for b/138962304.
9074TEST_P(QuicConnectionTest, RtoAndWriteBlocked) {
fayangd3016832019-08-08 07:24:45 -07009075 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9076
9077 QuicStreamId stream_id = 2;
9078 QuicPacketNumber last_data_packet;
9079 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
9080 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9081
9082 // Writer gets blocked.
9083 writer_->SetWriteBlocked();
9084
9085 // Cancel the stream.
9086 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9087 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
fayang67f82272019-08-14 16:08:45 -07009088 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
9089 .WillRepeatedly(
9090 Invoke(&notifier_, &SimpleSessionNotifier::WillingToWrite));
fayangd3016832019-08-08 07:24:45 -07009091 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9092
9093 // Retransmission timer fires in RTO mode.
9094 connection_.GetRetransmissionAlarm()->Fire();
9095 // Verify no packets get flushed when writer is blocked.
9096 EXPECT_EQ(0u, connection_.NumQueuedPackets());
9097}
9098
9099// Regresstion test for b/138962304.
9100TEST_P(QuicConnectionTest, TlpAndWriteBlocked) {
fayangd3016832019-08-08 07:24:45 -07009101 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9102 connection_.SetMaxTailLossProbes(1);
9103
9104 QuicStreamId stream_id = 2;
9105 QuicPacketNumber last_data_packet;
9106 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
9107 SendStreamDataToPeer(4, "foo", 0, NO_FIN, &last_data_packet);
9108 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9109
9110 // Writer gets blocked.
9111 writer_->SetWriteBlocked();
9112
9113 // Cancel stream 2.
9114 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9115 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
9116 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9117
fayange62e63c2019-12-04 07:16:25 -08009118 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
fayangd3016832019-08-08 07:24:45 -07009119 // Retransmission timer fires in TLP mode.
9120 connection_.GetRetransmissionAlarm()->Fire();
9121 // Verify one packets is forced flushed when writer is blocked.
9122 EXPECT_EQ(1u, connection_.NumQueuedPackets());
9123}
9124
fayang67f82272019-08-14 16:08:45 -07009125// Regresstion test for b/139375344.
9126TEST_P(QuicConnectionTest, RtoForcesSendingPing) {
fayangcff885a2019-10-22 07:39:04 -07009127 if (connection_.PtoEnabled()) {
fayang67f82272019-08-14 16:08:45 -07009128 return;
9129 }
9130 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9131 connection_.SetMaxTailLossProbes(2);
9132 EXPECT_EQ(0u, connection_.GetStats().tlp_count);
9133 EXPECT_EQ(0u, connection_.GetStats().rto_count);
9134
9135 SendStreamDataToPeer(2, "foo", 0, NO_FIN, nullptr);
9136 QuicTime retransmission_time =
9137 connection_.GetRetransmissionAlarm()->deadline();
9138 EXPECT_NE(QuicTime::Zero(), retransmission_time);
9139 // TLP fires.
9140 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
9141 clock_.AdvanceTime(retransmission_time - clock_.Now());
9142 connection_.GetRetransmissionAlarm()->Fire();
9143 EXPECT_EQ(1u, connection_.GetStats().tlp_count);
9144 EXPECT_EQ(0u, connection_.GetStats().rto_count);
9145 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9146
9147 // Packet 1 gets acked.
9148 QuicAckFrame frame = InitAckFrame(1);
9149 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
9150 ProcessAckPacket(1, &frame);
9151 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9152 retransmission_time = connection_.GetRetransmissionAlarm()->deadline();
9153
9154 // RTO fires, verify a PING packet gets sent because there is no data to send.
9155 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(3), _, _));
fayangec14d2b2020-10-02 12:00:05 -07009156 if (!GetQuicReloadableFlag(quic_let_connection_handle_pings)) {
9157 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
9158 SendPing();
9159 }));
9160 }
fayang67f82272019-08-14 16:08:45 -07009161 clock_.AdvanceTime(retransmission_time - clock_.Now());
9162 connection_.GetRetransmissionAlarm()->Fire();
9163 EXPECT_EQ(1u, connection_.GetStats().tlp_count);
9164 EXPECT_EQ(1u, connection_.GetStats().rto_count);
9165 EXPECT_EQ(1u, writer_->ping_frames().size());
9166}
9167
fayangce0a3162019-08-15 09:05:36 -07009168TEST_P(QuicConnectionTest, ProbeTimeout) {
fayangce0a3162019-08-15 09:05:36 -07009169 QuicConfig config;
9170 QuicTagVector connection_options;
9171 connection_options.push_back(k2PTO);
9172 config.SetConnectionOptionsToSend(connection_options);
9173 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9174 connection_.SetFromConfig(config);
9175 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9176
9177 QuicStreamId stream_id = 2;
9178 QuicPacketNumber last_packet;
9179 SendStreamDataToPeer(stream_id, "foooooo", 0, NO_FIN, &last_packet);
9180 SendStreamDataToPeer(stream_id, "foooooo", 7, NO_FIN, &last_packet);
9181 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9182
9183 // Reset stream.
9184 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9185 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9186
9187 // Fire the PTO and verify only the RST_STREAM is resent, not stream data.
9188 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9189 connection_.GetRetransmissionAlarm()->Fire();
9190 EXPECT_EQ(0u, writer_->stream_frames().size());
9191 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
9192 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9193}
9194
fayang97ce41e2019-10-07 08:37:29 -07009195TEST_P(QuicConnectionTest, CloseConnectionAfter6ClientPTOs) {
fayang97ce41e2019-10-07 08:37:29 -07009196 QuicConfig config;
9197 QuicTagVector connection_options;
9198 connection_options.push_back(k1PTO);
9199 connection_options.push_back(k6PTO);
9200 config.SetConnectionOptionsToSend(connection_options);
dschinazif7c6a912020-05-05 11:39:53 -07009201 QuicConfigPeer::SetNegotiated(&config, true);
dschinazie7c38a52020-05-29 15:25:45 -07009202 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
9203 QuicConfigPeer::SetReceivedOriginalConnectionId(
9204 &config, connection_.connection_id());
9205 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
9206 &config, connection_.connection_id());
9207 }
fayang97ce41e2019-10-07 08:37:29 -07009208 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9209 connection_.SetFromConfig(config);
fayang656cbb52020-06-09 13:29:35 -07009210 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangaa4f3f22020-06-05 16:22:00 -07009211 EXPECT_CALL(visitor_, GetHandshakeState())
fayang37b3c5c2020-09-16 15:20:41 -07009212 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
fayangaa4f3f22020-06-05 16:22:00 -07009213 }
fayang37b3c5c2020-09-16 15:20:41 -07009214 connection_.OnHandshakeComplete();
fayang97ce41e2019-10-07 08:37:29 -07009215 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9216
9217 // Send stream data.
9218 SendStreamDataToPeer(
9219 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
9220 0, FIN, nullptr);
9221
fayang97ce41e2019-10-07 08:37:29 -07009222 // Fire the retransmission alarm 5 times.
9223 for (int i = 0; i < 5; ++i) {
ianswett825b48b2020-05-11 06:25:04 -07009224 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
fayang97ce41e2019-10-07 08:37:29 -07009225 connection_.GetRetransmissionAlarm()->Fire();
9226 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
9227 EXPECT_TRUE(connection_.connected());
9228 }
fayang2205d952020-05-12 13:45:56 -07009229 EXPECT_CALL(visitor_, OnPathDegrading());
9230 connection_.PathDegradingTimeout();
fayang97ce41e2019-10-07 08:37:29 -07009231
9232 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveTlpCount());
9233 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveRtoCount());
9234 EXPECT_EQ(5u, connection_.sent_packet_manager().GetConsecutivePtoCount());
9235 // Closes connection on 6th PTO.
ianswett825b48b2020-05-11 06:25:04 -07009236 // May send multiple connecction close packets with multiple PN spaces.
9237 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
fayang97ce41e2019-10-07 08:37:29 -07009238 EXPECT_CALL(visitor_,
9239 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
fayang2205d952020-05-12 13:45:56 -07009240 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
9241 connection_.GetBlackholeDetectorAlarm()->Fire();
fayang97ce41e2019-10-07 08:37:29 -07009242 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
9243 EXPECT_FALSE(connection_.connected());
9244 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
9245}
9246
fayangce0a3162019-08-15 09:05:36 -07009247TEST_P(QuicConnectionTest, CloseConnectionAfter7ClientPTOs) {
fayangce0a3162019-08-15 09:05:36 -07009248 QuicConfig config;
9249 QuicTagVector connection_options;
9250 connection_options.push_back(k2PTO);
9251 connection_options.push_back(k7PTO);
9252 config.SetConnectionOptionsToSend(connection_options);
dschinazif7c6a912020-05-05 11:39:53 -07009253 QuicConfigPeer::SetNegotiated(&config, true);
dschinazie7c38a52020-05-29 15:25:45 -07009254 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
9255 QuicConfigPeer::SetReceivedOriginalConnectionId(
9256 &config, connection_.connection_id());
9257 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
9258 &config, connection_.connection_id());
9259 }
fayangce0a3162019-08-15 09:05:36 -07009260 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9261 connection_.SetFromConfig(config);
fayang656cbb52020-06-09 13:29:35 -07009262 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangaa4f3f22020-06-05 16:22:00 -07009263 EXPECT_CALL(visitor_, GetHandshakeState())
fayang37b3c5c2020-09-16 15:20:41 -07009264 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
fayangaa4f3f22020-06-05 16:22:00 -07009265 }
fayang37b3c5c2020-09-16 15:20:41 -07009266 connection_.OnHandshakeComplete();
fayangce0a3162019-08-15 09:05:36 -07009267 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9268
9269 // Send stream data.
9270 SendStreamDataToPeer(
9271 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
9272 0, FIN, nullptr);
9273
9274 // Fire the retransmission alarm 6 times.
9275 for (int i = 0; i < 6; ++i) {
9276 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
9277 connection_.GetRetransmissionAlarm()->Fire();
9278 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
9279 EXPECT_TRUE(connection_.connected());
9280 }
fayang2205d952020-05-12 13:45:56 -07009281 EXPECT_CALL(visitor_, OnPathDegrading());
9282 connection_.PathDegradingTimeout();
fayangce0a3162019-08-15 09:05:36 -07009283
9284 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveTlpCount());
9285 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveRtoCount());
9286 EXPECT_EQ(6u, connection_.sent_packet_manager().GetConsecutivePtoCount());
9287 // Closes connection on 7th PTO.
9288 EXPECT_CALL(visitor_,
9289 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07009290 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
fayang2205d952020-05-12 13:45:56 -07009291 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
9292 connection_.GetBlackholeDetectorAlarm()->Fire();
fayangce0a3162019-08-15 09:05:36 -07009293 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
9294 EXPECT_FALSE(connection_.connected());
9295 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
9296}
9297
9298TEST_P(QuicConnectionTest, CloseConnectionAfter8ClientPTOs) {
fayangce0a3162019-08-15 09:05:36 -07009299 QuicConfig config;
9300 QuicTagVector connection_options;
9301 connection_options.push_back(k2PTO);
9302 connection_options.push_back(k8PTO);
dschinazif7c6a912020-05-05 11:39:53 -07009303 QuicConfigPeer::SetNegotiated(&config, true);
dschinazie7c38a52020-05-29 15:25:45 -07009304 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
9305 QuicConfigPeer::SetReceivedOriginalConnectionId(
9306 &config, connection_.connection_id());
9307 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
9308 &config, connection_.connection_id());
9309 }
fayangce0a3162019-08-15 09:05:36 -07009310 config.SetConnectionOptionsToSend(connection_options);
9311 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9312 connection_.SetFromConfig(config);
fayang656cbb52020-06-09 13:29:35 -07009313 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangaa4f3f22020-06-05 16:22:00 -07009314 EXPECT_CALL(visitor_, GetHandshakeState())
fayang37b3c5c2020-09-16 15:20:41 -07009315 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
fayangaa4f3f22020-06-05 16:22:00 -07009316 }
fayang37b3c5c2020-09-16 15:20:41 -07009317 connection_.OnHandshakeComplete();
fayangce0a3162019-08-15 09:05:36 -07009318 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9319
9320 // Send stream data.
9321 SendStreamDataToPeer(
9322 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
9323 0, FIN, nullptr);
9324
9325 // Fire the retransmission alarm 7 times.
9326 for (int i = 0; i < 7; ++i) {
9327 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
9328 connection_.GetRetransmissionAlarm()->Fire();
9329 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
9330 EXPECT_TRUE(connection_.connected());
9331 }
fayang2205d952020-05-12 13:45:56 -07009332 EXPECT_CALL(visitor_, OnPathDegrading());
9333 connection_.PathDegradingTimeout();
fayangce0a3162019-08-15 09:05:36 -07009334
9335 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveTlpCount());
9336 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveRtoCount());
9337 EXPECT_EQ(7u, connection_.sent_packet_manager().GetConsecutivePtoCount());
9338 // Closes connection on 8th PTO.
9339 EXPECT_CALL(visitor_,
9340 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07009341 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
fayang2205d952020-05-12 13:45:56 -07009342 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
9343 connection_.GetBlackholeDetectorAlarm()->Fire();
fayangce0a3162019-08-15 09:05:36 -07009344 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
9345 EXPECT_FALSE(connection_.connected());
9346 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
9347}
9348
fayang5f135052019-08-22 17:59:40 -07009349TEST_P(QuicConnectionTest, DeprecateHandshakeMode) {
9350 if (!connection_.version().SupportsAntiAmplificationLimit()) {
9351 return;
9352 }
9353 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9354 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9355
9356 // Send CHLO.
9357 connection_.SendCryptoStreamData();
9358 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9359
9360 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
9361 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
9362 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9363 QuicAckFrame frame1 = InitAckFrame(1);
9364 // Received ACK for packet 1.
9365 ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL);
9366
9367 // Verify retransmission alarm is still set because handshake is not
9368 // confirmed although there is nothing in flight.
9369 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9370 EXPECT_EQ(0u, connection_.GetStats().pto_count);
9371 EXPECT_EQ(0u, connection_.GetStats().crypto_retransmit_count);
9372
9373 // PTO fires, verify a PING packet gets sent because there is no data to send.
fayang5d011982020-05-13 14:14:38 -07009374 EXPECT_CALL(*send_algorithm_,
9375 OnPacketSent(_, _,
9376 GetQuicReloadableFlag(quic_default_on_pto)
9377 ? QuicPacketNumber(2)
9378 : QuicPacketNumber(3),
9379 _, _));
fayangec14d2b2020-10-02 12:00:05 -07009380 if (!GetQuicReloadableFlag(quic_let_connection_handle_pings)) {
9381 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
9382 SendPing();
9383 }));
9384 }
fayang5f135052019-08-22 17:59:40 -07009385 connection_.GetRetransmissionAlarm()->Fire();
9386 EXPECT_EQ(1u, connection_.GetStats().pto_count);
fayangaf9903b2020-05-14 14:34:28 -07009387 EXPECT_EQ(1u, connection_.GetStats().crypto_retransmit_count);
fayang5f135052019-08-22 17:59:40 -07009388 EXPECT_EQ(1u, writer_->ping_frames().size());
9389}
9390
9391TEST_P(QuicConnectionTest, AntiAmplificationLimit) {
9392 if (!connection_.version().SupportsAntiAmplificationLimit()) {
9393 return;
9394 }
fayang5f135052019-08-22 17:59:40 -07009395 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9396
9397 set_perspective(Perspective::IS_SERVER);
9398 // Verify no data can be sent at the beginning because bytes received is 0.
9399 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9400 connection_.SendCryptoDataWithString("foo", 0);
fayang60d9c042020-07-06 08:42:40 -07009401 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
9402 EXPECT_FALSE(connection_.CanWrite(NO_RETRANSMITTABLE_DATA));
fayang5f135052019-08-22 17:59:40 -07009403 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9404
9405 // Receives packet 1.
9406 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
9407
9408 const size_t anti_amplification_factor =
fayang60d9c042020-07-06 08:42:40 -07009409 GetQuicFlag(FLAGS_quic_anti_amplification_factor);
fayang5f135052019-08-22 17:59:40 -07009410 // Verify now packets can be sent.
9411 for (size_t i = 0; i < anti_amplification_factor; ++i) {
9412 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9413 connection_.SendCryptoDataWithString("foo", i * 3);
9414 // Verify retransmission alarm is not set if throttled by anti-amplification
9415 // limit.
9416 EXPECT_EQ(i != anti_amplification_factor - 1,
9417 connection_.GetRetransmissionAlarm()->IsSet());
9418 }
9419 // Verify server is throttled by anti-amplification limit.
9420 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9421 connection_.SendCryptoDataWithString("foo", anti_amplification_factor * 3);
9422
9423 // Receives packet 2.
9424 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
9425 // Verify more packets can be sent.
9426 for (size_t i = anti_amplification_factor; i < anti_amplification_factor * 2;
9427 ++i) {
9428 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9429 connection_.SendCryptoDataWithString("foo", i * 3);
9430 }
9431 // Verify server is throttled by anti-amplification limit.
9432 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9433 connection_.SendCryptoDataWithString("foo",
9434 2 * anti_amplification_factor * 3);
9435
9436 ProcessPacket(3);
9437 // Verify anti-amplification limit is gone after address validation.
9438 for (size_t i = 0; i < 100; ++i) {
9439 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9440 connection_.SendStreamDataWithString(3, "first", i * 0, NO_FIN);
9441 }
9442}
9443
fayang84305ed2020-08-24 13:00:40 -07009444TEST_P(QuicConnectionTest, 3AntiAmplificationLimit) {
9445 if (!connection_.version().SupportsAntiAmplificationLimit()) {
9446 return;
9447 }
9448 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9449
9450 set_perspective(Perspective::IS_SERVER);
9451 QuicConfig config;
9452 QuicTagVector connection_options;
9453 connection_options.push_back(k3AFF);
9454 config.SetInitialReceivedConnectionOptions(connection_options);
9455 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
9456 QuicConfigPeer::SetReceivedOriginalConnectionId(
9457 &config, connection_.connection_id());
9458 QuicConfigPeer::SetReceivedInitialSourceConnectionId(&config,
9459 QuicConnectionId());
9460 }
9461 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9462 connection_.SetFromConfig(config);
9463
9464 // Verify no data can be sent at the beginning because bytes received is 0.
9465 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9466 connection_.SendCryptoDataWithString("foo", 0);
9467 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
9468 EXPECT_FALSE(connection_.CanWrite(NO_RETRANSMITTABLE_DATA));
9469 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9470
9471 // Receives packet 1.
9472 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
9473
9474 const size_t anti_amplification_factor = 3;
9475 // Verify now packets can be sent.
9476 for (size_t i = 0; i < anti_amplification_factor; ++i) {
9477 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9478 connection_.SendCryptoDataWithString("foo", i * 3);
9479 // Verify retransmission alarm is not set if throttled by anti-amplification
9480 // limit.
9481 EXPECT_EQ(i != anti_amplification_factor - 1,
9482 connection_.GetRetransmissionAlarm()->IsSet());
9483 }
9484 // Verify server is throttled by anti-amplification limit.
9485 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9486 connection_.SendCryptoDataWithString("foo", anti_amplification_factor * 3);
9487
9488 // Receives packet 2.
9489 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
9490 // Verify more packets can be sent.
9491 for (size_t i = anti_amplification_factor; i < anti_amplification_factor * 2;
9492 ++i) {
9493 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9494 connection_.SendCryptoDataWithString("foo", i * 3);
9495 }
9496 // Verify server is throttled by anti-amplification limit.
9497 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9498 connection_.SendCryptoDataWithString("foo",
9499 2 * anti_amplification_factor * 3);
9500
9501 ProcessPacket(3);
9502 // Verify anti-amplification limit is gone after address validation.
9503 for (size_t i = 0; i < 100; ++i) {
9504 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9505 connection_.SendStreamDataWithString(3, "first", i * 0, NO_FIN);
9506 }
9507}
9508
fayang2f1d6032020-09-08 12:15:30 -07009509TEST_P(QuicConnectionTest, 10AntiAmplificationLimit) {
9510 if (!connection_.version().SupportsAntiAmplificationLimit()) {
9511 return;
9512 }
9513 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9514
9515 set_perspective(Perspective::IS_SERVER);
9516 QuicConfig config;
9517 QuicTagVector connection_options;
9518 connection_options.push_back(k10AF);
9519 config.SetInitialReceivedConnectionOptions(connection_options);
9520 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
9521 QuicConfigPeer::SetReceivedOriginalConnectionId(
9522 &config, connection_.connection_id());
9523 QuicConfigPeer::SetReceivedInitialSourceConnectionId(&config,
9524 QuicConnectionId());
9525 }
9526 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9527 connection_.SetFromConfig(config);
9528
9529 // Verify no data can be sent at the beginning because bytes received is 0.
9530 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9531 connection_.SendCryptoDataWithString("foo", 0);
9532 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
9533 EXPECT_FALSE(connection_.CanWrite(NO_RETRANSMITTABLE_DATA));
9534 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9535
9536 // Receives packet 1.
9537 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
9538
9539 const size_t anti_amplification_factor = 10;
9540 // Verify now packets can be sent.
9541 for (size_t i = 0; i < anti_amplification_factor; ++i) {
9542 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9543 connection_.SendCryptoDataWithString("foo", i * 3);
9544 // Verify retransmission alarm is not set if throttled by anti-amplification
9545 // limit.
9546 EXPECT_EQ(i != anti_amplification_factor - 1,
9547 connection_.GetRetransmissionAlarm()->IsSet());
9548 }
9549 // Verify server is throttled by anti-amplification limit.
9550 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9551 connection_.SendCryptoDataWithString("foo", anti_amplification_factor * 3);
9552
9553 // Receives packet 2.
9554 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
9555 // Verify more packets can be sent.
9556 for (size_t i = anti_amplification_factor; i < anti_amplification_factor * 2;
9557 ++i) {
9558 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9559 connection_.SendCryptoDataWithString("foo", i * 3);
9560 }
9561 // Verify server is throttled by anti-amplification limit.
9562 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9563 connection_.SendCryptoDataWithString("foo",
9564 2 * anti_amplification_factor * 3);
9565
9566 ProcessPacket(3);
9567 // Verify anti-amplification limit is gone after address validation.
9568 for (size_t i = 0; i < 100; ++i) {
9569 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9570 connection_.SendStreamDataWithString(3, "first", i * 0, NO_FIN);
9571 }
9572}
9573
fayang6a258412020-05-28 08:57:12 -07009574TEST_P(QuicConnectionTest, AckPendingWithAmplificationLimited) {
fayang60d9c042020-07-06 08:42:40 -07009575 if (!connection_.version().SupportsAntiAmplificationLimit()) {
fayang6a258412020-05-28 08:57:12 -07009576 return;
9577 }
9578 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9579 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(AnyNumber());
9580 set_perspective(Perspective::IS_SERVER);
9581 use_tagging_decrypter();
9582 connection_.SetEncrypter(ENCRYPTION_INITIAL,
9583 std::make_unique<TaggingEncrypter>(0x01));
9584 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
9585 // Receives packet 1.
9586 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
9587 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
9588 std::make_unique<TaggingEncrypter>(0x02));
9589 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
fayang9adfb532020-06-04 06:58:45 -07009590 EXPECT_TRUE(connection_.HasPendingAcks());
fayang6a258412020-05-28 08:57:12 -07009591 // Send response in different encryption level and cause amplification factor
9592 // throttled.
9593 size_t i = 0;
9594 while (connection_.CanWrite(HAS_RETRANSMITTABLE_DATA)) {
9595 connection_.SendCryptoDataWithString(std::string(1024, 'a'), i * 1024,
9596 ENCRYPTION_HANDSHAKE);
9597 ++i;
9598 }
9599 // Verify ACK is still pending.
fayang9adfb532020-06-04 06:58:45 -07009600 EXPECT_TRUE(connection_.HasPendingAcks());
fayang6a258412020-05-28 08:57:12 -07009601
9602 // Fire ACK alarm and verify ACK cannot be sent due to amplification factor.
9603 clock_.AdvanceTime(connection_.GetAckAlarm()->deadline() - clock_.Now());
9604 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9605 connection_.GetAckAlarm()->Fire();
9606 // Verify ACK alarm is cancelled.
fayang9adfb532020-06-04 06:58:45 -07009607 EXPECT_FALSE(connection_.HasPendingAcks());
fayang6a258412020-05-28 08:57:12 -07009608
9609 // Receives packet 2 and verify ACK gets flushed.
9610 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9611 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
9612 EXPECT_FALSE(writer_->ack_frames().empty());
9613}
9614
fkastenholza3660102019-08-28 05:19:24 -07009615TEST_P(QuicConnectionTest, ConnectionCloseFrameType) {
9616 if (!VersionHasIetfQuicFrames(version().transport_version)) {
9617 // Test relevent only for IETF QUIC.
9618 return;
9619 }
9620 const QuicErrorCode kQuicErrorCode = IETF_QUIC_PROTOCOL_VIOLATION;
9621 // Use the (unknown) frame type of 9999 to avoid triggering any logic
9622 // which might be associated with the processing of a known frame type.
9623 const uint64_t kTransportCloseFrameType = 9999u;
9624 QuicFramerPeer::set_current_received_frame_type(
9625 QuicConnectionPeer::GetFramer(&connection_), kTransportCloseFrameType);
9626 // Do a transport connection close
9627 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
9628 connection_.CloseConnection(
9629 kQuicErrorCode, "Some random error message",
9630 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
9631 const std::vector<QuicConnectionCloseFrame>& connection_close_frames =
9632 writer_->connection_close_frames();
9633 ASSERT_EQ(1u, connection_close_frames.size());
9634 EXPECT_EQ(IETF_QUIC_TRANSPORT_CONNECTION_CLOSE,
9635 connection_close_frames[0].close_type);
bnc77e77b82020-04-05 10:36:49 -07009636 EXPECT_EQ(kQuicErrorCode, connection_close_frames[0].quic_error_code);
fkastenholza3660102019-08-28 05:19:24 -07009637 EXPECT_EQ(kTransportCloseFrameType,
9638 connection_close_frames[0].transport_close_frame_type);
9639}
9640
fayang0fcbf352019-08-30 11:15:58 -07009641// Regression test for b/137401387 and b/138962304.
9642TEST_P(QuicConnectionTest, RtoPacketAsTwo) {
fayangcff885a2019-10-22 07:39:04 -07009643 if (connection_.PtoEnabled()) {
fayang0fcbf352019-08-30 11:15:58 -07009644 return;
9645 }
9646 connection_.SetMaxTailLossProbes(1);
9647 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
9648 std::string stream_data(3000, 's');
9649 // Send packets 1 - 66 and exhaust cwnd.
9650 for (size_t i = 0; i < 22; ++i) {
9651 // 3 packets for each stream, the first 2 are guaranteed to be full packets.
9652 SendStreamDataToPeer(i + 2, stream_data, 0, FIN, nullptr);
9653 }
9654 CongestionBlockWrites();
9655
9656 // Fires TLP. Please note, this tail loss probe has 1 byte less stream data
9657 // compared to packet 1 because packet number length increases.
9658 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(67), _, _));
9659 connection_.GetRetransmissionAlarm()->Fire();
9660 // Fires RTO. Please note, although packets 2 and 3 *should* be RTOed, but
9661 // packet 2 gets RTOed to two packets because packet number length increases.
9662 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(68), _, _));
9663 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(69), _, _));
9664 connection_.GetRetransmissionAlarm()->Fire();
9665
9666 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9667 // Resets all streams except 2 and ack packets 1 and 2. Now, packet 3 is the
9668 // only one containing retransmittable frames.
9669 for (size_t i = 1; i < 22; ++i) {
9670 notifier_.OnStreamReset(i + 2, QUIC_STREAM_CANCELLED);
9671 }
9672 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
9673 QuicAckFrame frame =
9674 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(3)}});
9675 ProcessAckPacket(1, &frame);
9676 CongestionUnblockWrites();
9677
9678 // Fires TLP, verify a PING gets sent because packet 3 is marked
9679 // RTO_RETRANSMITTED.
9680 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(70), _, _));
fayangec14d2b2020-10-02 12:00:05 -07009681 if (!GetQuicReloadableFlag(quic_let_connection_handle_pings)) {
9682 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
9683 SendPing();
9684 }));
9685 }
fayang0fcbf352019-08-30 11:15:58 -07009686 connection_.GetRetransmissionAlarm()->Fire();
9687}
9688
fayang4c1c2362019-09-13 07:20:01 -07009689TEST_P(QuicConnectionTest, PtoSkipsPacketNumber) {
fayang4c1c2362019-09-13 07:20:01 -07009690 QuicConfig config;
9691 QuicTagVector connection_options;
9692 connection_options.push_back(k1PTO);
9693 connection_options.push_back(kPTOS);
9694 config.SetConnectionOptionsToSend(connection_options);
9695 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9696 connection_.SetFromConfig(config);
9697 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9698
9699 QuicStreamId stream_id = 2;
9700 QuicPacketNumber last_packet;
9701 SendStreamDataToPeer(stream_id, "foooooo", 0, NO_FIN, &last_packet);
9702 SendStreamDataToPeer(stream_id, "foooooo", 7, NO_FIN, &last_packet);
9703 EXPECT_EQ(QuicPacketNumber(2), last_packet);
9704 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9705
9706 // Fire PTO and verify the PTO retransmission skips one packet number.
9707 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9708 connection_.GetRetransmissionAlarm()->Fire();
9709 EXPECT_EQ(1u, writer_->stream_frames().size());
9710 EXPECT_EQ(QuicPacketNumber(4), writer_->last_packet_header().packet_number);
9711 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9712}
9713
fayang58f71072019-11-05 08:47:02 -08009714TEST_P(QuicConnectionTest, SendCoalescedPackets) {
9715 if (!connection_.version().CanSendCoalescedPackets()) {
9716 return;
9717 }
fayang6100ab72020-03-18 13:16:25 -07009718 MockQuicConnectionDebugVisitor debug_visitor;
9719 connection_.set_debug_visitor(&debug_visitor);
wubacc7c972020-09-14 16:16:32 -07009720 if (connection_.sent_packet_manager()
9721 .give_sent_packet_to_debug_visitor_after_sent()) {
9722 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _)).Times(3);
9723 } else {
9724 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(3);
9725 }
fayang6100ab72020-03-18 13:16:25 -07009726 EXPECT_CALL(debug_visitor, OnCoalescedPacketSent(_, _)).Times(1);
fayang44ae4e92020-04-28 13:09:42 -07009727 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
fayang58f71072019-11-05 08:47:02 -08009728 {
9729 QuicConnection::ScopedPacketFlusher flusher(&connection_);
9730 use_tagging_decrypter();
9731 connection_.SetEncrypter(ENCRYPTION_INITIAL,
9732 std::make_unique<TaggingEncrypter>(0x01));
9733 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
9734 connection_.SendCryptoDataWithString("foo", 0);
9735 // Verify this packet is on hold.
9736 EXPECT_EQ(0u, writer_->packets_write_attempts());
9737
9738 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
9739 std::make_unique<TaggingEncrypter>(0x02));
9740 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
9741 connection_.SendCryptoDataWithString("bar", 3);
9742 EXPECT_EQ(0u, writer_->packets_write_attempts());
9743
9744 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
9745 std::make_unique<TaggingEncrypter>(0x03));
9746 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
9747 SendStreamDataToPeer(2, "baz", 3, NO_FIN, nullptr);
9748 }
9749 // Verify all 3 packets are coalesced in the same UDP datagram.
9750 EXPECT_EQ(1u, writer_->packets_write_attempts());
9751 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
9752 // Verify the packet is padded to full.
9753 EXPECT_EQ(connection_.max_packet_length(), writer_->last_packet_size());
9754
9755 // Verify packet process.
9756 EXPECT_EQ(1u, writer_->crypto_frames().size());
9757 EXPECT_EQ(0u, writer_->stream_frames().size());
9758 // Verify there is coalesced packet.
9759 EXPECT_NE(nullptr, writer_->coalesced_packet());
9760}
9761
dschinazi6458eb32020-06-23 12:38:41 -07009762TEST_P(QuicConnectionTest, LegacyVersionEncapsulation) {
9763 connection_.EnableLegacyVersionEncapsulation("test.example.org");
9764
9765 MockQuicConnectionDebugVisitor debug_visitor;
9766 connection_.set_debug_visitor(&debug_visitor);
wubacc7c972020-09-14 16:16:32 -07009767 if (connection_.sent_packet_manager()
9768 .give_sent_packet_to_debug_visitor_after_sent()) {
9769 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _)).Times(1);
9770 } else {
9771 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(1);
9772 }
dschinazi6458eb32020-06-23 12:38:41 -07009773
9774 // Our TestPacketWriter normally parses the sent packet using the version
9775 // from the connection, so here we need to tell it to use the encapsulation
9776 // version, and reset the initial decrypter for that version.
9777 writer_->framer()->SetSupportedVersions(
9778 SupportedVersions(LegacyVersionForEncapsulation()));
9779 writer_->framer()->framer()->SetInitialObfuscators(
9780 connection_.connection_id());
9781
9782 {
9783 QuicConnection::ScopedPacketFlusher flusher(&connection_);
9784 connection_.SendCryptoDataWithString("TEST_CRYPTO_DATA", /*offset=*/0);
9785 }
9786
9787 EXPECT_EQ(1u, writer_->packets_write_attempts());
9788 // Verify that the packet is fully padded.
9789 EXPECT_EQ(connection_.max_packet_length(), writer_->last_packet_size());
9790
9791 // Check that the connection stats show Legacy Version Encapsulation was used.
9792 EXPECT_GT(connection_.GetStats().sent_legacy_version_encapsulated_packets,
9793 0u);
9794
9795 // Verify that the sent packet was in fact encapsulated, and check header.
9796 const QuicPacketHeader& encapsulated_header = writer_->last_packet_header();
9797 EXPECT_TRUE(encapsulated_header.version_flag);
9798 EXPECT_EQ(encapsulated_header.version, LegacyVersionForEncapsulation());
9799 EXPECT_EQ(encapsulated_header.destination_connection_id,
9800 connection_.connection_id());
9801
9802 // Encapsulated packet should contain a stream frame for the crypto stream,
9803 // optionally padding, and nothing else.
9804 EXPECT_EQ(0u, writer_->crypto_frames().size());
9805 EXPECT_EQ(1u, writer_->stream_frames().size());
9806 EXPECT_EQ(writer_->frame_count(), writer_->framer()->padding_frames().size() +
9807 writer_->stream_frames().size());
9808}
9809
fayang01062942020-01-22 07:23:23 -08009810TEST_P(QuicConnectionTest, ClientReceivedHandshakeDone) {
9811 if (!connection_.version().HasHandshakeDone()) {
9812 return;
9813 }
9814 EXPECT_CALL(visitor_, OnHandshakeDoneReceived());
9815 QuicFrames frames;
9816 frames.push_back(QuicFrame(QuicHandshakeDoneFrame()));
9817 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
9818 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
9819}
9820
9821TEST_P(QuicConnectionTest, ServerReceivedHandshakeDone) {
9822 if (!connection_.version().HasHandshakeDone()) {
9823 return;
9824 }
9825 set_perspective(Perspective::IS_SERVER);
9826 EXPECT_CALL(visitor_, OnHandshakeDoneReceived()).Times(0);
9827 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
9828 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
9829 QuicFrames frames;
9830 frames.push_back(QuicFrame(QuicHandshakeDoneFrame()));
9831 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
9832 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
9833 EXPECT_EQ(1, connection_close_frame_count_);
9834 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
9835 IsError(IETF_QUIC_PROTOCOL_VIOLATION));
9836}
9837
fayang18ff23b2020-01-28 09:19:00 -08009838TEST_P(QuicConnectionTest, MultiplePacketNumberSpacePto) {
9839 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
9840 return;
9841 }
9842 use_tagging_decrypter();
9843 // Send handshake packet.
9844 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
9845 std::make_unique<TaggingEncrypter>(0x02));
9846 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
fayang44ae4e92020-04-28 13:09:42 -07009847 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
fayang18ff23b2020-01-28 09:19:00 -08009848 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
9849 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
9850
9851 // Send application data.
9852 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
9853 0, NO_FIN);
9854 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
9855 QuicTime retransmission_time =
9856 connection_.GetRetransmissionAlarm()->deadline();
9857 EXPECT_NE(QuicTime::Zero(), retransmission_time);
9858
9859 // Retransmit handshake data.
9860 clock_.AdvanceTime(retransmission_time - clock_.Now());
fayang5d011982020-05-13 14:14:38 -07009861 EXPECT_CALL(*send_algorithm_,
9862 OnPacketSent(_, _,
9863 GetQuicReloadableFlag(quic_default_on_pto)
9864 ? QuicPacketNumber(3)
9865 : QuicPacketNumber(4),
9866 _, _));
fayangd8682452020-09-28 09:09:29 -07009867 if (!GetQuicReloadableFlag(quic_fix_missing_initial_keys2)) {
9868 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
9869 }
fayang18ff23b2020-01-28 09:19:00 -08009870 connection_.GetRetransmissionAlarm()->Fire();
fayangf5f83e52020-09-14 10:29:29 -07009871 // Verify 1-RTT packet gets coalesced with handshake retransmission.
9872 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
fayang18ff23b2020-01-28 09:19:00 -08009873
9874 // Send application data.
9875 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
9876 4, NO_FIN);
9877 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
9878 retransmission_time = connection_.GetRetransmissionAlarm()->deadline();
9879 EXPECT_NE(QuicTime::Zero(), retransmission_time);
9880
9881 // Retransmit handshake data again.
9882 clock_.AdvanceTime(retransmission_time - clock_.Now());
fayangfe963c52020-07-16 06:56:09 -07009883 QuicPacketNumber handshake_retransmission =
9884 GetQuicReloadableFlag(quic_default_on_pto) ? QuicPacketNumber(5)
9885 : QuicPacketNumber(7);
fayangf5f83e52020-09-14 10:29:29 -07009886 handshake_retransmission += 1;
9887 EXPECT_CALL(*send_algorithm_,
9888 OnPacketSent(_, _, handshake_retransmission + 1, _, _));
fayang5d011982020-05-13 14:14:38 -07009889 EXPECT_CALL(*send_algorithm_,
fayangfe963c52020-07-16 06:56:09 -07009890 OnPacketSent(_, _, handshake_retransmission, _, _));
fayangd8682452020-09-28 09:09:29 -07009891 if (!GetQuicReloadableFlag(quic_fix_missing_initial_keys2)) {
9892 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
9893 }
fayang18ff23b2020-01-28 09:19:00 -08009894 connection_.GetRetransmissionAlarm()->Fire();
fayangf5f83e52020-09-14 10:29:29 -07009895 // Verify 1-RTT packet gets coalesced with handshake retransmission.
9896 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
fayang18ff23b2020-01-28 09:19:00 -08009897
9898 // Discard handshake key.
9899 connection_.OnHandshakeComplete();
9900 retransmission_time = connection_.GetRetransmissionAlarm()->deadline();
9901 EXPECT_NE(QuicTime::Zero(), retransmission_time);
9902
9903 // Retransmit application data.
9904 clock_.AdvanceTime(retransmission_time - clock_.Now());
fayangfe963c52020-07-16 06:56:09 -07009905 QuicPacketNumber application_retransmission =
9906 GetQuicReloadableFlag(quic_default_on_pto) ? QuicPacketNumber(6)
9907 : QuicPacketNumber(9);
fayangf5f83e52020-09-14 10:29:29 -07009908 application_retransmission += 2;
fayang5d011982020-05-13 14:14:38 -07009909 EXPECT_CALL(*send_algorithm_,
fayangfe963c52020-07-16 06:56:09 -07009910 OnPacketSent(_, _, application_retransmission, _, _));
fayang18ff23b2020-01-28 09:19:00 -08009911 connection_.GetRetransmissionAlarm()->Fire();
9912 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
9913}
9914
dschinazie7c38a52020-05-29 15:25:45 -07009915void QuicConnectionTest::TestClientRetryHandling(
9916 bool invalid_retry_tag,
9917 bool missing_original_id_in_config,
9918 bool wrong_original_id_in_config,
9919 bool missing_retry_id_in_config,
9920 bool wrong_retry_id_in_config) {
dschinazi39e5e552020-05-06 13:55:24 -07009921 if (invalid_retry_tag) {
dschinazie7c38a52020-05-29 15:25:45 -07009922 ASSERT_FALSE(missing_original_id_in_config);
9923 ASSERT_FALSE(wrong_original_id_in_config);
9924 ASSERT_FALSE(missing_retry_id_in_config);
9925 ASSERT_FALSE(wrong_retry_id_in_config);
dschinazi39e5e552020-05-06 13:55:24 -07009926 } else {
dschinazie7c38a52020-05-29 15:25:45 -07009927 ASSERT_FALSE(missing_original_id_in_config && wrong_original_id_in_config);
9928 ASSERT_FALSE(missing_retry_id_in_config && wrong_retry_id_in_config);
dschinazi39e5e552020-05-06 13:55:24 -07009929 }
dschinazi278efae2020-01-28 17:03:09 -08009930 if (!version().HasRetryIntegrityTag()) {
9931 return;
9932 }
dschinazi39e5e552020-05-06 13:55:24 -07009933
9934 // These values come from draft-ietf-quic-tls Appendix A.4.
dschinazi39e5e552020-05-06 13:55:24 -07009935 char retry_packet27[] = {
9936 0xff, 0xff, 0x00, 0x00, 0x1b, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a,
9937 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0xa5, 0x23, 0xcb, 0x5b,
9938 0xa5, 0x24, 0x69, 0x5f, 0x65, 0x69, 0xf2, 0x93, 0xa1, 0x35, 0x9d, 0x8e};
dschinazib3fed9e2020-06-11 11:59:33 -07009939 char retry_packet29[] = {
9940 0xff, 0xff, 0x00, 0x00, 0x1d, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a,
9941 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0xd1, 0x69, 0x26, 0xd8,
9942 0x1f, 0x6f, 0x9c, 0xa2, 0x95, 0x3a, 0x8a, 0xa4, 0x57, 0x5e, 0x1e, 0x49};
dschinazi39e5e552020-05-06 13:55:24 -07009943
9944 char* retry_packet;
9945 size_t retry_packet_length;
dschinazib3fed9e2020-06-11 11:59:33 -07009946 if (version() == ParsedQuicVersion::Draft29()) {
9947 retry_packet = retry_packet29;
9948 retry_packet_length = QUICHE_ARRAYSIZE(retry_packet29);
dschinazib3fed9e2020-06-11 11:59:33 -07009949 } else if (version() == ParsedQuicVersion::Draft27()) {
dschinazi39e5e552020-05-06 13:55:24 -07009950 retry_packet = retry_packet27;
9951 retry_packet_length = QUICHE_ARRAYSIZE(retry_packet27);
dschinazi39e5e552020-05-06 13:55:24 -07009952 } else {
dschinazi278efae2020-01-28 17:03:09 -08009953 // TODO(dschinazi) generate retry packets for all versions once we have
9954 // server-side support for generating these programmatically.
9955 return;
9956 }
9957
dschinazi278efae2020-01-28 17:03:09 -08009958 char original_connection_id_bytes[] = {0x83, 0x94, 0xc8, 0xf0,
9959 0x3e, 0x51, 0x57, 0x08};
9960 char new_connection_id_bytes[] = {0xf0, 0x67, 0xa5, 0x50,
9961 0x2a, 0x42, 0x62, 0xb5};
9962 char retry_token_bytes[] = {0x74, 0x6f, 0x6b, 0x65, 0x6e};
9963
9964 QuicConnectionId original_connection_id(
9965 original_connection_id_bytes,
9966 QUICHE_ARRAYSIZE(original_connection_id_bytes));
9967 QuicConnectionId new_connection_id(new_connection_id_bytes,
9968 QUICHE_ARRAYSIZE(new_connection_id_bytes));
9969
9970 std::string retry_token(retry_token_bytes,
9971 QUICHE_ARRAYSIZE(retry_token_bytes));
9972
dschinazi39e5e552020-05-06 13:55:24 -07009973 if (invalid_retry_tag) {
9974 // Flip the last bit of the retry packet to prevent the integrity tag
9975 // from validating correctly.
9976 retry_packet[retry_packet_length - 1] ^= 1;
dschinazi278efae2020-01-28 17:03:09 -08009977 }
9978
dschinazi39e5e552020-05-06 13:55:24 -07009979 QuicConnectionId config_original_connection_id = original_connection_id;
dschinazie7c38a52020-05-29 15:25:45 -07009980 if (wrong_original_id_in_config) {
dschinazi39e5e552020-05-06 13:55:24 -07009981 // Flip the first bit of the connection ID.
9982 ASSERT_FALSE(config_original_connection_id.IsEmpty());
9983 config_original_connection_id.mutable_data()[0] ^= 0x80;
9984 }
dschinazie7c38a52020-05-29 15:25:45 -07009985 QuicConnectionId config_retry_source_connection_id = new_connection_id;
9986 if (wrong_retry_id_in_config) {
9987 // Flip the first bit of the connection ID.
9988 ASSERT_FALSE(config_retry_source_connection_id.IsEmpty());
9989 config_retry_source_connection_id.mutable_data()[0] ^= 0x80;
9990 }
dschinazi278efae2020-01-28 17:03:09 -08009991
dschinazi39e5e552020-05-06 13:55:24 -07009992 // Make sure the connection uses the connection ID from the test vectors,
9993 QuicConnectionPeer::SetServerConnectionId(&connection_,
9994 original_connection_id);
dschinazi278efae2020-01-28 17:03:09 -08009995
dschinazi39e5e552020-05-06 13:55:24 -07009996 // Process the RETRY packet.
9997 connection_.ProcessUdpPacket(
9998 kSelfAddress, kPeerAddress,
9999 QuicReceivedPacket(retry_packet, retry_packet_length, clock_.Now()));
10000
10001 if (invalid_retry_tag) {
10002 // Make sure we refuse to process a RETRY with invalid tag.
10003 EXPECT_FALSE(connection_.GetStats().retry_packet_processed);
10004 EXPECT_EQ(connection_.connection_id(), original_connection_id);
dschinazi278efae2020-01-28 17:03:09 -080010005 EXPECT_TRUE(QuicPacketCreatorPeer::GetRetryToken(
dschinazi39e5e552020-05-06 13:55:24 -070010006 QuicConnectionPeer::GetPacketCreator(&connection_))
dschinazi278efae2020-01-28 17:03:09 -080010007 .empty());
dschinazi39e5e552020-05-06 13:55:24 -070010008 return;
dschinazi278efae2020-01-28 17:03:09 -080010009 }
dschinazi39e5e552020-05-06 13:55:24 -070010010
10011 // Make sure we correctly parsed the RETRY.
10012 EXPECT_TRUE(connection_.GetStats().retry_packet_processed);
10013 EXPECT_EQ(connection_.connection_id(), new_connection_id);
10014 EXPECT_EQ(QuicPacketCreatorPeer::GetRetryToken(
10015 QuicConnectionPeer::GetPacketCreator(&connection_)),
10016 retry_token);
10017 // Make sure our fake framer has the new post-retry INITIAL keys.
10018 writer_->framer()->framer()->SetInitialObfuscators(new_connection_id);
10019
10020 // Test validating the original_connection_id from the config.
10021 QuicConfig received_config;
10022 QuicConfigPeer::SetNegotiated(&received_config, true);
dschinazie7c38a52020-05-29 15:25:45 -070010023 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
10024 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
10025 &received_config, connection_.connection_id());
10026 if (!missing_retry_id_in_config) {
10027 QuicConfigPeer::SetReceivedRetrySourceConnectionId(
10028 &received_config, config_retry_source_connection_id);
10029 }
10030 }
10031 if (!missing_original_id_in_config) {
dschinazi39e5e552020-05-06 13:55:24 -070010032 QuicConfigPeer::SetReceivedOriginalConnectionId(
10033 &received_config, config_original_connection_id);
10034 }
dschinazie7c38a52020-05-29 15:25:45 -070010035
10036 if (missing_original_id_in_config || wrong_original_id_in_config ||
10037 missing_retry_id_in_config || wrong_retry_id_in_config) {
dschinazi39e5e552020-05-06 13:55:24 -070010038 EXPECT_CALL(visitor_,
10039 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10040 .Times(1);
10041 } else {
10042 EXPECT_CALL(visitor_,
10043 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10044 .Times(0);
10045 }
10046 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
10047 connection_.SetFromConfig(received_config);
dschinazie7c38a52020-05-29 15:25:45 -070010048 if (missing_original_id_in_config || wrong_original_id_in_config ||
10049 missing_retry_id_in_config || wrong_retry_id_in_config) {
10050 ASSERT_FALSE(connection_.connected());
dschinazi39e5e552020-05-06 13:55:24 -070010051 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
10052 } else {
10053 EXPECT_TRUE(connection_.connected());
10054 }
10055}
10056
10057TEST_P(QuicConnectionTest, ClientParsesRetry) {
10058 TestClientRetryHandling(/*invalid_retry_tag=*/false,
dschinazie7c38a52020-05-29 15:25:45 -070010059 /*missing_original_id_in_config=*/false,
10060 /*wrong_original_id_in_config=*/false,
10061 /*missing_retry_id_in_config=*/false,
10062 /*wrong_retry_id_in_config=*/false);
dschinazi39e5e552020-05-06 13:55:24 -070010063}
10064
dschinazie7c38a52020-05-29 15:25:45 -070010065TEST_P(QuicConnectionTest, ClientParsesRetryInvalidTag) {
dschinazi39e5e552020-05-06 13:55:24 -070010066 TestClientRetryHandling(/*invalid_retry_tag=*/true,
dschinazie7c38a52020-05-29 15:25:45 -070010067 /*missing_original_id_in_config=*/false,
10068 /*wrong_original_id_in_config=*/false,
10069 /*missing_retry_id_in_config=*/false,
10070 /*wrong_retry_id_in_config=*/false);
dschinazi39e5e552020-05-06 13:55:24 -070010071}
10072
dschinazie7c38a52020-05-29 15:25:45 -070010073TEST_P(QuicConnectionTest, ClientParsesRetryMissingOriginalId) {
dschinazi39e5e552020-05-06 13:55:24 -070010074 TestClientRetryHandling(/*invalid_retry_tag=*/false,
dschinazie7c38a52020-05-29 15:25:45 -070010075 /*missing_original_id_in_config=*/true,
10076 /*wrong_original_id_in_config=*/false,
10077 /*missing_retry_id_in_config=*/false,
10078 /*wrong_retry_id_in_config=*/false);
dschinazi39e5e552020-05-06 13:55:24 -070010079}
10080
dschinazie7c38a52020-05-29 15:25:45 -070010081TEST_P(QuicConnectionTest, ClientParsesRetryWrongOriginalId) {
dschinazi39e5e552020-05-06 13:55:24 -070010082 TestClientRetryHandling(/*invalid_retry_tag=*/false,
dschinazie7c38a52020-05-29 15:25:45 -070010083 /*missing_original_id_in_config=*/false,
10084 /*wrong_original_id_in_config=*/true,
10085 /*missing_retry_id_in_config=*/false,
10086 /*wrong_retry_id_in_config=*/false);
10087}
10088
10089TEST_P(QuicConnectionTest, ClientParsesRetryMissingRetryId) {
10090 if (!connection_.version().AuthenticatesHandshakeConnectionIds()) {
10091 // Versions that do not authenticate connection IDs never send the
10092 // retry_source_connection_id transport parameter.
10093 return;
10094 }
10095 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10096 /*missing_original_id_in_config=*/false,
10097 /*wrong_original_id_in_config=*/false,
10098 /*missing_retry_id_in_config=*/true,
10099 /*wrong_retry_id_in_config=*/false);
10100}
10101
10102TEST_P(QuicConnectionTest, ClientParsesRetryWrongRetryId) {
10103 if (!connection_.version().AuthenticatesHandshakeConnectionIds()) {
10104 // Versions that do not authenticate connection IDs never send the
10105 // retry_source_connection_id transport parameter.
10106 return;
10107 }
10108 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10109 /*missing_original_id_in_config=*/false,
10110 /*wrong_original_id_in_config=*/false,
10111 /*missing_retry_id_in_config=*/false,
10112 /*wrong_retry_id_in_config=*/true);
dschinazi39e5e552020-05-06 13:55:24 -070010113}
10114
10115TEST_P(QuicConnectionTest, ClientReceivesOriginalConnectionIdWithoutRetry) {
dschinazie7c38a52020-05-29 15:25:45 -070010116 if (!connection_.version().UsesTls()) {
10117 // QUIC+TLS is required to transmit connection ID transport parameters.
10118 return;
10119 }
10120 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
10121 // Versions that authenticate connection IDs always send the
10122 // original_destination_connection_id transport parameter.
10123 return;
10124 }
10125 // Make sure that receiving the original_destination_connection_id transport
10126 // parameter fails the handshake when no RETRY packet was received before it.
dschinazi39e5e552020-05-06 13:55:24 -070010127 QuicConfig received_config;
10128 QuicConfigPeer::SetNegotiated(&received_config, true);
10129 QuicConfigPeer::SetReceivedOriginalConnectionId(&received_config,
10130 TestConnectionId(0x12345));
10131 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
10132 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10133 .Times(1);
10134 connection_.SetFromConfig(received_config);
10135 EXPECT_FALSE(connection_.connected());
10136 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
dschinazi278efae2020-01-28 17:03:09 -080010137}
10138
dschinazie7c38a52020-05-29 15:25:45 -070010139TEST_P(QuicConnectionTest, ClientReceivesRetrySourceConnectionIdWithoutRetry) {
10140 if (!connection_.version().AuthenticatesHandshakeConnectionIds()) {
10141 // Versions that do not authenticate connection IDs never send the
10142 // retry_source_connection_id transport parameter.
10143 return;
10144 }
10145 // Make sure that receiving the retry_source_connection_id transport parameter
10146 // fails the handshake when no RETRY packet was received before it.
10147 QuicConfig received_config;
10148 QuicConfigPeer::SetNegotiated(&received_config, true);
10149 QuicConfigPeer::SetReceivedRetrySourceConnectionId(&received_config,
10150 TestConnectionId(0x12345));
10151 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
10152 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10153 .Times(1);
10154 connection_.SetFromConfig(received_config);
10155 EXPECT_FALSE(connection_.connected());
10156 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
10157}
10158
fayang0e3035e2020-02-03 13:30:36 -080010159// Regression test for http://crbug/1047977
10160TEST_P(QuicConnectionTest, MaxStreamsFrameCausesConnectionClose) {
10161 if (!VersionHasIetfQuicFrames(connection_.transport_version())) {
10162 return;
10163 }
10164 // Received frame causes connection close.
10165 EXPECT_CALL(visitor_, OnMaxStreamsFrame(_))
10166 .WillOnce(InvokeWithoutArgs([this]() {
10167 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10168 connection_.CloseConnection(
10169 QUIC_TOO_MANY_BUFFERED_CONTROL_FRAMES, "error",
10170 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10171 return true;
10172 }));
10173 QuicFrames frames;
10174 frames.push_back(QuicFrame(QuicMaxStreamsFrame()));
10175 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10176 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10177}
10178
10179TEST_P(QuicConnectionTest, StreamsBlockedFrameCausesConnectionClose) {
10180 if (!VersionHasIetfQuicFrames(connection_.transport_version())) {
10181 return;
10182 }
10183 // Received frame causes connection close.
10184 EXPECT_CALL(visitor_, OnStreamsBlockedFrame(_))
10185 .WillOnce(InvokeWithoutArgs([this]() {
10186 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10187 connection_.CloseConnection(
10188 QUIC_TOO_MANY_BUFFERED_CONTROL_FRAMES, "error",
10189 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10190 return true;
10191 }));
10192 QuicFrames frames;
10193 frames.push_back(
10194 QuicFrame(QuicStreamsBlockedFrame(kInvalidControlFrameId, 10, false)));
10195 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10196 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10197}
10198
fayang79400d52020-02-13 10:13:05 -080010199TEST_P(QuicConnectionTest,
10200 BundleAckWithConnectionCloseMultiplePacketNumberSpace) {
10201 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10202 return;
10203 }
10204 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10205 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10206 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
10207 // Receives packet 1000 in initial data.
10208 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
10209 // Receives packet 2000 in application data.
10210 ProcessDataPacketAtLevel(2000, false, ENCRYPTION_FORWARD_SECURE);
10211 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10212 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
10213 connection_.CloseConnection(
10214 kQuicErrorCode, "Some random error message",
10215 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10216
10217 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
10218
10219 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
10220 EXPECT_EQ(1u, writer_->connection_close_frames().size());
10221 // Verify ack is bundled.
10222 EXPECT_EQ(1u, writer_->ack_frames().size());
10223
10224 if (!connection_.version().CanSendCoalescedPackets()) {
10225 // Each connection close packet should be sent in distinct UDP packets.
10226 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
10227 writer_->connection_close_packets());
10228 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
10229 writer_->packets_write_attempts());
10230 return;
10231 }
10232
10233 // A single UDP packet should be sent with multiple connection close packets
10234 // coalesced together.
10235 EXPECT_EQ(1u, writer_->packets_write_attempts());
10236
10237 // Only the first packet has been processed yet.
10238 EXPECT_EQ(1u, writer_->connection_close_packets());
10239
10240 // ProcessPacket resets the visitor and frees the coalesced packet.
10241 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
10242 auto packet = writer_->coalesced_packet()->Clone();
10243 writer_->framer()->ProcessPacket(*packet);
10244 EXPECT_EQ(1u, writer_->connection_close_packets());
10245 EXPECT_EQ(1u, writer_->connection_close_frames().size());
10246 // Verify ack is bundled.
10247 EXPECT_EQ(1u, writer_->ack_frames().size());
10248 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
10249}
10250
fayang61453cb2020-03-11 11:32:26 -070010251// Regression test for b/151220135.
10252TEST_P(QuicConnectionTest, SendPingWhenSkipPacketNumberForPto) {
10253 if (!VersionSupportsMessageFrames(connection_.transport_version())) {
10254 return;
10255 }
10256 QuicConfig config;
10257 QuicTagVector connection_options;
10258 connection_options.push_back(kPTOS);
10259 connection_options.push_back(k1PTO);
10260 config.SetConnectionOptionsToSend(connection_options);
dschinazied459c02020-05-07 16:12:23 -070010261 if (connection_.version().UsesTls()) {
10262 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
10263 &config, kMaxAcceptedDatagramFrameSize);
10264 }
fayang61453cb2020-03-11 11:32:26 -070010265 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10266 connection_.SetFromConfig(config);
fayang37b3c5c2020-09-16 15:20:41 -070010267 connection_.OnHandshakeComplete();
fayang61453cb2020-03-11 11:32:26 -070010268 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
10269
10270 EXPECT_EQ(MESSAGE_STATUS_SUCCESS, SendMessage("message"));
10271 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
10272
fayang80f9cc62020-04-22 08:08:20 -070010273 // PTO fires, verify a PING packet gets sent because there is no data to
10274 // send.
10275 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(3), _, _));
fayangec14d2b2020-10-02 12:00:05 -070010276 if (!GetQuicReloadableFlag(quic_let_connection_handle_pings)) {
10277 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
10278 SendPing();
10279 }));
10280 }
fayang61453cb2020-03-11 11:32:26 -070010281 connection_.GetRetransmissionAlarm()->Fire();
fayang80f9cc62020-04-22 08:08:20 -070010282 EXPECT_EQ(1u, connection_.GetStats().pto_count);
10283 EXPECT_EQ(0u, connection_.GetStats().crypto_retransmit_count);
10284 EXPECT_EQ(1u, writer_->ping_frames().size());
fayang61453cb2020-03-11 11:32:26 -070010285}
10286
fayangcc210e72020-05-05 14:41:34 -070010287// Regression test for b/155757133
10288TEST_P(QuicConnectionTest, DonotChangeQueuedAcks) {
10289 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10290 return;
10291 }
10292 const size_t kMinRttMs = 40;
10293 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
10294 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
10295 QuicTime::Delta::Zero(), QuicTime::Zero());
10296 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10297 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
10298 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10299
10300 ProcessPacket(2);
10301 ProcessPacket(3);
10302 ProcessPacket(4);
10303 // Process a packet containing stream frame followed by ACK of packets 1.
10304 QuicFrames frames;
10305 frames.push_back(QuicFrame(QuicStreamFrame(
10306 QuicUtils::GetFirstBidirectionalStreamId(
10307 connection_.version().transport_version, Perspective::IS_CLIENT),
10308 false, 0u, quiche::QuicheStringPiece())));
10309 QuicAckFrame ack_frame = InitAckFrame(1);
10310 frames.push_back(QuicFrame(&ack_frame));
10311 // Receiving stream frame causes something to send.
10312 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([this]() {
10313 connection_.SendControlFrame(QuicFrame(new QuicWindowUpdateFrame(1, 0, 0)));
10314 // Verify now the queued ACK contains packet number 2.
10315 EXPECT_TRUE(QuicPacketCreatorPeer::QueuedFrames(
10316 QuicConnectionPeer::GetPacketCreator(&connection_))[0]
10317 .ack_frame->packets.Contains(QuicPacketNumber(2)));
10318 }));
10319 ProcessFramesPacketAtLevel(9, frames, ENCRYPTION_FORWARD_SECURE);
fayang97da12c2020-06-29 08:22:42 -070010320 EXPECT_TRUE(writer_->ack_frames()[0].packets.Contains(QuicPacketNumber(2)));
fayangcc210e72020-05-05 14:41:34 -070010321}
10322
fayange9304002020-05-07 11:57:48 -070010323TEST_P(QuicConnectionTest, DonotExtendIdleTimeOnUndecryptablePackets) {
10324 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10325 QuicConfig config;
10326 connection_.SetFromConfig(config);
10327 // Subtract a second from the idle timeout on the client side.
10328 QuicTime initial_deadline =
10329 clock_.ApproximateNow() +
10330 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
10331 EXPECT_EQ(initial_deadline, connection_.GetTimeoutAlarm()->deadline());
10332
10333 // Received an undecryptable packet.
10334 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
10335 const uint8_t tag = 0x07;
10336 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
10337 std::make_unique<TaggingEncrypter>(tag));
10338 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
fayang655bb412020-06-24 10:20:47 -070010339 // Verify deadline does not get extended.
10340 EXPECT_EQ(initial_deadline, connection_.GetTimeoutAlarm()->deadline());
10341 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
fayange9304002020-05-07 11:57:48 -070010342 QuicTime::Delta delay = initial_deadline - clock_.ApproximateNow();
10343 clock_.AdvanceTime(delay);
fayang655bb412020-06-24 10:20:47 -070010344 connection_.GetTimeoutAlarm()->Fire();
10345 // Verify connection gets closed.
10346 EXPECT_FALSE(connection_.connected());
fayange9304002020-05-07 11:57:48 -070010347}
10348
fayang9f430a52020-05-08 07:28:33 -070010349TEST_P(QuicConnectionTest, BundleAckWithImmediateResponse) {
10350 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10351 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10352
10353 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([this]() {
10354 connection_.SendControlFrame(QuicFrame(new QuicWindowUpdateFrame(1, 0, 0)));
10355 }));
10356 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10357 ProcessDataPacket(1);
fayangf0fa58f2020-06-24 09:13:11 -070010358 // Verify ACK is bundled with WINDOW_UPDATE.
10359 EXPECT_FALSE(writer_->ack_frames().empty());
10360 EXPECT_FALSE(connection_.HasPendingAcks());
fayang9f430a52020-05-08 07:28:33 -070010361}
10362
fayangf44a6672020-05-27 12:51:45 -070010363TEST_P(QuicConnectionTest, AckAlarmFiresEarly) {
10364 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10365 return;
10366 }
10367 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10368 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
10369 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10370 }
10371 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
10372 use_tagging_decrypter();
10373 // Receives packet 1000 in initial data.
10374 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
fayang9adfb532020-06-04 06:58:45 -070010375 EXPECT_TRUE(connection_.HasPendingAcks());
fayangf44a6672020-05-27 12:51:45 -070010376
10377 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
10378 std::make_unique<TaggingEncrypter>(0x02));
10379 SetDecrypter(ENCRYPTION_ZERO_RTT,
10380 std::make_unique<StrictTaggingDecrypter>(0x02));
10381 connection_.SetEncrypter(ENCRYPTION_INITIAL,
10382 std::make_unique<TaggingEncrypter>(0x02));
10383 // Receives packet 1000 in application data.
10384 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
fayang9adfb532020-06-04 06:58:45 -070010385 EXPECT_TRUE(connection_.HasPendingAcks());
fayangf44a6672020-05-27 12:51:45 -070010386 // Verify ACK deadline does not change.
10387 EXPECT_EQ(clock_.ApproximateNow() + kAlarmGranularity,
10388 connection_.GetAckAlarm()->deadline());
10389
10390 // Ack alarm fires early.
fayang00e7ec62020-07-27 09:26:53 -070010391 // Verify the earliest ACK is flushed.
10392 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
fayangf44a6672020-05-27 12:51:45 -070010393 connection_.GetAckAlarm()->Fire();
fayang9adfb532020-06-04 06:58:45 -070010394 EXPECT_TRUE(connection_.HasPendingAcks());
fayang00e7ec62020-07-27 09:26:53 -070010395 EXPECT_EQ(clock_.ApproximateNow() + DefaultDelayedAckTime(),
10396 connection_.GetAckAlarm()->deadline());
fayangf44a6672020-05-27 12:51:45 -070010397}
10398
fayangf78b6932020-06-08 08:36:45 -070010399TEST_P(QuicConnectionTest, ClientOnlyBlackholeDetectionClient) {
fayang656cbb52020-06-09 13:29:35 -070010400 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangf78b6932020-06-08 08:36:45 -070010401 return;
10402 }
10403 QuicConfig config;
10404 QuicTagVector connection_options;
10405 connection_options.push_back(kCBHD);
10406 config.SetConnectionOptionsToSend(connection_options);
10407 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10408 connection_.SetFromConfig(config);
10409 EXPECT_CALL(visitor_, GetHandshakeState())
10410 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
10411 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
10412 // Send stream data.
10413 SendStreamDataToPeer(
10414 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
10415 0, FIN, nullptr);
10416 // Verify blackhole detection is in progress.
10417 EXPECT_TRUE(connection_.GetBlackholeDetectorAlarm()->IsSet());
10418}
10419
10420TEST_P(QuicConnectionTest, ClientOnlyBlackholeDetectionServer) {
fayang656cbb52020-06-09 13:29:35 -070010421 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangf78b6932020-06-08 08:36:45 -070010422 return;
10423 }
10424 set_perspective(Perspective::IS_SERVER);
10425 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
10426 if (version().SupportsAntiAmplificationLimit()) {
10427 QuicConnectionPeer::SetAddressValidated(&connection_);
10428 }
10429 QuicConfig config;
10430 QuicTagVector connection_options;
10431 connection_options.push_back(kCBHD);
10432 config.SetInitialReceivedConnectionOptions(connection_options);
10433 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10434 connection_.SetFromConfig(config);
10435 EXPECT_CALL(visitor_, GetHandshakeState())
10436 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
10437 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
10438 // Send stream data.
10439 SendStreamDataToPeer(
10440 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
10441 0, FIN, nullptr);
10442 // Verify blackhole detection is disabled.
10443 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
10444}
10445
10446TEST_P(QuicConnectionTest, 2RtoBlackholeDetection) {
fayang656cbb52020-06-09 13:29:35 -070010447 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangf78b6932020-06-08 08:36:45 -070010448 return;
10449 }
10450 QuicConfig config;
10451 QuicTagVector connection_options;
10452 connection_options.push_back(k2RTO);
10453 config.SetConnectionOptionsToSend(connection_options);
10454 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10455 connection_.SetFromConfig(config);
10456 const size_t kMinRttMs = 40;
10457 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
10458 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
10459 QuicTime::Delta::Zero(), QuicTime::Zero());
10460 EXPECT_CALL(visitor_, GetHandshakeState())
10461 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
10462 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
10463 // Send stream data.
10464 SendStreamDataToPeer(
10465 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
10466 0, FIN, nullptr);
10467 // Verify blackhole delay is expected.
10468 EXPECT_EQ(clock_.Now() +
10469 connection_.sent_packet_manager().GetNetworkBlackholeDelay(2),
10470 QuicConnectionPeer::GetBlackholeDetectionDeadline(&connection_));
10471}
10472
10473TEST_P(QuicConnectionTest, 3RtoBlackholeDetection) {
fayang656cbb52020-06-09 13:29:35 -070010474 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangf78b6932020-06-08 08:36:45 -070010475 return;
10476 }
10477 QuicConfig config;
10478 QuicTagVector connection_options;
10479 connection_options.push_back(k3RTO);
10480 config.SetConnectionOptionsToSend(connection_options);
10481 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10482 connection_.SetFromConfig(config);
10483 const size_t kMinRttMs = 40;
10484 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
10485 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
10486 QuicTime::Delta::Zero(), QuicTime::Zero());
10487 EXPECT_CALL(visitor_, GetHandshakeState())
10488 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
10489 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
10490 // Send stream data.
10491 SendStreamDataToPeer(
10492 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
10493 0, FIN, nullptr);
10494 // Verify blackhole delay is expected.
10495 EXPECT_EQ(clock_.Now() +
10496 connection_.sent_packet_manager().GetNetworkBlackholeDelay(3),
10497 QuicConnectionPeer::GetBlackholeDetectionDeadline(&connection_));
10498}
10499
10500TEST_P(QuicConnectionTest, 4RtoBlackholeDetection) {
fayang656cbb52020-06-09 13:29:35 -070010501 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangf78b6932020-06-08 08:36:45 -070010502 return;
10503 }
10504 QuicConfig config;
10505 QuicTagVector connection_options;
10506 connection_options.push_back(k4RTO);
10507 config.SetConnectionOptionsToSend(connection_options);
10508 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10509 connection_.SetFromConfig(config);
10510 const size_t kMinRttMs = 40;
10511 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
10512 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
10513 QuicTime::Delta::Zero(), QuicTime::Zero());
10514 EXPECT_CALL(visitor_, GetHandshakeState())
10515 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
10516 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
10517 // Send stream data.
10518 SendStreamDataToPeer(
10519 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
10520 0, FIN, nullptr);
10521 // Verify blackhole delay is expected.
10522 EXPECT_EQ(clock_.Now() +
10523 connection_.sent_packet_manager().GetNetworkBlackholeDelay(4),
10524 QuicConnectionPeer::GetBlackholeDetectionDeadline(&connection_));
10525}
10526
10527TEST_P(QuicConnectionTest, 6RtoBlackholeDetection) {
fayang656cbb52020-06-09 13:29:35 -070010528 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangf78b6932020-06-08 08:36:45 -070010529 return;
10530 }
10531 QuicConfig config;
10532 QuicTagVector connection_options;
10533 connection_options.push_back(k6RTO);
10534 config.SetConnectionOptionsToSend(connection_options);
10535 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10536 connection_.SetFromConfig(config);
10537 const size_t kMinRttMs = 40;
10538 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
10539 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
10540 QuicTime::Delta::Zero(), QuicTime::Zero());
10541 EXPECT_CALL(visitor_, GetHandshakeState())
10542 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
10543 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
10544 // Send stream data.
10545 SendStreamDataToPeer(
10546 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
10547 0, FIN, nullptr);
10548 // Verify blackhole delay is expected.
10549 EXPECT_EQ(clock_.Now() +
10550 connection_.sent_packet_manager().GetNetworkBlackholeDelay(6),
10551 QuicConnectionPeer::GetBlackholeDetectionDeadline(&connection_));
10552}
10553
fayang656cbb52020-06-09 13:29:35 -070010554// Regresstion test for b/158491591.
10555TEST_P(QuicConnectionTest, MadeForwardProgressOnDiscardingKeys) {
10556 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10557 return;
10558 }
10559 use_tagging_decrypter();
10560 // Send handshake packet.
10561 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10562 std::make_unique<TaggingEncrypter>(0x02));
10563 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10564 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
10565 QuicConfig config;
10566 QuicTagVector connection_options;
10567 connection_options.push_back(k5RTO);
10568 config.SetConnectionOptionsToSend(connection_options);
10569 QuicConfigPeer::SetNegotiated(&config, true);
10570 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
10571 EXPECT_CALL(visitor_, GetHandshakeState())
10572 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
10573 }
10574 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
10575 QuicConfigPeer::SetReceivedOriginalConnectionId(
10576 &config, connection_.connection_id());
10577 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
10578 &config, connection_.connection_id());
10579 }
10580 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10581 connection_.SetFromConfig(config);
10582
10583 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
10584 EXPECT_TRUE(connection_.BlackholeDetectionInProgress());
10585 // Discard handshake keys.
10586 connection_.OnHandshakeComplete();
10587 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
10588 // Verify blackhole detection stops.
10589 EXPECT_FALSE(connection_.BlackholeDetectionInProgress());
10590 } else {
10591 // Problematic: although there is nothing in flight, blackhole detection is
10592 // still in progress.
10593 EXPECT_TRUE(connection_.BlackholeDetectionInProgress());
10594 }
10595}
10596
fayang750b54f2020-06-18 06:26:54 -070010597TEST_P(QuicConnectionTest, ProcessUndecryptablePacketsBasedOnEncryptionLevel) {
10598 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10599 return;
10600 }
10601 // SetFromConfig is always called after construction from InitializeSession.
10602 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10603 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10604 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(AnyNumber());
10605 QuicConfig config;
10606 connection_.SetFromConfig(config);
10607 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10608 connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
10609 use_tagging_decrypter();
10610
10611 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10612 std::make_unique<TaggingEncrypter>(0x01));
10613 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
10614 std::make_unique<TaggingEncrypter>(0x02));
10615
10616 for (uint64_t i = 1; i <= 3; ++i) {
10617 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
10618 }
10619 ProcessDataPacketAtLevel(4, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
10620 for (uint64_t j = 5; j <= 7; ++j) {
10621 ProcessDataPacketAtLevel(j, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
10622 }
10623 EXPECT_EQ(7u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
10624 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
10625 SetDecrypter(ENCRYPTION_HANDSHAKE,
10626 std::make_unique<StrictTaggingDecrypter>(0x01));
10627 EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
fayang750b54f2020-06-18 06:26:54 -070010628 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10629 std::make_unique<TaggingEncrypter>(0x01));
fayangd01e9962020-09-24 11:29:31 -070010630 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
fayang4bf78e22020-08-03 08:29:48 -070010631 // Verify all ENCRYPTION_HANDSHAKE packets get processed.
10632 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(6);
fayang750b54f2020-06-18 06:26:54 -070010633 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
fayangdd523b32020-09-15 14:53:17 -070010634 if (GetQuicReloadableFlag(quic_fix_undecryptable_packets2)) {
10635 EXPECT_EQ(1u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
10636 } else {
10637 EXPECT_EQ(4u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
10638 }
fayang750b54f2020-06-18 06:26:54 -070010639
10640 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
10641 std::make_unique<StrictTaggingDecrypter>(0x02));
10642 EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
10643 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10644 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
10645 std::make_unique<TaggingEncrypter>(0x02));
fayang4bf78e22020-08-03 08:29:48 -070010646 // Verify the 1-RTT packet gets processed.
10647 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
fayang750b54f2020-06-18 06:26:54 -070010648 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
10649 EXPECT_EQ(0u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
10650}
10651
fayanga39d0362020-06-22 08:57:35 -070010652TEST_P(QuicConnectionTest, ServerBundlesInitialDataWithInitialAck) {
fayang7d4b0172020-06-18 14:05:45 -070010653 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10654 return;
10655 }
10656 set_perspective(Perspective::IS_SERVER);
10657 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
10658 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10659 }
10660 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
10661 use_tagging_decrypter();
10662 // Receives packet 1000 in initial data.
10663 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
10664 EXPECT_TRUE(connection_.HasPendingAcks());
10665
10666 connection_.SetEncrypter(ENCRYPTION_INITIAL,
10667 std::make_unique<TaggingEncrypter>(0x01));
10668 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10669 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
10670 QuicTime expected_pto_time =
10671 connection_.sent_packet_manager().GetRetransmissionTime();
10672
10673 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
10674 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10675 std::make_unique<TaggingEncrypter>(0x02));
10676 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
fayangd8682452020-09-28 09:09:29 -070010677 if (GetQuicReloadableFlag(quic_fix_missing_initial_keys2)) {
10678 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
10679 } else {
10680 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(2);
10681 }
fayang7d4b0172020-06-18 14:05:45 -070010682 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
10683 // Verify PTO time does not change.
10684 EXPECT_EQ(expected_pto_time,
10685 connection_.sent_packet_manager().GetRetransmissionTime());
10686
10687 // Receives packet 1001 in initial data.
10688 ProcessCryptoPacketAtLevel(1001, ENCRYPTION_INITIAL);
10689 EXPECT_TRUE(connection_.HasPendingAcks());
10690 // Receives packet 1002 in initial data.
10691 ProcessCryptoPacketAtLevel(1002, ENCRYPTION_INITIAL);
10692 EXPECT_FALSE(writer_->ack_frames().empty());
fayangc6312d42020-07-06 08:15:28 -070010693 // Verify CRYPTO frame is bundled with INITIAL ACK.
10694 EXPECT_FALSE(writer_->crypto_frames().empty());
10695 // Verify PTO time changes.
10696 EXPECT_NE(expected_pto_time,
10697 connection_.sent_packet_manager().GetRetransmissionTime());
fayang7d4b0172020-06-18 14:05:45 -070010698}
10699
fayanga39d0362020-06-22 08:57:35 -070010700TEST_P(QuicConnectionTest, ClientBundlesHandshakeDataWithHandshakeAck) {
10701 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10702 return;
10703 }
10704 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
10705 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
10706 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10707 }
10708 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
10709 use_tagging_decrypter();
10710 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10711 std::make_unique<TaggingEncrypter>(0x02));
10712 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10713 SetDecrypter(ENCRYPTION_HANDSHAKE,
10714 std::make_unique<StrictTaggingDecrypter>(0x02));
10715 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10716 std::make_unique<TaggingEncrypter>(0x02));
10717 // Receives packet 1000 in handshake data.
10718 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_HANDSHAKE);
10719 EXPECT_TRUE(connection_.HasPendingAcks());
fayangd8682452020-09-28 09:09:29 -070010720 if (GetQuicReloadableFlag(quic_fix_missing_initial_keys2)) {
10721 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
10722 } else {
10723 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(2);
10724 }
fayanga39d0362020-06-22 08:57:35 -070010725 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
10726
10727 // Receives packet 1001 in handshake data.
10728 ProcessCryptoPacketAtLevel(1001, ENCRYPTION_HANDSHAKE);
10729 EXPECT_TRUE(connection_.HasPendingAcks());
10730 // Receives packet 1002 in handshake data.
10731 ProcessCryptoPacketAtLevel(1002, ENCRYPTION_HANDSHAKE);
10732 EXPECT_FALSE(writer_->ack_frames().empty());
fayangc6312d42020-07-06 08:15:28 -070010733 // Verify CRYPTO frame is bundled with HANDSHAKE ACK.
10734 EXPECT_FALSE(writer_->crypto_frames().empty());
fayanga39d0362020-06-22 08:57:35 -070010735}
10736
fayang04bd30d2020-06-22 15:04:57 -070010737// Regresstion test for b/156232673.
10738TEST_P(QuicConnectionTest, CoalescePacketOfLowerEncryptionLevel) {
10739 if (!connection_.version().CanSendCoalescedPackets()) {
10740 return;
10741 }
fayangf627e012020-07-13 08:10:44 -070010742 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
fayang04bd30d2020-06-22 15:04:57 -070010743 {
10744 QuicConnection::ScopedPacketFlusher flusher(&connection_);
10745 use_tagging_decrypter();
10746 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10747 std::make_unique<TaggingEncrypter>(0x01));
10748 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
10749 std::make_unique<TaggingEncrypter>(0x02));
10750 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
fayangbd7ad682020-06-23 10:49:12 -070010751 SendStreamDataToPeer(2, std::string(1286, 'a'), 0, NO_FIN, nullptr);
fayang04bd30d2020-06-22 15:04:57 -070010752 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10753 // Try to coalesce a HANDSHAKE packet after 1-RTT packet.
fayangf627e012020-07-13 08:10:44 -070010754 // Verify soft max packet length gets resumed and handshake packet gets
10755 // successfully sent.
10756 connection_.SendCryptoDataWithString("a", 0, ENCRYPTION_HANDSHAKE);
fayang04bd30d2020-06-22 15:04:57 -070010757 }
10758}
10759
fayang5c2c7b52020-07-09 13:47:16 -040010760// Regression test for b/160790422.
10761TEST_P(QuicConnectionTest, ServerRetransmitsHandshakeDataEarly) {
10762 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10763 return;
10764 }
10765 set_perspective(Perspective::IS_SERVER);
10766 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
10767 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10768 }
10769 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
10770 use_tagging_decrypter();
10771 // Receives packet 1000 in initial data.
10772 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
10773 EXPECT_TRUE(connection_.HasPendingAcks());
10774
10775 connection_.SetEncrypter(ENCRYPTION_INITIAL,
10776 std::make_unique<TaggingEncrypter>(0x01));
10777 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10778 // Send INITIAL 1.
10779 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
10780 QuicTime expected_pto_time =
10781 connection_.sent_packet_manager().GetRetransmissionTime();
10782
10783 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
10784 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10785 std::make_unique<TaggingEncrypter>(0x02));
10786 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
fayangd8682452020-09-28 09:09:29 -070010787 if (GetQuicReloadableFlag(quic_fix_missing_initial_keys2)) {
10788 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
10789 } else {
10790 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(3);
10791 }
fayang5c2c7b52020-07-09 13:47:16 -040010792 // Send HANDSHAKE 2 and 3.
10793 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
10794 connection_.SendCryptoDataWithString("bar", 3, ENCRYPTION_HANDSHAKE);
10795 // Verify PTO time does not change.
10796 EXPECT_EQ(expected_pto_time,
10797 connection_.sent_packet_manager().GetRetransmissionTime());
10798
10799 // Receives ACK for HANDSHAKE 2.
10800 QuicFrames frames;
10801 auto ack_frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
10802 frames.push_back(QuicFrame(&ack_frame));
10803 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
10804 ProcessFramesPacketAtLevel(30, frames, ENCRYPTION_HANDSHAKE);
10805 // Discard INITIAL key.
10806 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
10807 connection_.NeuterUnencryptedPackets();
10808 // Receives PING from peer.
10809 frames.clear();
10810 frames.push_back(QuicFrame(QuicPingFrame()));
10811 frames.push_back(QuicFrame(QuicPaddingFrame(3)));
10812 ProcessFramesPacketAtLevel(31, frames, ENCRYPTION_HANDSHAKE);
10813 EXPECT_EQ(clock_.Now() + kAlarmGranularity,
10814 connection_.GetAckAlarm()->deadline());
10815 // Fire ACK alarm.
10816 clock_.AdvanceTime(kAlarmGranularity);
10817 connection_.GetAckAlarm()->Fire();
10818 EXPECT_FALSE(writer_->ack_frames().empty());
fayangb94ffb22020-08-25 14:00:09 -070010819 // Verify handshake data gets retransmitted early.
10820 EXPECT_FALSE(writer_->crypto_frames().empty());
fayang5c2c7b52020-07-09 13:47:16 -040010821}
10822
fayangfe963c52020-07-16 06:56:09 -070010823// Regression test for b/161228202
10824TEST_P(QuicConnectionTest, InflatedRttSample) {
10825 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10826 return;
10827 }
10828 // 30ms RTT.
10829 const QuicTime::Delta kTestRTT = QuicTime::Delta::FromMilliseconds(30);
10830 set_perspective(Perspective::IS_SERVER);
10831 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
10832 use_tagging_decrypter();
10833 // Receives packet 1000 in initial data.
10834 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
10835 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10836 }
10837 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
10838 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
10839 EXPECT_TRUE(connection_.HasPendingAcks());
10840
10841 connection_.SetEncrypter(ENCRYPTION_INITIAL,
10842 std::make_unique<TaggingEncrypter>(0x01));
10843 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10844 // Send INITIAL 1.
nharper4de16872020-07-16 11:16:03 -070010845 std::string initial_crypto_data(512, 'a');
10846 connection_.SendCryptoDataWithString(initial_crypto_data, 0,
fayangfe963c52020-07-16 06:56:09 -070010847 ENCRYPTION_INITIAL);
10848 ASSERT_TRUE(connection_.sent_packet_manager()
10849 .GetRetransmissionTime()
10850 .IsInitialized());
10851 QuicTime::Delta pto_timeout =
10852 connection_.sent_packet_manager().GetRetransmissionTime() - clock_.Now();
10853 // Send Handshake 2.
10854 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10855 std::make_unique<TaggingEncrypter>(0x02));
10856 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
fayangd8682452020-09-28 09:09:29 -070010857 if (GetQuicReloadableFlag(quic_fix_missing_initial_keys2)) {
10858 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
10859 } else {
10860 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(2);
10861 }
nharper4de16872020-07-16 11:16:03 -070010862 std::string handshake_crypto_data(1024, 'a');
10863 connection_.SendCryptoDataWithString(handshake_crypto_data, 0,
fayangfe963c52020-07-16 06:56:09 -070010864 ENCRYPTION_HANDSHAKE);
10865
10866 // INITIAL 1 gets lost and PTO fires.
10867 clock_.AdvanceTime(pto_timeout);
10868 connection_.GetRetransmissionAlarm()->Fire();
10869
10870 clock_.AdvanceTime(kTestRTT);
10871 // Assume retransmitted INITIAL gets received.
10872 QuicFrames frames;
10873 QuicPacketNumber initial_retransmission =
10874 GetQuicReloadableFlag(quic_default_on_pto) ? QuicPacketNumber(3)
10875 : QuicPacketNumber(4);
10876 auto ack_frame =
10877 InitAckFrame({{initial_retransmission, initial_retransmission + 1}});
10878 frames.push_back(QuicFrame(&ack_frame));
10879 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _))
10880 .Times(AnyNumber());
10881 ProcessFramesPacketAtLevel(1001, frames, ENCRYPTION_INITIAL);
10882 EXPECT_EQ(kTestRTT, rtt_stats->latest_rtt());
10883 // Because retransmitted INITIAL gets received so HANDSHAKE 2 gets processed.
10884 frames.clear();
fayangf5f83e52020-09-14 10:29:29 -070010885 // HANDSHAKE 5 is also processed.
10886 QuicAckFrame ack_frame2 =
10887 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)},
10888 {initial_retransmission + 1, initial_retransmission + 2}});
fayangfe963c52020-07-16 06:56:09 -070010889 ack_frame2.ack_delay_time = QuicTime::Delta::Zero();
10890 frames.push_back(QuicFrame(&ack_frame2));
10891 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_HANDSHAKE);
fayangf5f83e52020-09-14 10:29:29 -070010892 // Verify RTT inflation gets mitigated.
10893 EXPECT_EQ(rtt_stats->latest_rtt(), kTestRTT);
fayangfe963c52020-07-16 06:56:09 -070010894}
10895
fayangdceb9a32020-07-29 10:57:04 -070010896// Regression test for b/161228202
10897TEST_P(QuicConnectionTest, CoalscingPacketCausesInfiniteLoop) {
10898 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10899 return;
10900 }
10901 set_perspective(Perspective::IS_SERVER);
10902 use_tagging_decrypter();
10903 // Receives packet 1000 in initial data.
10904 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
10905 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10906 }
10907 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
10908
10909 // Set anti amplification factor to 2, such that RetransmitDataOfSpaceIfAny
10910 // makes no forward progress and causes infinite loop.
10911 SetQuicFlag(FLAGS_quic_anti_amplification_factor, 2);
10912
10913 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
10914 EXPECT_TRUE(connection_.HasPendingAcks());
10915
10916 connection_.SetEncrypter(ENCRYPTION_INITIAL,
10917 std::make_unique<TaggingEncrypter>(0x01));
10918 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10919 // Send INITIAL 1.
10920 std::string initial_crypto_data(512, 'a');
10921 connection_.SendCryptoDataWithString(initial_crypto_data, 0,
10922 ENCRYPTION_INITIAL);
10923 ASSERT_TRUE(connection_.sent_packet_manager()
10924 .GetRetransmissionTime()
10925 .IsInitialized());
10926 QuicTime::Delta pto_timeout =
10927 connection_.sent_packet_manager().GetRetransmissionTime() - clock_.Now();
10928 // Send Handshake 2.
10929 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10930 std::make_unique<TaggingEncrypter>(0x02));
10931 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
fayangf5f83e52020-09-14 10:29:29 -070010932 // Verify HANDSHAKE packet is coalesced with INITIAL retransmission.
fayangd8682452020-09-28 09:09:29 -070010933 if (GetQuicReloadableFlag(quic_fix_missing_initial_keys2)) {
10934 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
10935 } else {
10936 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(2);
10937 }
fayangdceb9a32020-07-29 10:57:04 -070010938 std::string handshake_crypto_data(1024, 'a');
10939 connection_.SendCryptoDataWithString(handshake_crypto_data, 0,
10940 ENCRYPTION_HANDSHAKE);
10941
10942 // INITIAL 1 gets lost and PTO fires.
10943 clock_.AdvanceTime(pto_timeout);
10944 connection_.GetRetransmissionAlarm()->Fire();
10945}
10946
fayang001c8282020-07-29 12:39:29 -070010947TEST_P(QuicConnectionTest, TestingLiveness) {
10948 const size_t kMinRttMs = 40;
10949 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
10950 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
10951 QuicTime::Delta::Zero(), QuicTime::Zero());
10952 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10953 QuicConfig config;
10954
10955 CryptoHandshakeMessage msg;
10956 std::string error_details;
10957 QuicConfig client_config;
10958 client_config.SetInitialStreamFlowControlWindowToSend(
10959 kInitialStreamFlowControlWindowForTest);
10960 client_config.SetInitialSessionFlowControlWindowToSend(
10961 kInitialSessionFlowControlWindowForTest);
10962 client_config.SetIdleNetworkTimeout(QuicTime::Delta::FromSeconds(30));
10963 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
10964 const QuicErrorCode error =
10965 config.ProcessPeerHello(msg, CLIENT, &error_details);
10966 EXPECT_THAT(error, IsQuicNoError());
10967
10968 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
10969 QuicConfigPeer::SetReceivedOriginalConnectionId(
10970 &config, connection_.connection_id());
10971 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
10972 &config, connection_.connection_id());
10973 }
10974
10975 connection_.SetFromConfig(config);
10976 connection_.OnHandshakeComplete();
10977 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10978 ASSERT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
10979 EXPECT_FALSE(connection_.MaybeTestLiveness());
10980
10981 QuicTime deadline = connection_.GetTimeoutAlarm()->deadline();
10982 QuicTime::Delta timeout = deadline - clock_.ApproximateNow();
10983 // Advance time to near the idle timeout.
10984 clock_.AdvanceTime(timeout - QuicTime::Delta::FromMilliseconds(1));
10985 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10986 EXPECT_TRUE(connection_.MaybeTestLiveness());
10987 // Verify idle deadline does not change.
10988 EXPECT_EQ(deadline, connection_.GetTimeoutAlarm()->deadline());
10989}
10990
fayang8bff33c2020-08-06 07:37:22 -070010991TEST_P(QuicConnectionTest, SilentIdleTimeout) {
10992 set_perspective(Perspective::IS_SERVER);
10993 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
10994 if (version().SupportsAntiAmplificationLimit()) {
10995 QuicConnectionPeer::SetAddressValidated(&connection_);
10996 }
10997
10998 QuicConfig config;
10999 QuicConfigPeer::SetNegotiated(&config, true);
11000 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
11001 QuicConfigPeer::SetReceivedOriginalConnectionId(
11002 &config, connection_.connection_id());
11003 QuicConfigPeer::SetReceivedInitialSourceConnectionId(&config,
11004 QuicConnectionId());
11005 }
11006 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11007 connection_.SetFromConfig(config);
11008
11009 EXPECT_TRUE(connection_.connected());
11010 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
11011
11012 EXPECT_CALL(visitor_,
11013 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
11014 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
11015 connection_.GetTimeoutAlarm()->Fire();
fayang66f16bf2020-10-02 09:29:44 -070011016 // Verify the connection close packets get serialized and added to
11017 // termination packets list.
11018 EXPECT_NE(nullptr,
11019 QuicConnectionPeer::GetConnectionClosePacket(&connection_));
fayang88259af2020-08-07 08:59:06 -070011020}
11021
fayang7bc93b72020-08-11 10:45:57 -070011022TEST_P(QuicConnectionTest, DonotSendPing) {
11023 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
11024 connection_.OnHandshakeComplete();
11025 EXPECT_TRUE(connection_.connected());
11026 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
11027 .WillRepeatedly(Return(true));
11028 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
11029 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
11030
11031 SendStreamDataToPeer(
11032 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
11033 "GET /", 0, FIN, nullptr);
11034 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
11035 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
11036 EXPECT_EQ(QuicTime::Delta::FromSeconds(15),
11037 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
11038
11039 // Now recevie an ACK and response of the previous packet, which will move the
11040 // ping alarm forward.
11041 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
11042 QuicFrames frames;
11043 QuicAckFrame ack_frame = InitAckFrame(1);
11044 frames.push_back(QuicFrame(&ack_frame));
11045 frames.push_back(QuicFrame(QuicStreamFrame(
11046 GetNthClientInitiatedStreamId(0, connection_.transport_version()), true,
11047 0u, quiche::QuicheStringPiece())));
11048 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
11049 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
11050 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
11051 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
11052 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
11053 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
11054 // The ping timer is set slightly less than 15 seconds in the future, because
11055 // of the 1s ping timer alarm granularity.
11056 EXPECT_EQ(
11057 QuicTime::Delta::FromSeconds(15) - QuicTime::Delta::FromMilliseconds(5),
11058 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
11059
11060 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15));
11061 // Suppose now ShouldKeepConnectionAlive returns false.
11062 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
11063 .WillRepeatedly(Return(false));
fayange3938ca2020-08-31 09:19:27 -070011064 // Verify PING does not get sent.
fayangec14d2b2020-10-02 12:00:05 -070011065 if (GetQuicReloadableFlag(quic_let_connection_handle_pings)) {
11066 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
11067 } else {
11068 EXPECT_CALL(visitor_, SendPing()).Times(0);
11069 }
fayang7bc93b72020-08-11 10:45:57 -070011070 connection_.GetPingAlarm()->Fire();
11071}
11072
fayangc4bb0722020-08-14 11:19:56 -070011073// Regression test for b/159698337
11074TEST_P(QuicConnectionTest, DuplicateAckCausesLostPackets) {
11075 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
11076 return;
11077 }
11078 // Finish handshake.
11079 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
fayangc4bb0722020-08-14 11:19:56 -070011080 notifier_.NeuterUnencryptedData();
11081 connection_.NeuterUnencryptedPackets();
11082 connection_.OnHandshakeComplete();
11083 EXPECT_CALL(visitor_, GetHandshakeState())
11084 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
11085
11086 std::string data(1200, 'a');
11087 // Send data packets 1 - 5.
11088 for (size_t i = 0; i < 5; ++i) {
11089 SendStreamDataToPeer(
11090 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
11091 i * 1200, i == 4 ? FIN : NO_FIN, nullptr);
11092 }
11093 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
11094
11095 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _)).Times(3);
11096
11097 // ACK packet 5 and 1 and 2 are detected lost.
11098 QuicAckFrame frame =
11099 InitAckFrame({{QuicPacketNumber(5), QuicPacketNumber(6)}});
11100 LostPacketVector lost_packets;
11101 lost_packets.push_back(
11102 LostPacket(QuicPacketNumber(1), kMaxOutgoingPacketSize));
11103 lost_packets.push_back(
11104 LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
11105 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
11106 .Times(AnyNumber())
11107 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
11108 Return(LossDetectionInterface::DetectionStats())));
11109 ProcessAckPacket(1, &frame);
11110 EXPECT_TRUE(connection_.BlackholeDetectionInProgress());
11111 QuicAlarm* retransmission_alarm = connection_.GetRetransmissionAlarm();
11112 EXPECT_TRUE(retransmission_alarm->IsSet());
11113
11114 // ACK packet 1 - 5 and 7.
11115 QuicAckFrame frame2 =
11116 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(6)},
11117 {QuicPacketNumber(7), QuicPacketNumber(8)}});
11118 ProcessAckPacket(2, &frame2);
11119 EXPECT_TRUE(connection_.BlackholeDetectionInProgress());
11120
11121 // ACK packet 7 again and assume packet 6 is detected lost.
11122 QuicAckFrame frame3 =
11123 InitAckFrame({{QuicPacketNumber(7), QuicPacketNumber(8)}});
11124 lost_packets.clear();
11125 lost_packets.push_back(
11126 LostPacket(QuicPacketNumber(6), kMaxOutgoingPacketSize));
11127 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
11128 .Times(AnyNumber())
11129 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
11130 Return(LossDetectionInterface::DetectionStats())));
11131 ProcessAckPacket(3, &frame3);
11132 // Make sure loss detection is cancelled even there is no new acked packets.
11133 EXPECT_FALSE(connection_.BlackholeDetectionInProgress());
11134}
11135
fayangc7f8b472020-08-19 16:26:15 -070011136TEST_P(QuicConnectionTest, ShorterIdleTimeoutOnSentPackets) {
11137 EXPECT_TRUE(connection_.connected());
11138 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
11139 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(100),
11140 QuicTime::Delta::Zero(), QuicTime::Zero());
11141
11142 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11143 QuicConfig config;
11144 config.SetClientConnectionOptions(QuicTagVector{kFIDT});
11145 QuicConfigPeer::SetNegotiated(&config, true);
11146 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
11147 EXPECT_CALL(visitor_, GetHandshakeState())
11148 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
11149 }
11150 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
11151 QuicConfigPeer::SetReceivedOriginalConnectionId(
11152 &config, connection_.connection_id());
11153 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
11154 &config, connection_.connection_id());
11155 }
11156 connection_.SetFromConfig(config);
11157
11158 ASSERT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
11159 // Send a packet close to timeout.
11160 QuicTime::Delta timeout =
11161 connection_.GetTimeoutAlarm()->deadline() - clock_.Now();
11162 clock_.AdvanceTime(timeout - QuicTime::Delta::FromSeconds(1));
11163 // Send stream data.
11164 SendStreamDataToPeer(
11165 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
11166 0, FIN, nullptr);
11167 // Verify this sent packet does not extend idle timeout since 1s is > PTO
11168 // delay.
11169 ASSERT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
11170 EXPECT_EQ(QuicTime::Delta::FromSeconds(1),
11171 connection_.GetTimeoutAlarm()->deadline() - clock_.Now());
11172
11173 // Received an ACK 100ms later.
11174 clock_.AdvanceTime(timeout - QuicTime::Delta::FromMilliseconds(100));
11175 QuicAckFrame ack = InitAckFrame(1);
11176 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
11177 ProcessAckPacket(1, &ack);
11178 // Verify idle timeout gets extended.
11179 EXPECT_EQ(clock_.Now() + timeout, connection_.GetTimeoutAlarm()->deadline());
11180}
11181
fayange447bc62020-08-27 13:47:11 -070011182// Regression test for b/166255274
11183TEST_P(QuicConnectionTest,
11184 ReserializeInitialPacketInCoalescerAfterDiscardingInitialKey) {
11185 SetQuicReloadableFlag(
11186 quic_neuter_initial_packet_in_coalescer_with_initial_key_discarded, true);
fayang9a74ee92020-09-23 15:49:11 -070011187 if (!connection_.version().CanSendCoalescedPackets() ||
fayangd8682452020-09-28 09:09:29 -070011188 !GetQuicReloadableFlag(quic_fix_missing_initial_keys2)) {
fayang9a74ee92020-09-23 15:49:11 -070011189 // Cannot set quic_fix_missing_initial_keys in the test since connection_ is
11190 // created since the setup.
fayange447bc62020-08-27 13:47:11 -070011191 return;
11192 }
11193 use_tagging_decrypter();
11194 connection_.SetEncrypter(ENCRYPTION_INITIAL,
11195 std::make_unique<TaggingEncrypter>(0x01));
11196 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
11197 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
11198 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
11199 EXPECT_TRUE(connection_.HasPendingAcks());
11200 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
11201 std::make_unique<TaggingEncrypter>(0x02));
11202 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
fayangd8682452020-09-28 09:09:29 -070011203 EXPECT_CALL(visitor_, OnHandshakePacketSent()).WillOnce(Invoke([this]() {
fayange447bc62020-08-27 13:47:11 -070011204 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
11205 connection_.NeuterUnencryptedPackets();
fayangd8682452020-09-28 09:09:29 -070011206 }));
11207 {
11208 QuicConnection::ScopedPacketFlusher flusher(&connection_);
11209 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
11210 // Verify the packet is on hold.
11211 EXPECT_EQ(0u, writer_->packets_write_attempts());
11212 // Flush pending ACKs.
11213 connection_.GetAckAlarm()->Fire();
fayange447bc62020-08-27 13:47:11 -070011214 }
11215 // If not setting
11216 // quic_neuter_initial_packet_in_coalescer_with_initial_key_discarded, there
11217 // will be pending frames in the creator.
11218 EXPECT_FALSE(connection_.packet_creator().HasPendingFrames());
11219 // The ACK frame is deleted along with initial_packet_ in coalescer. Sending
11220 // connection close would cause this (released) ACK frame be serialized (and
11221 // crashes).
11222 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
11223 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_FORWARD_SECURE);
fayang9a74ee92020-09-23 15:49:11 -070011224 EXPECT_TRUE(connection_.connected());
fayange447bc62020-08-27 13:47:11 -070011225}
11226
danzh8a27a1a2020-09-02 10:26:28 -070011227// Check that if there are two PATH_CHALLENGE frames in the packet, the latter
11228// one is ignored.
11229TEST_P(QuicConnectionTest, ReceiveMultiplePathChallenge) {
11230 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
11231 return;
11232 }
11233 PathProbeTestInit(Perspective::IS_SERVER);
11234
11235 // Clear direct_peer_address.
11236 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
11237 // Clear effective_peer_address, it is the same as direct_peer_address for
11238 // this test.
11239 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
11240 QuicSocketAddress());
11241 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
11242
11243 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
11244 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
11245 } else {
11246 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
11247 }
fayangf08e1792020-09-30 13:23:42 -070011248 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
11249 ENCRYPTION_FORWARD_SECURE);
danzh8a27a1a2020-09-02 10:26:28 -070011250 EXPECT_EQ(kPeerAddress, connection_.peer_address());
11251 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
11252
11253 QuicPathFrameBuffer path_frame_buffer1{0, 1, 2, 3, 4, 5, 6, 7};
11254 QuicPathFrameBuffer path_frame_buffer2{8, 9, 10, 11, 12, 13, 14, 15};
11255 QuicFrames frames;
11256 frames.push_back(
11257 QuicFrame(new QuicPathChallengeFrame(0, path_frame_buffer1)));
11258 frames.push_back(
11259 QuicFrame(new QuicPathChallengeFrame(0, path_frame_buffer2)));
11260 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback6(),
11261 /*port=*/23456);
11262
11263 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
11264
11265 // Expect 2 packets to be sent: the first are padded PATH_RESPONSE(s) to the
11266 // alternative peer address. The 2nd is a ACK-only packet to the original
11267 // peer address.
11268 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11269 .Times(2)
11270 .WillOnce(Invoke([=]() {
11271 EXPECT_EQ((connection_.send_path_response() ? 1u : 2u),
11272 writer_->path_response_frames().size());
11273 // The final check is to ensure that the random data in the response
11274 // matches the random data from the challenge.
11275 EXPECT_EQ(0,
11276 memcmp(path_frame_buffer1.data(),
11277 &(writer_->path_response_frames().front().data_buffer),
11278 sizeof(path_frame_buffer1)));
11279 if (!connection_.send_path_response()) {
11280 EXPECT_EQ(
11281 0, memcmp(path_frame_buffer2.data(),
11282 &(writer_->path_response_frames().back().data_buffer),
11283 sizeof(path_frame_buffer2)));
11284 } else {
11285 EXPECT_EQ(1u, writer_->padding_frames().size());
11286 }
11287 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
11288 }))
11289 .WillOnce(Invoke([=]() {
11290 // The last write of ACK-only packet should still use the old peer
11291 // address.
11292 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
11293 }));
fayangf08e1792020-09-30 13:23:42 -070011294 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
11295 ENCRYPTION_FORWARD_SECURE);
danzh8a27a1a2020-09-02 10:26:28 -070011296}
11297
11298TEST_P(QuicConnectionTest, ReceiveStreamFrameBeforePathChallenge) {
11299 if (!VersionHasIetfQuicFrames(connection_.version().transport_version) ||
11300 !connection_.send_path_response()) {
11301 return;
11302 }
11303 PathProbeTestInit(Perspective::IS_SERVER);
11304
11305 // Clear direct_peer_address.
11306 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
11307 // Clear effective_peer_address, it is the same as direct_peer_address for
11308 // this test.
11309 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
11310 QuicSocketAddress());
11311 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
11312
11313 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
11314 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
11315 } else {
11316 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
11317 }
fayangf08e1792020-09-30 13:23:42 -070011318 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
11319 ENCRYPTION_INITIAL);
danzh8a27a1a2020-09-02 10:26:28 -070011320 EXPECT_EQ(kPeerAddress, connection_.peer_address());
11321 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
11322
11323 QuicFrames frames;
11324 frames.push_back(QuicFrame(frame1_));
11325 QuicPathFrameBuffer path_frame_buffer{0, 1, 2, 3, 4, 5, 6, 7};
11326 frames.push_back(QuicFrame(new QuicPathChallengeFrame(0, path_frame_buffer)));
11327 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback6(),
11328 /*port=*/23456);
11329
11330 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE));
11331 EXPECT_CALL(visitor_, OnStreamFrame(_))
11332 .WillOnce(Invoke([=](const QuicStreamFrame& frame) {
11333 // Send some data on the stream. The STREAM_FRAME should be built into
11334 // one packet together with the latter PATH_RESPONSE.
11335 std::string data{"response body"};
11336 struct iovec iov;
11337 MakeIOVector(data, &iov);
11338 connection_.producer()->SaveStreamData(frame.stream_id, &iov, 1, 0u,
11339 data.length());
11340 return notifier_.WriteOrBufferData(frame.stream_id, data.length(),
11341 NO_FIN);
11342 }));
11343 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
fayangf08e1792020-09-30 13:23:42 -070011344 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
11345 ENCRYPTION_FORWARD_SECURE);
danzh8a27a1a2020-09-02 10:26:28 -070011346
11347 // Verify that this packet contains a STREAM_FRAME and a
11348 // PATH_RESPONSE_FRAME.
11349 EXPECT_EQ(1u, writer_->stream_frames().size());
11350 EXPECT_EQ(1u, writer_->path_response_frames().size());
11351 // The final check is to ensure that the random data in the response
11352 // matches the random data from the challenge.
11353 EXPECT_EQ(0, memcmp(path_frame_buffer.data(),
11354 &(writer_->path_response_frames().front().data_buffer),
11355 sizeof(path_frame_buffer)));
11356 EXPECT_EQ(1u, writer_->padding_frames().size());
11357 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
11358}
11359
11360TEST_P(QuicConnectionTest, ReceiveStreamFrameFollowingPathChallenge) {
11361 if (!VersionHasIetfQuicFrames(connection_.version().transport_version) ||
11362 !connection_.send_path_response()) {
11363 return;
11364 }
11365 PathProbeTestInit(Perspective::IS_SERVER);
11366
11367 // Clear direct_peer_address.
11368 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
11369 // Clear effective_peer_address, it is the same as direct_peer_address for
11370 // this test.
11371 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
11372 QuicSocketAddress());
11373 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
11374
11375 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
11376 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
11377 } else {
11378 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
11379 }
fayangf08e1792020-09-30 13:23:42 -070011380 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
11381 ENCRYPTION_INITIAL);
danzh8a27a1a2020-09-02 10:26:28 -070011382 EXPECT_EQ(kPeerAddress, connection_.peer_address());
11383 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
11384
11385 QuicFrames frames;
11386 QuicPathFrameBuffer path_frame_buffer{0, 1, 2, 3, 4, 5, 6, 7};
11387 frames.push_back(QuicFrame(new QuicPathChallengeFrame(0, path_frame_buffer)));
11388 // PATH_RESPONSE should be flushed out before the rest packet is parsed.
11389 frames.push_back(QuicFrame(frame1_));
11390 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback6(),
11391 /*port=*/23456);
11392 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11393 .WillOnce(Invoke([=]() {
11394 // Verify that this packet contains a PATH_RESPONSE_FRAME.
11395 EXPECT_EQ(0u, writer_->stream_frames().size());
11396 EXPECT_EQ(1u, writer_->path_response_frames().size());
11397 // The final check is to ensure that the random data in the response
11398 // matches the random data from the challenge.
11399 EXPECT_EQ(0,
11400 memcmp(path_frame_buffer.data(),
11401 &(writer_->path_response_frames().front().data_buffer),
11402 sizeof(path_frame_buffer)));
11403 EXPECT_EQ(1u, writer_->padding_frames().size());
11404 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
11405 }))
11406 .WillOnce(Invoke([=]() {
11407 // Verify that this packet contains a STREAM_FRAME.
11408 EXPECT_EQ(1u, writer_->stream_frames().size());
11409 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
11410 }));
11411 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE));
11412 EXPECT_CALL(visitor_, OnStreamFrame(_))
11413 .WillOnce(Invoke([=](const QuicStreamFrame& frame) {
11414 // Send some data on the stream. The STREAM_FRAME should be built into
11415 // one packet together with the latter PATH_RESPONSE.
11416 std::string data{"response body"};
11417 struct iovec iov;
11418 MakeIOVector(data, &iov);
11419 connection_.producer()->SaveStreamData(frame.stream_id, &iov, 1, 0u,
11420 data.length());
11421 return notifier_.WriteOrBufferData(frame.stream_id, data.length(),
11422 NO_FIN);
11423 }));
11424
fayangf08e1792020-09-30 13:23:42 -070011425 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
11426 ENCRYPTION_FORWARD_SECURE);
danzh8a27a1a2020-09-02 10:26:28 -070011427}
11428
11429// Tests that a PATH_CHALLENGE is received in between other frames in an out of
11430// order packet.
11431TEST_P(QuicConnectionTest, PathChallengeWithDataInOutOfOrderPacket) {
11432 if (!VersionHasIetfQuicFrames(connection_.version().transport_version) ||
11433 !connection_.send_path_response()) {
11434 return;
11435 }
11436 PathProbeTestInit(Perspective::IS_SERVER);
11437
11438 // Clear direct_peer_address.
11439 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
11440 // Clear effective_peer_address, it is the same as direct_peer_address for
11441 // this test.
11442 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
11443 QuicSocketAddress());
11444 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
11445
11446 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
11447 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
11448 } else {
11449 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
11450 }
11451 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
fayangf08e1792020-09-30 13:23:42 -070011452 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
11453 ENCRYPTION_FORWARD_SECURE);
danzh8a27a1a2020-09-02 10:26:28 -070011454 EXPECT_EQ(kPeerAddress, connection_.peer_address());
11455 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
11456
11457 QuicFrames frames;
11458 frames.push_back(QuicFrame(frame1_));
11459 QuicPathFrameBuffer path_frame_buffer{0, 1, 2, 3, 4, 5, 6, 7};
11460 frames.push_back(QuicFrame(new QuicPathChallengeFrame(0, path_frame_buffer)));
11461 frames.push_back(QuicFrame(frame2_));
11462 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback6(),
11463 /*port=*/23456);
11464
11465 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0u);
11466 EXPECT_CALL(visitor_, OnStreamFrame(_))
11467 .Times(2)
11468 .WillRepeatedly(Invoke([=](const QuicStreamFrame& frame) {
11469 // Send some data on the stream. The STREAM_FRAME should be built into
11470 // one packet together with the latter PATH_RESPONSE.
11471 std::string data{"response body"};
11472 struct iovec iov;
11473 MakeIOVector(data, &iov);
11474 connection_.producer()->SaveStreamData(frame.stream_id, &iov, 1, 0u,
11475 data.length());
11476 return notifier_.WriteOrBufferData(frame.stream_id, data.length(),
11477 NO_FIN);
11478 }));
11479 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11480 .WillOnce(Invoke([=]() {
11481 // Verify that this packet contains a STREAM_FRAME and is sent to the
11482 // original peer address.
11483 EXPECT_EQ(1u, writer_->stream_frames().size());
11484 // No connection migration should happen because the packet is received
11485 // out of order.
11486 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
11487 }))
11488 .WillOnce(Invoke([=]() {
11489 EXPECT_EQ(1u, writer_->path_response_frames().size());
11490 // The final check is to ensure that the random data in the response
11491 // matches the random data from the challenge.
11492 EXPECT_EQ(0,
11493 memcmp(path_frame_buffer.data(),
11494 &(writer_->path_response_frames().front().data_buffer),
11495 sizeof(path_frame_buffer)));
11496 EXPECT_EQ(1u, writer_->padding_frames().size());
11497 // PATH_RESPONSE should be sent in another packet to a different peer
11498 // address.
11499 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
11500 }))
11501 .WillOnce(Invoke([=]() {
11502 // Verify that this packet contains a STREAM_FRAME and is sent to the
11503 // original peer address.
11504 EXPECT_EQ(1u, writer_->stream_frames().size());
11505 // No connection migration should happen because the packet is received
11506 // out of order.
11507 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
11508 }));
11509 // Lower the packet number so that receiving this packet shouldn't trigger
11510 // peer migration.
11511 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 1);
fayangf08e1792020-09-30 13:23:42 -070011512 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
11513 ENCRYPTION_FORWARD_SECURE);
danzh8a27a1a2020-09-02 10:26:28 -070011514}
11515
11516// Tests that a PATH_CHALLENGE is cached if its PATH_RESPONSE can't be sent.
11517TEST_P(QuicConnectionTest, FailToWritePathResponse) {
11518 if (!VersionHasIetfQuicFrames(connection_.version().transport_version) ||
11519 !connection_.send_path_response()) {
11520 return;
11521 }
11522 PathProbeTestInit(Perspective::IS_SERVER);
11523
11524 // Clear direct_peer_address.
11525 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
11526 // Clear effective_peer_address, it is the same as direct_peer_address for
11527 // this test.
11528 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
11529 QuicSocketAddress());
11530 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
11531
11532 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
11533 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
11534 } else {
11535 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
11536 }
11537 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
fayangf08e1792020-09-30 13:23:42 -070011538 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
11539 ENCRYPTION_INITIAL);
danzh8a27a1a2020-09-02 10:26:28 -070011540 EXPECT_EQ(kPeerAddress, connection_.peer_address());
11541 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
11542
11543 QuicFrames frames;
11544 QuicPathFrameBuffer path_frame_buffer{0, 1, 2, 3, 4, 5, 6, 7};
11545 frames.push_back(QuicFrame(new QuicPathChallengeFrame(0, path_frame_buffer)));
11546 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback6(),
11547 /*port=*/23456);
11548
11549 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0u);
11550 // Lower the packet number so that receiving this packet shouldn't trigger
11551 // peer migration.
11552 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 1);
11553 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
11554 writer_->SetWriteBlocked();
fayangf08e1792020-09-30 13:23:42 -070011555 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
11556 ENCRYPTION_FORWARD_SECURE);
danzh8a27a1a2020-09-02 10:26:28 -070011557
11558 EXPECT_EQ(
11559 1u,
11560 QuicConnectionPeer::pending_path_challenge_payloads(&connection_).size());
11561
11562 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
11563 writer_->SetWritable();
11564 connection_.OnCanWrite();
11565 EXPECT_EQ(1u, writer_->path_response_frames().size());
11566 // The final check is to ensure that the random data in the response
11567 // matches the random data from the challenge.
11568 EXPECT_EQ(0, memcmp(path_frame_buffer.data(),
11569 &(writer_->path_response_frames().front().data_buffer),
11570 sizeof(path_frame_buffer)));
11571 EXPECT_EQ(1u, writer_->padding_frames().size());
11572 // PATH_RESPONSE should be sent in another packet to a different peer
11573 // address.
11574 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
11575 EXPECT_TRUE(QuicConnectionPeer::pending_path_challenge_payloads(&connection_)
11576 .empty());
11577}
11578
fayang5d91f082020-09-11 14:47:26 -070011579// Regression test for b/168101557.
11580TEST_P(QuicConnectionTest, HandshakeDataDoesNotGetPtoed) {
fayangf5f83e52020-09-14 10:29:29 -070011581 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
fayang5d91f082020-09-11 14:47:26 -070011582 return;
11583 }
11584 set_perspective(Perspective::IS_SERVER);
11585 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
11586 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
11587 }
11588 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
11589 use_tagging_decrypter();
11590 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
11591 EXPECT_TRUE(connection_.HasPendingAcks());
11592
11593 connection_.SetEncrypter(ENCRYPTION_INITIAL,
11594 std::make_unique<TaggingEncrypter>(0x01));
11595 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
11596 // Send INITIAL 1.
11597 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
11598
11599 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
11600 std::make_unique<TaggingEncrypter>(0x02));
11601 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11602 SetDecrypter(ENCRYPTION_HANDSHAKE,
11603 std::make_unique<StrictTaggingDecrypter>(0x02));
11604 // Send HANDSHAKE packets.
11605 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
11606 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
11607
11608 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
11609 std::make_unique<TaggingEncrypter>(0x03));
11610 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
11611 // Send half RTT packet.
11612 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
11613
11614 // Receives HANDSHAKE 1.
11615 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
11616 std::make_unique<TaggingEncrypter>(0x02));
11617 ProcessCryptoPacketAtLevel(1, ENCRYPTION_HANDSHAKE);
11618 // Discard INITIAL key.
11619 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
11620 connection_.NeuterUnencryptedPackets();
11621 // Verify there is pending ACK.
11622 ASSERT_TRUE(connection_.HasPendingAcks());
11623 // Set the send alarm.
11624 connection_.GetSendAlarm()->Set(clock_.ApproximateNow());
11625
11626 // Fire ACK alarm.
fayangd8682452020-09-28 09:09:29 -070011627 if (!GetQuicReloadableFlag(quic_fix_missing_initial_keys2)) {
11628 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
11629 }
fayang5d91f082020-09-11 14:47:26 -070011630 connection_.GetAckAlarm()->Fire();
11631 if (GetQuicReloadableFlag(quic_fix_pto_pending_timer_count)) {
11632 // Verify 1-RTT packet is coalesced with handshake packet.
11633 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
11634 } else {
11635 // Verify handshake crypto frame is not bundled.
11636 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
11637 EXPECT_FALSE(writer_->ack_frames().empty());
11638 EXPECT_TRUE(writer_->crypto_frames().empty());
11639 }
11640 connection_.GetSendAlarm()->Fire();
11641
11642 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
11643 if (GetQuicReloadableFlag(quic_fix_pto_pending_timer_count)) {
fayangd8682452020-09-28 09:09:29 -070011644 if (!GetQuicReloadableFlag(quic_fix_missing_initial_keys2)) {
11645 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
11646 }
fayangec14d2b2020-10-02 12:00:05 -070011647 } else if (GetQuicReloadableFlag(quic_let_connection_handle_pings)) {
11648 if (!GetQuicReloadableFlag(quic_fix_missing_initial_keys2)) {
11649 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
11650 }
fayang5d91f082020-09-11 14:47:26 -070011651 } else {
11652 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(0);
11653 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
11654 SendPing();
11655 }));
11656 }
11657 connection_.GetRetransmissionAlarm()->Fire();
11658 if (GetQuicReloadableFlag(quic_fix_pto_pending_timer_count)) {
11659 // Verify a handshake packet gets PTOed and 1-RTT packet gets coalesced.
11660 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
11661 } else {
fayangec14d2b2020-10-02 12:00:05 -070011662 if (GetQuicReloadableFlag(quic_let_connection_handle_pings)) {
11663 // Verify PING is sent in the right encryption level.
11664 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
11665 } else {
11666 // Verify an 1-RTT PING gets sent because there is nothing to PTO, bummer,
11667 // since this 1-RTT PING cannot be processed by peer and there is a
11668 // deadlock.
11669 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
11670 }
fayang5d91f082020-09-11 14:47:26 -070011671 EXPECT_FALSE(writer_->ping_frames().empty());
11672 }
11673}
11674
fayang068512c2020-09-14 07:29:40 -070011675// Regression test for b/168294218.
fayang9a74ee92020-09-23 15:49:11 -070011676TEST_P(QuicConnectionTest, CoalescerHandlesInitialKeyDiscard) {
11677 if (!connection_.version().CanSendCoalescedPackets() ||
fayangd8682452020-09-28 09:09:29 -070011678 !GetQuicReloadableFlag(quic_fix_missing_initial_keys2)) {
fayang068512c2020-09-14 07:29:40 -070011679 return;
11680 }
11681 SetQuicReloadableFlag(quic_discard_initial_packet_with_key_dropped, true);
fayangd8682452020-09-28 09:09:29 -070011682 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
fayang068512c2020-09-14 07:29:40 -070011683 EXPECT_CALL(visitor_, OnHandshakePacketSent()).WillOnce(Invoke([this]() {
11684 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
11685 connection_.NeuterUnencryptedPackets();
11686 }));
11687 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
11688
11689 EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
11690 {
11691 QuicConnection::ScopedPacketFlusher flusher(&connection_);
11692 use_tagging_decrypter();
11693 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
11694 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(1));
11695 connection_.SetEncrypter(ENCRYPTION_INITIAL,
11696 std::make_unique<TaggingEncrypter>(0x01));
11697 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
11698 std::make_unique<TaggingEncrypter>(0x02));
11699 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11700 connection_.SendCryptoDataWithString(std::string(1300, 'a'), 0);
11701 // Verify this packet is on hold.
11702 EXPECT_EQ(0u, writer_->packets_write_attempts());
11703 }
fayang9a74ee92020-09-23 15:49:11 -070011704 EXPECT_TRUE(connection_.connected());
fayang068512c2020-09-14 07:29:40 -070011705}
11706
fayangba9d95e2020-09-24 14:30:45 -070011707// Regresstion test for b/168294218
11708TEST_P(QuicConnectionTest, ZeroRttRejectionAndMissingInitialKeys) {
11709 if (!connection_.SupportsMultiplePacketNumberSpaces() ||
fayangd8682452020-09-28 09:09:29 -070011710 !GetQuicReloadableFlag(quic_fix_missing_initial_keys2)) {
fayangba9d95e2020-09-24 14:30:45 -070011711 return;
11712 }
11713 // Not defer send in response to packet.
11714 connection_.set_defer_send_in_response_to_packets(false);
11715 EXPECT_CALL(visitor_, OnHandshakePacketSent()).WillOnce(Invoke([this]() {
11716 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
11717 connection_.NeuterUnencryptedPackets();
11718 }));
11719 EXPECT_CALL(visitor_, OnCryptoFrame(_))
11720 .WillRepeatedly(Invoke([=](const QuicCryptoFrame& frame) {
11721 if (frame.level == ENCRYPTION_HANDSHAKE) {
11722 // 0-RTT gets rejected.
11723 connection_.MarkZeroRttPacketsForRetransmission(0);
11724 // Send Crypto data.
11725 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
11726 std::make_unique<TaggingEncrypter>(0x03));
11727 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11728 connection_.SendCryptoStreamData();
11729 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
11730 std::make_unique<TaggingEncrypter>(0x04));
11731 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
11732 // Retransmit rejected 0-RTT packets.
11733 connection_.OnCanWrite();
11734 // Advance INITIAL ack delay to trigger initial ACK to be sent AFTER
11735 // the retransmission of rejected 0-RTT packets while the HANDSHAKE
11736 // packet is still in the coalescer, such that the INITIAL key gets
11737 // dropped between SendAllPendingAcks and actually send the ack frame,
11738 // bummer.
11739 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(1));
11740 }
11741 }));
11742 use_tagging_decrypter();
11743 connection_.SetEncrypter(ENCRYPTION_INITIAL,
11744 std::make_unique<TaggingEncrypter>(0x01));
11745 connection_.SendCryptoStreamData();
11746 // Send 0-RTT packet.
11747 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
11748 std::make_unique<TaggingEncrypter>(0x02));
11749 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
11750 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
11751
11752 QuicAckFrame frame1 = InitAckFrame(1);
11753 // Received ACK for packet 1.
11754 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
11755 ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL);
11756 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
11757
11758 // Fire retransmission alarm.
fayangec14d2b2020-10-02 12:00:05 -070011759 if (!GetQuicReloadableFlag(quic_let_connection_handle_pings)) {
11760 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
11761 SendPing();
11762 }));
11763 }
fayangba9d95e2020-09-24 14:30:45 -070011764 connection_.GetRetransmissionAlarm()->Fire();
11765
11766 QuicFrames frames1;
11767 frames1.push_back(QuicFrame(&crypto_frame_));
11768 QuicFrames frames2;
11769 QuicCryptoFrame crypto_frame(ENCRYPTION_HANDSHAKE, 0,
11770 quiche::QuicheStringPiece(data1));
11771 frames2.push_back(QuicFrame(&crypto_frame));
11772 ProcessCoalescedPacket(
11773 {{2, frames1, ENCRYPTION_INITIAL}, {3, frames2, ENCRYPTION_HANDSHAKE}});
11774}
11775
fayangf2e0d902020-09-25 14:47:19 -070011776TEST_P(QuicConnectionTest, OnZeroRttPacketAcked) {
11777 if (!connection_.version().UsesTls()) {
11778 return;
11779 }
11780 MockQuicConnectionDebugVisitor debug_visitor;
11781 connection_.set_debug_visitor(&debug_visitor);
11782 use_tagging_decrypter();
11783 connection_.SetEncrypter(ENCRYPTION_INITIAL,
11784 std::make_unique<TaggingEncrypter>(0x01));
11785 connection_.SendCryptoStreamData();
11786 // Send 0-RTT packet.
11787 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
11788 std::make_unique<TaggingEncrypter>(0x02));
11789 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
11790 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
11791 connection_.SendStreamDataWithString(4, "bar", 0, NO_FIN);
11792 // Received ACK for packet 1, HANDSHAKE packet and 1-RTT ACK.
11793 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _))
11794 .Times(AnyNumber());
11795 QuicFrames frames1;
11796 QuicAckFrame ack_frame1 = InitAckFrame(1);
11797 frames1.push_back(QuicFrame(&ack_frame1));
11798
11799 QuicFrames frames2;
11800 QuicCryptoFrame crypto_frame(ENCRYPTION_HANDSHAKE, 0,
11801 quiche::QuicheStringPiece(data1));
11802 frames2.push_back(QuicFrame(&crypto_frame));
11803 EXPECT_CALL(debug_visitor, OnZeroRttPacketAcked()).Times(0);
11804 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
11805 ProcessCoalescedPacket(
11806 {{1, frames1, ENCRYPTION_INITIAL}, {2, frames2, ENCRYPTION_HANDSHAKE}});
11807
11808 QuicFrames frames3;
11809 QuicAckFrame ack_frame2 =
11810 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
11811 frames3.push_back(QuicFrame(&ack_frame2));
11812 EXPECT_CALL(debug_visitor, OnZeroRttPacketAcked()).Times(1);
11813 ProcessCoalescedPacket({{3, frames3, ENCRYPTION_FORWARD_SECURE}});
11814
11815 QuicFrames frames4;
11816 QuicAckFrame ack_frame3 =
11817 InitAckFrame({{QuicPacketNumber(3), QuicPacketNumber(4)}});
11818 frames4.push_back(QuicFrame(&ack_frame3));
11819 EXPECT_CALL(debug_visitor, OnZeroRttPacketAcked()).Times(0);
11820 ProcessCoalescedPacket({{4, frames4, ENCRYPTION_FORWARD_SECURE}});
11821}
11822
QUICHE teama6ef0a62019-03-07 20:34:33 -050011823} // namespace
11824} // namespace test
11825} // namespace quic